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.

fix(assets): releaseGroup dropped fonts on the floor

esengine7caf31a05a7a
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 0be6a6b29..2dfb95a21 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -157,6 +157,63 @@ function emptyBundle(): AssetBundle {
return { textures: new Map(), materials: new Map(), spine: new Map(), fonts: new Map() };
}
+
+/**
+ * How one addressable asset type is acquired and given back.
+ *
+ * ONE table, because two of them drift: load handled `font` and release did
+ * not, so every group carrying a font kept its reference forever. A type that
+ * can be loaded and has no release channel now has to say so out loud.
+ */
+interface GroupAssetChannel {
+ load(assets: Assets, path: string, bundle: AssetBundle): Promise<void>;
+ /** null when something else owns the lifetime — see `spine`. */
+ release: ((assets: Assets, path: string) => void) | null;
+ /** In the bundle `loadByLabel` returns: the types a scene can display. */
+ displayable: boolean;
+}
+
+const GROUP_ASSET_CHANNELS: Readonly<Record<string, GroupAssetChannel>> = {
+ texture: {
+ load: (a, path, b) => a.loadTexture(path).then((r) => { b.textures.set(path, r); }),
+ release: (a, path) => a.releaseTexture(path),
+ displayable: true,
+ },
+ material: {
+ load: (a, path, b) => a.loadMaterial(path).then((r) => { b.materials.set(path, r); }),
+ release: (a, path) => a.releaseTyped('material', path),
+ displayable: true,
+ },
+ font: {
+ load: (a, path, b) => a.loadFont(path).then((r) => { b.fonts.set(path, r); }),
+ release: (a, path) => a.releaseTyped('font', path),
+ displayable: true,
+ },
+ 'bitmap-font': {
+ load: (a, path, b) => a.loadFont(path).then((r) => { b.fonts.set(path, r); }),
+ release: (a, path) => a.releaseTyped('font', path),
+ displayable: true,
+ },
+ spine: {
+ load: (a, path, b) => a.loadSpine(path).then((r) => { b.spine.set(path, r); }),
+ // Skeletons bind to spawned entities and are owned by the
+ // SpineAssetLoader / SpineManager lifecycle; releasing one here could
+ // yank it out from under a live entity.
+ release: null,
+ displayable: true,
+ },
+ prefab: {
+ load: (a, path) => a.loadPrefab(path).then(() => {}),
+ release: (a, path) => a.releaseTyped('prefab', path),
+ displayable: false,
+ },
+ audio: {
+ load: (a, path) => a.loadAudio(path).then(() => {}),
+ release: (a, path) => a.releaseTyped('audio', path),
+ displayable: false,
+ },
+};
+
/**
* Describes one asset a scene / prefab referenced that couldn't be
* materialized into a usable handle. The caller of preloadSceneAssets
@@ -630,20 +687,13 @@ export class Assets {
log.warn('asset', `releaseGroup('${groupName}') called but no manifest is set`);
return;
}
+ const mode = model.bundleMode(groupName);
for (const asset of model.assetsInGroup(groupName)) {
- const path = this.resolveLoadPath_(asset.path);
- switch (asset.type) {
- case 'texture': this.releaseTexture(path); break;
- case 'material': this.releaseTyped('material', path); break;
- case 'bitmap-font': this.releaseTyped('font', path); break;
- case 'prefab': this.releaseTyped('prefab', path); break;
- case 'audio': this.releaseTyped('audio', path); break;
- // Spine skeletons bind to spawned entities and are owned by
- // the SpineAssetLoader / SpineManager lifecycle, not the
- // generic cache — releasing them here could yank a skeleton
- // out from under a live entity.
- default: break;
- }
+ // The SAME path loadGroup acquired under. Resolving it a different
+ // way here would release a key nobody holds, which is a leak that
+ // looks exactly like a working release.
+ const path = this.manifestAssetUrl_(asset.path, mode === 'remote');
+ GROUP_ASSET_CHANNELS[asset.type]?.release?.(this, path);
}
}
@@ -827,19 +877,9 @@ export class Assets {
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;
- }
+ const channel = GROUP_ASSET_CHANNELS[type];
+ if (!channel?.displayable) return null;
+ return channel.load(this, path, bundle);
}
/**
@@ -851,13 +891,8 @@ export class Assets {
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;
- }
+ const channel = GROUP_ASSET_CHANNELS[type];
+ return channel ? channel.load(this, path, bundle) : null;
}
/**
@@ -1243,7 +1278,11 @@ export class Assets {
if (path !== null) this.releaseTyped('material', path);
}
- private releaseTyped(type: string, ref: string): void {
+ /**
+ * @internal Release one reference to a typed asset by path — the door the
+ * group channel table uses. Game code calls the named release* methods.
+ */
+ releaseTyped(type: string, ref: string): void {
const path = this.resolveLoadPath_(ref);
// NOT gated on a live cache entry: a generation superseded by
// invalidate() is out of the cache while its holders still owe a
diff --git a/sdk/tests/asset-group-channel-parity.test.ts b/sdk/tests/asset-group-channel-parity.test.ts
new file mode 100644
index 000000000..85e8b0e7d
--- /dev/null
+++ b/sdk/tests/asset-group-channel-parity.test.ts
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Every type loadGroup acquires, releaseGroup gives back.
+ *
+ * They were two switch statements. Load handled `font`; release listed only
+ * `bitmap-font`, so a group carrying a font held its reference for the life of
+ * the process — and nothing failed, because no test walked both halves for the
+ * same type. Now one table drives both, and this walks every entry in it.
+ *
+ * A new addressable type is a new row here. That is the point: a row with a
+ * loader and no release has to say so out loud (spine does), rather than being
+ * a case somebody forgot to add to the second switch.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { Assets } from '../src/asset/Assets';
+import type { AddressableManifest, AddressableAssetType } from '../src/asset/AddressableManifest';
+import type { Backend } from '../src/asset/Backend';
+
+vi.mock('../src/wasm/resourceManager', () => ({
+ initResourceManager: vi.fn(),
+ shutdownResourceManager: vi.fn(),
+ getResourceManager: vi.fn(() => null),
+ requireResourceManager: vi.fn(() => ({
+ releaseTexture: vi.fn(),
+ getTextureDimensions: vi.fn(() => null),
+ setTextureMetadata: vi.fn(),
+ })),
+ evictTextureDimensions: vi.fn(),
+ textureDimensions: vi.fn(() => null),
+}));
+
+const mockModule = { _malloc: () => 0, _free: () => {}, HEAPU8: new Uint8Array(8) } as never;
+
+const backend = {
+ fetchBinary: async () => new ArrayBuffer(8),
+ fetchText: async () => '{}',
+ resolveUrl: (p: string) => p,
+} as unknown as Backend;
+
+/**
+ * One row per addressable type a group can carry, with the loader to stub and
+ * the release the type is supposed to route to. `releasesVia: null` means the
+ * type's lifetime is owned elsewhere and releaseGroup must NOT touch it.
+ */
+const TYPES: Array<{
+ type: AddressableAssetType;
+ loadMethod: keyof Assets;
+ releasesVia: string | null;
+}> = [
+ { type: 'texture', loadMethod: 'loadTexture', releasesVia: 'texture' },
+ { type: 'material', loadMethod: 'loadMaterial', releasesVia: 'material' },
+ { type: 'font', loadMethod: 'loadFont', releasesVia: 'font' },
+ { type: 'bitmap-font', loadMethod: 'loadFont', releasesVia: 'font' },
+ { type: 'prefab', loadMethod: 'loadPrefab', releasesVia: 'prefab' },
+ { type: 'audio', loadMethod: 'loadAudio', releasesVia: 'audio' },
+ // Skeletons bind to spawned entities and belong to the SpineManager
+ // lifecycle; releasing one here could yank it from under a live entity.
+ { type: 'spine', loadMethod: 'loadSpine', releasesVia: null },
+];
+
+function manifestWith(type: AddressableAssetType): AddressableManifest {
+ return {
+ version: '2.0',
+ groups: {
+ dlc: {
+ bundleMode: 'local',
+ labels: [],
+ assets: { 'a.bin': { path: 'a.bin', type, size: 0, labels: [] } },
+ },
+ },
+ } as AddressableManifest;
+}
+
+describe.each(TYPES)('group channel: $type', (row) => {
+ it('is loaded by loadGroup and released by releaseGroup', async () => {
+ const assets = Assets.create({ backend, module: mockModule });
+ assets.setManifest(manifestWith(row.type));
+
+ const load = vi.spyOn(assets, row.loadMethod as 'loadTexture')
+ .mockResolvedValue({ handle: 1, width: 1, height: 1 } as never);
+ // releaseTexture and releaseTyped are the only two release doors; both
+ // are watched so a row cannot pass by going through neither.
+ const releaseTexture = vi.spyOn(assets, 'releaseTexture').mockImplementation(() => {});
+ const releaseTyped = vi.spyOn(assets, 'releaseTyped').mockImplementation(() => {});
+
+ await assets.loadGroup('dlc');
+ expect(load, `loadGroup never loaded a ${row.type}`).toHaveBeenCalledWith('a.bin');
+
+ assets.releaseGroup('dlc');
+
+ if (row.releasesVia === null) {
+ expect(releaseTexture, `releaseGroup released a ${row.type}, whose lifetime is owned elsewhere`).not.toHaveBeenCalled();
+ expect(releaseTyped, `releaseGroup released a ${row.type}, whose lifetime is owned elsewhere`).not.toHaveBeenCalled();
+ return;
+ }
+ if (row.releasesVia === 'texture') {
+ expect(releaseTexture, 'a texture was loaded by the group and never released').toHaveBeenCalledWith('a.bin');
+ return;
+ }
+ expect(
+ releaseTyped.mock.calls.map((c) => c[0]),
+ `a ${row.type} was loaded by the group and never released`,
+ ).toContain(row.releasesVia);
+ });
+});
+
+describe('group release addressing', () => {
+ it('releases the same path it loaded', async () => {
+ // A release that resolves the path differently frees a key nobody holds:
+ // a leak that looks exactly like a working release.
+ const assets = Assets.create({ backend, module: mockModule });
+ assets.setManifest(manifestWith('texture'));
+ const load = vi.spyOn(assets, 'loadTexture')
+ .mockResolvedValue({ handle: 1, width: 1, height: 1 } as never);
+ const release = vi.spyOn(assets, 'releaseTexture').mockImplementation(() => {});
+
+ await assets.loadGroup('dlc');
+ assets.releaseGroup('dlc');
+
+ expect(release.mock.calls[0][0]).toBe(load.mock.calls[0][0]);
+ });
+});