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
perf(physics): synchronize only changed static body groups
yhh3d9c1a376787
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 089f02481..af1999a24 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,10 @@ published separately; it ships inside the editor.## [Unreleased]+### Fixed++- **Static physics synchronization skips unchanged body groups.** Authored Transform writes select individual static bodies, while each immediate parent's composed frame selects only its affected children. Unrelated dynamic or authored motion avoids per-body change checks and pose reads. Reparenting, re-enabling and pixels-per-unit edits refresh the correct bodies. Paused simulations release write history and refresh poses on resume; plugin cleanup releases the reader and frame/despawn observers.+## [0.89.0] - 2026-10-16### Fixeddiff --git a/sdk/src/physics/Physics2DPlugin.ts b/sdk/src/physics/Physics2DPlugin.tsindex ffa60708e..adfa2b472 100644--- a/sdk/src/physics/Physics2DPlugin.ts+++ b/sdk/src/physics/Physics2DPlugin.ts@@ -115,6 +115,7 @@ interface Physics2DInstance {released: boolean;module: PhysicsWasmModule | null;runtime: Physics2DRuntimeData;+ disposeSystems: (() => void) | null;}export class Physics2DPlugin implements Plugin {@@ -134,7 +135,7 @@ 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 };+ const instance: Physics2DInstance = { released: false, module: null, runtime, disposeSystems: null };this.instances_.set(app, instance);this.latestInstance_ = instance;const bridge = new PhysicsBridge();@@ -186,7 +187,7 @@ export class Physics2DPlugin implements Plugin {this.config_.maxLinearSpeed,);- registerPhysics2DSystem(app, module, this.config_);+ instance.disposeSystems = registerPhysics2DSystem(app, module, this.config_);app.getResource(Physics2DRuntime).module = module;app.insertResource(Physics2D, Physics2DAPI._fromModule(module));@@ -224,6 +225,8 @@ export class Physics2DPlugin implements Plugin {const module = instance.module;instance.module = null;instance.runtime.module = null;+ instance.disposeSystems?.();+ instance.disposeSystems = null;module?._physics_shutdown();}}diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.tsindex fa0fd79ba..5adda440c 100644--- a/sdk/src/physics/PhysicsSystem.ts+++ b/sdk/src/physics/PhysicsSystem.ts@@ -44,6 +44,7 @@ import {} from './PhysicsTypes';import { withMalloc } from '../wasm/wasmScratch';import { engineApi, type EngineApi } from '../ecs/bridge/engineApi';+import { StaticBodyPoses2D } from './StaticBodyPoses2D';/*** The engine surface this file drives. `getTransformPtr` is the web module's own@@ -684,7 +685,7 @@ export function registerPhysics2DSystem(app: App,module: PhysicsWasmModule,config: ResolvedPhysics2DConfig,-): void {+): () => void {const trackedEntities = new Set<Entity>();const trackedJoints = new Set<Entity>();const trackedOneWay = new Set<Entity>();@@ -705,18 +706,13 @@ export function registerPhysics2DSystem(const physicsComponents = [RigidBody2D, ...COLLIDER_TYPES, ...JOINT_TYPES, OneWayPlatform2D];for (const c of physicsComponents) app.world.enableChangeTracking(c);const kinematicEntities = new Set<Entity>();- const staticPoses = new Map<Entity, { x: number; y: number; angle: number; parent: Entity | null }>();- const staticParentPoses = new Map<Entity, { values: number[]; checked: number; changed: boolean }>();- let staticSyncSequence = 0;- let lastStaticEpoch = -1;- let lastStaticTick = -1;- let lastStaticPpu = -1;+ const staticPoses = new StaticBodyPoses2D(app.world);let lastStructuralVersion = -1;const world = app.world;world.enableChangeTracking(Transform);- world.onDespawn((entity: Entity) => {+ const offDespawn = world.onDespawn((entity: Entity) => {if (trackedJoints.has(entity)) {module._physics_destroyJoint(entity);trackedJoints.delete(entity);@@ -867,9 +863,7 @@ export function registerPhysics2DSystem(else kinematicEntities.delete(entity);if (cached.bodyType === BodyType.Static) {const parent = world.has(entity, Parent) ? world.get(entity, Parent).entity : null;- const pose = staticPoses.get(entity);- if (pose) pose.parent = parent;- else staticPoses.set(entity, { x: NaN, y: NaN, angle: NaN, parent });+ staticPoses.track(entity, parent);parentedBodies.delete(entity);} else staticPoses.delete(entity);cached.syncedTick = world.getWorldTick();@@ -912,63 +906,9 @@ export function registerPhysics2DSystem(lastEntitySyncTick = world.getWorldTick();lastStructuralVersion = structuralVersion;- const staticParents = new Set<Entity>();- for (const pose of staticPoses.values()) if (pose.parent !== null) staticParents.add(pose.parent);- for (const parent of staticParentPoses.keys()) {- if (!staticParents.has(parent)) staticParentPoses.delete(parent);- }} // end if (needReconcile)- const staticEpoch = world.transformEpoch();- if (staticPoses.size > 0 && (needReconcile || staticEpoch < 0- || staticEpoch !== lastStaticEpoch || ppu !== lastStaticPpu)) {- world.ensureTransformsComposed();- const sequence = ++staticSyncSequence;- for (const [entity, pose] of staticPoses) {- if (!cachedProps.get(entity)?.enabled) continue;- const hasParent = pose.parent !== null;- if (!needReconcile && ppu === lastStaticPpu- && !world.isChangedSince(entity, Transform, lastStaticTick)) {- if (pose.parent === null) continue;- let parentPose = staticParentPoses.get(pose.parent);- if (parentPose?.checked !== sequence) {- if (!world.has(pose.parent, Transform)) {- if (parentPose) {- parentPose.checked = sequence; parentPose.changed = true;- } else {- parentPose = { values: [], checked: sequence, changed: true };- staticParentPoses.set(pose.parent, parentPose);- }- } else {- const tf = world.get(pose.parent, Transform) as TransformData;- const p = tf.worldPosition, r = tf.worldRotation, s = tf.worldScale;- const values = [p.x, p.y, p.z, r.x, r.y, r.z, r.w, s.x, s.y, s.z];- const changed = !parentPose || values.some((value, index) => value !== parentPose!.values[index]);- if (parentPose) {- parentPose.values = values; parentPose.checked = sequence; parentPose.changed = changed;- } else {- parentPose = { values, checked: sequence, changed };- staticParentPoses.set(pose.parent, parentPose);- }- }- }- if (!parentPose.changed) continue;- }- if (!world.isEntityActive(entity)) continue;- const tf = world.get(entity, Transform) as TransformData;- const position = hasParent ? tf.worldPosition : tf.position;- const rotation = hasParent ? tf.worldRotation : tf.rotation;- const x = position.x * invPpu, y = position.y * invPpu;- const angle = quatToAngleZ(rotation);- if (pose.x !== x || pose.y !== y || pose.angle !== angle) {- module._physics_setBodyTransform(entity, x, y, angle);- pose.x = x; pose.y = y; pose.angle = angle;- }- }- }- lastStaticEpoch = world.transformEpoch();- lastStaticTick = world.getWorldTick() - 1;- lastStaticPpu = ppu;+ staticPoses.sync(module, ppu, needReconcile, entity => !!cachedProps.get(entity)?.enabled);// Kinematic bodies are driven by their Transform (changed via gameplay,// not tracked as a physics edit) — push every step, even when the@@ -1043,4 +983,6 @@ export function registerPhysics2DSystem(),{ runIf: playModeOnly, profileDomain: 'physics' });+ const offFrameEnd = app.onFrameEnd(() => { if (app.isPaused() || !playModeOnly()) staticPoses.pause(); });+ return () => { offFrameEnd(); offDespawn(); staticPoses.dispose(); };}diff --git a/sdk/src/physics/StaticBodyPoses2D.ts b/sdk/src/physics/StaticBodyPoses2D.tsnew file mode 100644index 000000000..5d6803017--- /dev/null+++ b/sdk/src/physics/StaticBodyPoses2D.ts@@ -0,0 +1,111 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { Transform, type TransformData } from '../ecs/component';+import type { World } from '../ecs/world';+import type { Entity } from '../types';+import type { PhysicsWasmModule } from './PhysicsModuleLoader';+import { quatToAngleZ } from './PhysicsTypes';++interface StaticPose { x: number; y: number; angle: number; parent: Entity | null }++/** Static poses follow sparse authored writes and their immediate parent's world+ * frame. Dynamic writeback may invalidate composition without editing either. */+export class StaticBodyPoses2D {+ private poses = new Map<Entity, StaticPose>();+ private groups = new Map<Entity, Set<Entity>>();+ private parents = new Map<Entity, number[]>();+ private reader: number | null = null;+ private epoch = -1;+ private tick = -1;+ private ppu = -1;++ constructor(private readonly world: World) {}++ set(entity: Entity, pose: StaticPose): void {+ if (this.poses.get(entity)?.parent !== pose.parent) this.delete(entity);+ this.poses.set(entity, pose);+ if (pose.parent !== null) {+ let group = this.groups.get(pose.parent);+ if (!group) { group = new Set(); this.groups.set(pose.parent, group); }+ group.add(entity);+ }+ }++ track(entity: Entity, parent: Entity | null): void {+ const previous = this.poses.get(entity);+ if (previous?.parent === parent) return;+ this.set(entity, previous ? { ...previous, parent } : { x: NaN, y: NaN, angle: NaN, parent });+ }++ delete(entity: Entity): void {+ const parent = this.poses.get(entity)?.parent;+ if (parent != null) {+ const group = this.groups.get(parent);+ group?.delete(entity);+ if (!group?.size) { this.groups.delete(parent); this.parents.delete(parent); }+ }+ this.poses.delete(entity);+ }++ /** A stopped simulation owes a full pose refresh, but retains no write history. */+ pause(): void {+ if (this.reader !== null) this.world.disposeWriteReader(Transform, this.reader);+ this.reader = null;+ this.epoch = -1;+ }++ sync(module: PhysicsWasmModule, ppu: number, reconcile: boolean, enabled: (entity: Entity) => boolean): void {+ const world = this.world;+ if (!this.poses.size) { this.pause(); return; }+ const first = this.reader === null;+ if (first) this.reader = world.registerWriteReaderFrom(Transform, world.getWorldTick());+ const epoch = world.transformEpoch();+ if (first || reconcile || epoch < 0 || epoch !== this.epoch || ppu !== this.ppu) {+ world.ensureTransformsComposed();+ const all = first || reconcile || epoch < 0 || ppu !== this.ppu;+ const changedParents = new Set<Entity>();+ for (const parent of this.groups.keys()) {+ let changed = true;+ if (world.has(parent, Transform)) {+ const tf = world.get(parent, Transform) as TransformData;+ const p = tf.worldPosition, r = tf.worldRotation, s = tf.worldScale;+ const values = [p.x, p.y, p.z, r.x, r.y, r.z, r.w, s.x, s.y, s.z];+ const old = this.parents.get(parent);+ changed = !old || values.some((value, index) => value !== old[index]);+ this.parents.set(parent, values);+ } else this.parents.delete(parent);+ if (!all && changed) changedParents.add(parent);+ }+ const invPpu = 1 / ppu;+ const sync = (entity: Entity) => {+ if (!enabled(entity) || !world.isEntityActive(entity)) return;+ const pose = this.poses.get(entity)!;+ const tf = world.get(entity, Transform) as TransformData;+ const position = pose.parent !== null ? tf.worldPosition : tf.position;+ const rotation = pose.parent !== null ? tf.worldRotation : tf.rotation;+ const x = position.x * invPpu, y = position.y * invPpu, angle = quatToAngleZ(rotation);+ if (pose.x !== x || pose.y !== y || pose.angle !== angle) {+ module._physics_setBodyTransform(entity, x, y, angle);+ pose.x = x; pose.y = y; pose.angle = angle;+ }+ };+ if (all) for (const entity of this.poses.keys()) sync(entity);+ else {+ for (const parent of changedParents) for (const entity of this.groups.get(parent)!) sync(entity);+ const written = new Set(world.getWrittenEntitiesSince(Transform, this.tick));+ for (const entity of written) {+ const pose = this.poses.get(entity);+ if (pose && (pose.parent === null || !changedParents.has(pose.parent))) sync(entity);+ }+ }+ }+ this.epoch = world.transformEpoch();+ this.tick = world.getWorldTick() - 1;+ this.ppu = ppu;+ world.advanceWriteReader(Transform, this.reader!, this.tick);+ }++ dispose(): void {+ this.pause(); this.poses.clear(); this.groups.clear(); this.parents.clear();+ }+}diff --git a/sdk/tests/physics-static-sparse-wasm.test.ts b/sdk/tests/physics-static-sparse-wasm.test.tsnew file mode 100644index 000000000..398e5477e--- /dev/null+++ b/sdk/tests/physics-static-sparse-wasm.test.ts@@ -0,0 +1,111 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';+import { App } from '../src/app/app';+import { Transform, Canvas } from '../src/ecs/component';+import { Physics2DPlugin } from '../src/physics/Physics2DPlugin';+import { Physics2DRuntime } from '../src/physics/Physics2DRuntime';+import { Physics2D } from '../src/physics/Physics2D';+import { RigidBody2D, BoxCollider2D, BodyType } from '../src/physics/PhysicsComponents';+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';+import type { ESEngineModule } from '../src/wasm';+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';+import { setEditorMode, setPlayMode } from '../src/ecs/env';++let engine: ESEngineModule;+const apps: App[] = [];+afterEach(() => { setEditorMode(false); setPlayMode(false); for (const app of apps.splice(0)) app.quit(); vi.restoreAllMocks(); });++async function scene() {+ engine.setActiveContext(null);+ const app = App.new(); apps.push(app);+ app.connectCpp(new engine.Registry(), engine, { ownedRegistry: true });+ const module = await loadSideModule<PhysicsWasmModule>('physics');+ const move = vi.spyOn(module, '_physics_setBodyTransform');+ const plugin = new Physics2DPlugin('', { gravity: { x: 0, y: 0 }, fixedTimestep: 1 / 60 }, async () => module);+ app.addPlugin(plugin);+ await app.getResource(Physics2DRuntime).initPromise;+ const world = app.world, parent = world.spawn(), unrelated = world.spawn(), bodies: number[] = [];+ world.insert(parent, Transform); world.insert(unrelated, Transform);+ for (let i = 0; i < 256; i++) {+ const body = world.spawn(); bodies.push(body);+ world.insert(body, Transform, { position: { x: i * 40, y: 0, z: 0 } });+ world.insert(body, RigidBody2D, { bodyType: BodyType.Static });+ world.insert(body, BoxCollider2D, { halfExtents: { x: .05, y: .05 }, radius: 0 });+ world.setParent(body, parent);+ }+ await app.stepFrames(3, 1 / 60); move.mockClear();+ const hit = (body = bodies[0], y = 0) => app.getResource(Physics2D).raycast({ x: -50, y }, { x: 1, y: 0 }, 300)+ .find(value => value.entity === body);+ return { app, world, module, move, plugin, parent, unrelated, bodies, hit };+}++describe.skipIf(!HAS_WASM || !hasSideModule('physics'))('sparse static physics synchronization', () => {+ beforeAll(async () => { engine = await loadWasmModule(); });++ it('ignores unrelated authored motion and reads only the edited static child', async () => {+ const { app, world, move, unrelated, bodies, hit } = await scene();+ const ids = new Set(bodies), get = vi.spyOn(world, 'get'), changed = vi.spyOn(world, 'isChangedSince');+ for (let i = 0; i < 20; i++) {+ world.update(unrelated, Transform, value => { value.position.x++; });+ await app.tick(1 / 60);+ }+ expect(get.mock.calls.filter(([id, c]) => c === Transform && ids.has(id))).toHaveLength(0);+ expect(changed.mock.calls.filter(([id, c]) => c === Transform && ids.has(id))).toHaveLength(0);+ expect(move).not.toHaveBeenCalled();+ world.update(bodies[0], Transform, value => { value.position.x += 7; }); get.mockClear();+ await app.stepFrames(2, 1 / 60);+ expect(get.mock.calls.filter(([id, c]) => c === Transform && ids.has(id)).map(([id]) => id)).toEqual([bodies[0]]);+ expect(move).toHaveBeenCalledOnce(); expect(hit()?.point.x).toBeCloseTo(2, 3);+ });++ it('observes a native-driven parent while unrelated static groups stay untouched', async () => {+ const { app, world, parent, bodies, move, hit } = await scene();+ const stableParent = world.spawn(), stableBody = world.spawn();+ world.insert(stableParent, Transform); world.insert(stableBody, Transform, { position: { x: 0, y: 500, z: 0 } });+ world.insert(stableBody, RigidBody2D, { bodyType: BodyType.Static });+ world.insert(stableBody, BoxCollider2D); world.setParent(stableBody, stableParent);+ await app.stepFrames(2, 1 / 60); move.mockClear();+ const get = vi.spyOn(world, 'get');+ // Native/AOT producers invalidate composition without recording a JS write.+ const ptr = engine.getTransformPtr(world.getCppRegistry()!, parent) >> 2;+ engine.HEAPF32[ptr + 1] = 30; world.invalidateTransformComposition();+ await app.stepFrames(2, 1 / 60);+ expect(move).toHaveBeenCalledTimes(bodies.length);+ expect(hit(bodies[0], 30)?.point.x).toBeCloseTo(-5, 3);+ expect(get.mock.calls.filter(([id, c]) => id === stableBody && c === Transform)).toHaveLength(0);+ });++ it('refreshes reparented, re-enabled and rescaled bodies without recreating them', async () => {+ const { app, world, parent, bodies, hit, module } = await scene();+ const first = bodies[0], second = world.spawn(), canvas = world.spawn();+ world.insert(second, Transform, { position: { x: 50, y: 0, z: 0 } });+ world.insert(canvas, Canvas, { pixelsPerUnit: 100 });+ await app.tick(1 / 60); const count = module._physics_getBodyCount();+ world.setParent(first, second); await app.stepFrames(2, 1 / 60);+ expect(hit()?.point.x).toBeCloseTo(45, 3);+ world.update(first, RigidBody2D, value => { value.enabled = false; }); await app.tick(1 / 60);+ world.update(first, Transform, value => { value.position.x = 10; }); await app.tick(1 / 60);+ world.update(first, RigidBody2D, value => { value.enabled = true; }); await app.tick(1 / 60);+ expect(hit()?.point.x).toBeCloseTo(55, 3);+ world.update(canvas, Canvas, value => { value.pixelsPerUnit = 200; }); await app.tick(1 / 60);+ expect(hit()?.point.x).toBeCloseTo(50, 3);+ world.setParent(first, parent); await app.tick(1 / 60);+ expect(hit()?.point.x).toBeCloseTo(0, 3); expect(module._physics_getBodyCount()).toBe(count);+ });++ it.each(['host', 'editor'] as const)('releases write history during %s pause and refreshes on resume', async mode => {+ const { app, world, bodies, hit, plugin } = await scene();+ expect(world.writeReaderCount(Transform)).toBe(1);+ if (mode === 'host') app.setPaused(true); else { setEditorMode(true); setPlayMode(false); }+ await app.tick(1 / 60);+ expect(world.writeReaderCount(Transform)).toBe(0);+ for (let i = 0; i < 50; i++) { world.update(bodies[0], Transform, value => { value.position.x += 1; }); await app.tick(1 / 60); }+ expect(world.bufferedWriteRows(Transform)).toBe(0);+ if (mode === 'host') app.setPaused(false); else setPlayMode(true);+ await app.stepFrames(2, 1 / 60);+ expect(hit()?.point.x).toBeCloseTo(45, 3); expect(world.writeReaderCount(Transform)).toBe(1);+ plugin.cleanup(app);+ expect(world.writeReaderCount(Transform)).toBe(0); expect(world.bufferedWriteRows(Transform)).toBe(0);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 213b2eb42..8c64b7f1a 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 = {+ 'perf(physics): synchronize only changed static body groups':+ { note: 'Static physics synchronization skips unchanged body groups.' },'perf(editor): project visible tile collision chunks':{ note: 'Tile collision overlays project only visible local chunks.' },'perf(editor): synchronize local tile collision frames':