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
fix(sdk): lifecycle correctness batch — teardown reaches UI sub-plugins, timers survive reentrancy, FX state dies with its entity
esengine34cfd94a76a8
diff --git a/sdk/src/asset/loaders/MaterialAssetLoader.ts b/sdk/src/asset/loaders/MaterialAssetLoader.tsindex b19bc6324..99ba2fcb5 100644--- a/sdk/src/asset/loaders/MaterialAssetLoader.ts+++ b/sdk/src/asset/loaders/MaterialAssetLoader.ts@@ -4,6 +4,7 @@ import type { AssetLoader, LoadContext, MaterialResult } from '../AssetLoader';import type { MaterialAssetData, ShaderHandle } from '../../material';import { Material } from '../../material';import { AsyncCache } from '../AsyncCache';+import { log } from '../../logger';export class MaterialAssetLoader implements AssetLoader<MaterialResult> {readonly type = 'material';@@ -55,8 +56,9 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {try {const tex = await ctx.loadTexture(texPath);Material.setUniform(handle, name, Material.tex(tex.handle));- } catch {+ } catch (e) {// Missing texture: leave the param unbound (it samples whatever is at the unit).+ log.warn('asset', `Material ${matPath}: failed to load texture '${texPath}' for param '${name}'`, e);}}}diff --git a/sdk/src/mesh2d.ts b/sdk/src/mesh2d.tsindex 90859411f..6ac5b0a87 100644--- a/sdk/src/mesh2d.ts+++ b/sdk/src/mesh2d.ts@@ -96,6 +96,10 @@ export class Mesh2DPlugin implements Plugin {const api = new Mesh2DAPI(module, registry);app.insertResource(Meshes2D, api);+ app.world.onDespawn((entity: Entity) => {+ if (api.getGeometry(entity)) api.clearGeometry(entity);+ });+// The geometry payload is authored in the component data but isn't a C++// field — carry it out-of-band and upload it through the validated entry// point on load (the same pattern as particle gradients / tilemap chunks).diff --git a/sdk/src/particle/ParticlePlugin.ts b/sdk/src/particle/ParticlePlugin.tsindex 7f9bbdd50..d1abfcf53 100644--- a/sdk/src/particle/ParticlePlugin.ts+++ b/sdk/src/particle/ParticlePlugin.ts@@ -29,6 +29,12 @@ export class ParticlePlugin implements Plugin {// C++ field — carry it out-of-band and bake it into the sim's LUT on load.const gradients = this.gradients_;const sizeCurves = this.sizeCurves_;++ app.world.onDespawn((entity) => {+ if (gradients.delete(entity)) api.setColorLut(entity, null);+ if (sizeCurves.delete(entity)) api.setSizeLut(entity, null);+ });+registerSceneComponentCodec('ParticleEmitter', {outOfBandFields: ['colorGradient', 'sizeCurve'],importData: (entity, outOfBand) => {diff --git a/sdk/src/renderTexture.ts b/sdk/src/renderTexture.tsindex 23e634ad1..9a84152fb 100644--- a/sdk/src/renderTexture.ts+++ b/sdk/src/renderTexture.ts@@ -58,7 +58,7 @@ export const RenderTexture = {},resize(rt: RenderTextureHandle, width: number, height: number): RenderTextureHandle {- Renderer.releaseRenderTarget(rt._handle);+ RenderTexture.release(rt);return RenderTexture.create({ width, height, depth: rt._depth, filter: rt._filter });},diff --git a/sdk/src/timer.ts b/sdk/src/timer.tsindex bb418f45c..9ee26dad8 100644--- a/sdk/src/timer.ts+++ b/sdk/src/timer.ts@@ -10,6 +10,7 @@ import { defineSystem } from './system';import { Schedule } from './system';import { Time } from './resource';import { playModeOnly } from './env';+import { log } from './logger';import type { Plugin } from './app';// =============================================================================@@ -172,14 +173,23 @@ export class TimerManager {const scaledDt = dt * this.timeScale_;const toRemove: number[] = [];- for (const [id, entry] of this.timers_) {- if (entry.paused) continue;+ // Snapshot ids: Map iterators see mid-iteration insertions, so a timer+ // created inside a callback would receive this tick's dt (and a+ // self-rescheduling delay(0) would loop forever within one tick).+ const ids = [...this.timers_.keys()];+ for (const id of ids) {+ const entry = this.timers_.get(id);+ if (!entry || entry.paused) continue;entry.elapsed += scaledDt;if (entry.elapsed >= entry.delay) {if (!entry.handle) entry.handle = new TimerHandle(this, id);- entry.callback(entry.handle);+ try {+ entry.callback(entry.handle);+ } catch (e) {+ log.error('timer', `Timer callback error (id=${id})`, e);+ }entry.repeatCount++;if (entry.repeat) {diff --git a/sdk/src/trail/TrailPlugin.ts b/sdk/src/trail/TrailPlugin.tsindex a4383270f..5917f1801 100644--- a/sdk/src/trail/TrailPlugin.ts+++ b/sdk/src/trail/TrailPlugin.ts@@ -6,6 +6,7 @@ import { Res } from '../resource';import { Time, type TimeData } from '../resource';import { fxPreviewOrPlayMode } from '../env';import type { ESEngineModule, CppRegistry } from '../wasm';+import { TrailRenderer } from '../component';import { Trail, TrailAPI } from './TrailAPI';export class TrailPlugin implements Plugin {@@ -17,6 +18,12 @@ export class TrailPlugin implements Plugin {const api = new TrailAPI(module, registry);app.insertResource(Trail, api);+ // Trail history lives in a C++ side table keyed by entity, not in the+ // component — drop it on despawn or the recorded points leak.+ app.world.onDespawn((entity) => {+ if (app.world.has(entity, TrailRenderer)) api.clear(entity);+ });+// Trail point recording is gameplay — frozen in editor edit mode, runs in// play mode / standalone runtime (matches particles/animation/physics).// The FX edit-preview flag is the one authoring exception (env.ts):diff --git a/sdk/src/ui/layout/safe-area.ts b/sdk/src/ui/layout/safe-area.tsindex 70d687529..309d92622 100644--- a/sdk/src/ui/layout/safe-area.ts+++ b/sdk/src/ui/layout/safe-area.ts@@ -84,6 +84,15 @@ export class SafeAreaPlugin implements Plugin {name = PluginName.SafeArea;dependencies = [PluginName.UILayout];+ private onResize_: (() => void) | null = null;++ cleanup(): void {+ if (this.onResize_ && typeof window !== 'undefined') {+ window.removeEventListener('resize', this.onResize_);+ }+ this.onResize_ = null;+ }+build(app: App): void {registerComponent('SafeArea', SafeArea);@@ -100,10 +109,11 @@ export class SafeAreaPlugin implements Plugin {dirty = true;});} else if (typeof window !== 'undefined') {- window.addEventListener('resize', () => {+ this.onResize_ = () => {cachedInsets = getSafeAreaInsets();dirty = true;- });+ };+ window.addEventListener('resize', this.onResize_);}app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(diff --git a/sdk/src/ui/ui-plugin.ts b/sdk/src/ui/ui-plugin.tsindex 4641a2eb0..c0b635071 100644--- a/sdk/src/ui/ui-plugin.ts+++ b/sdk/src/ui/ui-plugin.ts@@ -32,24 +32,38 @@ import type { UIEventQueue } from './core/events';import type { ListView } from './collection/list-view';import type { ScrollContainer } from './collection/scroll-container';+// Build order is dependency-ordered (not execution order): layout first (it+// owns the layout resources), then interaction before behavior so the shared+// UIEvents resource exists when behavior reads it at build.+const SUB_PLUGINS: Plugin[] = [+ uiLayoutPlugin,+ uiMaskPlugin,+ safeAreaPlugin,+ textPlugin,+ uiInteractionPlugin,+ uiBehaviorPlugin,+ uiControllerPlugin,+ dragPlugin,+ focusPlugin,+ textInputPlugin,+ uiRenderOrderPlugin,+];+export class UIPlugin implements Plugin {name = 'ui';build(app: App): void {- // Build order is dependency-ordered (not execution order): layout first- // (it owns the layout resources), then interaction before behavior so- // the shared UIEvents resource exists when behavior reads it at build.- uiLayoutPlugin.build(app);- uiMaskPlugin.build(app);- safeAreaPlugin.build(app);- textPlugin.build(app);- uiInteractionPlugin.build(app);- uiBehaviorPlugin.build(app);- uiControllerPlugin.build(app);- dragPlugin.build(app);- focusPlugin.build(app);- textInputPlugin.build(app);- uiRenderOrderPlugin.build(app);+ for (const plugin of SUB_PLUGINS) {+ plugin.build(app);+ }+ }++ // App.quit only reaches *installed* plugins — the composed sub-plugins'+ // cleanups are unreachable unless forwarded here.+ cleanup(app?: App): void {+ for (let i = SUB_PLUGINS.length - 1; i >= 0; i--) {+ SUB_PLUGINS[i].cleanup?.(app);+ }}/** Shared UI event bus (delegates to the behavior layer). */diff --git a/sdk/tests/fx-despawn-cleanup.test.ts b/sdk/tests/fx-despawn-cleanup.test.tsnew file mode 100644index 000000000..451652991--- /dev/null+++ b/sdk/tests/fx-despawn-cleanup.test.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The FX plugins keep per-entity state outside the ECS (authored+ * geometry, gradient/curve maps, native trail history). Despawning an+ * entity must drop that state — the world.onDespawn pattern the+ * audio/video/spine plugins already follow.+ */+import { describe, it, expect, vi } from 'vitest';+import { App } from '../src/app';+import { AppContext, setDefaultContext } from '../src/context';+import { setEditorMode, setPlayMode } from '../src/env';+import { createMockModule } from './mocks/wasm';+import { Mesh2DPlugin, Meshes2D } from '../src/mesh2d';+import { ParticlePlugin } from '../src/particle/ParticlePlugin';+import { TrailPlugin } from '../src/trail/TrailPlugin';+import { TrailRenderer } from '../src/component';+import type { ESEngineModule } from '../src/wasm';++// Like bootMockApp, but connects through App so plugins see app.wasmModule.+function bootApp(): { app: App; module: ESEngineModule } {+ setDefaultContext(new AppContext());+ setEditorMode(false);+ setPlayMode(false);+ const app = App.new();+ const module = createMockModule();+ app.connectCpp(module.getRegistry(), module);+ return { app, module };+}++function withAllocator(module: ESEngineModule): void {+ const heap = new Uint8Array(1 << 16);+ let brk = 16;+ const m = module as unknown as Record<string, unknown>;+ m._malloc = (size: number) => { const p = brk; brk = (brk + size + 15) & ~15; return p; };+ m._free = () => {};+ m.HEAPU8 = heap;+}++describe('FX per-entity state on despawn', () => {+ it('Mesh2D: despawn drops the authored geometry entry', () => {+ const { app, module } = bootApp();+ withAllocator(module);+ (module as unknown as Record<string, unknown>).mesh2d_setGeometry = vi.fn();++ app.addPlugin(new Mesh2DPlugin());+ const api = app.getResource(Meshes2D);+ const e = app.world.spawn();+ api.setGeometry(e, { positions: [0, 0, 1, 0, 0, 1], indices: [0, 1, 2] });+ expect(api.getGeometry(e)).toBeDefined();++ app.world.despawn(e);+ expect(api.getGeometry(e)).toBeUndefined();+ });++ it('Particle: despawn drops gradient/size-curve entries and clears the native LUTs', () => {+ const { app, module } = bootApp();+ const setColorLut = vi.fn();+ const setSizeLut = vi.fn();+ const m = module as unknown as Record<string, unknown>;+ m.particle_set_color_lut = setColorLut;+ m.particle_set_size_lut = setSizeLut;++ const plugin = new ParticlePlugin();+ app.addPlugin(plugin);+ const e = app.world.spawn();+ const other = app.world.spawn();+ const gradients = (plugin as unknown as { gradients_: Map<number, unknown> }).gradients_;+ const sizeCurves = (plugin as unknown as { sizeCurves_: Map<number, unknown> }).sizeCurves_;+ gradients.set(e as number, { stops: [{ t: 0, color: { r: 1, g: 1, b: 1, a: 1 } }] });+ gradients.set(other as number, { stops: [{ t: 0, color: { r: 1, g: 1, b: 1, a: 1 } }] });+ sizeCurves.set(e as number, { keys: [{ t: 0, v: 1 }] });++ app.world.despawn(e);++ expect(gradients.has(e as number)).toBe(false);+ expect(sizeCurves.has(e as number)).toBe(false);+ expect(gradients.has(other as number)).toBe(true);+ expect(setColorLut).toHaveBeenCalledWith(e, 0, 0);+ expect(setSizeLut).toHaveBeenCalledWith(e, 0, 0);+ });++ it('Trail: despawn clears native history only for entities with TrailRenderer', () => {+ const { app, module } = bootApp();+ const trailClear = vi.fn();+ (module as unknown as Record<string, unknown>).trail_clear = trailClear;++ app.addPlugin(new TrailPlugin());+ const withTrail = app.world.spawn();+ app.world.insert(withTrail, TrailRenderer);+ const without = app.world.spawn();++ app.world.despawn(without);+ expect(trailClear).not.toHaveBeenCalled();++ app.world.despawn(withTrail);+ expect(trailClear).toHaveBeenCalledTimes(1);+ expect(trailClear.mock.calls[0][1]).toBe(withTrail);+ });+});diff --git a/sdk/tests/material-asset-loader.test.ts b/sdk/tests/material-asset-loader.test.tsnew file mode 100644index 000000000..9e9201746--- /dev/null+++ b/sdk/tests/material-asset-loader.test.ts@@ -0,0 +1,64 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../src/material', () => ({+ Material: {+ createFromAsset: vi.fn().mockReturnValue(11),+ setUniform: vi.fn(),+ tex: vi.fn((handle: number) => ({ kind: 'tex', handle })),+ compileShader: vi.fn().mockReturnValue(7),+ release: vi.fn(),+ },+}));++import { MaterialAssetLoader } from '../src/asset/loaders/MaterialAssetLoader';+import { Material } from '../src/material';+import type { LoadContext } from '../src/asset/AssetLoader';++const MAT_PATH = 'assets/materials/foo.esmaterial';+const TEX_REF = 'missing.png';++function makeCtx(): LoadContext {+ const materialJson = JSON.stringify({+ type: 'material',+ shader: 'fx.esshader',+ properties: { mainTex: TEX_REF },+ });+ return {+ catalog: { getBuildPath: (p: string) => p },+ loadText: vi.fn(async (p: string) => (p.endsWith('.esmaterial') ? materialJson : '// shader src')),+ loadTexture: vi.fn().mockRejectedValue(new Error('404 not found')),+ } as unknown as LoadContext;+}++describe('MaterialAssetLoader texture failure', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (Material.createFromAsset as ReturnType<typeof vi.fn>).mockReturnValue(11);+ (Material.compileShader as ReturnType<typeof vi.fn>).mockReturnValue(7);+ });++ it('still resolves the material and leaves the param unbound', async () => {+ const loader = new MaterialAssetLoader();+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});++ const result = await loader.load(MAT_PATH, makeCtx());++ expect(result.handle).toBe(11);+ expect(Material.setUniform).not.toHaveBeenCalled();+ warnSpy.mockRestore();+ });++ it('warns with the material path and the texture path', async () => {+ const loader = new MaterialAssetLoader();+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});++ await loader.load(MAT_PATH, makeCtx());++ const combined = warnSpy.mock.calls.map(c => String(c[0])).join('\n');+ expect(combined).toContain(MAT_PATH);+ expect(combined).toContain('assets/materials/missing.png');+ warnSpy.mockRestore();+ });+});diff --git a/sdk/tests/renderTexture.test.ts b/sdk/tests/renderTexture.test.tsindex 82754742d..585a5a516 100644--- a/sdk/tests/renderTexture.test.ts+++ b/sdk/tests/renderTexture.test.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { describe, it, expect, beforeEach, vi } from 'vitest';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';vi.mock('../src/renderer', () => ({Renderer: {@@ -15,6 +15,8 @@ vi.mock('../src/renderer', () => ({import { RenderTexture } from '../src/renderTexture';import { Renderer } from '../src/renderer';+import { initResourceManager, shutdownResourceManager } from '../src/resourceManager';+import type { CppResourceManager } from '../src/wasm';describe('RenderTexture', () => {beforeEach(() => {@@ -141,6 +143,42 @@ describe('RenderTexture', () => {});});+ describe('resize with a live resource manager', () => {+ let registerExternalTexture: ReturnType<typeof vi.fn>;+ let releaseTexture: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ let nextTexture = 700;+ registerExternalTexture = vi.fn(() => nextTexture++);+ releaseTexture = vi.fn();+ initResourceManager({+ registerExternalTexture,+ releaseTexture,+ getTextureDimensions: vi.fn(),+ } as unknown as CppResourceManager);+ });++ afterEach(() => {+ shutdownResourceManager();+ });++ it('releases the old texture-table entry on resize', () => {+ const rt = RenderTexture.create({ width: 64, height: 64 });+ expect(rt.texture).toBe(700);++ RenderTexture.resize(rt, 128, 128);+ expect(releaseTexture).toHaveBeenCalledWith(700);+ });++ it('returns a fresh texture handle after resize', () => {+ const rt = RenderTexture.create({ width: 64, height: 64 });+ const resized = RenderTexture.resize(rt, 128, 128);++ expect(resized.texture).toBe(701);+ expect(registerExternalTexture).toHaveBeenCalledTimes(2);+ });+ });+describe('begin / end', () => {it('calls Renderer.begin with viewProjection and handle', () => {const vp = new Float32Array(16);diff --git a/sdk/tests/timer.test.ts b/sdk/tests/timer.test.tsindex f2d8c92c4..87bdf333e 100644--- a/sdk/tests/timer.test.ts+++ b/sdk/tests/timer.test.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { describe, it, expect, beforeEach } from 'vitest';+import { describe, it, expect, beforeEach, vi } from 'vitest';import { TimerManager } from '../src/timer';describe('TimerManager', () => {@@ -147,6 +147,54 @@ describe('TimerManager', () => {});});+ describe('tick reentrancy and callback errors', () => {+ it('does not advance a timer created inside a callback by the current tick', () => {+ let innerFired = false;+ manager.delay(0.5, () => {+ manager.delay(0.5, () => { innerFired = true; });+ });++ manager.tick(0.5);+ expect(innerFired).toBe(false);++ manager.tick(0.5);+ expect(innerFired).toBe(true);+ });++ it('fires a self-rescheduling delay(0) exactly once per tick', () => {+ let count = 0;+ const reschedule = () => {+ count++;+ if (count < 100) manager.delay(0, reschedule);+ };+ manager.delay(0, reschedule);++ manager.tick(1 / 60);+ expect(count).toBe(1);++ manager.tick(1 / 60);+ expect(count).toBe(2);+ });++ it('removes a throwing one-shot and still fires later timers', () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ let throwCount = 0;+ let otherFired = 0;+ manager.delay(0.1, () => { throwCount++; throw new Error('boom'); });+ manager.delay(0.1, () => { otherFired++; });++ expect(() => manager.tick(0.2)).not.toThrow();+ expect(throwCount).toBe(1);+ expect(otherFired).toBe(1);+ expect(errorSpy).toHaveBeenCalled();++ manager.tick(0.2);+ expect(throwCount).toBe(1);+ expect(manager.activeCount).toBe(0);+ errorSpy.mockRestore();+ });+ });+describe('cancelAll', () => {it('removes all timers', () => {manager.delay(1.0, () => {});diff --git a/sdk/tests/ui-plugin-cleanup.test.ts b/sdk/tests/ui-plugin-cleanup.test.tsnew file mode 100644index 000000000..ef85407a4--- /dev/null+++ b/sdk/tests/ui-plugin-cleanup.test.ts@@ -0,0 +1,68 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file UIPlugin composes eleven sub-plugin builds; App.quit only calls+ * cleanup() on *installed* plugins, so the composed plugin must forward+ * teardown to its sub-plugins or their cleanups are unreachable.+ */+import { describe, it, expect, vi } from 'vitest';+import { App } from '../src/app';+import { uiPlugin } from '../src/ui/ui-plugin';+import { safeAreaPlugin } from '../src/ui/layout/safe-area';+import { textInputPlugin, TextInputPlugin } from '../src/ui/text/text-input-plugin';+import { AppContext, setDefaultContext } from '../src/context';+import { setEditorMode, setPlayMode } from '../src/env';+import { createMockModule } from './mocks/wasm';++describe('UIPlugin teardown', () => {+ it('forwards cleanup to sub-plugins in reverse build order', () => {+ expect(typeof uiPlugin.cleanup).toBe('function');++ const order: string[] = [];+ const tiSpy = vi.spyOn(textInputPlugin, 'cleanup').mockImplementation(() => { order.push('textInput'); });+ const saSpy = vi.spyOn(safeAreaPlugin, 'cleanup').mockImplementation(() => { order.push('safeArea'); });++ uiPlugin.cleanup!(App.new());++ expect(order).toEqual(['textInput', 'safeArea']);+ tiSpy.mockRestore();+ saSpy.mockRestore();+ });++ it('SafeAreaPlugin removes its window resize listener on cleanup', () => {+ const added: EventListener[] = [];+ const removed: EventListener[] = [];+ const addSpy = vi.spyOn(window, 'addEventListener').mockImplementation((type, fn) => {+ if (type === 'resize') added.push(fn as EventListener);+ });+ const removeSpy = vi.spyOn(window, 'removeEventListener').mockImplementation((type, fn) => {+ if (type === 'resize') removed.push(fn as EventListener);+ });++ safeAreaPlugin.build(App.new());+ expect(added.length).toBe(1);++ safeAreaPlugin.cleanup?.();+ expect(removed).toEqual(added);++ addSpy.mockRestore();+ removeSpy.mockRestore();+ });++ it('TextInputPlugin.cleanup removes the hidden textarea from the DOM', () => {+ setDefaultContext(new AppContext());+ setEditorMode(false);+ setPlayMode(false);+ const app = App.new();+ const module = createMockModule();+ app.connectCpp(module.getRegistry(), module);+ const before = document.querySelectorAll('textarea').length;++ const plugin = new TextInputPlugin();+ plugin.build(app);+ expect(document.querySelectorAll('textarea').length).toBe(before + 1);++ plugin.cleanup();+ expect(document.querySelectorAll('textarea').length).toBe(before);+ });+});