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(physics): isolate async Box2D module ownership by app
yhhcc3c8f86bb23
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 815d4185b..28a4ded35 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Box2D initialization and shutdown belong to their App.** Stopping an App before its module finishes loading prevents late physics initialization and system installation. Shared plugin instances keep independent bridges and module ownership, so an older App cannot shut down or replace a newer App's physics world; cancelled load failures do not change the stopped App's subsystem status.+- **Screen-excluded UI scissor regions no longer submit draws.** Root scissor masks intersect the current view's viewport before propagating to descendants. Empty regions skip UI visual collection and batch geometry/index/command allocation, including text submissions; stencil-only entries remain drawable. Moving a masked subtree back into view restores its draws on the next frame.- **Animation despawn subscriptions belong to their App.** Shared animation plugins withdraw the quitting App's listener while preserving other Apps' tween cancellation, sprite-event cleanup, and animator removal callbacks. Repeated preview shutdowns no longer leave stale subscriptions on older worlds.diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex a17ffb68a..69ce8fbed 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -5641,7 +5641,7 @@ sensorExits: SensorEvent[]## Physics2DPlugin — class @experimental```build: (app: App) => void-cleanup: () => void+cleanup: (app?: App) => voidname: stringstatic new (wasmUrl: string, config?: Physics2DPluginConfig, factory?: PhysicsModuleFactory): Physics2DPluginstatic prototype: Physics2DPlugindiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex bbeed92aa..5a43e5337 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -5835,7 +5835,7 @@ sensorExits: SensorEvent[]## Physics2DPlugin — class @experimental```build: (app: App) => void-cleanup: () => void+cleanup: (app?: App) => voidname: stringstatic new (wasmUrl: string, config?: Physics2DPluginConfig, factory?: PhysicsModuleFactory): Physics2DPluginstatic prototype: Physics2DPlugindiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 1972c35e5..e41e4369e 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -5636,7 +5636,7 @@ sensorExits: SensorEvent[]## Physics2DPlugin — class @experimental```build: (app: App) => void-cleanup: () => void+cleanup: (app?: App) => voidname: stringstatic new (wasmUrl: string, config?: Physics2DPluginConfig, factory?: PhysicsModuleFactory): Physics2DPluginstatic prototype: Physics2DPlugindiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex e13cf49db..03fc6e27f 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -5909,7 +5909,7 @@ sensorExits: SensorEvent[]## Physics2DPlugin — class @experimental```build: (app: App) => void-cleanup: () => void+cleanup: (app?: App) => voidname: stringstatic new (wasmUrl: string, config?: Physics2DPluginConfig, factory?: PhysicsModuleFactory): Physics2DPluginstatic prototype: Physics2DPlugindiff --git a/sdk/etc/physics.api.md b/sdk/etc/physics.api.mdindex a00696fcd..3fd0420b2 100644--- a/sdk/etc/physics.api.md+++ b/sdk/etc/physics.api.md@@ -426,7 +426,7 @@ sensorExits: SensorEvent[]## Physics2DPlugin — class @experimental```build: (app: App) => void-cleanup: () => void+cleanup: (app?: App) => voidname: stringstatic new (wasmUrl: string, config?: Physics2DPluginConfig, factory?: PhysicsModuleFactory): Physics2DPluginstatic prototype: Physics2DPlugindiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 00fe42c3b..e40aed0d7 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -5643,7 +5643,7 @@ sensorExits: SensorEvent[]## Physics2DPlugin — class @experimental```build: (app: App) => void-cleanup: () => void+cleanup: (app?: App) => voidname: stringstatic new (wasmUrl: string, config?: Physics2DPluginConfig, factory?: PhysicsModuleFactory): Physics2DPluginstatic prototype: Physics2DPlugindiff --git a/sdk/src/physics/Physics2DPlugin.ts b/sdk/src/physics/Physics2DPlugin.tsindex bb47373c4..fc2a43295 100644--- a/sdk/src/physics/Physics2DPlugin.ts+++ b/sdk/src/physics/Physics2DPlugin.ts@@ -19,7 +19,7 @@ import {} from './PhysicsModuleLoader';import { setupPhysics2DDebugDraw } from './Physics2DDebugDraw';import { PhysicsBridge } from './PhysicsBridge';-import { Physics2DRuntime } from './Physics2DRuntime';+import { Physics2DRuntime, type Physics2DRuntimeData } from './Physics2DRuntime';import { Physics2DAPI, Physics2D } from './Physics2D';import { registerPhysics2DSystem } from './PhysicsSystem';import { registerCharacterController2DSystem } from './CharacterController2DSystem';@@ -110,13 +110,19 @@ function assertModuleContract(module: PhysicsWasmModule): void {);}+interface Physics2DInstance {+ released: boolean;+ module: PhysicsWasmModule | null;+ runtime: Physics2DRuntimeData;+}+export class Physics2DPlugin implements Plugin {name = 'physics';private config_: ResolvedPhysics2DConfig;private wasmUrl_: string;private factory_?: PhysicsModuleFactory;- private bridge_ = new PhysicsBridge();- private module_: PhysicsWasmModule | null = null;+ private readonly instances_ = new WeakMap<App, Physics2DInstance>();+ private latestInstance_: Physics2DInstance | null = null;constructor(wasmUrl: string, config: Physics2DPluginConfig = {}, factory?: PhysicsModuleFactory) {this.wasmUrl_ = wasmUrl;@@ -125,6 +131,12 @@ export class Physics2DPlugin implements Plugin {}build(app: App): void {+ this.cleanup(app);+ const runtime = { module: null as PhysicsWasmModule | null, initPromise: null as Promise<void> | null };+ const instance = { released: false, module: null as PhysicsWasmModule | null, runtime };+ this.instances_.set(app, instance);+ this.latestInstance_ = instance;+ const bridge = new PhysicsBridge();app.insertResource(Physics2DEvents, {collisionEnters: [],collisionExits: [],@@ -132,12 +144,13 @@ export class Physics2DPlugin implements Plugin {sensorEnters: [],sensorExits: [],});- app.insertResource(Physics2DRuntime, { module: null, initPromise: null });+ app.insertResource(Physics2DRuntime, runtime);// wasm loading → show "initializing", not a stuck "registered".app.subsystems.transition('physics', 'initializing');const initPromise = loadPhysicsModule(this.wasmUrl_, this.factory_).then((loaded: PhysicsWasmModule) => {+ if (instance.released) return;// Push a terminal Box2D abort to the registry too (not just the// bridge's call-time guard). Set before connect() so the bridge's// abort guard preserves and chains this handler.@@ -152,9 +165,9 @@ export class Physics2DPlugin implements Plugin {// abort safety without changing a single call.assertModuleContract(loaded);- this.bridge_.connect(loaded);- const module = this.bridge_.module;- this.module_ = module;+ bridge.connect(loaded);+ const module = bridge.module;+ instance.module = module;module._physics_init(this.config_.gravity.x,@@ -188,6 +201,7 @@ export class Physics2DPlugin implements Plugin {);initPromise.catch((e) => {+ if (instance.released) return;app.subsystems.markError('physics', e instanceof Error ? e.message : String(e));handleWasmError(e, 'Physics2DPlugin.init');});@@ -200,9 +214,16 @@ export class Physics2DPlugin implements Plugin {* joints, contact state) leaked across an engine re-init. The bridge-guarded* module makes the call abort-safe; null after so a double cleanup is a no-op.*/- cleanup(): void {- this.module_?._physics_shutdown();- this.module_ = null;+ cleanup(app?: App): void {+ const instance = app ? this.instances_.get(app) : this.latestInstance_;+ if (!instance || instance.released) return;+ instance.released = true;+ if (app) this.instances_.delete(app);+ if (instance === this.latestInstance_) this.latestInstance_ = null;+ const module = instance.module;+ instance.module = null;+ instance.runtime.module = null;+ module?._physics_shutdown();}}diff --git a/sdk/tests/physics-plugin-lifecycle.test.ts b/sdk/tests/physics-plugin-lifecycle.test.tsnew file mode 100644index 000000000..9e7264c8c--- /dev/null+++ b/sdk/tests/physics-plugin-lifecycle.test.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, expect, it, vi } from 'vitest';+import { App } from '../src/app/app';+import { Physics2DPlugin } from '../src/physics/Physics2DPlugin';+import { Physics2DRuntime } from '../src/physics/Physics2DRuntime';+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';+const apps: App[] = [];+function module() {+ return Object.fromEntries([+ '_physics_init', '_physics_shutdown', '_physics_setWorldConfig', '_physics_step',+ '_physics_capturePoses', '_physics_getInterpolatedCount', '_physics_getInterpolatedTransforms',+ '_physics_collectEvents', '_physics_getDynamicBodyCount', '_physics_getDynamicBodyTransforms',+ '_physics_setBodyTransform',+ ].map(name => [name, vi.fn(() => 0)])) as unknown as PhysicsWasmModule;+}+function build(plugin: Physics2DPlugin) { const app = App.new(); apps.push(app); app.addPlugin(plugin); return app; }+afterEach(() => { for (const app of apps.splice(0)) app.quit(); });+it('quitting before the module arrives prevents late initialization and system installation', async () => {+ const loaded = module(); let resolve!: (m: PhysicsWasmModule) => void;+ const plugin = new Physics2DPlugin('', {}, () => new Promise(done => { resolve = done; }));+ const app = build(plugin), runtime = app.getResource(Physics2DRuntime), install = vi.spyOn(app, 'addSystem');+ app.quit(); resolve(loaded); await runtime.initPromise;+ expect(loaded._physics_init).not.toHaveBeenCalled(); expect(install).not.toHaveBeenCalled();+ expect(runtime.module).toBeNull();+});+it('quitting an older app shuts down only its own Box2D module', async () => {+ const firstModule = module(), secondModule = module();+ const factory = vi.fn().mockResolvedValueOnce(firstModule).mockResolvedValueOnce(secondModule);+ const plugin = new Physics2DPlugin('', {}, factory), first = build(plugin), second = build(plugin);+ await Promise.all([first.getResource(Physics2DRuntime).initPromise, second.getResource(Physics2DRuntime).initPromise]);+ first.quit(); expect(firstModule._physics_shutdown).toHaveBeenCalledOnce();+ expect(secondModule._physics_shutdown).not.toHaveBeenCalled();+ second.quit(); expect(secondModule._physics_shutdown).toHaveBeenCalledOnce();+});+it('late completion from a cancelled older app cannot replace the newer app module', async () => {+ const oldModule = module(), currentModule = module(); let resolve!: (m: PhysicsWasmModule) => void;+ const factory = vi.fn().mockImplementationOnce(() => new Promise(done => { resolve = done; })).mockResolvedValueOnce(currentModule);+ const plugin = new Physics2DPlugin('', {}, factory), first = build(plugin), oldRuntime = first.getResource(Physics2DRuntime);+ first.quit(); const second = build(plugin); await second.getResource(Physics2DRuntime).initPromise;+ resolve(oldModule); await oldRuntime.initPromise; second.quit();+ expect(oldModule._physics_init).not.toHaveBeenCalled(); expect(currentModule._physics_shutdown).toHaveBeenCalledOnce();+});+it('parameterless cleanup shuts down the latest module once without losing the older owner', async () => {+ const firstModule = module(), secondModule = module();+ const factory = vi.fn().mockResolvedValueOnce(firstModule).mockResolvedValueOnce(secondModule);+ const plugin = new Physics2DPlugin('', {}, factory), first = build(plugin), second = build(plugin);+ await Promise.all([first.getResource(Physics2DRuntime).initPromise, second.getResource(Physics2DRuntime).initPromise]);+ plugin.cleanup(); plugin.cleanup(); expect(secondModule._physics_shutdown).toHaveBeenCalledOnce();+ expect(second.getResource(Physics2DRuntime).module).toBeNull(); expect(firstModule._physics_shutdown).not.toHaveBeenCalled();+ first.quit(); second.quit(); expect(firstModule._physics_shutdown).toHaveBeenCalledOnce();+ expect(secondModule._physics_shutdown).toHaveBeenCalledOnce();+});+it('a cancelled load failure does not mark the stopped app as failed', async () => {+ let reject!: (error: Error) => void;+ const plugin = new Physics2DPlugin('', {}, () => new Promise((_, fail) => { reject = fail; }));+ const app = build(plugin), runtime = app.getResource(Physics2DRuntime), failed = vi.spyOn(app.subsystems, 'markError');+ app.quit(); reject(Error('late load failure')); await runtime.initPromise?.catch(() => {});+ expect(failed).not.toHaveBeenCalled(); expect(runtime.module).toBeNull();+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex c2af25113..096fa3e3f 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(physics): isolate async Box2D module ownership by app':+ { note: 'Box2D initialization and shutdown belong to their App.' },'perf(render): skip geometry outside UI scissor viewports':{ note: 'Screen-excluded UI scissor regions no longer submit draws.' },'fix(animation): isolate despawn subscriptions by app':