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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(assets): cooked builds resolve path refs - the material chain renders from a shipped game
yhhb4ea89755ad4
diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.tsindex d1ea0079c..3aa5dad20 100644--- a/desktop/electron/cookAssets.ts+++ b/desktop/electron/cookAssets.ts@@ -79,6 +79,41 @@ function swapExt(p: string, ext: string): string {return (cur ? p.slice(0, p.length - cur.length) : p) + ext;}+/**+ * Rewrite a material's RELATIVE refs (shader / instanceOf / texture properties)+ * to the referenced asset's logical project path. Materials resolve relative+ * refs against their own directory at runtime — a structure content-addressed+ * staging destroys — so the staged copy carries directory-free logical refs and+ * the runtime's logical→staged maps take it from there. Logical paths outside+ * the runtime's passthrough prefixes ship as "/<logical>" (project-absolute).+ * `@uuid:`/URL refs and already-logical refs pass through unchanged.+ */+function rewriteMaterialRefs(+ bytes: Uint8Array,+ matPath: string,+ byPath: Map<string, AssetEntry>,+): Uint8Array {+ const json = JSON.parse(Buffer.from(bytes).toString('utf8')) as Record<string, unknown>;+ const dir = matPath.includes('/') ? matPath.slice(0, matPath.lastIndexOf('/')) : '';+ const rewrite = (ref: unknown): unknown => {+ if (typeof ref !== 'string' || ref.startsWith('@uuid:') || ref.includes('://')) return ref;+ const norm = ref.replace(/^\.\//, '').replace(/^\//, '');+ if (byPath.has(norm)) return ref; // already a logical project path+ const joined = dir ? `${dir}/${norm}` : norm;+ if (!byPath.has(joined)) return ref; // not an asset ref (or missing) — leave it+ // Passthrough-safe spelling: bare when the runtime treats it as absolute,+ // "/"-rooted otherwise (both registered by the cooked host's maps).+ return joined.startsWith('assets/') ? joined : `/${joined}`;+ };+ if (typeof json.shader === 'string') json.shader = rewrite(json.shader);+ if (typeof json.instanceOf === 'string') json.instanceOf = rewrite(json.instanceOf);+ if (json.properties && typeof json.properties === 'object') {+ const props = json.properties as Record<string, unknown>;+ for (const key of Object.keys(props)) props[key] = rewrite(props[key]);+ }+ return new TextEncoder().encode(JSON.stringify(json, null, 2) + '\n');+}+export interface CookResult {ok: boolean;/** Absolute output dir the assets + manifest were staged into. */@@ -170,6 +205,14 @@ export async function cookAssets(ext = '.ktx2';compressedFormats = COMPRESSED_TARGETS;}+ // Materials: relative refs → logical project paths (see rewriteMaterialRefs).+ if (ext.toLowerCase() === '.esmaterial') {+ try {+ data = rewriteMaterialRefs(data, entry.path, byPath);+ } catch (err) {+ warnings.push(`${entry.path}: material ref rewrite failed — ${err instanceof Error ? err.message : String(err)}`);+ }+ }// Shaders ship as-authored; a WGSL twin is what makes one run on the// WebGPU backend, so a twin-less shader is worth a cook-time warning// (generation is a dev-time step — tools/gen-shader-twins.mjs writes thediff --git a/desktop/scripts/headless-cooked-verify.mjs b/desktop/scripts/headless-cooked-verify.mjsindex b59bdda98..c1ce5e992 100644--- a/desktop/scripts/headless-cooked-verify.mjs+++ b/desktop/scripts/headless-cooked-verify.mjs@@ -67,15 +67,20 @@ app.whenReady().then(async () => {const c = window.__estellaCooked.capture();const { width: w, height: h, rgba } = c;const at = (x, y) => { const X = Math.round(x*(w-1)); const Y = (h-1)-Math.round(y*(h-1)); const i=(Y*w+X)*4; return [rgba[i], rgba[i+1], rgba[i+2]]; };- return { w, h, center: at(0.5, 0.5), corner: at(0.04, 0.04) };+ return { w, h, left: at(0.3, 0.5), right: at(0.7, 0.5), corner: at(0.04, 0.04) };})()`);- const [cr, cg, cb] = cap.center;- const greenOk = Math.abs(cg - 180) <= 70 && cr <= 70 && cb <= 70;+ // Left quad = the KTX2 texture (green); right quad = the PATH-referenced+ // material chain (its shader paints u_tint red) — proving the cooked+ // logical→staged resolution end to end, not just uuid refs.+ const [lr, lg, lb] = cap.left;+ const greenOk = Math.abs(lg - 180) <= 70 && lr <= 70 && lb <= 70;+ const [rr, rg, rb] = cap.right;+ const redOk = rr >= 180 && rg <= 70 && rb <= 70;const cornerBlack = cap.corner[0] <= 40 && cap.corner[1] <= 40 && cap.corner[2] <= 40;- const ok = greenOk && cornerBlack;+ const ok = greenOk && redOk && cornerBlack;console.log(`\n[verify:render:cooked] ${ok ? 'PASS' : 'FAIL'}`);- console.log('DRIVE_RESULT ' + JSON.stringify({ ...cap, greenOk, cornerBlack, diag: diag.slice(0, 6) }));+ console.log('DRIVE_RESULT ' + JSON.stringify({ ...cap, greenOk, redOk, cornerBlack, diag: diag.slice(0, 6) }));process.exitCode = ok ? 0 : 1;} catch (e) {console.log('\n[verify:render:cooked] FAIL — ' + (e?.message ?? e));diff --git a/desktop/src/gameHost.ts b/desktop/src/gameHost.tsindex d1be47327..4588b40fc 100644--- a/desktop/src/gameHost.ts+++ b/desktop/src/gameHost.ts@@ -12,13 +12,13 @@* (shared with the play realm's import-map work).*/import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime } from 'esengine';-import type { ESEngineModule, SceneData } from 'esengine';+import type { CatalogData, ESEngineModule, SceneData } from 'esengine';interface GameConfig {entryScene: string;}interface CookedManifest {- entries: { uuid: string; path: string; type: string }[];+ entries: { uuid: string; path: string; sourcePath?: string; type: string }[];}async function boot(): Promise<void> {@@ -48,7 +48,23 @@ async function boot(): Promise<void> {const manifest = (await (await fetch('./assets.manifest.json')).json()) as CookedManifest;const sceneData = (await (await fetch(`./${cfg.entryScene}`)).json()) as SceneData;const assetManifest: Record<string, string> = {};- for (const e of manifest.entries) assetManifest[e.uuid.toLowerCase()] = `./${e.path}`;+ // Logical → staged resolution for PATH-style refs, twice over: `pathMap` for+ // Assets-level refs (resolved before extension sniffing, so a .png staged as+ // .ktx2 transcodes), `catalog` buildPaths for the loaders' inner text refs+ // (a material's shader). Both derive from the manifest's sourcePath — the+ // asset's logical identity that content-addressed staging preserves.+ const pathMap: Record<string, string> = {};+ const catalog: CatalogData = { version: 1, entries: {} };+ for (const e of manifest.entries) {+ assetManifest[e.uuid.toLowerCase()] = `./${e.path}`;+ const logical = e.sourcePath ?? e.path;+ pathMap[logical] = `./${e.path}`;+ catalog.entries[logical] = { type: e.type, buildPath: `./${e.path}` };+ // The cook writes project-absolute refs as "/<logical>" when the logical+ // path lacks a passthrough prefix — register that spelling too.+ pathMap[`/${logical}`] = `./${e.path}`;+ catalog.entries[`/${logical}`] = { type: e.type, buildPath: `./${e.path}` };+ }const wasmBase = new URL('./wasm/', import.meta.url).href; // relative → mount-path agnosticconst { default: createModule } = (await import(/* @vite-ignore */ `${wasmBase}esengine.js`)) as {@@ -98,6 +114,8 @@ async function boot(): Promise<void> {canvas,sceneData,assetManifest,+ assetPathMap: pathMap,+ catalogData: catalog,wasmBaseUrl: wasmBase.replace(/\/$/, ''),});}diff --git a/desktop/tests/cook-assets.test.ts b/desktop/tests/cook-assets.test.tsindex 1cb0d226f..e0dbcf2b0 100644--- a/desktop/tests/cook-assets.test.ts+++ b/desktop/tests/cook-assets.test.ts@@ -231,7 +231,8 @@ describe('cookAssets (A4)', () => {// The real-content shape: the scene names the material by PROJECT PATH (no// @uuid:), and the material names its shader + texture RELATIVE to itself.wa('assets/materials/m.esmaterial', 'material', MAT, JSON.stringify({- version: '1.0', type: 'material', shader: 'm.esshader', properties: { u_mask: 'green.png' },+ version: '1.0', type: 'material', shader: 'm.esshader',+ properties: { u_mask: 'green.png', u_mode: 'additive' },}));wa('assets/materials/m.esshader', 'shader', SHADER,'#pragma shader "M"\n#pragma fragment\nvoid main() {}\n#pragma end\n');@@ -258,6 +259,16 @@ describe('cookAssets (A4)', () => {const mat = m.entries.find((e) => e.uuid === MAT)!;expect(mat.sourcePath).toBe('assets/materials/m.esmaterial');expect(mat.path).toMatch(/^assets\/[0-9a-f]{16}\.esmaterial$/);++ // The staged material's RELATIVE refs were rewritten to logical project+ // paths (content addressing destroys the directory structure relative+ // resolution relies on); non-asset strings pass through untouched.+ const stagedMat = JSON.parse(readFileSync(path.join(ca.outDir, mat.path), 'utf8')) as {+ shader: string; properties: Record<string, string>;+ };+ expect(stagedMat.shader).toBe('assets/materials/m.esshader');+ expect(stagedMat.properties.u_mask).toBe('assets/materials/green.png');+ expect(stagedMat.properties.u_mode).toBe('additive');} finally {rmSync(r, { recursive: true, force: true });}diff --git a/desktop/tests/cooked-verify-fixture.test.ts b/desktop/tests/cooked-verify-fixture.test.tsindex 7c3e56860..2f4538e8d 100644--- a/desktop/tests/cooked-verify-fixture.test.ts+++ b/desktop/tests/cooked-verify-fixture.test.ts@@ -17,10 +17,32 @@ const OUT = path.resolve(HERE, '..', '.cooked-verify');const SRC = path.resolve(HERE, '..', '.cooked-src');const TEX = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';const SCN = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';+const MAT = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';+const SHD = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';const meta = (uuid: string, type: string) => JSON.stringify({ uuid, version: '2.0', type, importer: {} });+// A user material chain referenced entirely by PATH: the scene names the+// material by project path, the material names its shader + a texture RELATIVE+// to itself — the forms real content uses. The shader paints solid red via a+// reflected param, so the cooked render proves the whole logical→staged+// resolution (dep-graph inclusion, cook ref rewrite, runtime pathMap+catalog).+const TINT_SHADER = `#pragma shader "CookTint"+#pragma version 300 es+#pragma domain Unlit2D+#pragma param u_tint color default(1,1,1,1)+#pragma param u_tex texture default(white)++#pragma fragment+precision mediump float;+in vec4 v_color;+in vec2 v_texCoord;+out vec4 fragColor;+void main() { fragColor = u_tint; }+#pragma end+`;+describe.skipIf(!process.env.ESTELLA_COOK_FIXTURE)('cooked-verify fixture', () => {- it('cooks a content-addressed build of a green KTX2 sprite', async () => {+ it('cooks a content-addressed build: green KTX2 sprite + path-ref material chain', async () => {rmSync(SRC, { recursive: true, force: true });rmSync(OUT, { recursive: true, force: true });@@ -28,6 +50,13 @@ describe.skipIf(!process.env.ESTELLA_COOK_FIXTURE)('cooked-verify fixture', () =copyFileSync(path.resolve(HERE, '..', 'public', 'scenes', 'ktx2-test', 'green.ktx2'),path.join(SRC, 'assets', 'green.ktx2'));writeFileSync(path.join(SRC, 'assets', 'green.ktx2.meta'), meta(TEX, 'texture'));+ writeFileSync(path.join(SRC, 'assets', 'tint.esshader'), TINT_SHADER);+ writeFileSync(path.join(SRC, 'assets', 'tint.esshader.meta'), meta(SHD, 'shader'));+ writeFileSync(path.join(SRC, 'assets', 'red.esmaterial'), JSON.stringify({+ version: '1.0', type: 'material', shader: 'tint.esshader',+ properties: { u_tint: { r: 1, g: 0, b: 0, a: 1 }, u_tex: 'green.ktx2' },+ }));+ writeFileSync(path.join(SRC, 'assets', 'red.esmaterial.meta'), meta(MAT, 'material'));mkdirSync(path.join(SRC, 'scenes'), { recursive: true });writeFileSync(path.join(SRC, 'scenes', 'main.esscene'), JSON.stringify({@@ -36,9 +65,13 @@ describe.skipIf(!process.env.ESTELLA_COOK_FIXTURE)('cooked-verify fixture', () ={ type: 'Transform', data: { position: { x: 0, y: 0, z: 10 } } },{ type: 'Camera', data: { projectionType: 1, orthoSize: 300, isActive: true, priority: 0 } },] },- { id: 1, name: 'Quad', parent: null, children: [], visible: true, components: [- { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } },- { type: 'Sprite', data: { size: { x: 200, y: 200 }, color: { r: 1, g: 1, b: 1, a: 1 }, texture: `@uuid:${TEX}` } },+ { id: 1, name: 'GreenQuad', parent: null, children: [], visible: true, components: [+ { type: 'Transform', data: { position: { x: -150, y: 0, z: 0 } } },+ { type: 'Sprite', data: { size: { x: 250, y: 250 }, color: { r: 1, g: 1, b: 1, a: 1 }, texture: `@uuid:${TEX}` } },+ ] },+ { id: 2, name: 'RedMaterialQuad', parent: null, children: [], visible: true, components: [+ { type: 'Transform', data: { position: { x: 150, y: 0, z: 0 } } },+ { type: 'Sprite', data: { size: { x: 250, y: 250 }, color: { r: 1, g: 1, b: 1, a: 1 }, material: 'assets/red.esmaterial' } },] },],}));diff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.mdindex 234cf632c..9030b44a4 100644--- a/docs/REARCHITECTURE.md+++ b/docs/REARCHITECTURE.md@@ -192,7 +192,8 @@ TS 驱动的主 pass clear 退出边界,`clear` 家族退出公共 RHI:**WebGPU 异步 readback seam(2026-07-08,后端不对称性收口)**:同步 `readPixels` 退出 RHI,全接口统一为异步四段 `requestReadback / pollReadback / takeReadback / discardReadback`(GL = 请求时同步读、首 poll 即 Ready;WebGPU = `copyTextureToBuffer` → 256 对齐 staging + `mapAsync(AllowSpontaneous)`,跨事件循环 turn 落地;行序统一 bottom-up 契约在 take 时翻转)。RenderFrame 的两个消费者(材质预览 renderToTarget、帧调试器 replayToDrawCall)改为 pass 关闭后请求 + `pollPreview/SnapshotReadback` 落地(顺带修 snapshot 尺寸 getter 读当前帧而非快照时尺寸的隐患);TS 侧 `Material.renderPreview`/`Renderer.getSnapshotImageData` 转 Promise(`readback.ts` 单一 poll 循环,双后端同码)。离屏色纹理补 `CopySrc` usage。**材质预览断言在 WebGPU 下点亮**:mat-tint 场景(补了手写 WGSL 孪生的用户 `.esshader` 资产)双后端 EXPECT + PREVIEW 像素精确 PASS——顺带证明场景资产 shader 带孪生即可整链上 WebGPU。**Phase 4 转换管线(2026-07-08)**:用户 `.esshader` 的 GLSL→WGSL 自动孪生落地——`tools/gen-shader-twins.mjs`:引擎 wasm 新绑定 `esshader_cookInfo`(web glue 可在纯 Node 加载)吐出与运行时逐字节一致的装配后 GLSL + 纹理单元反射(零漂移),经方言适配(310 es、precision 全 highp、显式引擎绑定注入、combined sampler 拆对、函数采样器参数/实参拆分、varying location 按名对齐)→ `glslangValidator -V` → `naga` → 自包含 `#pragma vertex|fragment wgsl full` 孪生段(ShaderParser 新语义:full 段跳过全部注入头)。9 个 fixture shader 批量生成后,mat-lit 系/mat-tex/mat-dissolve/mat-graph/mat-builtin-lit/mat-instance **在 WebGPU 全部从全黑转绿,lit 像素与 GL 逐点一致**(15 场景 battery)。带 `#pragma switch` 的 shader 跳过(排列需逐集合,手写孪生)。**cook 集成第一层(2026-07-08)——资产依赖图现代化**:assetDb 依赖图从"仅 scene/prefab 的 @uuid:"扩展为**任意 JSON 资产 × 三种引用形态**——`@uuid:`、裸 uuid(anim 帧的 extractUuid 形态,仅命中索引才建边,防实体 id 误伤)、**路径引用**(项目路径 + 相对本文档目录,只有真实资产命中才建边零误报);扫描类型 scene/prefab/material/tileset/animclip/statemachine/behaviortree。真实项目(路径引用内容)的材质→shader→纹理链自此进入 cook 闭包(此前 deps 全空,整链被静默剔除)。cook manifest 新增 `sourcePath`(逻辑身份,内容寻址改名后路径引用的运行时映射依据);`.esshader` 无 WGSL 孪生 → cook 告警(生成是开发期步骤,保 cook 确定性 + 零转换器依赖)。-**剩余**:CA 构建的运行时路径解析(gameHost 用 sourcePath 喂 Catalog buildPath + resolvePlayAssetRef 路径分支;**注意存量缺口**——材质内相对引用按 staged 目录解析,在 CA 构建下对 @uuid: 引用同样破损,需 loader 侧以逻辑路径做相对解析,牵 Assets 内部,单独切片);转换器 vendored wasm 交付(glslang wasm + naga wasm32-wasi,仿 build-tools/basis);CI 无 WebGPU 适配器(webgpu verify 仅本地)。+**cook 集成第二层(2026-07-08)——CA 构建运行时路径解析闭环**:三件套——① cook 期把材质的**相对引用重写为逻辑项目路径**(内容寻址摧毁了相对解析依赖的目录结构;非 assets/-根的逻辑路径写成 `/<logical>`,双拼写皆注册;@uuid:/URL/非资产字符串原样通过),顺带根治"@uuid: 引用的材质在 CA 构建下内部相对引用同样破损"的存量缺口——loader 零改动;② `resolvePlayAssetRef` 增 pathMap 参数(逻辑→staged,**先于扩展名嗅探**,.png→.ktx2 换名对 KTX2 检测可见,与 uuid 分支同契约);③ 生产首次喂 `Catalog` buildPath(`AssetsOptions.catalog` 一直存在但空转——loader 内部文本 fetch 如材质取 shader 走 `getBuildPath`),经 `RuntimeInitConfig.catalog`/`PlayRealmRuntimeConfig.catalogData` 管道在 per-App Assets 首次创建时注入,gameHost 从 manifest sourcePath 构建两张映射。验证:cooked e2e 升级为双象限——绿 KTX2 精灵(uuid 引用)+ **红材质精灵(全路径引用链:场景→材质项目路径→shader/纹理相对引用)**,发行运行时逐像素 PASS([0,181,0]/[255,0,0])。+**剩余**:转换器 vendored wasm 交付(glslang wasm + naga wasm32-wasi,仿 build-tools/basis);音频路径引用在 CA 构建下仍走 assetBaseUrl 裸 fetch(Audio 有独立 loader,未过 resolveRef——已知缺口);wechat/playable 导出线采用 CA 时复用同一 sourcePath 机制;CI 无 WebGPU 适配器(webgpu verify 仅本地)。见 `REARCH_WGSL.md`(本地 gitignore,同 RC6/2D_PARITY 约定):着色器版图盘点(uniform 数据已全后端中立,剩程序文本)、岔路拍板(有限集人工孪生 / 图材质 AST 双发射 / 用户材质 cook 期转换——拒绝运行时翻译器的 MB 级体积代价)、四期计划(源语言接缝 → WebGPUDevice 原型 → 双语发射 → cook 期用户材质)。**Phase 0 已落地**:最后 3 个 GLSL ES 1.00 残留(SDK outline/drop-shadow/color-matrix 滤镜)重写为 fragment-only `.esshader` 反射路径——顺带修复其设计性破损(raw 形态无 `u_projection` 来源、无属性绑定、mat4 超 `setMaterialUniform` 的 vec4 上限**从未能传入**;色彩矩阵改为 4×vec4 行 + 偏移列,新增 `Filters.colorMatrixUniforms` 助手)。全仓每个程序自此都在现代缝上(300 es + UBO 反射)。**Phase 1(源语言接缝)已落地**:RHI 补上最后一块后端中立拼图——`createProgram` 收语言标签的 `GfxShaderSource`,新增 `supportsShaderLanguage` 能力查询(GL = 仅 GLSL ES 300;`Shader::compile` 在任何 GPU 调用前对不支持的语言快速失败);语言贯穿 Shader/ResourceManager(DrawParams 重写仅对 GLSL 生效);`ShaderParser::assembleStage` 获得 `ShaderTargetLanguage` 参数(WGSL 发射 = Phase 3)。MockGfxDevice 新增 `wgslSupported` 开关 + 语言门用例;行为零变化(8 harness + 场景抽样等价)。**Phase 2 切片 1(WebGPU 后端启动)已落地**:emdawnwebgpu 端口(Dawn)集成为测试目标独立依赖(主构建零影响);`renderer/webgpu/` 新增纯映射层(GfxEnums→WGPU 全翻译,blend/模板表镜像 GLDevice 语义,load-op 规则与 RenderPassDesc 契约一致)+ 空设备安全的 `WebGPUDevice` 骨架(缓冲/纹理/WGSL 模块真实现,布局/管线描述符保留待惰性构建,pass/draw 为切片 2 结构化桩);`test_webgpu_device` 用真 Dawn 头编译验证全部描述符拼写,入 CI。diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 6f507b56a..d7e697938 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -49,6 +49,9 @@ export {AssetPlugin,assetPlugin,AssetRefCounter,+ Catalog,+ type CatalogData,+ type CatalogEntry,decodeImageBitmap,decodeImagePixels,imageBitmapOptions,diff --git a/sdk/src/playRealmRuntime.ts b/sdk/src/playRealmRuntime.tsindex 9c8eb3daf..8eb6aff65 100644--- a/sdk/src/playRealmRuntime.ts+++ b/sdk/src/playRealmRuntime.ts@@ -21,6 +21,7 @@ import { Audio } from './audio/Audio';import { initRuntime } from './runtimeLoader';import type { RuntimeAssetSource } from './runtimeAssets';import { HttpBackend } from './asset/Backend';+import { Catalog, type CatalogData } from './asset/Catalog';import type { AddressableManifest } from './asset/AddressableManifest';import type { SceneData } from './scene';import type { PhysicsPluginConfig } from './physics/PhysicsPlugin';@@ -35,6 +36,20 @@ export interface PlayRealmRuntimeConfig {sceneData: SceneData;/** Lowercased uuid → fetchable URL (e.g. `estella://project/<path>`). */assetManifest: Record<string, string>;+ /**+ * Logical (source) path → fetchable staged path, for cooked builds whose+ * content-addressed staging renamed the physical files. Path-style refs+ * (a scene's "assets/x.esmaterial") resolve through this BEFORE extension+ * sniffing, exactly like uuid refs — so a .png staged as .ktx2 transcodes.+ * Omit when files are served at their logical paths (the editor realm).+ */+ assetPathMap?: Record<string, string>;+ /**+ * Logical path → build-path catalog for the same cooked case: loaders fetch+ * their INNER text refs (a material's shader) through Catalog.getBuildPath,+ * which is identity without this. Omit alongside assetPathMap.+ */+ catalogData?: CatalogData | null;manifest?: AddressableManifest | null;/** Base URL the engine side-modules (physics.wasm, …) are served from — same* dir as esengine.wasm. When set, the realm can load physics on demand. */@@ -73,7 +88,12 @@ export interface PlayRealmRuntimeConfig {* resolves against the project root, not the `.esengine/play/` subdir the realm* runs from. Pure.*/-export function resolvePlayAssetRef(ref: string, manifest: Record<string, string>, assetBaseUrl?: string): string {+export function resolvePlayAssetRef(+ ref: string,+ manifest: Record<string, string>,+ assetBaseUrl?: string,+ pathMap?: Record<string, string>,+): string {const uuid = ref.startsWith(UUID_REF_PREFIX)? ref.slice(UUID_REF_PREFIX.length).toLowerCase(): extractUuid(ref);@@ -82,6 +102,13 @@ export function resolvePlayAssetRef(ref: string, manifest: Record<string, stringif (!url) throw new Error(`asset not in play manifest: ${ref}`);return url;}+ // Cooked builds: a logical path maps to its staged file (content-addressed+ // rename + possible extension swap) — resolved here so the result is the+ // extension-bearing physical path, same contract as the uuid branch.+ if (pathMap) {+ const staged = pathMap[ref] ?? pathMap[ref.replace(/^\.?\//, '')];+ if (staged) return staged;+ }const base = (assetBaseUrl ?? '').replace(/\/$/, '');// Idempotent, like HttpBackend.resolveUrl: an already-resolved absolute URL or// base-prefixed path must not be prefixed again. Preload resolves a ref once to@@ -91,12 +118,16 @@ export function resolvePlayAssetRef(ref: string, manifest: Record<string, stringreturn base ? `${base}/${ref.replace(/^\//, '')}` : ref;}-function createPlayRealmSource(manifest: Record<string, string>, assetBaseUrl?: string): RuntimeAssetSource {+function createPlayRealmSource(+ manifest: Record<string, string>,+ assetBaseUrl?: string,+ pathMap?: Record<string, string>,+): RuntimeAssetSource {const backend = new HttpBackend({ baseUrl: '' });return {backend,decodePixels: (path) => fetchDecodePixels(backend.resolveUrl(path)),- resolveRef: (ref) => resolvePlayAssetRef(ref, manifest, assetBaseUrl),+ resolveRef: (ref) => resolvePlayAssetRef(ref, manifest, assetBaseUrl, pathMap),};}@@ -107,7 +138,7 @@ function createPlayRealmSource(manifest: Record<string, string>, assetBaseUrl?:*/export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Promise<void> {const { app, module, canvas, sceneData, assetManifest, assetBaseUrl } = config;- const source = createPlayRealmSource(assetManifest, assetBaseUrl);+ const source = createPlayRealmSource(assetManifest, assetBaseUrl, config.assetPathMap);// Audio has its own loader (not the asset source), so point it at the project// root too: playSFX/playBGM take project-relative paths, not uuid refs.if (assetBaseUrl && app.hasResource(Audio)) {@@ -117,6 +148,7 @@ export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Promapp,module,source,+ catalog: config.catalogData ? Catalog.fromJson(config.catalogData) : undefined,scenes: [{ name: '__play', data: sceneData }],firstScene: '__play',aspectRatio: canvas.width / canvas.height,diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex c11acc3da..1cc97160b 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -30,6 +30,7 @@ import { type RuntimeAssetSource, type TextureParams } from './runtimeAssets';import { loadSpineAssets, applySpineEntities } from './spine/loadSpineScene';import { transcoderFromModule, type BasisWasmModule } from './asset/basisTranscoder';import type { AddressableManifest, ManifestModel } from './asset/AddressableManifest';+import type { Catalog } from './asset/Catalog';// =============================================================================// Public Interface@@ -70,7 +71,7 @@ const runtimeImportSettings = new WeakMap<AssetsClass, Record<string, TextureImp* neither and applied no atlas-frame indirection).*/function ensureRuntimeAssets(- app: App, module: ESEngineModule, source: RuntimeAssetSource,+ app: App, module: ESEngineModule, source: RuntimeAssetSource, catalog?: Catalog,): AssetsClass {if (app.hasResource(AssetsResource)) {const existing = app.getResource(AssetsResource);@@ -81,6 +82,7 @@ function ensureRuntimeAssets(const assets = AssetsClass.create({backend: source.backend,module,+ catalog,getAudio: () => (app.hasResource(Audio) ? app.getResource(Audio) : null),getSpriteAnimation: () => (app.hasResource(SpriteAnimation) ? app.getResource(SpriteAnimation) : null),});@@ -301,6 +303,13 @@ export interface RuntimeInitConfig {* existed before initRuntime, which the runtime instance replaces.*/manifest?: AddressableManifest | ManifestModel | null;+ /**+ * Logical-path → build-path catalog for cooked builds (content-addressed+ * staging renames physical files): loaders route their inner text refs (a+ * material's shader path) through Catalog.getBuildPath, which is identity+ * without one. Applied when the per-App runtime Assets is first created.+ */+ catalog?: Catalog;scenes: Array<{ name: string; data: SceneData }>;firstScene: string;spineModule?: SpineWasmModule | null;@@ -321,7 +330,9 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {// Install the per-App runtime Assets up front (scene loads reuse it) and// hand it the manifest so on-demand loadGroup works from the first frame.- const assets = ensureRuntimeAssets(app, config.module, config.source);+ // The catalog rides the same first-creation moment (later ensure calls+ // return the existing instance).+ const assets = ensureRuntimeAssets(app, config.module, config.source, config.catalog);if (config.manifest) assets.setManifest(config.manifest);const sceneOpts: Omit<LoadRuntimeSceneOptions, 'sceneData' | 'sceneName'> = {diff --git a/sdk/tests/play-asset-ref.test.ts b/sdk/tests/play-asset-ref.test.tsindex 90028895a..6ab71340b 100644--- a/sdk/tests/play-asset-ref.test.ts+++ b/sdk/tests/play-asset-ref.test.ts@@ -39,4 +39,37 @@ describe('resolvePlayAssetRef', () => {expect(resolvePlayAssetRef(uuid, manifest, BASE)).toBe('estella://project/assets/textures/idle_0.png');expect(resolvePlayAssetRef(uuid.toUpperCase(), manifest, BASE)).toBe('estella://project/assets/textures/idle_0.png');});++ // Cooked builds: content-addressed staging renames physical files, so a+ // logical path resolves through the pathMap — to the extension-bearing+ // staged path (a .png staged as .ktx2 must sniff as KTX2), same contract+ // as the uuid branch. Leading "/" and "./" spellings hit the same entry.+ describe('cooked pathMap', () => {+ const pathMap = {+ 'assets/hero.png': './assets/1234567890abcdef.ktx2',+ 'assets/red.esmaterial': './assets/fedcba0987654321.esmaterial',+ };++ it('maps a logical path to its staged file', () => {+ expect(resolvePlayAssetRef('assets/hero.png', {}, undefined, pathMap))+ .toBe('./assets/1234567890abcdef.ktx2');+ });++ it('normalizes leading "/" and "./" spellings', () => {+ expect(resolvePlayAssetRef('/assets/red.esmaterial', {}, undefined, pathMap))+ .toBe('./assets/fedcba0987654321.esmaterial');+ expect(resolvePlayAssetRef('./assets/red.esmaterial', {}, undefined, pathMap))+ .toBe('./assets/fedcba0987654321.esmaterial');+ });++ it('falls through to the path branch for unmapped refs', () => {+ expect(resolvePlayAssetRef('assets/other.png', {}, undefined, pathMap))+ .toBe('assets/other.png');+ });++ it('uuid refs take priority over the pathMap', () => {+ expect(resolvePlayAssetRef('@uuid:AAAA', MANIFEST, undefined, pathMap))+ .toBe('estella://project/assets/textures/hero.png');+ });+ });});