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(asset): resolve UUID refs in scene/prefab loading
esengine3573423a9ff5
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 1a60fb100..5416febaa 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -23,6 +23,7 @@ import { getAssetFields } from './AssetFieldRegistry';import { discoverSceneAssets } from './discoverAssets';import type { SceneData } from '../scene';import { SceneHandle, type ReleaseCallback } from './SceneHandle';+import type { AssetRegistry } from './AssetRegistry';export interface AssetsOptions {backend: Backend;@@ -69,6 +70,7 @@ export class Assets {private genericCache_ = new Map<string, AsyncCache<unknown>>();private loadContext_: LoadContext | null = null;private assetRefResolver_: AssetRefResolver | null = null;+ private assetRegistry_: AssetRegistry | null = null;private constructor(options: AssetsOptions) {this.backend = options.backend;@@ -271,7 +273,13 @@ export class Assets {sceneData: SceneData,onProgress?: (loaded: number, total: number) => void,): Promise<SceneAssetResult> {- const discovered = discoverSceneAssets(sceneData);+ const discovered = discoverSceneAssets(sceneData, (ref) => this.resolveRef(ref));+ if (discovered.unresolved.length > 0) {+ console.warn(+ `[Assets] ${discovered.unresolved.length} unresolved asset ref(s):`,+ discovered.unresolved,+ );+ }const texturePaths = discovered.byType.get('texture') ?? new Set<string>();const materialPaths = discovered.byType.get('material') ?? new Set<string>();const fontPaths = discovered.byType.get('font') ?? new Set<string>();@@ -347,13 +355,22 @@ export class Assets {for (const comp of entity.components) {const fields = getAssetFields(comp.type);for (const { field, type } of fields) {- const value = comp.data[field];- if (typeof value !== 'string' || !value) continue;+ const ref = comp.data[field];+ if (typeof ref !== 'string' || !ref) continue;++ // UUID refs resolve to their current path; plain paths+ // pass through. Unknown UUID → null, handle will be 0+ // (caller's getter returns 0 when the key is missing).+ const path = this.resolveRef(ref);+ if (path == null) {+ comp.data[field] = 0;+ continue;+ }switch (type) {case 'texture': {- comp.data[field] = textureHandles.get(value) ?? 0;- const atlasInfo = this.catalog.getAtlasFrame(value);+ comp.data[field] = textureHandles.get(path) ?? 0;+ const atlasInfo = this.catalog.getAtlasFrame(path);if (atlasInfo) {comp.data['uvOffset'] = { x: atlasInfo.uvOffset[0], y: atlasInfo.uvOffset[1] };comp.data['uvScale'] = { x: atlasInfo.uvScale[0], y: atlasInfo.uvScale[1] };@@ -367,10 +384,10 @@ export class Assets {break;}case 'material':- comp.data[field] = materialHandles.get(value) ?? 0;+ comp.data[field] = materialHandles.get(path) ?? 0;break;case 'font':- comp.data[field] = fontHandles.get(value) ?? 0;+ comp.data[field] = fontHandles.get(path) ?? 0;break;}}@@ -463,6 +480,32 @@ export class Assets {return this.assetRefResolver_;}+ /**+ * Attach an AssetRegistry so that scene/prefab refs of the form+ * `"@uuid:..."` are resolved to current paths before loading.+ * Convenience over `setAssetRefResolver`: sets the resolver to+ * `registry.resolveRef`.+ */+ setAssetRegistry(registry: AssetRegistry): void {+ this.assetRegistry_ = registry;+ this.assetRefResolver_ = (ref) => registry.resolveRef(ref);+ }++ getAssetRegistry(): AssetRegistry | null {+ return this.assetRegistry_;+ }++ /**+ * Resolve any serialized asset ref (UUID or plain path) to a concrete+ * path. Returns null when a UUID ref can't be matched to a known+ * asset. Without a registry/resolver configured, refs pass through+ * unchanged — legacy path-only scenes keep working.+ */+ resolveRef(ref: string): string | null {+ if (this.assetRefResolver_) return this.assetRefResolver_(ref);+ return ref;+ }+// =========================================================================// Private// =========================================================================diff --git a/sdk/src/asset/discoverAssets.ts b/sdk/src/asset/discoverAssets.tsindex ad83b1b68..0c8a54848 100644--- a/sdk/src/asset/discoverAssets.ts+++ b/sdk/src/asset/discoverAssets.ts@@ -1,6 +1,19 @@/*** @file discoverAssets.ts- * @brief Unified asset discovery from scene/prefab data+ * @brief Unified asset discovery from scene/prefab data.+ *+ * Each component may reference assets in three ways: a custom+ * `discoverAssets` callback, declared `assetFields`, or paired+ * `spineFields`. This module walks a SceneData and buckets every+ * such ref by asset type.+ *+ * Refs in serialized data may be either a concrete path+ * (`"assets/player.png"`, legacy) or a UUID reference+ * (`"@uuid:xxxxxxxx-..."`, produced by the meta-driven pipeline).+ * An optional `refResolver` callback translates a ref to its+ * current path before bucketing. Without a resolver the ref is+ * passed through unchanged — works for legacy scenes that still+ * store paths directly.*/import { getComponent } from '../component';@@ -14,14 +27,38 @@ export interface SpineAssetRef {export interface SceneAssetRefs {byType: Map<string, Set<string>>;spines: SpineAssetRef[];+ /**+ * Refs seen during discovery that could not be resolved to a path+ * (e.g. unknown UUID). Callers surface this to the user so missing+ * assets don't silently turn into texture handle 0.+ */+ unresolved: string[];}-export function discoverSceneAssets(sceneData: SceneData): SceneAssetRefs {+/** Turns a raw serialized ref into a concrete path (or null if unknown). */+export type RefResolver = (ref: string) => string | null;++export function discoverSceneAssets(+ sceneData: SceneData,+ refResolver?: RefResolver,+): SceneAssetRefs {const byType = new Map<string, Set<string>>();const spines: SpineAssetRef[] = [];const spineKeys = new Set<string>();+ const unresolved: string[] = [];++ const resolve = (raw: string): string | null => {+ const r = refResolver ? refResolver(raw) : raw;+ if (r == null || r === '') {+ unresolved.push(raw);+ return null;+ }+ return r;+ };- const addAsset = (type: string, path: string): void => {+ const addAsset = (type: string, raw: string): void => {+ const path = resolve(raw);+ if (path == null) return;let set = byType.get(type);if (!set) {set = new Set();@@ -55,20 +92,24 @@ export function discoverSceneAssets(sceneData: SceneData): SceneAssetRefs {}if (comp.spineFields) {- const skelPath = data[comp.spineFields.skeletonField] as string;- const atlasPath = data[comp.spineFields.atlasField] as string;- if (skelPath && atlasPath) {- const key = `${skelPath}:${atlasPath}`;- if (!spineKeys.has(key)) {- spineKeys.add(key);- spines.push({ skeleton: skelPath, atlas: atlasPath });+ const skelRaw = data[comp.spineFields.skeletonField] as string;+ const atlasRaw = data[comp.spineFields.atlasField] as string;+ if (skelRaw && atlasRaw) {+ const skel = resolve(skelRaw);+ const atlas = resolve(atlasRaw);+ if (skel != null && atlas != null) {+ const key = `${skel}:${atlas}`;+ if (!spineKeys.has(key)) {+ spineKeys.add(key);+ spines.push({ skeleton: skel, atlas });+ }}}}}}- return { byType, spines };+ return { byType, spines, unresolved };}export function getAssetPathsByType(refs: SceneAssetRefs, type: AssetFieldType): Set<string> {diff --git a/sdk/tests/discoverAssets.test.ts b/sdk/tests/discoverAssets.test.tsindex c68902498..baacec639 100644--- a/sdk/tests/discoverAssets.test.ts+++ b/sdk/tests/discoverAssets.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, beforeEach } from 'vitest';import { defineComponent, clearUserComponents } from '../src/component';import { discoverSceneAssets, getAssetPathsByType } from '../src/asset/discoverAssets';+import { AssetRegistry, makeUuidRef } from '../src/asset/AssetRegistry';import type { SceneData } from '../src/scene';const SPRITE_NAME = 'DiscoverTest_Sprite';@@ -195,3 +196,130 @@ describe('discoverSceneAssets', () => {expect(refs.spines).toHaveLength(0);});});++describe('discoverSceneAssets with UUID refResolver', () => {+ const UUID_PLAYER = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa';+ const UUID_LOGO = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb';+ const UUID_MAT = 'cccccccc-3333-4333-8333-cccccccccccc';+ const UUID_MUSIC = 'dddddddd-4444-4444-8444-dddddddddddd';+ const UUID_MISSING = 'eeeeeeee-5555-4555-8555-eeeeeeeeeeee';++ function makeRegistry(): AssetRegistry {+ const reg = new AssetRegistry();+ reg.addEntry({ uuid: UUID_PLAYER, path: 'assets/player.png', type: 'texture' });+ reg.addEntry({ uuid: UUID_LOGO, path: 'assets/logo.png', type: 'texture' });+ reg.addEntry({ uuid: UUID_MAT, path: 'assets/mat1.mat', type: 'material' });+ reg.addEntry({ uuid: UUID_MUSIC, path: 'assets/bgm.mp3', type: 'audio' });+ return reg;+ }++ it('resolves @uuid: refs to current paths before bucketing', () => {+ const reg = makeRegistry();+ const scene = makeScene([{+ id: 1, name: 'e1', parent: null, children: [],+ components: [{+ type: SPRITE_NAME,+ data: {+ texture: makeUuidRef(UUID_PLAYER),+ material: makeUuidRef(UUID_MAT),+ color: { r: 1, g: 1, b: 1, a: 1 },+ },+ }],+ }]);++ const refs = discoverSceneAssets(scene, (ref) => reg.resolveRef(ref));++ expect(getAssetPathsByType(refs, 'texture')).toEqual(new Set(['assets/player.png']));+ expect(getAssetPathsByType(refs, 'material')).toEqual(new Set(['assets/mat1.mat']));+ expect(refs.unresolved).toEqual([]);+ });++ it('passes plain path strings through unchanged (legacy)', () => {+ const reg = makeRegistry();+ const scene = makeScene([{+ id: 1, name: 'e1', parent: null, children: [],+ components: [{+ type: SPRITE_NAME,+ data: { texture: 'assets/legacy.png', material: '', color: { r: 1, g: 1, b: 1, a: 1 } },+ }],+ }]);++ const refs = discoverSceneAssets(scene, (ref) => reg.resolveRef(ref));++ expect(getAssetPathsByType(refs, 'texture')).toEqual(new Set(['assets/legacy.png']));+ });++ it('mixes @uuid: and plain-path refs in the same scene', () => {+ const reg = makeRegistry();+ const scene = makeScene([+ {+ id: 1, name: 'e1', parent: null, children: [],+ components: [{+ type: SPRITE_NAME,+ data: {+ texture: makeUuidRef(UUID_PLAYER),+ material: 'assets/legacy.mat',+ color: { r: 1, g: 1, b: 1, a: 1 },+ },+ }],+ },+ {+ id: 2, name: 'e2', parent: null, children: [],+ components: [{+ type: AUDIO_NAME,+ data: { clip: makeUuidRef(UUID_MUSIC) },+ }],+ },+ ]);++ const refs = discoverSceneAssets(scene, (ref) => reg.resolveRef(ref));++ expect(getAssetPathsByType(refs, 'texture')).toEqual(new Set(['assets/player.png']));+ expect(getAssetPathsByType(refs, 'material')).toEqual(new Set(['assets/legacy.mat']));+ expect(getAssetPathsByType(refs, 'audio')).toEqual(new Set(['assets/bgm.mp3']));+ });++ it('records unknown UUID refs in `unresolved` and excludes them from bucketing', () => {+ const reg = makeRegistry();+ const scene = makeScene([{+ id: 1, name: 'e1', parent: null, children: [],+ components: [{+ type: SPRITE_NAME,+ data: {+ texture: makeUuidRef(UUID_MISSING),+ material: makeUuidRef(UUID_MAT),+ color: { r: 1, g: 1, b: 1, a: 1 },+ },+ }],+ }]);++ const refs = discoverSceneAssets(scene, (ref) => reg.resolveRef(ref));++ expect(getAssetPathsByType(refs, 'texture').size).toBe(0);+ expect(getAssetPathsByType(refs, 'material')).toEqual(new Set(['assets/mat1.mat']));+ expect(refs.unresolved).toEqual([makeUuidRef(UUID_MISSING)]);+ });++ it('resolves spineFields via the same resolver', () => {+ const reg = new AssetRegistry();+ const UUID_SKEL = '11111111-1111-4111-8111-111111111111';+ const UUID_ATLAS = '22222222-2222-4222-8222-222222222222';+ reg.addEntry({ uuid: UUID_SKEL, path: 'assets/hero.skel', type: 'spine' });+ reg.addEntry({ uuid: UUID_ATLAS, path: 'assets/hero.atlas', type: 'spine' });++ const scene = makeScene([{+ id: 1, name: 'e1', parent: null, children: [],+ components: [{+ type: SPINE_NAME,+ data: {+ skeleton: makeUuidRef(UUID_SKEL),+ atlas: makeUuidRef(UUID_ATLAS),+ },+ }],+ }]);++ const refs = discoverSceneAssets(scene, (ref) => reg.resolveRef(ref));++ expect(refs.spines).toEqual([{ skeleton: 'assets/hero.skel', atlas: 'assets/hero.atlas' }]);+ });+});diff --git a/tools/asset-meta.js b/tools/asset-meta.jsindex 134bab8e7..aa543524c 100644--- a/tools/asset-meta.js+++ b/tools/asset-meta.js@@ -9,9 +9,10 @@* identity for scene/prefab references and must survive across runs.** Usage:- * node tools/asset-meta.js <dir>... # generate missing metas- * node tools/asset-meta.js <dir> --dry-run # preview only- * node tools/asset-meta.js <dir> --check # exit 1 if any missing (CI)+ * node tools/asset-meta.js <dir>... # generate missing metas+ * node tools/asset-meta.js <dir> --dry-run # preview only+ * node tools/asset-meta.js <dir> --check # exit 1 if any missing (CI)+ * node tools/asset-meta.js <dir> --emit-manifest <out> # also write runtime manifest* node tools/asset-meta.js <dir> --verbose** Exit codes:@@ -244,13 +245,110 @@ function printSummary(results, { verbose, dryRun, check }) {);}+/**+ * Scan every `.meta` sidecar under `dir` and collect their contents+ * as AssetManifest entries keyed by path relative to `dir`.+ */+export async function buildManifest(dir, options = {}) {+ const { manifestBase } = options;+ const root = resolve(dir);+ const base = manifestBase ? resolve(manifestBase) : root;++ const entries = [];+ const warnings = [];++ for await (const filePath of walk(root)) {+ const type = getAssetType(filePath);+ if (type === null) continue;++ const metaPath = filePath + '.meta';+ if (!(await exists(metaPath))) continue;++ let raw;+ try {+ raw = await readFile(metaPath, 'utf8');+ } catch (err) {+ warnings.push({ metaPath, reason: `read failed: ${err.message}` });+ continue;+ }++ let meta;+ try {+ meta = JSON.parse(raw);+ } catch (err) {+ warnings.push({ metaPath, reason: `malformed JSON: ${err.message}` });+ continue;+ }++ if (!meta || typeof meta.uuid !== 'string' || !meta.type) {+ warnings.push({ metaPath, reason: 'missing uuid or type' });+ continue;+ }++ // Manifest paths are relative + forward-slashed so the runtime+ // (web / wechat) can treat them as URL-ish without OS-specific+ // backslash handling.+ const relPath = relative(base, filePath).replace(/\\/g, '/');++ entries.push({+ uuid: meta.uuid,+ path: relPath,+ type: meta.type,+ importer: meta.importer ?? {},+ });+ }++ entries.sort((a, b) => a.path.localeCompare(b.path));++ return { manifest: { version: '1.0', entries }, warnings };+}++async function emitManifest(outPath, dirs, manifestBase) {+ const allEntries = [];+ const allWarnings = [];+ for (const dir of dirs) {+ const { manifest, warnings } = await buildManifest(dir, { manifestBase });+ allEntries.push(...manifest.entries);+ allWarnings.push(...warnings);+ }++ // Detect UUID collisions across scanned dirs — caller almost certainly+ // wants to know.+ const byUuid = new Map();+ const collisions = [];+ for (const e of allEntries) {+ const prior = byUuid.get(e.uuid);+ if (prior) collisions.push({ uuid: e.uuid, a: prior.path, b: e.path });+ else byUuid.set(e.uuid, e);+ }++ if (collisions.length > 0) {+ console.error('\nUUID collision(s) detected:');+ for (const c of collisions) {+ console.error(` ${c.uuid}: ${c.a} vs ${c.b}`);+ }+ }+ if (allWarnings.length > 0) {+ console.warn('\nWarnings:');+ for (const w of allWarnings) console.warn(` ${w.metaPath} — ${w.reason}`);+ }++ const manifest = { version: '1.0', entries: allEntries };+ await writeFile(outPath, JSON.stringify(manifest, null, 2) + '\n', 'utf8');+ console.log(`\nwrote manifest: ${outPath} (${allEntries.length} entries)`);++ return collisions.length === 0;+}+async function main() {const { values, positionals } = parseArgs({options: {- 'dry-run': { type: 'boolean', default: false },- 'check': { type: 'boolean', default: false },- 'verbose': { type: 'boolean', short: 'v', default: false },- 'help': { type: 'boolean', short: 'h', default: false },+ 'dry-run': { type: 'boolean', default: false },+ 'check': { type: 'boolean', default: false },+ 'verbose': { type: 'boolean', short: 'v', default: false },+ 'help': { type: 'boolean', short: 'h', default: false },+ 'emit-manifest': { type: 'string' },+ 'manifest-base': { type: 'string' },},allowPositionals: true,});@@ -259,10 +357,12 @@ async function main() {console.log(`Usage: node tools/asset-meta.js <dir>... [options]Options:- --dry-run Show what would be created, write nothing- --check Exit 1 if any asset is missing .meta (CI mode)- -v, --verbose Log every asset considered- -h, --help Show this help`);+ --dry-run Show what would be created, write nothing+ --check Exit 1 if any asset is missing .meta (CI mode)+ --emit-manifest <file> After generating, write AssetManifest JSON here+ --manifest-base <dir> Base dir for manifest paths (default: scanned dir)+ -v, --verbose Log every asset considered+ -h, --help Show this help`);process.exit(values.help ? 0 : 2);}@@ -288,7 +388,16 @@ Options:if (values.check) {const anyMissing = results.some(r => r.created.length > 0);- process.exit(anyMissing ? 1 : 0);+ if (anyMissing) process.exit(1);+ }++ if (values['emit-manifest']) {+ const ok = await emitManifest(+ values['emit-manifest'],+ positionals,+ values['manifest-base'],+ );+ if (!ok) process.exit(1);}}