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): release app-owned loaders during plugin cleanup

yhh8ee4bc5d2c4d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 37bb41967..0e7c67499 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Fixed
+- **Asset loaders release their App's resources on shutdown.** Asset plugin cleanup releases the default loader and any runtime replacement, clearing reference bookkeeping and making held textures evictable before the renderer is reused. Shared plugin instances clean up only the selected App; stopped device recovery cannot continue through a later loader. Unused loaders can release safely before a native resource manager exists.
+
- **Particle gradient uploads survive WASM memory growth.** Color, size, and speed LUT uploads read the current heap after allocating their staging memory, preventing detached-buffer errors when a large scene causes memory expansion. LUTs borrowed from the heap are preserved before allocation; independent arrays avoid this copy. Staging memory is still released if the native setter throws.
- **Web focus loss cancels held pointer input and pending edges.** Blurring or hiding the game and replacing its input target releases host key, mouse, and touch tracking, clears stale render/fixed-step edges, and cancels UI presses without clicking them. The next touch can become the primary pointer, and late releases from the cancelled gesture are ignored.
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index abf2358ba..2cb6d234c 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -893,6 +893,7 @@ value: T
## AssetPlugin — class @experimental
```
build: (app: App) => void
+cleanup: (app?: App) => void
name: string
static new (): AssetPlugin
static prototype: AssetPlugin
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 085e43665..90e49c91d 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -893,6 +893,7 @@ value: T
## AssetPlugin — class @experimental
```
build: (app: App) => void
+cleanup: (app?: App) => void
name: string
static new (): AssetPlugin
static prototype: AssetPlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index e9b028e04..9b1fe932b 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -888,6 +888,7 @@ value: T
## AssetPlugin — class @experimental
```
build: (app: App) => void
+cleanup: (app?: App) => void
name: string
static new (): AssetPlugin
static prototype: AssetPlugin
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 100af1e6c..99174b370 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -888,6 +888,7 @@ value: T
## AssetPlugin — class @experimental
```
build: (app: App) => void
+cleanup: (app?: App) => void
name: string
static new (): AssetPlugin
static prototype: AssetPlugin
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 3ee71f612..4bb2f86ec 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -888,6 +888,7 @@ value: T
## AssetPlugin — class @experimental
```
build: (app: App) => void
+cleanup: (app?: App) => void
name: string
static new (): AssetPlugin
static prototype: AssetPlugin
diff --git a/sdk/src/asset/AssetPlugin.ts b/sdk/src/asset/AssetPlugin.ts
index 97a63b385..89007963c 100644
--- a/sdk/src/asset/AssetPlugin.ts
+++ b/sdk/src/asset/AssetPlugin.ts
@@ -12,6 +12,13 @@ import { Audio, type AudioAPI } from '../audio/Audio';
import { SpriteAnimation, type SpriteAnimationAPI } from '../animation/SpriteAnimator';
import { Localization, type LocalizationAPI } from '../i18n/Localization';
import { log } from '../util/logger';
+import { disposeAll } from '../util/disposeAll';
+
+interface AssetPluginState {
+ created: AssetsClass;
+ current: () => AssetsClass | null;
+ released: boolean;
+}
/**
* The asset loader a system receives from `Res(Assets)`.
@@ -39,8 +46,11 @@ export const Assets = defineResource<AssetsData>(
export class AssetPlugin implements Plugin {
name = 'asset';
+ private readonly states_ = new WeakMap<App, AssetPluginState>();
+ private latestState_: AssetPluginState | null = null;
build(app: App): void {
+ this.cleanup(app);
const module = app.wasmModule;
if (!module) {
log.warn('asset', 'AssetPlugin: No WASM module available');
@@ -72,7 +82,24 @@ export class AssetPlugin implements Plugin {
() => app.hasResource(Assets) ? app.getResource(Assets) : null);
app.insertResource(Assets, assets);
- this.driveDeviceRecovery_(app);
+ const state: AssetPluginState = { created: assets,
+ current: () => app.hasResource(Assets) ? app.getResource(Assets) : null, released: false };
+ this.states_.set(app, state);
+ this.latestState_ = state;
+ this.driveDeviceRecovery_(app, state);
+ }
+
+ /** Release both the default loader and any runtime replacement owned by this App. */
+ cleanup(app?: App): void {
+ const state = app ? this.states_.get(app) : this.latestState_;
+ if (!state || state.released) return;
+ state.released = true;
+ if (app) this.states_.delete(app);
+ if (state === this.latestState_) this.latestState_ = null;
+ const current = state.current();
+ disposeAll(current && current !== state.created ? [state.created, current] : [state.created], assets => {
+ try { assets.releaseAll(); } finally { assets.getRefCounter()?.clear(); }
+ });
}
/**
@@ -81,13 +108,14 @@ export class AssetPlugin implements Plugin {
* lost its GPU stayed lost. Timed off UNSCALED delta — a paused game still
* has to come back — and backed off, since each attempt re-fetches content.
*/
- private driveDeviceRecovery_(app: App): void {
+ private driveDeviceRecovery_(app: App, state: AssetPluginState): void {
let inFlight = false;
let waited = 0;
let backoff = 0;
let downtime = 0;
app.addSystemToSchedule(Schedule.First, defineSystem([], () => {
+ if (state.released) return;
const status = getDeviceStatus();
if (status === DeviceStatus.Live || status === DeviceStatus.Dead) {
backoff = 0;
@@ -108,8 +136,9 @@ export class AssetPlugin implements Plugin {
// decoder. Never recover the instance captured during plugin build.
const recoverCurrent = async (): Promise<boolean> => {
let assets = app.hasResource(Assets) ? app.getResource(Assets) : null;
- while (assets) {
+ while (assets && !state.released) {
const whole = await assets.recoverFromDeviceLoss();
+ if (state.released) return false;
const current = app.hasResource(Assets) ? app.getResource(Assets) : null;
if (current === assets) return whole;
assets = current;
@@ -118,6 +147,7 @@ export class AssetPlugin implements Plugin {
};
void recoverCurrent()
.then((whole) => {
+ if (state.released) return;
if (whole) {
log.info('asset', `Device recovered after ${lostFor.toFixed(1)}s`);
backoff = 0;
@@ -126,6 +156,7 @@ export class AssetPlugin implements Plugin {
backoff = Math.min(backoff ? backoff * 2 : RECOVERY_RETRY_S, RECOVERY_RETRY_MAX_S);
})
.catch((e) => {
+ if (state.released) return;
log.warn('asset', 'Device recovery threw; will retry', e);
backoff = Math.min(backoff ? backoff * 2 : RECOVERY_RETRY_S, RECOVERY_RETRY_MAX_S);
})
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index c3178ade5..43df1a6ee 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -2323,6 +2323,7 @@ export class Assets {
for (const info of this.textureCache_.values()) handles.add(info.handle);
this.textureCache_.clearAll();
for (const { value } of this.textureRefs_.drain()) handles.add(value);
+ if (handles.size === 0) return;
const rm = requireResourceManager();
disposeAll([...handles], handle => {
evictTextureDimensions(handle);
diff --git a/sdk/tests/asset-empty-release.test.ts b/sdk/tests/asset-empty-release.test.ts
new file mode 100644
index 000000000..f6a5034a8
--- /dev/null
+++ b/sdk/tests/asset-empty-release.test.ts
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { expect, it } from 'vitest';
+import { Assets } from '../src/asset/Assets';
+import { HttpBackend } from '../src/asset/Backend';
+import { AppContext, getDefaultContext, setDefaultContext } from '../src/ecs/context';
+import type { ESEngineModule } from '../src/wasm';
+
+it('releases an unused loader before a native resource manager exists, repeatedly', () => {
+ const previous = getDefaultContext(); setDefaultContext(new AppContext());
+ try {
+ const assets = Assets.create({ backend: new HttpBackend({ baseUrl: '' }), module: {} as ESEngineModule });
+ expect(() => assets.releaseAll()).not.toThrow();
+ expect(() => assets.releaseAll()).not.toThrow();
+ expect(assets.sizes().refRows).toBe(0);
+ } finally { setDefaultContext(previous); }
+});
diff --git a/sdk/tests/asset-plugin-lifecycle.test.ts b/sdk/tests/asset-plugin-lifecycle.test.ts
new file mode 100644
index 000000000..110defba9
--- /dev/null
+++ b/sdk/tests/asset-plugin-lifecycle.test.ts
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+const device = vi.hoisted(() => ({ status: 0 }));
+vi.mock('../src/render/renderer', async original => ({
+ ...await original<typeof import('../src/render/renderer')>(), getDeviceStatus: () => device.status,
+}));
+import { App } from '../src/app/app';
+import { AssetPlugin, Assets } from '../src/asset/AssetPlugin';
+import { Assets as AssetsClass } from '../src/asset/Assets';
+import { AssetRefCounter } from '../src/asset/AssetRefCounter';
+import type { ESEngineModule } from '../src/wasm';
+const apps: App[] = [];
+function loader() {
+ const counter = new AssetRefCounter();
+ return { releaseAll: vi.fn(), getRefCounter: () => counter, setRefCounter: vi.fn(),
+ getTextureLoader: () => ({ setTranscoderProvider: vi.fn() }),
+ recoverFromDeviceLoss: vi.fn().mockResolvedValue(true) };
+}
+function build(plugin: AssetPlugin, value: ReturnType<typeof loader>) {
+ const app = App.new(); apps.push(app);
+ vi.spyOn(app, 'wasmModule', 'get').mockReturnValue({} as ESEngineModule);
+ vi.mocked(AssetsClass.create).mockReturnValue(value as unknown as AssetsClass);
+ app.addPlugin(plugin); return app;
+}
+beforeEach(() => { device.status = 0; vi.spyOn(AssetsClass, 'create'); });
+afterEach(() => { for (const app of apps.splice(0)) app.quit({ keepRenderer: true }); vi.restoreAllMocks(); });
+it('releases the app loader exactly once on shutdown', () => {
+ const value = loader(), app = build(new AssetPlugin(), value);
+ app.quit({ keepRenderer: true }); app.quit({ keepRenderer: true });
+ expect(value.releaseAll).toHaveBeenCalledOnce();
+});
+it('releases runtime replacement and default loaders while preserving another app', () => {
+ const plugin = new AssetPlugin(), firstValue = loader(), secondValue = loader(), replacement = loader();
+ const first = build(plugin, firstValue); build(plugin, secondValue);
+ first.insertResource(Assets, replacement as unknown as AssetsClass);
+ first.quit({ keepRenderer: true });
+ expect(firstValue.releaseAll).toHaveBeenCalledOnce(); expect(replacement.releaseAll).toHaveBeenCalledOnce();
+ expect(secondValue.releaseAll).not.toHaveBeenCalled();
+});
+it('parameterless cleanup releases only the latest app, once', () => {
+ const plugin = new AssetPlugin(), firstValue = loader(), secondValue = loader();
+ build(plugin, firstValue); build(plugin, secondValue);
+ plugin.cleanup(); plugin.cleanup();
+ expect(secondValue.releaseAll).toHaveBeenCalledOnce(); expect(firstValue.releaseAll).not.toHaveBeenCalled();
+});
+it('a failing default loader does not prevent the runtime loader from releasing', () => {
+ const plugin = new AssetPlugin(), value = loader(), app = build(plugin, value), replacement = loader();
+ app.insertResource(Assets, replacement as unknown as AssetsClass);
+ value.releaseAll.mockImplementation(() => { throw Error('release failed'); });
+ expect(() => plugin.cleanup(app)).toThrow();
+ expect(replacement.releaseAll).toHaveBeenCalledOnce(); plugin.cleanup(app);
+ expect(value.releaseAll).toHaveBeenCalledOnce();
+});
+it('replacing a loader during recovery still recovers the active replacement', async () => {
+ const old = loader(), app = build(new AssetPlugin(), old), replacement = loader();
+ let resolve!: (value: boolean) => void;
+ old.recoverFromDeviceLoss.mockImplementation(() => new Promise(done => { resolve = done; }));
+ device.status = 1; await app.tick(1 / 60);
+ app.insertResource(Assets, replacement as unknown as AssetsClass); resolve(false);
+ await vi.waitFor(() => expect(replacement.recoverFromDeviceLoss).toHaveBeenCalledOnce());
+});
+it('a stopped recovery cannot move on to a later loader', async () => {
+ const old = loader(), app = build(new AssetPlugin(), old), replacement = loader();
+ let resolve!: (value: boolean) => void;
+ old.recoverFromDeviceLoss.mockImplementation(() => new Promise(done => { resolve = done; }));
+ device.status = 1; await app.tick(1 / 60); app.quit({ keepRenderer: true });
+ app.insertResource(Assets, replacement as unknown as AssetsClass); resolve(false);
+ await new Promise(done => setTimeout(done, 0));
+ expect(replacement.recoverFromDeviceLoss).not.toHaveBeenCalled();
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 8470a84b1..680da445b 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'fix(assets): release app-owned loaders during plugin cleanup':
+ { note: "Asset loaders release their App's resources on shutdown." },
'fix(particles): refresh LUT heap views after allocation':
{ note: 'Particle gradient uploads survive WASM memory growth.' },
'fix(input): cancel held web input on focus loss':