Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(assets): one description of a texture, read by every realm that draws it

esengined9be2e8fc86c
diff --git a/desktop/electron/addressableManifest.ts b/desktop/electron/addressableManifest.ts
index 0a57ecf0c..26f883ee9 100644
--- a/desktop/electron/addressableManifest.ts
+++ b/desktop/electron/addressableManifest.ts
@@ -18,6 +18,7 @@
import { readFile, stat } from 'node:fs/promises';
import path from 'node:path';
import { deriveManifestRevision, type AddressableManifest } from '../../sdk/src/asset/AddressableManifest';
+import { textureImportSettingsFrom, type ParsedTextureImportSettings } from '../../sdk/src/asset/textureImportSettings';
/** The flat v1.0 cook manifest this reads (see cookAssets `CookManifestEntry`). */
interface FlatManifest {
@@ -25,6 +26,7 @@ interface FlatManifest {
uuid: string; path: string; sourcePath?: string; type: string;
contentHash?: string; size?: number; group?: string; groupMode?: string;
compressedFormats?: string[];
+ importer?: Record<string, unknown>;
atlas?: { page: number; frame: { x: number; y: number; width: number; height: number }; pageWidth: number; pageHeight: number };
}[];
}
@@ -57,6 +59,7 @@ export async function buildAddressableManifest(absOut: string): Promise<string>
type Entry = {
path: string; address?: string; type: string; size: number; labels: string[]; contentHash?: string;
compressedFormats?: string[];
+ textureImport?: ParsedTextureImportSettings;
metadata?: { atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number }; atlasPageWidth?: number; atlasPageHeight?: number };
};
type Group = { bundleMode: string; labels: string[]; assets: Record<string, Entry> };
@@ -74,6 +77,13 @@ export async function buildAddressableManifest(absOut: string): Promise<string>
// the addressable manifest — the flat one it came from is a build-time
// intermediate that no longer ships.
if (e.compressedFormats?.length) entry.compressedFormats = e.compressedFormats;
+ // Parsed here, not shipped raw: the runtime needs how the texture is sampled
+ // and sliced, never the cook's own knobs (maxSize, compression format). This
+ // is the ONLY channel a packaged build has for the `.meta` — without it a
+ // 9-sliced frame stretches in the shipped game while looking right in the
+ // editor.
+ const textureImport = textureImportSettingsFrom(e.importer);
+ if (textureImport) entry.textureImport = textureImport;
// The logical source path rides as the asset's address: path-style refs
// resolve through it. Only meaningful when staging renamed the file.
if (e.sourcePath && e.sourcePath !== e.path) entry.address = e.sourcePath;
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index 9633f03f5..cde9f05d2 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -11,7 +11,6 @@
* import of an editor module here would break the realm bundle. Type-only
* imports are erased before resolution and are safe.
*/
-import type { ParsedTextureImportSettings } from 'esengine';
import type { SceneData, PhysicsPluginConfig, AudioProjectConfig, ThemeOverrides, AddressableManifest } from 'esengine';
/**
@@ -54,11 +53,6 @@ export interface PlayNetConfig {
export interface PlayPayload {
sceneData: SceneData;
assetManifest: Record<string, string>;
- /** Per-texture import settings (filter/wrap/sRGB, 9-slice border) keyed by the
- * authored `@uuid:` ref, so the realm samples and slices its textures exactly
- * as the edit viewport does. They describe the ASSET, so they travel beside
- * the scene rather than inside it. */
- textureImports?: Record<string, ParsedTextureImportSettings>;
/** AddressableManifest (groups + bundle modes) so `Assets.loadGroup` — remote /
* lazy groups — works in Play exactly as in a shipped build. */
manifest?: AddressableManifest;
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index 863c59804..f8855c0ef 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -208,9 +208,6 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
canvas,
sceneData: msg.sceneData,
assetManifest: msg.assetManifest,
- // Per-texture import settings from the editor's asset database, so the realm
- // samples and 9-slices its textures exactly as the edit viewport does.
- textureImports: msg.textureImports,
// Addressable manifest → Assets.loadGroup works in the realm (remote / lazy
// groups) just like a shipped build. Remote assets resolve same-origin
// estella:// via assetBaseUrl, so no remoteRoot is set here.
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index f047d7d43..efb298663 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1481,13 +1481,24 @@ class ProjectStoreImpl {
if (['.esscene', '.esanim', '.estilemap', '.estileset', '.estimeline', '.json', '.eslocale'].includes(ext)) return 'json';
return 'binary';
};
- type Asset = { path: string; type: string; size: number; labels: string[] };
+ type Asset = {
+ path: string; type: string; size: number; labels: string[];
+ textureImport?: ParsedTextureImportSettings;
+ };
const groups: Record<string, { bundleMode: string; labels: string[]; assets: Record<string, Asset> }> = {};
for (const [uuid, raw] of this.uuidToPath) {
const path = raw.replace(/\\/g, '/');
const { name, delivery } = resolveAssetGroup(path, this.assetGroupsConfig);
const g = (groups[name] ??= { bundleMode: delivery, labels: [], assets: {} });
- g.assets[uuid.toLowerCase()] = { path, type: typeOfExt(path), size: 0, labels: [] };
+ // How the texture is sampled and 9-sliced travels with the asset, exactly
+ // as it does in a cooked manifest — so Play reads it through the same
+ // channel a shipped build does, rather than a play-only side band that can
+ // drift from it.
+ const textureImport = textureImportSettingsFrom(this.uuidToImporter.get(uuid));
+ g.assets[uuid.toLowerCase()] = {
+ path, type: typeOfExt(path), size: 0, labels: [],
+ ...(textureImport ? { textureImport } : {}),
+ };
}
groups.main ??= { bundleMode: 'local', labels: [], assets: {} };
return { version: '2.0', groups } as unknown as AddressableManifest;
@@ -1496,7 +1507,6 @@ class ProjectStoreImpl {
playPayload(): {
sceneData: SceneData;
assetManifest: Record<string, string>;
- textureImports: Record<string, ParsedTextureImportSettings>;
manifest: AddressableManifest;
entrySceneName?: string;
extraScenes?: Array<{ name: string; path: string }>;
@@ -1515,15 +1525,6 @@ class ProjectStoreImpl {
// same-origin estella:// — no cross-scheme dance needed.
const assetManifest: Record<string, string> = {};
for (const [uuid, path] of this.uuidToPath) assetManifest[uuid] = `estella://project/${path}`;
- // Import settings ride to the realm keyed by the authored `@uuid:` ref — the
- // spelling a component holds — so a played scene samples and slices exactly
- // as the edit viewport does. They stay OUT of the scene: they describe the
- // asset, and a copy in the scene goes stale when the `.meta` changes.
- const textureImports: Record<string, ParsedTextureImportSettings> = {};
- for (const [uuid, importer] of this.uuidToImporter) {
- const settings = textureImportSettingsFrom(importer);
- if (settings) textureImports[UUID_PREFIX + uuid] = settings;
- }
// Play == ship: register every other project scene under its export name
// (scenes-dir-relative path sans extension — the same rule exportGame's
// discoverProjectScenes uses), so SceneManager.switchTo('levels/boss')
@@ -1571,7 +1572,7 @@ class ProjectStoreImpl {
const uiTheme = this.uiTheme();
const uiThemeOverrides = this.uiThemeOverrides();
return {
- sceneData, assetManifest, textureImports, manifest: this.buildPlayManifest(), physicsEnabled: f.enabled, physicsConfig,
+ sceneData, assetManifest, manifest: this.buildPlayManifest(), physicsEnabled: f.enabled, physicsConfig,
...(currentScene ? { entrySceneName: exportSceneName(currentScene) } : {}),
...(extraScenes.length > 0 ? { extraScenes } : {}),
...(audioConfig.buses ? { audioConfig } : {}),
diff --git a/desktop/tests/addressable-manifest.test.ts b/desktop/tests/addressable-manifest.test.ts
new file mode 100644
index 000000000..5cd89fbea
--- /dev/null
+++ b/desktop/tests/addressable-manifest.test.ts
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The ship manifest is a packaged build's ONLY channel for the `.meta`.
+ *
+ * The cook records each asset's importer block, but assembling the addressable
+ * manifest used to drop it — so a shipped game had no filter/wrap/sRGB and no
+ * 9-slice border, and a frame that sliced correctly in the editor stretched in
+ * the build. What ships is the PARSED runtime half: the renderer needs how the
+ * texture is sampled, never the cook's own knobs.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { buildAddressableManifest } from '../electron/addressableManifest';
+import type { AddressableManifest } from '../../sdk/src/asset/AddressableManifest';
+
+const SLICED = {
+ uuid: 'A0C281AF-F1E6-43F1-9561-834D9AFB25B5',
+ path: 'assets/ui/Button_Red.png',
+ type: 'texture',
+ size: 100,
+ importer: {
+ maxSize: 2048, compress: true, compressFormat: 'uastc',
+ filterMode: 'linear', wrapMode: 'clamp', sRGB: true,
+ sliceBorder: { left: 23, right: 24, top: 25, bottom: 29 },
+ },
+};
+const PLAIN = {
+ uuid: 'B0000000-0000-4000-8000-000000000000',
+ path: 'assets/ui/Background.png',
+ type: 'texture',
+ size: 100,
+ // Cook-only knobs plus an all-zero border: nothing the renderer acts on.
+ importer: {
+ maxSize: 2048, compress: true, compressFormat: 'uastc',
+ sliceBorder: { left: 0, right: 0, top: 0, bottom: 0 },
+ },
+};
+
+describe('buildAddressableManifest — texture import settings', () => {
+ let dir: string;
+
+ beforeEach(async () => {
+ dir = await mkdtemp(path.join(tmpdir(), 'estella-manifest-'));
+ });
+ afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+ });
+
+ const build = async (entries: unknown[]): Promise<AddressableManifest> => {
+ await writeFile(path.join(dir, 'assets.manifest.json'), JSON.stringify({ entries }));
+ return JSON.parse(await buildAddressableManifest(dir)) as AddressableManifest;
+ };
+
+ it('ships the parsed settings, not the raw importer block', async () => {
+ const manifest = await build([SLICED]);
+ const asset = manifest.groups.main.assets[SLICED.uuid.toLowerCase()];
+
+ expect(asset.textureImport).toEqual({
+ filter: 'linear', wrap: 'clamp', srgb: true,
+ sliceBorder: { left: 23, right: 24, top: 25, bottom: 29 },
+ });
+ // The cook's own settings stay behind — they mean nothing to a renderer.
+ expect(JSON.stringify(asset)).not.toContain('maxSize');
+ expect(JSON.stringify(asset)).not.toContain('compressFormat');
+ });
+
+ it('omits the field for an asset whose importer says nothing renderable', async () => {
+ const manifest = await build([PLAIN]);
+ const asset = manifest.groups.main.assets[PLAIN.uuid.toLowerCase()];
+
+ expect(asset.textureImport).toBeUndefined();
+ });
+
+ it('is answerable by every ref spelling once the runtime indexes it', async () => {
+ const manifest = await build([{ ...SLICED, sourcePath: 'assets/ui/Button_Red.png', path: 'ca/9f3a1b.png' }]);
+ const { ManifestModel } = await import('../../sdk/src/asset/AddressableManifest');
+ const lookup = ManifestModel.fromJson(manifest).textureImportLookup();
+
+ // The uuid, the staged path a content-addressed cook renamed it to, and the
+ // authored address a path-style ref still names it by.
+ for (const ref of [
+ SLICED.uuid.toLowerCase(), `@uuid:${SLICED.uuid.toLowerCase()}`,
+ 'ca/9f3a1b.png', 'assets/ui/Button_Red.png', '/assets/ui/Button_Red.png',
+ ]) {
+ expect(lookup(ref)?.sliceBorder, ref).toEqual({ left: 23, right: 24, top: 25, bottom: 29 });
+ }
+ });
+});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index f15e478c8..5fd459072 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -84,6 +84,7 @@ labels: string[]
metadata: { atlas?: string; atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number; }; atlasPageWidth?: number; atlasPageHeight?: number; } | undefined
path: string
size: number
+textureImport: ParsedTextureImportSettings | undefined
type: AddressableAssetType
```
@@ -3841,6 +3842,7 @@ groupsByMode: (mode: BundleMode) => string[]
remoteAssetPath: (ref: string) => string | null
resolvePath: (ref: string, normalize?: (ref: string) => string) => string
revision: () => string | null
+textureImportLookup: () => (ref: string) => ParsedTextureImportSettings | undefined
static empty: () => ManifestModel
static fromJson: (manifest: AddressableManifest) => ManifestModel
static new (manifest: AddressableManifest): ManifestModel
@@ -4296,6 +4298,7 @@ catalog: Catalog | undefined
manifest: AddressableManifest
model: ManifestModel
resolvePath: (ref: string) => string
+textureImport: (ref: string) => ParsedTextureImportSettings | undefined
```
## PackagedAssetSourceOptions — interface
@@ -4850,7 +4853,6 @@ physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
remoteRoot: string | undefined
sceneData: SceneData
-textureImports: Record<string, ParsedTextureImportSettings> | undefined
uiTheme: "dark" | "light" | undefined
uiThemeOverrides: ThemeOverrides | undefined
wasmBaseUrl: string | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index a129f606a..e9a6b85f5 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -84,6 +84,7 @@ labels: string[]
metadata: { atlas?: string; atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number; }; atlasPageWidth?: number; atlasPageHeight?: number; } | undefined
path: string
size: number
+textureImport: ParsedTextureImportSettings | undefined
type: AddressableAssetType
```
@@ -3849,6 +3850,7 @@ groupsByMode: (mode: BundleMode) => string[]
remoteAssetPath: (ref: string) => string | null
resolvePath: (ref: string, normalize?: (ref: string) => string) => string
revision: () => string | null
+textureImportLookup: () => (ref: string) => ParsedTextureImportSettings | undefined
static empty: () => ManifestModel
static fromJson: (manifest: AddressableManifest) => ManifestModel
static new (manifest: AddressableManifest): ManifestModel
@@ -4450,6 +4452,7 @@ catalog: Catalog | undefined
manifest: AddressableManifest
model: ManifestModel
resolvePath: (ref: string) => string
+textureImport: (ref: string) => ParsedTextureImportSettings | undefined
```
## PackagedAssetSourceOptions — interface
@@ -5004,7 +5007,6 @@ physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
remoteRoot: string | undefined
sceneData: SceneData
-textureImports: Record<string, ParsedTextureImportSettings> | undefined
uiTheme: "dark" | "light" | undefined
uiThemeOverrides: ThemeOverrides | undefined
wasmBaseUrl: string | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index c39b7a748..89ea22ad6 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -79,6 +79,7 @@ labels: string[]
metadata: { atlas?: string; atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number; }; atlasPageWidth?: number; atlasPageHeight?: number; } | undefined
path: string
size: number
+textureImport: ParsedTextureImportSettings | undefined
type: AddressableAssetType
```
@@ -3836,6 +3837,7 @@ groupsByMode: (mode: BundleMode) => string[]
remoteAssetPath: (ref: string) => string | null
resolvePath: (ref: string, normalize?: (ref: string) => string) => string
revision: () => string | null
+textureImportLookup: () => (ref: string) => ParsedTextureImportSettings | undefined
static empty: () => ManifestModel
static fromJson: (manifest: AddressableManifest) => ManifestModel
static new (manifest: AddressableManifest): ManifestModel
@@ -4291,6 +4293,7 @@ catalog: Catalog | undefined
manifest: AddressableManifest
model: ManifestModel
resolvePath: (ref: string) => string
+textureImport: (ref: string) => ParsedTextureImportSettings | undefined
```
## PackagedAssetSourceOptions — interface
@@ -4845,7 +4848,6 @@ physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
remoteRoot: string | undefined
sceneData: SceneData
-textureImports: Record<string, ParsedTextureImportSettings> | undefined
uiTheme: "dark" | "light" | undefined
uiThemeOverrides: ThemeOverrides | undefined
wasmBaseUrl: string | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 0a4e2905e..dfc33bbfe 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -79,6 +79,7 @@ labels: string[]
metadata: { atlas?: string; atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number; }; atlasPageWidth?: number; atlasPageHeight?: number; } | undefined
path: string
size: number
+textureImport: ParsedTextureImportSettings | undefined
type: AddressableAssetType
```
@@ -3836,6 +3837,7 @@ groupsByMode: (mode: BundleMode) => string[]
remoteAssetPath: (ref: string) => string | null
resolvePath: (ref: string, normalize?: (ref: string) => string) => string
revision: () => string | null
+textureImportLookup: () => (ref: string) => ParsedTextureImportSettings | undefined
static empty: () => ManifestModel
static fromJson: (manifest: AddressableManifest) => ManifestModel
static new (manifest: AddressableManifest): ManifestModel
@@ -4506,6 +4508,7 @@ catalog: Catalog | undefined
manifest: AddressableManifest
model: ManifestModel
resolvePath: (ref: string) => string
+textureImport: (ref: string) => ParsedTextureImportSettings | undefined
```
## PackagedAssetSourceOptions — interface
@@ -5060,7 +5063,6 @@ physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
remoteRoot: string | undefined
sceneData: SceneData
-textureImports: Record<string, ParsedTextureImportSettings> | undefined
uiTheme: "dark" | "light" | undefined
uiThemeOverrides: ThemeOverrides | undefined
wasmBaseUrl: string | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index fb24fa450..763ba1a5b 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -79,6 +79,7 @@ labels: string[]
metadata: { atlas?: string; atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number; }; atlasPageWidth?: number; atlasPageHeight?: number; } | undefined
path: string
size: number
+textureImport: ParsedTextureImportSettings | undefined
type: AddressableAssetType
```
@@ -3843,6 +3844,7 @@ groupsByMode: (mode: BundleMode) => string[]
remoteAssetPath: (ref: string) => string | null
resolvePath: (ref: string, normalize?: (ref: string) => string) => string
revision: () => string | null
+textureImportLookup: () => (ref: string) => ParsedTextureImportSettings | undefined
static empty: () => ManifestModel
static fromJson: (manifest: AddressableManifest) => ManifestModel
static new (manifest: AddressableManifest): ManifestModel
@@ -4298,6 +4300,7 @@ catalog: Catalog | undefined
manifest: AddressableManifest
model: ManifestModel
resolvePath: (ref: string) => string
+textureImport: (ref: string) => ParsedTextureImportSettings | undefined
```
## PackagedAssetSourceOptions — interface
@@ -4852,7 +4855,6 @@ physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
remoteRoot: string | undefined
sceneData: SceneData
-textureImports: Record<string, ParsedTextureImportSettings> | undefined
uiTheme: "dark" | "light" | undefined
uiThemeOverrides: ThemeOverrides | undefined
wasmBaseUrl: string | undefined
diff --git a/sdk/src/asset/AddressableManifest.ts b/sdk/src/asset/AddressableManifest.ts
index 518ec87a4..b65e1801d 100644
--- a/sdk/src/asset/AddressableManifest.ts
+++ b/sdk/src/asset/AddressableManifest.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { AddressableAssetType } from '../assetTypes';
+import { indexTextureImportSettings, type ParsedTextureImportSettings } from './textureImportSettings';
import { contentHashOf } from './contentHash';
export type { AddressableAssetType };
@@ -21,6 +22,14 @@ export interface AddressableManifestAsset {
contentHash?: string;
/** GPU compressed formats this asset was encoded for (e.g. ['astc-4x4','etc2-rgba8']). */
compressedFormats?: string[];
+ /**
+ * How the texture is sampled and sliced — the runtime half of the `.meta`
+ * importer block, parsed at cook time rather than shipped raw: a packaged
+ * realm needs filter/wrap/sRGB and the 9-slice border, never the cook's own
+ * settings (maxSize, compression format). Absent when the asset is not a
+ * texture or its importer says nothing the renderer acts on.
+ */
+ textureImport?: ParsedTextureImportSettings;
metadata?: {
atlas?: string;
atlasPage?: number;
@@ -163,6 +172,22 @@ export class ManifestModel {
return out;
}
+ /**
+ * Per-ref texture import settings for every asset that carries them — what a
+ * packaged realm answers `RuntimeAssetSource.textureImportSettings` with, so
+ * a shipped game samples and 9-slices exactly as the editor did.
+ */
+ textureImportLookup(): (ref: string) => ParsedTextureImportSettings | undefined {
+ return indexTextureImportSettings(
+ this.entries().map(({ key, asset }) => ({
+ uuid: key,
+ path: asset.path,
+ address: asset.address,
+ settings: asset.textureImport,
+ })),
+ );
+ }
+
/** The manifest's build content revision (see {@link deriveManifestRevision}),
* or null on a legacy manifest that predates the field. */
revision(): string | null {
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index a1fbbced0..3cd9324bf 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -997,7 +997,18 @@ export class Assets {
}
};
- pushHandleLoad(texturePaths, p => this.loadTexture(p), textureHandles, 'texture');
+ // Textures load through their AUTHORED ref, not the resolved path the
+ // handle map is keyed by: per-asset import settings (filter/wrap/sRGB and
+ // the 9-slice border) are looked up by the spelling a component carries,
+ // which is the resolver's documented contract. Resolution happens inside
+ // loadTexture anyway, so the bytes fetched are identical either way —
+ // feeding it the resolved path only strips the lookup of its key.
+ pushHandleLoad(
+ texturePaths,
+ p => this.loadTexture(discovered.rawFor.get(p) ?? p),
+ textureHandles,
+ 'texture',
+ );
pushHandleLoad(materialPaths, p => this.loadMaterial(p), materialHandles, 'material');
pushHandleLoad(fontPaths, p => this.loadFont(p), fontHandles, 'font');
// The runtime scene loader owns spine as a two-phase load+apply through the
diff --git a/sdk/src/asset/discoverAssets.ts b/sdk/src/asset/discoverAssets.ts
index 32e8441c8..a50647708 100644
--- a/sdk/src/asset/discoverAssets.ts
+++ b/sdk/src/asset/discoverAssets.ts
@@ -44,6 +44,13 @@ export interface SceneAssetRefs {
* absolute URLs would otherwise register under keys no component uses.
*/
rawByType: Map<string, Set<string>>;
+ /**
+ * Resolved path → the RAW ref it came from (first spelling wins; several refs
+ * can name one asset). Lets a caller that must bucket by resolved path — the
+ * handle maps are keyed that way — still load through the authored ref, which
+ * is the spelling per-asset lookups (texture import settings) are keyed by.
+ */
+ rawFor: Map<string, string>;
/**
* Skeleton/atlas pairs posed by SPINE. Split from {@link dragonBones} because
* the two are loaded by different runtimes: a pair handed to the wrong one is
@@ -70,6 +77,7 @@ export function discoverSceneAssets(
): SceneAssetRefs {
const byType = new Map<string, Set<string>>();
const rawByType = new Map<string, Set<string>>();
+ const rawFor = new Map<string, string>();
const spines: SkeletalAssetRef[] = [];
const dragonBones: SkeletalAssetRef[] = [];
// One set across both runtimes: the key is the pair, and the same pair cannot
@@ -100,6 +108,7 @@ export function discoverSceneAssets(
if (path == null) return;
bucket(byType, type, path);
bucket(rawByType, type, raw);
+ if (!rawFor.has(path)) rawFor.set(path, raw);
};
for (const entityData of sceneData.entities) {
@@ -154,7 +163,7 @@ export function discoverSceneAssets(
}
}
- return { byType, rawByType, spines, dragonBones, unresolved };
+ return { byType, rawByType, rawFor, spines, dragonBones, unresolved };
}
export function getAssetPathsByType(refs: SceneAssetRefs, type: AssetFieldType): Set<string> {
diff --git a/sdk/src/asset/textureImportSettings.ts b/sdk/src/asset/textureImportSettings.ts
index bfeb022a8..97682eaad 100644
--- a/sdk/src/asset/textureImportSettings.ts
+++ b/sdk/src/asset/textureImportSettings.ts
@@ -49,3 +49,35 @@ export function textureImportSettingsFrom(
? { filter, wrap, srgb, sliceBorder }
: undefined;
}
+
+/**
+ * Index settings by EVERY spelling a scene may name the asset with — its uuid
+ * bare and `@uuid:`-prefixed, its authored path with and without a leading
+ * slash, and the staged path a content-addressed cook renamed it to.
+ *
+ * One asset, several names, and which name a component carries is the project's
+ * choice: the meta-driven pipeline writes `@uuid:`, hand-authored and ported
+ * scenes hold paths. A lookup that indexes only one of them works on whichever
+ * projects happen to use that spelling and silently drops the settings for the
+ * rest — so the spelling fan-out is done ONCE, here, rather than guessed at by
+ * each realm's asset source.
+ */
+export function indexTextureImportSettings(
+ assets: Iterable<{
+ uuid?: string;
+ path?: string;
+ address?: string;
+ settings: ParsedTextureImportSettings | undefined;
+ }>,
+): (ref: string) => ParsedTextureImportSettings | undefined {
+ const byRef = new Map<string, ParsedTextureImportSettings>();
+ for (const { uuid, path, address, settings } of assets) {
+ if (!settings) continue;
+ for (const spelling of [uuid, uuid && `@uuid:${uuid}`, path, address]) {
+ if (!spelling) continue;
+ byRef.set(spelling, settings);
+ if (!spelling.startsWith('/')) byRef.set(`/${spelling}`, settings);
+ }
+ }
+ return byRef.size > 0 ? (ref) => byRef.get(ref) : () => undefined;
+}
diff --git a/sdk/src/packagedRuntime.ts b/sdk/src/packagedRuntime.ts
index f78a654a0..1974739f4 100644
--- a/sdk/src/packagedRuntime.ts
+++ b/sdk/src/packagedRuntime.ts
@@ -18,6 +18,7 @@ import { platformReadTextFile, platformLoadImagePixels } from './platform';
import { ManifestModel, type AddressableManifest } from './asset/AddressableManifest';
import { Catalog, atlasCatalogFields, type CatalogEntry } from './asset/Catalog';
import { FileSystemBackend, type Backend } from './asset/Backend';
+import type { ParsedTextureImportSettings } from './asset/textureImportSettings';
import { Audio } from './audio/Audio';
import { VideoPlayer } from './video/VideoAPI';
import type { App } from './app';
@@ -64,6 +65,8 @@ export interface PackagedAssetIndex {
addressOf(ref: string): string | null;
/** Every staged asset path — content-driven discovery (locale tables). */
assetPaths(): string[];
+ /** How a texture is sampled and 9-sliced, for any ref spelling. */
+ textureImport(ref: string): ParsedTextureImportSettings | undefined;
}
/**
@@ -124,6 +127,10 @@ export function indexPackagedManifest(manifest: AddressableManifest): PackagedAs
// the staged file), else the staged path — either keeps the extension
// .eslocale discovery filters on.
assetPaths: () => model.allAssets().map((a) => a.address ?? a.path),
+ // Built once per index: a scene preload asks for every texture it uses,
+ // and rebuilding the spelling map per ref would walk the whole manifest
+ // each time.
+ textureImport: model.textureImportLookup(),
};
}
@@ -153,6 +160,7 @@ export function createPackagedAssetSource(
resolveRef: index.resolvePath,
resolveAddress: index.addressOf,
listAssetPaths: index.assetPaths,
+ textureImportSettings: index.textureImport,
};
}
diff --git a/sdk/src/playRealmRuntime.ts b/sdk/src/playRealmRuntime.ts
index fd995eed5..731d8c6e5 100644
--- a/sdk/src/playRealmRuntime.ts
+++ b/sdk/src/playRealmRuntime.ts
@@ -22,10 +22,9 @@ import { VideoPlayer } from './video/VideoAPI';
import { initRuntime } from './runtimeLoader';
import type { ThemeOverrides } from './ui';
import type { RuntimeAssetSource } from './runtimeAssets';
-import type { ParsedTextureImportSettings } from './asset/textureImportSettings';
import { HttpBackend } from './asset/Backend';
import { Catalog, type CatalogData } from './asset/Catalog';
-import type { AddressableManifest } from './asset/AddressableManifest';
+import { ManifestModel, type AddressableManifest } from './asset/AddressableManifest';
import type { SceneData } from './scene';
import type { PhysicsPluginConfig } from './physics/PhysicsPlugin';
import type { AudioProjectConfig } from './audio/AudioProjectConfig';
@@ -55,13 +54,6 @@ export interface PlayRealmRuntimeConfig {
* Omit when files are served at their logical paths (the editor realm).
*/
assetPathMap?: Record<string, string>;
- /**
- * Per-texture import settings (filter/wrap/sRGB, 9-slice border) keyed by the
- * authored ref. Supplied by the editor from its asset database so a played
- * scene samples and slices its textures exactly as the edit viewport does —
- * without the settings being copied into the scene, where they would go stale.
- */
- textureImports?: Record<string, ParsedTextureImportSettings>;
/**
* Logical path → build-path catalog for the same cooked case: loaders fetch
* their INNER text refs (a material's shader) through Catalog.getBuildPath,
@@ -150,7 +142,7 @@ function createPlayRealmSource(
manifest: Record<string, string>,
assetBaseUrl?: string,
pathMap?: Record<string, string>,
- textureImports?: Record<string, ParsedTextureImportSettings>,
+ addressable?: AddressableManifest | null,
): RuntimeAssetSource {
const backend = new HttpBackend({ baseUrl: '' });
return {
@@ -161,10 +153,12 @@ function createPlayRealmSource(
// manifest's resolved URLs — both keep the real extension, which is all
// the .eslocale discovery filters on.
listAssetPaths: () => (pathMap ? Object.keys(pathMap) : Object.values(manifest)),
- // Keyed by the AUTHORED ref (`@uuid:…` or a project path) — the same
- // spelling a component holds — because that is what the loader asks with,
- // before resolveRef turns it into a realm URL.
- ...(textureImports ? { textureImportSettings: (ref: string) => textureImports[ref] } : {}),
+ // Sampling and the 9-slice border come off the addressable manifest, the
+ // same field a cooked build reads — Play and ship cannot disagree about
+ // an asset when they are looking at one description of it.
+ ...(addressable
+ ? { textureImportSettings: ManifestModel.fromJson(addressable).textureImportLookup() }
+ : {}),
};
}
@@ -175,7 +169,7 @@ function createPlayRealmSource(
*/
export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Promise<void> {
const { app, module, canvas, sceneData, assetManifest, assetBaseUrl } = config;
- const source = createPlayRealmSource(assetManifest, assetBaseUrl, config.assetPathMap, config.textureImports);
+ const source = createPlayRealmSource(assetManifest, assetBaseUrl, config.assetPathMap, config.manifest);
applyAssetRefResolvers(app, (ref) => resolvePlayAssetRef(ref, assetManifest, assetBaseUrl, config.assetPathMap));
const entryName = config.entrySceneName ?? '__play';
await initRuntime({
diff --git a/sdk/src/playableRuntime.ts b/sdk/src/playableRuntime.ts
index 659bb4a7a..17a59fdb8 100644
--- a/sdk/src/playableRuntime.ts
+++ b/sdk/src/playableRuntime.ts
@@ -17,7 +17,7 @@ import { initRuntime } from './runtimeLoader';
import type { ThemeOverrides } from './ui';
import type { RuntimeAssetSource } from './runtimeAssets';
import { EmbeddedBackend } from './asset/Backend';
-import type { AddressableManifest } from './asset/AddressableManifest';
+import { ManifestModel, type AddressableManifest } from './asset/AddressableManifest';
import type { Vec2 } from './types';
import type { SceneData } from './scene';
import { Audio } from './audio/Audio';
@@ -113,6 +113,12 @@ export async function initPlayableRuntime(config: PlayableRuntimeConfig): Promis
// Map keys are the shippable paths (logical aliases included) — the
// .eslocale discovery filters on extension, so aliases resolve fine.
listAssetPaths: () => Object.keys(assets),
+ // A single-file playable inlines the bytes but still ships the manifest,
+ // so filter/wrap/sRGB and the 9-slice border reach it the same way they
+ // reach every other packaged realm.
+ textureImportSettings: config.manifest
+ ? ManifestModel.fromJson(config.manifest).textureImportLookup()
+ : undefined,
};
if (app.hasResource(Audio)) {
diff --git a/sdk/tests/preload-texture-import.test.ts b/sdk/tests/preload-texture-import.test.ts
new file mode 100644
index 000000000..516047486
--- /dev/null
+++ b/sdk/tests/preload-texture-import.test.ts
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * Regression: a scene's textures must be preloaded through their AUTHORED ref,
+ * because that is the key per-asset import settings are looked up by.
+ *
+ * Scene discovery buckets by RESOLVED path (the handle maps are keyed that way),
+ * and preloading fed those resolved paths straight to loadTexture. In a realm
+ * whose resolver rewrites refs — the play realm prefixes `estella://project` —
+ * the settings resolver was then asked about a spelling no supplier had ever
+ * heard of, so filter/wrap/sRGB and the 9-slice border were silently dropped. A
+ * frame that sliced correctly in the edit viewport stretched the moment you
+ * pressed Play.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Assets } from '../src/asset/Assets';
+import { Catalog } from '../src/asset/Catalog';
+import type { Backend } from '../src/asset/Backend';
+import type { SceneData } from '../src/scene';
+import { defineComponent } from '../src/component';
+
+const setTextureMetadata = vi.fn();
+vi.mock('../src/resourceManager', () => ({
+ requireResourceManager: () => ({
+ createTexture: vi.fn(() => 7),
+ registerExternalTexture: vi.fn(() => 7),
+ releaseTexture: vi.fn(),
+ getTextureGLId: vi.fn(() => 1),
+ registerTextureWithPath: vi.fn(),
+ acquireTextureByPath: vi.fn(() => 0),
+ invalidateTexturePath: vi.fn(() => false),
+ getTextureDimensions: vi.fn(() => ({ width: 64, height: 64 })),
+ setTextureMetadata: (...args: unknown[]) => setTextureMetadata(...args),
+ }),
+ getResourceManager: () => null,
+ evictTextureDimensions: vi.fn(),
+}));
+
+const platformFactory = vi.hoisted(() => () => ({
+ platformCreateCanvas: () => ({
+ width: 64, height: 64,
+ getContext: () => ({
+ clearRect: vi.fn(),
+ drawImage: vi.fn(),
+ getImageData: () => ({ data: { buffer: new ArrayBuffer(64 * 64 * 4) } }),
+ }),
+ }),
+ platformCreateImage: () => {
+ const img: { width?: number; height?: number; onload?: () => void } = {};
+ setTimeout(() => { img.width = 64; img.height = 64; img.onload?.(); }, 0);
+ return img;
+ },
+ platformFetch: vi.fn(),
+ platformReadFile: vi.fn(),
+ platformReadTextFile: vi.fn(),
+ platformFileExists: vi.fn(),
+}));
+vi.mock('../src/platform', platformFactory);
+vi.mock('../src/platform/base', platformFactory);
+
+const mockModule = {
+ _malloc: vi.fn(() => 0),
+ _free: vi.fn(),
+ HEAPU8: new Uint8Array(64 * 64 * 4),
+ GL: null,
+ FS: null,
+} as never;
+
+const AUTHORED = 'assets/ui/Button_Yellow.png';
+const BORDER = { left: 24, right: 22, top: 25, bottom: 31 };
+
+const scene: SceneData = {
+ name: 's',
+ entities: [{
+ id: 1, name: 'Button', parent: null, children: [],
+ components: [{ type: 'UIVisual', data: { texture: AUTHORED, visualType: 3 } }],
+ }],
+};
+
+function backend(): Backend {
+ return {
+ fetchBinary: vi.fn(async () => new ArrayBuffer(8)),
+ fetchText: vi.fn(async () => '{}'),
+ resolveUrl: (p: string) => p,
+ resolvePath: (p: string) => p,
+ } as unknown as Backend;
+}
+
+describe('preloadSceneAssets — texture import settings', () => {
+ beforeEach(() => {
+ setTextureMetadata.mockClear();
+ defineComponent('UIVisual', { texture: '', visualType: 0 }, {
+ assetFields: [{ field: 'texture', type: 'texture' }],
+ });
+ });
+
+ it('asks the settings resolver with the authored ref, not the resolved path', async () => {
+ const assets = Assets.create({ backend: backend(), catalog: Catalog.empty(), module: mockModule });
+ // The play realm's shape: refs resolve to a realm URL the supplier has no
+ // key for. Only the authored spelling is answerable.
+ assets.setAssetRefResolver((ref) => (ref.includes('://') ? ref : `estella://project/${ref}`));
+ const asked: string[] = [];
+ assets.setTextureImportSettingsResolver((ref) => {
+ asked.push(ref);
+ return ref === AUTHORED ? { sliceBorder: BORDER } : undefined;
+ });
+
+ await assets.preloadSceneAssets(scene, undefined, { skipSpine: true });
+
+ expect(asked).toContain(AUTHORED);
+ expect(setTextureMetadata).toHaveBeenCalledWith(
+ expect.any(Number), BORDER.left, BORDER.right, BORDER.top, BORDER.bottom,
+ );
+ });
+
+ it('still keys the handle map by the resolved path', async () => {
+ const assets = Assets.create({ backend: backend(), catalog: Catalog.empty(), module: mockModule });
+ assets.setAssetRefResolver((ref) => (ref.includes('://') ? ref : `estella://project/${ref}`));
+
+ const { textureHandles } = await assets.preloadSceneAssets(scene, undefined, { skipSpine: true });
+
+ // resolveSceneAssetPaths looks handles up by resolved path — loading
+ // through the authored ref must not move that key.
+ expect(textureHandles.has(`estella://project/${AUTHORED}`)).toBe(true);
+ });
+
+ it('leaves the border unstamped when no supplier answers', async () => {
+ const assets = Assets.create({ backend: backend(), catalog: Catalog.empty(), module: mockModule });
+
+ await assets.preloadSceneAssets(scene, undefined, { skipSpine: true });
+
+ expect(setTextureMetadata).not.toHaveBeenCalled();
+ });
+});
diff --git a/sdk/tests/texture-import-settings.test.ts b/sdk/tests/texture-import-settings.test.ts
index 131b37b35..4110b590a 100644
--- a/sdk/tests/texture-import-settings.test.ts
+++ b/sdk/tests/texture-import-settings.test.ts
@@ -9,7 +9,7 @@
* border is stamped onto the texture and would clear one set elsewhere.
*/
import { describe, it, expect } from 'vitest';
-import { textureImportSettingsFrom } from '../src/asset/textureImportSettings';
+import { indexTextureImportSettings, textureImportSettingsFrom } from '../src/asset/textureImportSettings';
describe('textureImportSettingsFrom', () => {
it('maps filterMode/wrapMode to the loader filter/wrap shape', () => {
@@ -72,3 +72,38 @@ describe('textureImportSettingsFrom', () => {
});
});
});
+
+describe('indexTextureImportSettings', () => {
+ const sliced = textureImportSettingsFrom({ sliceBorder: { left: 24, right: 22, top: 25, bottom: 31 } });
+ const lookup = indexTextureImportSettings([
+ { uuid: 'abc-123', path: 'staged/9f3a.png', address: 'assets/ui/Button.png', settings: sliced },
+ ]);
+
+ // Which spelling a component carries is the PROJECT's choice: the meta-driven
+ // pipeline writes `@uuid:`, a ported or hand-authored scene holds a path. An
+ // index that answers only one of them loses the settings for every project
+ // that picked the other — the exact shape of "sliced in the editor, stretched
+ // in the build".
+ it('answers to every spelling of the same asset', () => {
+ for (const ref of [
+ 'abc-123', '@uuid:abc-123',
+ 'assets/ui/Button.png', '/assets/ui/Button.png',
+ 'staged/9f3a.png', '/staged/9f3a.png',
+ ]) {
+ expect(lookup(ref), ref).toBe(sliced);
+ }
+ });
+
+ it('does not answer for an asset it was never given', () => {
+ expect(lookup('assets/ui/Other.png')).toBeUndefined();
+ expect(lookup('@uuid:no-such')).toBeUndefined();
+ });
+
+ it('skips assets whose importer says nothing the renderer acts on', () => {
+ const empty = indexTextureImportSettings([
+ { uuid: 'x', path: 'a.png', settings: undefined },
+ ]);
+ expect(empty('x')).toBeUndefined();
+ expect(empty('a.png')).toBeUndefined();
+ });
+});