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
fix(assets): a bitmap font's page image survives the build
esenginee8f8e38c9540
diff --git a/desktop/tests/document-ref-cook-deps.test.ts b/desktop/tests/document-ref-cook-deps.test.tsindex 868ed2c70..30cd3faad 100644--- a/desktop/tests/document-ref-cook-deps.test.ts+++ b/desktop/tests/document-ref-cook-deps.test.ts@@ -26,6 +26,8 @@ const ESENV = '22222222-2222-4222-8222-222222222222';const CLIP = '33333333-3333-4333-8333-333333333333';const CONTROLLER = '44444444-4444-4444-8444-444444444444';const FRAME = '55555555-5555-4555-8555-555555555555';+const FNT = '66666666-6666-4666-8666-666666666666';+const FNT_PAGE = '77777777-7777-4777-8777-777777777777';const SCENE = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';function writeAsset(rel: string, type: string, uuid: string, body: string | Uint8Array = ''): void {@@ -47,6 +49,17 @@ const controller = JSON.stringify({states: [{ name: 'Idle', clip: 'assets/anim/idle.esanim', loop: true, transitions: [] }],});+// A bitmap font is TEXT, and names its page image the way a spine atlas does:+// as a sibling, resolved against the .fnt's own directory at load.+const fnt = [+ 'info face="tiny" size=8',+ 'common lineHeight=8 base=8 scaleW=16 scaleH=8 pages=1',+ 'page id=0 file="tiny.png"',+ 'chars count=1',+ 'char id=65 x=0 y=0 width=8 height=8 xoffset=0 yoffset=0 xadvance=8 page=0 chnl=15',+ '',+].join('\n');+const clip = JSON.stringify({version: '1.2', name: 'idle', fps: 8,frames: [{ texture: 'assets/anim/frame0.png', duration: 1 }],@@ -64,6 +77,10 @@ const scene = JSON.stringify({id: 2, name: 'Actor', parent: null, children: [],components: [{ type: 'UIController', data: { controller: 'assets/anim/player.esanimator' } }],},+ {+ id: 3, name: 'Label', parent: null, children: [],+ components: [{ type: 'BitmapText', data: { text: 'A', font: 'assets/fonts/tiny.fnt' } }],+ },],});@@ -74,6 +91,8 @@ beforeAll(() => {writeAsset('assets/anim/frame0.png', 'texture', FRAME, 'PNG');writeAsset('assets/anim/idle.esanim', 'animclip', CLIP, clip);writeAsset('assets/anim/player.esanimator', 'animatorcontroller', CONTROLLER, controller);+ writeAsset('assets/fonts/tiny.png', 'texture', FNT_PAGE, 'PNG');+ writeAsset('assets/fonts/tiny.fnt', 'bitmapFont', FNT, fnt);writeAsset('assets/scenes/main.esscene', 'scene', SCENE, scene);});@@ -87,6 +106,11 @@ describe('assets named only inside another document are cooked', () => {expect(index.deps[ESENV]).toContain(SPECULAR);});+ it('links a bitmap font → the page image it names', async () => {+ const { index } = await scanAssetDatabase(root, { write: false });+ expect(index.deps[FNT]).toContain(FNT_PAGE);+ });+it('links animator controller → the clip its state plays', async () => {const { index } = await scanAssetDatabase(root, { write: false });expect(index.deps[CONTROLLER]).toContain(CLIP);@@ -95,7 +119,7 @@ describe('assets named only inside another document are cooked', () => {it('ships both, and the clip\'s own frame through it', async () => {const res = await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });expect(res.ok).toBe(true);- expect(res.included).toEqual(expect.arrayContaining([SCENE, ESENV, SPECULAR, CONTROLLER, CLIP, FRAME]));+ expect(res.included).toEqual(expect.arrayContaining([SCENE, ESENV, SPECULAR, CONTROLLER, CLIP, FRAME, FNT, FNT_PAGE]));expect(res.unused).toEqual([]);});@@ -114,5 +138,10 @@ describe('assets named only inside another document are cooked', () => {const staged = JSON.parse(readFileSync(path.join(res.outDir, env.path), 'utf8')) as { specular: string };expect(staged.specular).toBe('assets/env/sky_env.png');expect(manifest.entries.some((e) => e.sourcePath === staged.specular)).toBe(true);++ // The bitmap font says the same thing in text rather than JSON.+ const font = manifest.entries.find((e) => e.uuid === FNT)!;+ const stagedFnt = readFileSync(path.join(res.outDir, font.path), 'utf8');+ expect(stagedFnt).toContain('file="assets/fonts/tiny.png"');});});diff --git a/pipeline/src/assets/assetDb.ts b/pipeline/src/assets/assetDb.tsindex 1d2fc947d..71775c2e4 100644--- a/pipeline/src/assets/assetDb.ts+++ b/pipeline/src/assets/assetDb.ts@@ -27,7 +27,7 @@ import { META_EXT, isContentDir, isContentFile, isNonContentPath } from './conteimport { adoptOrphan } from './assetMeta';// The runtime's tileset-path resolver (a dependency-free leaf) — shared so the dep scan// discovers a tilemap's tileset images the same way the loader will later request them.-import { resolveRelativePath } from '../../../sdk/src/tilemap/tiledPath';+import { resolveRelativePath } from '../../../sdk/src/asset/documentRef';// The spine-atlas page parser (a dependency-free leaf) — shared with the runtime loaders// so the dep scan discovers an atlas's texture pages the same way they will be requested.import { parseSpineAtlasPages } from '../../../sdk/src/spine/atlasPages';@@ -214,6 +214,10 @@ async function adoptOrphans(root: string, rel = '', adopted: string[] = []): Pro// so the cook keeps the textures instead of shipping an atlas that 404s them.const SKELETAL_ATLAS_TYPES = new Set(['spine-atlas', 'dragonbones-atlas']);+// A bitmap font is the same shape one step over: TEXT, naming its page image as a+// sibling, and nothing else in the project names that image either.+const FNT_PAGE = /(?:^|\n)\s*page\b[^\n]*\bfile="([^"]+)"/g;+// 'json' is a game's own data table. It is scanned like the rest because a// data-driven game names assets FROM its data — a spawn table holding `@uuid:`// refs is the ordinary way to do that — and an unscanned table means the cook@@ -318,7 +322,8 @@ async function computeDeps(const byPath = new Map(entries.map((e) => [e.path, e]));const uuids = new Set(entries.map((e) => e.uuid));const refEntries = (targets ?? entries).filter(- (e) => JSON_REF_TYPES.has(e.type) || SKELETAL_ATLAS_TYPES.has(getEditorType(e.path)),+ (e) => JSON_REF_TYPES.has(e.type) || e.type === 'bitmapFont'+ || SKELETAL_ATLAS_TYPES.has(getEditorType(e.path)),);type DepResult = { uuid: string; refs: string[] } | { warning: string };const depResults = await mapLimit(refEntries, SCAN_IO_CONCURRENCY, async (entry): Promise<DepResult> => {@@ -329,9 +334,16 @@ async function computeDeps(// Spine's atlas is a TEXT manifest and needs its own parser; DragonBones'// is JSON, so the generic walk below already finds its `imagePath`.const isSpineAtlas = getEditorType(entry.path) === 'spine-atlas';+ const isBitmapFont = entry.type === 'bitmapFont';try {const refs = new Set<string>();- if (isSpineAtlas) {+ if (isBitmapFont) {+ const content = await readTextInRoot(path.join(root, entry.path));+ for (const m of content.matchAll(FNT_PAGE)) {+ const dep = byPath.get(normalizeRefPath(resolveRelativePath(entry.path, m[1])));+ if (dep) refs.add(dep.uuid);+ }+ } else if (isSpineAtlas) {const content = await readTextInRoot(path.join(root, entry.path));for (const page of parseSpineAtlasPages(content)) {const dep = byPath.get(normalizeRefPath(resolveRelativePath(entry.path, page)));diff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.tsindex c9dd3de3c..8af354565 100644--- a/pipeline/src/assets/cookAssets.ts+++ b/pipeline/src/assets/cookAssets.ts@@ -29,7 +29,7 @@ import { readTextureCookSettings } from '../project/importSettings';// Single-source content hash (sdk/src/asset/contentHash.ts). Imported as source —// no hand-mirrored copy — so the cook and the runtime agree by construction.import { contentHashHex } from '../../../sdk/src/asset/contentHash';-import { resolveRelativePath } from '../../../sdk/src/tilemap/tiledPath';+import { resolveRelativePath } from '../../../sdk/src/asset/documentRef';// Single source for the folder→delivery-group model, shared with the editor Play// realm (sdk/src/asset/assetGroups.ts) so cook and editor never disagree.import { resolveAssetGroup, resolveAtlas, type AssetGroupsConfig } from '../../../sdk/src/asset/assetGroups';@@ -193,6 +193,25 @@ function logicalRef(ref: unknown, docPath: string, byPath: Map<string, AssetEntrreturn proj.startsWith('assets/') ? proj : `/${proj}`;}+/**+ * A bitmap font names its page image as a sibling, in TEXT rather than JSON — the+ * same staging problem, and the same fix: the staged copy names the project path.+ */+function rewriteFontRefs(+ bytes: Uint8Array,+ fntPath: string,+ byPath: Map<string, AssetEntry>,+): Uint8Array {+ const text = Buffer.from(bytes).toString('utf8');+ return new TextEncoder().encode(text.replace(+ /(\bpage\b[^\n]*\bfile=")([^"]+)(")/g,+ (whole, head: string, ref: string, tail: string) => {+ const logical = logicalRef(ref, fntPath, byPath);+ return typeof logical === 'string' ? `${head}${logical}${tail}` : whole;+ },+ ));+}+/*** A baked environment names its reflection atlas as a SIBLING file, which staging* moves out from under it — the runtime then asks for `assets/sky_env.png` and gets@@ -570,6 +589,14 @@ export async function cookAssets(warnings.push(`${entry.path}: material ref rewrite failed — ${err instanceof Error ? err.message : String(err)}`);}}+ // Bitmap fonts: the sibling page image → its logical project path.+ if (ext.toLowerCase() === '.fnt') {+ try {+ data = rewriteFontRefs(data, entry.path, byPath);+ } catch (err) {+ warnings.push(`${entry.path}: font ref rewrite failed — ${err instanceof Error ? err.message : String(err)}`);+ }+ }// Environments: the sibling reflection atlas → its logical project path.if (ext.toLowerCase() === '.esenv') {try {diff --git a/sdk/src/tilemap/tiledPath.ts b/sdk/src/asset/documentRef.tssimilarity index 85%rename from sdk/src/tilemap/tiledPath.tsrename to sdk/src/asset/documentRef.tsindex c74028d0e..01a9e72ea 100644--- a/sdk/src/tilemap/tiledPath.ts+++ b/sdk/src/asset/documentRef.ts@@ -33,13 +33,18 @@ export function isLogicalAssetRef(ref: string): boolean {}/**- * Resolve a ref a Tiled document carries: a logical project path stands as it is,- * anything else is relative to the document.+ * Resolve a ref one document carries about another asset: a logical project path+ * stands as it is, anything else is relative to the document. Every loader whose+ * document names a sibling resolves through this, because the cook rewrites all+ * of those refs to the same logical shape.*/-export function resolveTiledRef(documentPath: string, ref: string): string {+export function resolveDocumentRef(documentPath: string, ref: string): string {return isLogicalAssetRef(ref) ? ref : resolveRelativePath(documentPath, ref);}+/** @deprecated Name it for the question, not for Tiled: {@link resolveDocumentRef}. */+export const resolveTiledRef = resolveDocumentRef;+export function resolveRelativePath(basePath: string, relativePath: string): string {// Preserve a URL scheme+authority (e.g. "estella://project", "http://host")// before normalizing: the "//" after the scheme must survive, but the segmentdiff --git a/sdk/src/asset/loaders/EnvironmentAssetLoader.ts b/sdk/src/asset/loaders/EnvironmentAssetLoader.tsindex 72d9ce416..87a0c39c9 100644--- a/sdk/src/asset/loaders/EnvironmentAssetLoader.ts+++ b/sdk/src/asset/loaders/EnvironmentAssetLoader.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { AssetLoader, LoadContext } from '../AssetLoader';+import { resolveDocumentRef } from '../documentRef';import type { ESEngineModule } from '../../wasm';import { withScratch } from '../../wasm/wasmScratch';import { log } from '../../util/logger';@@ -55,7 +56,7 @@ export class EnvironmentAssetLoader implements AssetLoader<EnvironmentResult> {let specularHandle = 0;let specularPath: string | undefined;if (data.specular) {- const resolved = resolvePath(path, data.specular);+ const resolved = resolveDocumentRef(path, data.specular);try {// flipY false: the atlas' rows are a layout, not a picture. Row 0// is mip 0, and a load that turned it over would put the mip@@ -88,8 +89,4 @@ export class EnvironmentAssetLoader implements AssetLoader<EnvironmentResult> {}/** Resolve the atlas ref relative to the `.esenv`; rooted refs pass through. */-function resolvePath(fromPath: string, ref: string): string {- if (ref.startsWith('/') || ref.startsWith('http') || ref.startsWith('assets/')) return ref;- const dir = fromPath.substring(0, fromPath.lastIndexOf('/'));- return dir ? `${dir}/${ref}` : ref;-}+diff --git a/sdk/src/asset/loaders/FontAssetLoader.ts b/sdk/src/asset/loaders/FontAssetLoader.tsindex 56952db9d..2585ae7ec 100644--- a/sdk/src/asset/loaders/FontAssetLoader.ts+++ b/sdk/src/asset/loaders/FontAssetLoader.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { AssetLoader, LoadContext, FontResult } from '../AssetLoader';+import { resolveDocumentRef } from '../documentRef';import { requireResourceManager } from '../../wasm/resourceManager';import { getAssetTypeEntry } from '../../assetTypes';import { getPlatform } from '../../platform/base';@@ -79,9 +80,7 @@ export class FontAssetLoader implements AssetLoader<FontResult> {throw new Error(`No page texture found in .fnt file: ${path}`);}- const texName = pageMatch[1];- const dir = path.substring(0, path.lastIndexOf('/'));- const texPath = dir ? `${dir}/${texName}` : texName;+ const texPath = resolveDocumentRef(path, pageMatch[1]);const texResult = await ctx.loadTexture(texPath, false);const rm = requireResourceManager();diff --git a/sdk/src/asset/loaders/MaterialAssetLoader.ts b/sdk/src/asset/loaders/MaterialAssetLoader.tsindex a6ecdc63b..ce86a0c3e 100644--- a/sdk/src/asset/loaders/MaterialAssetLoader.ts+++ b/sdk/src/asset/loaders/MaterialAssetLoader.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { AssetLoader, LoadContext, MaterialResult } from '../AssetLoader';+import { resolveDocumentRef } from '../documentRef';import type { MaterialAssetData, ShaderHandle } from '../../render/material';import { Material } from '../../render/material';import { builtinShaderTemplate } from '../../render/builtinShaders';@@ -31,7 +32,7 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {// parent first, then build the instance from the asset's diffs. Parent shader resolution// and uniforms come from the parent material, so no shader is loaded here.if (data.instanceOf) {- const parentPath = resolveRelativePath(path, data.instanceOf);+ const parentPath = resolveDocumentRef(path, data.instanceOf);const parent = await this.load(parentPath, ctx);const handle = Material.createFromAsset(data, 0, parent.handle);const texturePaths = await this.applyTextureProps(handle, data, path, ctx);@@ -64,7 +65,7 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {const bound: string[] = [];for (const [name, value] of Object.entries(data.properties)) {if (typeof value !== 'string') continue;- const texPath = resolveRelativePath(matPath, value);+ const texPath = resolveDocumentRef(matPath, value);try {const tex = await ctx.loadTexture(texPath);Material.setUniform(handle, name, Material.tex(tex.handle));@@ -95,7 +96,7 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {// permutations, so the cache key folds the sorted features in.private async loadShader(matPath: string, ref: string, features: string[], ctx: LoadContext): Promise<ShaderHandle> {const isBuiltin = ref.startsWith(BUILTIN_SHADER_PREFIX);- const key = isBuiltin ? ref : resolveRelativePath(matPath, ref);+ const key = isBuiltin ? ref : resolveDocumentRef(matPath, ref);const cacheKey = features.length ? `${key}#${features.join('|')}` : key;const cached = this.shaderCache_.get(cacheKey);if (cached !== undefined) return cached;@@ -129,12 +130,4 @@ function enabledSwitches(switches: Record<string, boolean> | undefined): string[return Object.entries(switches).filter(([, on]) => on).map(([name]) => name).sort();}-// Resolve a ref (shader or parent material) relative to the referencing material's directory;-// absolute / http / assets-rooted refs pass through unchanged.-function resolveRelativePath(fromPath: string, ref: string): string {- if (ref.startsWith('/') || ref.startsWith('http') || ref.startsWith('assets/')) {- return ref;- }- const dir = fromPath.substring(0, fromPath.lastIndexOf('/'));- return dir ? `${dir}/${ref}` : ref;-}+diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.tsindex 3068817db..094d04611 100644--- a/sdk/src/tilemap/tiledLoader.ts+++ b/sdk/src/tilemap/tiledLoader.ts@@ -44,7 +44,7 @@ import { mergeCollisionTiles } from './collisionMerge';import { CHUNK_SIZE } from './chunkCodec';import { tileIdOf, tileFlagsOf } from './tileBits';import { log } from '../util/logger';-import { resolveRelativePath, resolveTiledRef, isLogicalAssetRef } from './tiledPath';+import { resolveRelativePath, resolveDocumentRef, resolveTiledRef, isLogicalAssetRef } from '../asset/documentRef';export interface TiledChunkData {x: number;@@ -600,10 +600,9 @@ export async function parseTmjWithExternals(return parseTmjJson(json);}-// resolveRelativePath now lives in ./tiledPath (a dependency-free leaf) so the editor's-// asset-dependency scan / cook can share the exact resolution the runtime loads with,-// without pulling the loader's engine deps. Re-exported here for existing importers.-export { resolveRelativePath, resolveTiledRef, isLogicalAssetRef };+// The resolution lives in ../asset/documentRef (a dependency-free leaf) so the+// cook and every loader share it. Re-exported for existing importers.+export { resolveRelativePath, resolveDocumentRef, resolveTiledRef, isLogicalAssetRef };export interface CollectionGridTile {/** Local tile id — also the grid slot, so gid → cell stays the identitydiff --git a/sdk/tests/tiled-path-resolution.test.ts b/sdk/tests/tiled-path-resolution.test.tsindex 915f75c17..c1cd5a7e3 100644--- a/sdk/tests/tiled-path-resolution.test.ts+++ b/sdk/tests/tiled-path-resolution.test.ts@@ -14,7 +14,7 @@// the same map by its cooked FILE path: every tile went invisible on the device with// "assets/assets/textures/tileset.png" not found.import { describe, it, expect } from 'vitest';-import { resolveRelativePath, resolveTiledRef, isLogicalAssetRef } from '../src/tilemap/tiledPath';+import { resolveRelativePath, resolveTiledRef, isLogicalAssetRef } from '../src/asset/documentRef';describe('isLogicalAssetRef', () => {it('recognizes the shape the cook emits', () => {