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): single addressable group/label channel + VRAM budget API (T1)
yhh3c6ceb6e048c
diff --git a/sdk/src/asset/AddressableManifest.ts b/sdk/src/asset/AddressableManifest.tsindex 0d536bacf..b6926dd36 100644--- a/sdk/src/asset/AddressableManifest.ts+++ b/sdk/src/asset/AddressableManifest.ts@@ -37,3 +37,105 @@ export interface AddressableManifest {version: '2.0';groups: Record<string, AddressableManifestGroup>;}++/**+ * Delivery mode for an addressable group — the single typed source of truth for+ * what was historically a bare `bundleMode: string` scattered across the cook /+ * export / runtime sides.+ * - `local` — ships in the main package, loaded eagerly (current default; the+ * value `exportWeChat` emits today).+ * - `lazy` — ships in a subpackage (e.g. a WeChat 分包), loaded on demand.+ * - `remote` — fetched from a remote / CDN URL on demand.+ */+export type BundleMode = 'local' | 'lazy' | 'remote';++export const BUNDLE_MODES: readonly BundleMode[] = ['local', 'lazy', 'remote'];++/**+ * Normalize a wire `bundleMode` string to a known {@link BundleMode}. Unknown /+ * missing values map to `local` — the safe default: treated as part of the main+ * package so the asset is always present.+ */+export function normalizeBundleMode(mode: string | undefined | null): BundleMode {+ return mode != null && (BUNDLE_MODES as readonly string[]).includes(mode)+ ? (mode as BundleMode)+ : 'local';+}++/**+ * Queryable view over an {@link AddressableManifest}. The manifest JSON is the+ * wire format; this is the **runtime single source of truth** for group / label+ * / bundle-mode questions, so loaders and exporters never re-walk `groups` by+ * hand and never re-interpret the bare `bundleMode` string.+ */+export class ManifestModel {+ private constructor(private readonly manifest: AddressableManifest) {}++ static fromJson(manifest: AddressableManifest): ManifestModel {+ return new ManifestModel(manifest);+ }++ static empty(): ManifestModel {+ return new ManifestModel({ version: '2.0', groups: {} });+ }++ /** All group names, in manifest order. */+ groupNames(): string[] {+ return Object.keys(this.manifest.groups);+ }++ group(name: string): AddressableManifestGroup | null {+ return this.manifest.groups[name] ?? null;+ }++ /** Typed delivery mode of a group (unknown group → `local`). */+ bundleMode(name: string): BundleMode {+ return normalizeBundleMode(this.manifest.groups[name]?.bundleMode);+ }++ /** Group names whose delivery mode equals `mode`. */+ groupsByMode(mode: BundleMode): string[] {+ return this.groupNames().filter((n) => this.bundleMode(n) === mode);+ }++ /** Assets in a group (empty for an unknown group). */+ assetsInGroup(name: string): AddressableManifestAsset[] {+ const g = this.manifest.groups[name];+ return g ? Object.values(g.assets) : [];+ }++ /** Asset paths in a group. */+ assetPathsInGroup(name: string): string[] {+ return this.assetsInGroup(name).map((a) => a.path);+ }++ /** Every asset across all groups. */+ allAssets(): AddressableManifestAsset[] {+ const out: AddressableManifestAsset[] = [];+ for (const g of Object.values(this.manifest.groups)) {+ out.push(...Object.values(g.assets));+ }+ return out;+ }++ /** Assets carrying `label` across all groups, deduped by path. */+ assetsByLabel(label: string): AddressableManifestAsset[] {+ const seen = new Set<string>();+ const out: AddressableManifestAsset[] = [];+ for (const a of this.allAssets()) {+ if (a.labels.includes(label) && !seen.has(a.path)) {+ seen.add(a.path);+ out.push(a);+ }+ }+ return out;+ }++ /** Find an asset by its path or its address (null if absent). */+ findAsset(pathOrAddress: string): AddressableManifestAsset | null {+ for (const a of this.allAssets()) {+ if (a.path === pathOrAddress || a.address === pathOrAddress) return a;+ }+ return null;+ }+}diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 9b0beba41..71e53f2c6 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -2,6 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { Backend } from './Backend';import { Catalog, type AtlasFrameInfo } from './Catalog';+import { ManifestModel, type AddressableManifest } from './AddressableManifest';import type {AssetLoader, LoadContext, TextureResult, SpineResult,MaterialResult, FontResult, AudioResult, AnimClipResult,@@ -76,6 +77,12 @@ async function runWithConcurrency(export interface AssetsOptions {backend: Backend;catalog?: Catalog;+ /**+ * Addressable manifest (groups + bundle modes). When set, enables+ * `loadGroup(name)`. Accepts the raw manifest JSON or a pre-built+ * {@link ManifestModel}. Optional — label/path loading works without it.+ */+ manifest?: AddressableManifest | ManifestModel;module: ESEngineModule;/*** Lazy accessor for the owning app's Audio API. AudioAssetLoader@@ -93,6 +100,10 @@ export interface AssetBundle {fonts: Map<string, FontResult>;}+function emptyBundle(): AssetBundle {+ return { textures: new Map(), materials: new Map(), spine: new Map(), fonts: new Map() };+}+/*** Describes one asset a scene / prefab referenced that couldn't be* materialized into a usable handle. The caller of preloadSceneAssets@@ -135,6 +146,7 @@ export class Assets {private baseUrl_?: string;private module_: ESEngineModule;+ private manifestModel_: ManifestModel | null = null;private getAudio_: () => import('../audio/Audio').AudioAPI | null;private getSpriteAnimation_: () => import('../animation/SpriteAnimator').SpriteAnimationApi | null;private loaders_ = new Map<string, AssetLoader<unknown>>();@@ -161,6 +173,7 @@ export class Assets {this.module_ = options.module;this.getAudio_ = options.getAudio ?? (() => null);this.getSpriteAnimation_ = options.getSpriteAnimation ?? (() => null);+ this.setManifest(options.manifest ?? null);this.textureLoader_ = new TextureLoader(options.module);this.spineLoader_ = new SpineAssetLoader(options.module);@@ -286,54 +299,87 @@ export class Assets {}// =========================================================================- // Label Batch Load+ // Addressable Manifest (groups / bundle modes)+ // =========================================================================++ /**+ * Set (or clear) the addressable manifest used by {@link loadGroup}.+ * Accepts the raw manifest JSON or a pre-built {@link ManifestModel};+ * `null` clears it.+ */+ setManifest(manifest: AddressableManifest | ManifestModel | null): void {+ this.manifestModel_ =+ manifest == null ? null+ : manifest instanceof ManifestModel ? manifest+ : ManifestModel.fromJson(manifest);+ }++ getManifest(): ManifestModel | null {+ return this.manifestModel_;+ }++ // =========================================================================+ // Batch Load (by label / by group)// =========================================================================async loadByLabel(label: string,onProgress?: (loaded: number, total: number) => void,): Promise<AssetBundle> {- const paths = this.catalog.getByLabel(label);- const bundle: AssetBundle = {- textures: new Map(),- materials: new Map(),- spine: new Map(),- fonts: new Map(),- };-+ const bundle = emptyBundle();let loadedCount = 0;const promises: Promise<void>[] = [];-const track = (p: Promise<void>): Promise<void> =>p.then(() => { onProgress?.(++loadedCount, totalCount); }).catch(() => { onProgress?.(++loadedCount, totalCount); });- for (const path of paths) {+ for (const path of this.catalog.getByLabel(label)) {const entry = this.catalog.getEntry(path);if (!entry) continue;+ const task = this.bundleLoadTask_(path, entry.type, bundle);+ if (task) promises.push(track(task));+ }- switch (entry.type) {- case 'texture':- promises.push(track(- this.loadTexture(path).then(r => { bundle.textures.set(path, r); }),- ));- break;- case 'material':- promises.push(track(- this.loadMaterial(path).then(r => { bundle.materials.set(path, r); }),- ));- break;- case 'spine':- promises.push(track(- this.loadSpine(path).then(r => { bundle.spine.set(path, r); }),- ));- break;- case 'font':- promises.push(track(- this.loadFont(path).then(r => { bundle.fonts.set(path, r); }),- ));- break;- }+ const totalCount = promises.length;+ onProgress?.(0, totalCount);+ loadedCount = 0;++ await Promise.allSettled(promises);+ return bundle;+ }++ /**+ * Load every asset in an addressable group through the typed loaders,+ * warming the cache (and populating the returned bundle for the four+ * displayable types). Requires a manifest (see {@link setManifest}); with+ * no manifest set, this is a no-op returning an empty bundle.+ *+ * This is the single group-loading channel — the basis for on-demand /+ * subpackage delivery. It dispatches through the same per-type loaders as+ * {@link loadByLabel}, so the two never diverge.+ */+ async loadGroup(+ groupName: string,+ onProgress?: (loaded: number, total: number) => void,+ ): Promise<AssetBundle> {+ const bundle = emptyBundle();+ const model = this.manifestModel_;+ if (!model) {+ log.warn('asset', `loadGroup('${groupName}') called but no manifest is set`);+ onProgress?.(0, 0);+ return bundle;+ }++ let loadedCount = 0;+ const promises: Promise<void>[] = [];+ const track = (p: Promise<void>): Promise<void> =>+ p.then(() => { onProgress?.(++loadedCount, totalCount); })+ .catch(() => { onProgress?.(++loadedCount, totalCount); });++ for (const asset of model.assetsInGroup(groupName)) {+ const path = this.resolveLoadPath_(asset.path);+ const task = this.groupLoadTask_(path, asset.type, bundle);+ if (task) promises.push(track(task));}const totalCount = promises.length;@@ -344,6 +390,48 @@ export class Assets {return bundle;}+ /**+ * Load one asset into the displayable bundle maps. Returns the in-flight+ * promise for the four bundle-able types (texture / material / spine /+ * font), or null for any other type. Shared by `loadByLabel` and+ * `loadGroup` so both dispatch through one channel.+ */+ private bundleLoadTask_(+ path: string, type: string, bundle: AssetBundle,+ ): Promise<void> | null {+ switch (type) {+ case 'texture':+ return this.loadTexture(path).then(r => { bundle.textures.set(path, r); });+ case 'material':+ return this.loadMaterial(path).then(r => { bundle.materials.set(path, r); });+ case 'spine':+ return this.loadSpine(path).then(r => { bundle.spine.set(path, r); });+ case 'font':+ case 'bitmap-font':+ return this.loadFont(path).then(r => { bundle.fonts.set(path, r); });+ default:+ return null;+ }+ }++ /**+ * Like {@link bundleLoadTask_} but also warms the cache for non-displayable+ * types that have a typed loader (prefab, audio), so a whole group / sub-+ * package preloads. Raw types (json / text / binary) and unknowns return+ * null — they have no typed loader and are fetched lazily on demand.+ */+ private groupLoadTask_(+ path: string, type: string, bundle: AssetBundle,+ ): Promise<void> | null {+ const bundled = this.bundleLoadTask_(path, type, bundle);+ if (bundled) return bundled;+ switch (type) {+ case 'prefab': return this.loadPrefab(path).then(() => {});+ case 'audio': return this.loadAudio(path).then(() => {});+ default: return null;+ }+ }+// =========================================================================// Raw Data (escape hatch)// =========================================================================diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.tsindex 5966f0d15..5077acbcd 100644--- a/sdk/src/asset/index.ts+++ b/sdk/src/asset/index.ts@@ -5,6 +5,10 @@ export {type AddressableManifest,type AddressableManifestGroup,type AddressableManifestAsset,+ type BundleMode,+ BUNDLE_MODES,+ normalizeBundleMode,+ ManifestModel,} from './AddressableManifest';export { xxh64, contentHashHex, contentHashOf } from './contentHash';export { AsyncCache } from './AsyncCache';diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 49fa8d81d..93e87a53d 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -56,12 +56,22 @@ export {type AddressableManifest,type AddressableManifestGroup,type AddressableManifestAsset,+ type BundleMode,+ BUNDLE_MODES,+ normalizeBundleMode,+ ManifestModel,type AssetsData,type TextureInfo,type SpineLoadResult,type AssetRefInfo,} from './asset';+// =============================================================================+// Resource budget (VRAM)+// =============================================================================++export { setTextureBudget } from './resourceManager';+// =============================================================================// Scene// =============================================================================diff --git a/sdk/src/resourceManager.ts b/sdk/src/resourceManager.tsindex 5d6e8e62b..f59f4714e 100644--- a/sdk/src/resourceManager.ts+++ b/sdk/src/resourceManager.ts@@ -53,6 +53,19 @@ export function requireResourceManager(): CppResourceManager {return rm_;}+/**+ * Set the resident GPU-texture byte budget. When resident bytes exceed this,+ * the C++ ResourcePool evicts least-recently-used unreferenced textures. `0`+ * (the default) disables caching — a texture frees the moment its refcount hits+ * zero. Negative / fractional inputs are clamped to a non-negative integer.+ *+ * This is the single game-facing surface over the C++ budget; there is no+ * parallel TS-side budget to drift from it.+ */+export function setTextureBudget(bytes: number): void {+ requireResourceManager().setTextureBudget(Math.max(0, Math.floor(bytes)));+}+export function evictTextureDimensions(handle: number): void {dimsCache_.delete(handle);}diff --git a/sdk/tests/asset-group-loading.test.ts b/sdk/tests/asset-group-loading.test.tsindex 8896d6504..d0be7e53e 100644--- a/sdk/tests/asset-group-loading.test.ts+++ b/sdk/tests/asset-group-loading.test.ts@@ -3,6 +3,7 @@import { describe, it, expect, vi } from 'vitest';import { Assets } from '../src/asset/Assets';import { Catalog, type CatalogData } from '../src/asset/Catalog';+import type { AddressableManifest } from '../src/asset/AddressableManifest';import type { Backend } from '../src/asset/Backend';const mockModule = {@@ -108,3 +109,80 @@ describe('Assets.loadByLabel with progress', () => {expect(progressCalls).toContainEqual([0, 0]);});});++function createManifest(): AddressableManifest {+ return {+ version: '2.0',+ groups: {+ main: {+ bundleMode: 'local',+ labels: [],+ assets: {+ 'tex1.png': { path: 'tex1.png', type: 'texture', size: 0, labels: ['ui'] },+ 'tex2.png': { path: 'tex2.png', type: 'texture', size: 0, labels: ['ui'] },+ },+ },+ extra: {+ bundleMode: 'lazy',+ labels: [],+ assets: {+ 'tex3.png': { path: 'tex3.png', type: 'texture', size: 0, labels: ['gameplay'] },+ },+ },+ },+ };+}++describe('Assets.loadGroup', () => {+ it('dispatches every asset in a group through the typed loader, into the bundle', async () => {+ const assets = createAssets();+ assets.setManifest(createManifest());+ // Spy the single texture channel so the assertion is about loadGroup's+ // dispatch, not the mock's image-decode pipeline.+ const spy = vi.spyOn(assets, 'loadTexture')+ .mockResolvedValue({ handle: 42, width: 64, height: 64 } as any);++ const progressCalls: [number, number][] = [];+ const bundle = await assets.loadGroup('main', (loaded, total) => {+ progressCalls.push([loaded, total]);+ });++ expect(spy.mock.calls.map(c => c[0]).sort()).toEqual(['tex1.png', 'tex2.png']);+ expect(bundle.textures.size).toBe(2);+ expect(progressCalls[0]).toEqual([0, 2]);+ const last = progressCalls[progressCalls.length - 1];+ expect(last[0]).toBe(last[1]);+ });++ it('loads a different group independently', async () => {+ const assets = createAssets();+ assets.setManifest(createManifest());+ const spy = vi.spyOn(assets, 'loadTexture')+ .mockResolvedValue({ handle: 7, width: 1, height: 1 } as any);+ const bundle = await assets.loadGroup('extra');+ expect(spy).toHaveBeenCalledTimes(1);+ expect(spy).toHaveBeenCalledWith('tex3.png');+ expect(bundle.textures.size).toBe(1);+ });++ it('reports 0/0 and an empty bundle for an unknown group', async () => {+ const assets = createAssets();+ assets.setManifest(createManifest());+ const progressCalls: [number, number][] = [];+ const bundle = await assets.loadGroup('missing', (loaded, total) => {+ progressCalls.push([loaded, total]);+ });+ expect(bundle.textures.size).toBe(0);+ expect(progressCalls).toContainEqual([0, 0]);+ });++ it('is a no-op when no manifest is set', async () => {+ const assets = createAssets();+ const progressCalls: [number, number][] = [];+ const bundle = await assets.loadGroup('main', (loaded, total) => {+ progressCalls.push([loaded, total]);+ });+ expect(bundle.textures.size).toBe(0);+ expect(progressCalls).toContainEqual([0, 0]);+ });+});diff --git a/sdk/tests/manifest-model.test.ts b/sdk/tests/manifest-model.test.tsnew file mode 100644index 000000000..0485e4b4f--- /dev/null+++ b/sdk/tests/manifest-model.test.ts@@ -0,0 +1,101 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import {+ ManifestModel,+ normalizeBundleMode,+ type AddressableManifest,+} from '../src/asset/AddressableManifest';++function manifest(): AddressableManifest {+ return {+ version: '2.0',+ groups: {+ main: {+ bundleMode: 'local',+ labels: [],+ assets: {+ 'a.png': { path: 'a.png', type: 'texture', size: 1, labels: ['ui'] },+ 'b.mat': { path: 'b.mat', type: 'material', size: 2, labels: ['ui', 'fx'] },+ },+ },+ level1: {+ bundleMode: 'lazy',+ labels: [],+ assets: {+ 'c.png': { path: 'c.png', address: '@c', type: 'texture', size: 3, labels: ['fx'] },+ },+ },+ cdn: {+ bundleMode: 'remote',+ labels: [],+ assets: {},+ },+ },+ };+}++describe('normalizeBundleMode', () => {+ it('passes through known modes', () => {+ expect(normalizeBundleMode('local')).toBe('local');+ expect(normalizeBundleMode('lazy')).toBe('lazy');+ expect(normalizeBundleMode('remote')).toBe('remote');+ });++ it('maps unknown / missing to local (safe default)', () => {+ expect(normalizeBundleMode('garbage')).toBe('local');+ expect(normalizeBundleMode('')).toBe('local');+ expect(normalizeBundleMode(undefined)).toBe('local');+ expect(normalizeBundleMode(null)).toBe('local');+ });+});++describe('ManifestModel', () => {+ const model = () => ManifestModel.fromJson(manifest());++ it('lists group names in manifest order', () => {+ expect(model().groupNames()).toEqual(['main', 'level1', 'cdn']);+ });++ it('returns typed bundle modes (unknown group → local)', () => {+ const m = model();+ expect(m.bundleMode('main')).toBe('local');+ expect(m.bundleMode('level1')).toBe('lazy');+ expect(m.bundleMode('cdn')).toBe('remote');+ expect(m.bundleMode('does-not-exist')).toBe('local');+ });++ it('filters groups by mode', () => {+ expect(model().groupsByMode('lazy')).toEqual(['level1']);+ expect(model().groupsByMode('local')).toEqual(['main']);+ expect(model().groupsByMode('remote')).toEqual(['cdn']);+ });++ it('lists assets and paths in a group', () => {+ expect(model().assetPathsInGroup('main')).toEqual(['a.png', 'b.mat']);+ expect(model().assetsInGroup('level1')).toHaveLength(1);+ expect(model().assetsInGroup('missing')).toEqual([]);+ });++ it('collects all assets across groups', () => {+ expect(model().allAssets()).toHaveLength(3);+ });++ it('finds assets by label, deduped, across groups', () => {+ const ui = model().assetsByLabel('ui').map(a => a.path);+ expect(ui).toEqual(['a.png', 'b.mat']);+ const fx = model().assetsByLabel('fx').map(a => a.path);+ expect(fx).toEqual(['b.mat', 'c.png']);+ });++ it('finds an asset by path or address', () => {+ expect(model().findAsset('a.png')?.path).toBe('a.png');+ expect(model().findAsset('@c')?.path).toBe('c.png');+ expect(model().findAsset('nope')).toBeNull();+ });++ it('empty() has no groups', () => {+ expect(ManifestModel.empty().groupNames()).toEqual([]);+ expect(ManifestModel.empty().allAssets()).toEqual([]);+ });+});diff --git a/sdk/tests/texture-budget.test.ts b/sdk/tests/texture-budget.test.tsnew file mode 100644index 000000000..864dea0dc--- /dev/null+++ b/sdk/tests/texture-budget.test.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import {+ initResourceManager,+ shutdownResourceManager,+ setTextureBudget,+} from '../src/resourceManager';++const setBudget = vi.fn();+const mockRm = {+ setTextureBudget: setBudget,+ getTextureDimensions: vi.fn(() => null),+} as any;++beforeEach(() => {+ setBudget.mockClear();+ initResourceManager(mockRm);+});++afterEach(() => {+ shutdownResourceManager();+});++describe('setTextureBudget', () => {+ it('forwards the budget to the C++ ResourceManager', () => {+ setTextureBudget(4 * 1024 * 1024);+ expect(setBudget).toHaveBeenCalledWith(4 * 1024 * 1024);+ });++ it('clamps negative budgets to 0', () => {+ setTextureBudget(-1);+ expect(setBudget).toHaveBeenCalledWith(0);+ });++ it('floors fractional budgets to an integer', () => {+ setTextureBudget(10.9);+ expect(setBudget).toHaveBeenCalledWith(10);+ });++ it('throws if no ResourceManager is initialized', () => {+ shutdownResourceManager();+ expect(() => setTextureBudget(1)).toThrow();+ });+});