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.

feat(asset): add AssetRegistry (uuid <-> path mapping)

esenginee353ce7a2c9d
diff --git a/sdk/src/asset/AssetRegistry.ts b/sdk/src/asset/AssetRegistry.ts
new file mode 100644
index 000000000..0e6190a27
--- /dev/null
+++ b/sdk/src/asset/AssetRegistry.ts
@@ -0,0 +1,206 @@
+/**
+ * @file AssetRegistry.ts
+ * @brief Maps stable asset UUIDs to file paths + importer settings.
+ *
+ * Scene / prefab JSON stores asset references as `"@uuid:<uuid-v4>"` strings.
+ * At load time the registry answers "which path does this UUID point to?" so
+ * the loader can fetch the bytes. Renaming a file on disk therefore never
+ * breaks a ref — the UUID (baked into the `.meta` sidecar) stays stable;
+ * only the path moves, and the registry is rebuilt from the new filesystem
+ * layout on next scan.
+ *
+ * The registry itself is pure data — it has no I/O. Populate it from an
+ * `AssetManifest` (produced at build time or scanned by a host-side tool)
+ * via `loadManifest()` / `addEntries()`. The asset system consults it
+ * through `resolveRef()` / `uuidToPath()`.
+ */
+
+/** Prefix that distinguishes a UUID ref from a raw path in serialized data. */
+export const UUID_REF_PREFIX = '@uuid:';
+
+/** UUID v4 regex — 8-4-4-4-12 lowercase hex. Generators use crypto.randomUUID(). */
+export const UUID_V4_REGEX =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+/**
+ * One row in the registry: the UUID, its current path on disk, the asset
+ * type (`"texture"`, `"audio"`, ...) and the free-form importer settings
+ * parsed out of the `.meta` sidecar.
+ */
+export interface AssetEntry {
+ uuid: string;
+ path: string;
+ type: string;
+ importer?: Record<string, unknown>;
+}
+
+/**
+ * Runtime-shipped manifest format. The build step (or editor host) scans
+ * every `.meta` file in the project and emits this shape; the SDK loads
+ * it once at startup to populate the registry.
+ */
+export interface AssetManifest {
+ version: '1.0';
+ entries: AssetEntry[];
+}
+
+/** True if `ref` is a `"@uuid:xxxxxxxx-xxxx-..."` string. */
+export function isUuidRef(ref: unknown): ref is string {
+ return typeof ref === 'string'
+ && ref.startsWith(UUID_REF_PREFIX)
+ && UUID_V4_REGEX.test(ref.slice(UUID_REF_PREFIX.length));
+}
+
+/** Extract the UUID out of a `"@uuid:..."` string, or null if not a ref. */
+export function extractUuid(ref: unknown): string | null {
+ if (!isUuidRef(ref)) return null;
+ return (ref as string).slice(UUID_REF_PREFIX.length).toLowerCase();
+}
+
+/** Build a `"@uuid:..."` serialized ref. Validates the UUID shape. */
+export function makeUuidRef(uuid: string): string {
+ if (!UUID_V4_REGEX.test(uuid)) {
+ throw new Error(`makeUuidRef: invalid UUID "${uuid}"`);
+ }
+ return UUID_REF_PREFIX + uuid.toLowerCase();
+}
+
+export class AssetRegistry {
+ private byUuid_ = new Map<string, AssetEntry>();
+ private byPath_ = new Map<string, AssetEntry>();
+
+ /** Number of registered assets. */
+ get size(): number {
+ return this.byUuid_.size;
+ }
+
+ /**
+ * Register a single entry. If an entry with the same UUID already
+ * exists the newer one replaces it (typical use: the host scanned
+ * the filesystem again after a rename).
+ *
+ * Throws if the entry is malformed (missing uuid / path, or UUID
+ * shape wrong). Prefer a noisy failure at load time over silent
+ * miss-resolutions later.
+ */
+ addEntry(entry: AssetEntry): void {
+ if (!entry || typeof entry !== 'object') {
+ throw new Error('AssetRegistry.addEntry: entry must be an object');
+ }
+ if (!UUID_V4_REGEX.test(entry.uuid)) {
+ throw new Error(
+ `AssetRegistry.addEntry: invalid uuid "${entry.uuid}" for path "${entry.path}"`,
+ );
+ }
+ if (typeof entry.path !== 'string' || entry.path.length === 0) {
+ throw new Error(
+ `AssetRegistry.addEntry: missing path for uuid "${entry.uuid}"`,
+ );
+ }
+
+ const uuid = entry.uuid.toLowerCase();
+ const normalized: AssetEntry = {
+ uuid,
+ path: entry.path,
+ type: entry.type,
+ importer: entry.importer,
+ };
+
+ // If this UUID existed under a different path, drop the stale path mapping.
+ const prior = this.byUuid_.get(uuid);
+ if (prior && prior.path !== normalized.path) {
+ this.byPath_.delete(prior.path);
+ }
+
+ this.byUuid_.set(uuid, normalized);
+ this.byPath_.set(normalized.path, normalized);
+ }
+
+ /**
+ * Register many entries. Invalid entries throw immediately and leave
+ * prior valid ones in place (no transactional rollback — caller
+ * should sanitize the manifest before handing it over).
+ */
+ addEntries(entries: readonly AssetEntry[]): void {
+ for (const entry of entries) {
+ this.addEntry(entry);
+ }
+ }
+
+ /** Load a manifest produced by the build/scan tool. */
+ loadManifest(manifest: AssetManifest): void {
+ if (manifest.version !== '1.0') {
+ throw new Error(
+ `AssetRegistry.loadManifest: unsupported version "${manifest.version}"`,
+ );
+ }
+ this.addEntries(manifest.entries);
+ }
+
+ /** Remove a single entry by UUID. Returns true if it was present. */
+ removeByUuid(uuid: string): boolean {
+ const key = uuid.toLowerCase();
+ const entry = this.byUuid_.get(key);
+ if (!entry) return false;
+ this.byUuid_.delete(key);
+ this.byPath_.delete(entry.path);
+ return true;
+ }
+
+ /** Full lookup by UUID. Returns null if unknown. */
+ resolveUuid(uuid: string): AssetEntry | null {
+ return this.byUuid_.get(uuid.toLowerCase()) ?? null;
+ }
+
+ /** Convenience: just the path for a UUID, or null. */
+ uuidToPath(uuid: string): string | null {
+ return this.byUuid_.get(uuid.toLowerCase())?.path ?? null;
+ }
+
+ /** Reverse lookup: which UUID is bound to this path, if any. */
+ pathToUuid(path: string): string | null {
+ return this.byPath_.get(path)?.uuid ?? null;
+ }
+
+ /** Reverse lookup with full entry. */
+ getEntryByPath(path: string): AssetEntry | null {
+ return this.byPath_.get(path) ?? null;
+ }
+
+ /** All entries of a given `.meta` type (`"texture"`, `"audio"`, ...). */
+ getAllByType(type: string): AssetEntry[] {
+ const out: AssetEntry[] = [];
+ for (const entry of this.byUuid_.values()) {
+ if (entry.type === type) out.push(entry);
+ }
+ return out;
+ }
+
+ /**
+ * Resolve any serialized asset ref to an on-disk path:
+ * - `"@uuid:xxxxxxxx-..."` → lookup UUID; returns path or null
+ * - plain string → returned as-is (treated as legacy path)
+ *
+ * This is the function the asset loader should call before hitting
+ * the filesystem. During the migration window, scenes / prefabs
+ * carry a mix of UUID refs and legacy paths; this handles both.
+ */
+ resolveRef(ref: string): string | null {
+ const uuid = extractUuid(ref);
+ if (uuid !== null) {
+ return this.uuidToPath(uuid);
+ }
+ return ref;
+ }
+
+ /** Iterate all entries. Stable across consecutive calls with no mutations. */
+ entries(): AssetEntry[] {
+ return Array.from(this.byUuid_.values());
+ }
+
+ /** Drop everything. Mainly for tests. */
+ clear(): void {
+ this.byUuid_.clear();
+ this.byPath_.clear();
+ }
+}
diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.ts
index 333e9b569..706f5d6a9 100644
--- a/sdk/src/asset/index.ts
+++ b/sdk/src/asset/index.ts
@@ -12,6 +12,16 @@ export { AssetRefCounter, type AssetRefInfo } from './AssetRefCounter';
export { Assets as AssetsImpl, type AssetsOptions, type AssetBundle, type SceneAssetResult } from './Assets';
export { type Backend, HttpBackend, EmbeddedBackend, type HttpBackendOptions } from './Backend';
export { Catalog, type CatalogData, type CatalogEntry, type AtlasFrameInfo } from './Catalog';
+export {
+ AssetRegistry,
+ UUID_REF_PREFIX,
+ UUID_V4_REGEX,
+ isUuidRef,
+ extractUuid,
+ makeUuidRef,
+ type AssetEntry,
+ type AssetManifest,
+} from './AssetRegistry';
export { type AssetLoader, type LoadContext, type TextureResult, type TextureResult as TextureInfo, type SpineResult, type SpineLoadResult, type MaterialResult, type FontResult, type AudioResult } from './AssetLoader';
export { SceneHandle } from './SceneHandle';
export {
diff --git a/sdk/tests/asset-registry.test.ts b/sdk/tests/asset-registry.test.ts
new file mode 100644
index 000000000..bb4ec6827
--- /dev/null
+++ b/sdk/tests/asset-registry.test.ts
@@ -0,0 +1,179 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ AssetRegistry,
+ UUID_REF_PREFIX,
+ UUID_V4_REGEX,
+ isUuidRef,
+ extractUuid,
+ makeUuidRef,
+ type AssetEntry,
+ type AssetManifest,
+} from '../src/asset/AssetRegistry';
+
+const UUID_A = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa';
+const UUID_B = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb';
+const UUID_C = 'cccccccc-3333-4333-8333-cccccccccccc';
+
+function textureEntry(uuid: string, path: string): AssetEntry {
+ return { uuid, path, type: 'texture', importer: { maxSize: 2048 } };
+}
+
+describe('AssetRegistry ref helpers', () => {
+ it('UUID_V4_REGEX matches the expected shape', () => {
+ expect(UUID_V4_REGEX.test(UUID_A)).toBe(true);
+ expect(UUID_V4_REGEX.test('not-a-uuid')).toBe(false);
+ expect(UUID_V4_REGEX.test('aaaa-1111-4111-8111-aaaaaaaaaaaa')).toBe(false);
+ });
+
+ it('isUuidRef detects the @uuid: prefix + valid body', () => {
+ expect(isUuidRef(`${UUID_REF_PREFIX}${UUID_A}`)).toBe(true);
+ expect(isUuidRef(UUID_A)).toBe(false);
+ expect(isUuidRef('@uuid:garbage')).toBe(false);
+ expect(isUuidRef('assets/player.png')).toBe(false);
+ expect(isUuidRef(null)).toBe(false);
+ expect(isUuidRef(123)).toBe(false);
+ });
+
+ it('extractUuid returns the lower-cased UUID', () => {
+ expect(extractUuid(`${UUID_REF_PREFIX}${UUID_A}`)).toBe(UUID_A);
+ expect(extractUuid(`${UUID_REF_PREFIX}${UUID_A.toUpperCase()}`)).toBe(UUID_A);
+ expect(extractUuid('assets/player.png')).toBeNull();
+ expect(extractUuid(null)).toBeNull();
+ });
+
+ it('makeUuidRef builds a canonical ref string', () => {
+ expect(makeUuidRef(UUID_A)).toBe(`${UUID_REF_PREFIX}${UUID_A}`);
+ expect(makeUuidRef(UUID_A.toUpperCase())).toBe(`${UUID_REF_PREFIX}${UUID_A}`);
+ expect(() => makeUuidRef('not-a-uuid')).toThrow();
+ });
+});
+
+describe('AssetRegistry CRUD', () => {
+ let reg: AssetRegistry;
+
+ beforeEach(() => {
+ reg = new AssetRegistry();
+ });
+
+ it('addEntry and resolveUuid roundtrip', () => {
+ reg.addEntry(textureEntry(UUID_A, 'assets/player.png'));
+ const entry = reg.resolveUuid(UUID_A);
+ expect(entry).not.toBeNull();
+ expect(entry!.path).toBe('assets/player.png');
+ expect(entry!.type).toBe('texture');
+ expect(entry!.importer).toEqual({ maxSize: 2048 });
+ });
+
+ it('uuidToPath and pathToUuid are inverses', () => {
+ reg.addEntry(textureEntry(UUID_A, 'assets/player.png'));
+ expect(reg.uuidToPath(UUID_A)).toBe('assets/player.png');
+ expect(reg.pathToUuid('assets/player.png')).toBe(UUID_A);
+ });
+
+ it('UUID case is normalized to lower', () => {
+ reg.addEntry(textureEntry(UUID_A.toUpperCase(), 'assets/player.png'));
+ expect(reg.uuidToPath(UUID_A)).toBe('assets/player.png');
+ expect(reg.uuidToPath(UUID_A.toUpperCase())).toBe('assets/player.png');
+ });
+
+ it('re-adding the same UUID with a new path updates the path index', () => {
+ reg.addEntry(textureEntry(UUID_A, 'assets/old/player.png'));
+ reg.addEntry(textureEntry(UUID_A, 'assets/new/player.png'));
+
+ expect(reg.size).toBe(1);
+ expect(reg.uuidToPath(UUID_A)).toBe('assets/new/player.png');
+ expect(reg.pathToUuid('assets/old/player.png')).toBeNull();
+ expect(reg.pathToUuid('assets/new/player.png')).toBe(UUID_A);
+ });
+
+ it('removeByUuid drops both indexes', () => {
+ reg.addEntry(textureEntry(UUID_A, 'assets/player.png'));
+ expect(reg.removeByUuid(UUID_A)).toBe(true);
+ expect(reg.removeByUuid(UUID_A)).toBe(false);
+ expect(reg.resolveUuid(UUID_A)).toBeNull();
+ expect(reg.pathToUuid('assets/player.png')).toBeNull();
+ });
+
+ it('rejects invalid UUID shape', () => {
+ expect(() => reg.addEntry({ uuid: 'not-a-uuid', path: 'a.png', type: 'texture' })).toThrow();
+ });
+
+ it('rejects missing path', () => {
+ expect(() => reg.addEntry({ uuid: UUID_A, path: '', type: 'texture' })).toThrow();
+ });
+
+ it('getAllByType filters by meta.type', () => {
+ reg.addEntry(textureEntry(UUID_A, 'a.png'));
+ reg.addEntry(textureEntry(UUID_B, 'b.png'));
+ reg.addEntry({ uuid: UUID_C, path: 'music.wav', type: 'audio' });
+
+ expect(reg.getAllByType('texture')).toHaveLength(2);
+ expect(reg.getAllByType('audio')).toHaveLength(1);
+ expect(reg.getAllByType('shader')).toHaveLength(0);
+ });
+
+ it('entries() returns a snapshot of all entries', () => {
+ reg.addEntry(textureEntry(UUID_A, 'a.png'));
+ reg.addEntry(textureEntry(UUID_B, 'b.png'));
+ const all = reg.entries();
+ expect(all).toHaveLength(2);
+ expect(all.map(e => e.uuid).sort()).toEqual([UUID_A, UUID_B].sort());
+ });
+
+ it('clear() drops everything', () => {
+ reg.addEntry(textureEntry(UUID_A, 'a.png'));
+ reg.addEntry(textureEntry(UUID_B, 'b.png'));
+ reg.clear();
+ expect(reg.size).toBe(0);
+ expect(reg.resolveUuid(UUID_A)).toBeNull();
+ });
+});
+
+describe('AssetRegistry.loadManifest', () => {
+ it('accepts a well-formed manifest', () => {
+ const reg = new AssetRegistry();
+ const manifest: AssetManifest = {
+ version: '1.0',
+ entries: [
+ textureEntry(UUID_A, 'a.png'),
+ textureEntry(UUID_B, 'b.png'),
+ ],
+ };
+ reg.loadManifest(manifest);
+ expect(reg.size).toBe(2);
+ });
+
+ it('rejects unsupported manifest version', () => {
+ const reg = new AssetRegistry();
+ const bad = { version: '2.0', entries: [] } as unknown as AssetManifest;
+ expect(() => reg.loadManifest(bad)).toThrow(/version/);
+ });
+});
+
+describe('AssetRegistry.resolveRef', () => {
+ let reg: AssetRegistry;
+
+ beforeEach(() => {
+ reg = new AssetRegistry();
+ reg.addEntry(textureEntry(UUID_A, 'assets/player.png'));
+ });
+
+ it('resolves @uuid: refs to the current path', () => {
+ expect(reg.resolveRef(makeUuidRef(UUID_A))).toBe('assets/player.png');
+ });
+
+ it('returns null for an unknown UUID ref', () => {
+ expect(reg.resolveRef(makeUuidRef(UUID_B))).toBeNull();
+ });
+
+ it('returns legacy path strings untouched (backward compat)', () => {
+ expect(reg.resolveRef('assets/other.png')).toBe('assets/other.png');
+ });
+
+ it('resolves after a path move via re-add', () => {
+ const ref = makeUuidRef(UUID_A);
+ expect(reg.resolveRef(ref)).toBe('assets/player.png');
+ reg.addEntry(textureEntry(UUID_A, 'assets/renamed/player.png'));
+ expect(reg.resolveRef(ref)).toBe('assets/renamed/player.png');
+ });
+});