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
feat(physics): unified reconciler — runtime collider/joint/enabled mutability (P2)
esengine5a8435884ff6
diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmakeindex e88f86db6..268076d06 100644--- a/cmake/Emscripten.cmake+++ b/cmake/Emscripten.cmake@@ -89,11 +89,12 @@ set(ES_EMSCRIPTEN_WXGAME_MAIN_MODULE_FLAGS--closure=0)-# Physics side module flags (SIDE_MODULE=2, pure .wasm, no JS glue)+# Physics side module flags (SIDE_MODULE=2, pure .wasm, no JS glue).+# SIDE_MODULE=2 already implies relocatable; the standalone -sRELOCATABLE=1 was+# removed in newer emscripten ("No longer supported"), so it's not listed.set(ES_EMSCRIPTEN_PHYSICS_SIDE_MODULE_FLAGS-sSIDE_MODULE=2-sWASM=1- -sRELOCATABLE=1-O3-flto)@@ -184,7 +185,9 @@ endfunction()# Helper function to apply physics SIDE_MODULE settingsfunction(es_apply_physics_side_module_settings TARGET_NAME)- target_compile_options(${TARGET_NAME} PRIVATE -fPIC -sRELOCATABLE=1 -flto)+ # -fPIC is enough for side-module objects; -sRELOCATABLE was removed in newer+ # emscripten and SIDE_MODULE=2 (link flags) already makes the module relocatable.+ target_compile_options(${TARGET_NAME} PRIVATE -fPIC -flto)string(REPLACE ";" " " LINK_FLAGS_STR "${ES_EMSCRIPTEN_PHYSICS_SIDE_MODULE_FLAGS}")set_target_properties(${TARGET_NAME} PROPERTIESdiff --git a/docs/REARCH_PHYSICS.md b/docs/REARCH_PHYSICS.mdindex fe8362dab..2bd1d380d 100644--- a/docs/REARCH_PHYSICS.md+++ b/docs/REARCH_PHYSICS.md@@ -1,9 +1,10 @@# Physics Architecture — Audit & Rearchitecture-**Status (2026-06-21):** audit complete; **P1 in progress** (FixedUpdate determinism +-render interpolation). Physics core = **Box2D 3.2.0** (the v3 rewrite) in a side wasm-module (`third_party/box2d`, C++ bindings `src/esengine/bindings/Physics*.cpp`), wrapped-by the TS SDK (`sdk/src/physics/*`).+**Status (2026-06-21):** audit complete; **P1 DONE** (FixedUpdate determinism + render+interpolation); **P2 DONE** (unified reconciler — runtime collider/joint/enabled+mutability). Physics core = **Box2D 3.2.0** (the v3 rewrite) in a side wasm module+(`third_party/box2d`, C++ bindings `src/esengine/bindings/Physics*.cpp`), wrapped by the+TS SDK (`sdk/src/physics/*`).## Verdict@@ -64,8 +65,20 @@ in the integration layer.- **P1 — FixedUpdate determinism + render interpolation (together).** Highest correctness +visible-quality win. SDK-only (no wasm rebuild). See below.-- **P2 — runtime collider/joint/`enabled` mutability.** Unblocks editor live-edit and the- physics project-settings.+- **P2 — runtime collider/joint/`enabled` mutability (DONE).** A unified declarative+ reconciler replaces the ad-hoc imperative loop: Box2D is a reconciled cache of each+ entity's component structure, kept in sync with minimal *in-place* Box2D v3 ops that+ preserve simulation state — never destroy-and-rebuild the body. Two new C++ primitives:+ `physics_setBodyEnabled` (`b2Body_Enable/Disable` — toggles `RigidBody.enabled` keeping+ shapes/velocity/joints) and `physics_clearShapes` (`b2DestroyShape` over the body's+ shapes, so colliders rebuild in place with the body — and its velocity/pose/contacts —+ intact). The reconciler (`PhysicsSystem.ts`) drives them off uniform `isChangedSince`+ dirty checks across RigidBody + every collider (`colliderSignature`) + every joint+ (`jointChangedOrGone`): body create/destroy/enable-disable/props; shapes rebuilt on+ collider set/field change; joints destroyed+recreated on change/removal. **Build note:**+ the physics wasm was rebuilt with emscripten 5.0.6 — required dropping the now-removed+ `-sRELOCATABLE=1` flag (`cmake/Emscripten.cmake`; `-sSIDE_MODULE=2` already implies it).+ Chain colliders aren't runtime-rebuilt (their `b2ChainId` isn't tracked — static geometry).- **P3 — `b2World_GetBodyEvents` + contact hit events + world-toggle config surface** (theconfig surface feeds the project-settings flow). Touches C++.- **P4 — batched writeback + identity-leak fixes + query `ppu` from live Canvas.**diff --git a/sdk/src/physics/PhysicsModuleLoader.ts b/sdk/src/physics/PhysicsModuleLoader.tsindex 46f35ce7b..948e93581 100644--- a/sdk/src/physics/PhysicsModuleLoader.ts+++ b/sdk/src/physics/PhysicsModuleLoader.ts@@ -13,6 +13,10 @@ export interface PhysicsWasmModule {fixedRotation: number, bullet: number): void;_physics_destroyBody(entityId: number): void;_physics_hasBody(entityId: number): number;+ /** Enable/disable a body in place (keeps shapes/velocity/joints). */+ _physics_setBodyEnabled(entityId: number, enabled: number): void;+ /** Destroy all of an entity's shapes, keeping the body, for in-place rebuild. */+ _physics_clearShapes(entityId: number): void;_physics_addBoxShape(entityId: number, halfW: number, halfH: number,offX: number, offY: number, radius: number,@@ -213,6 +217,8 @@ export async function loadPhysicsSideModule(_physics_createBody: cwrap('physics_createBody', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_createBody'],_physics_destroyBody: cwrap('physics_destroyBody', null, ['number']) as PhysicsWasmModule['_physics_destroyBody'],_physics_hasBody: cwrap('physics_hasBody', 'number', ['number']) as PhysicsWasmModule['_physics_hasBody'],+ _physics_setBodyEnabled: cwrap('physics_setBodyEnabled', null, ['number', 'number']) as PhysicsWasmModule['_physics_setBodyEnabled'],+ _physics_clearShapes: cwrap('physics_clearShapes', null, ['number']) as PhysicsWasmModule['_physics_clearShapes'],_physics_addBoxShape: cwrap('physics_addBoxShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addBoxShape'],_physics_addCircleShape: cwrap('physics_addCircleShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addCircleShape'],diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.tsindex b3d62cc7c..064cdd7cc 100644--- a/sdk/src/physics/PhysicsSystem.ts+++ b/sdk/src/physics/PhysicsSystem.ts@@ -530,6 +530,49 @@ interface CachedBodyProps {angularDamping: number;fixedRotation: boolean;bullet: boolean;+ /** Last-applied RigidBody.enabled — drives in-place enable/disable. */+ enabled: boolean;+ /** Bitmask of present collider components — drives shape rebuild on change. */+ colliderSig: number;+}++// The collider component types, in shape-add order. Their index is a stable bit+// in the per-entity collider signature (presence) — a change in the set, or any+// present collider's fields, triggers an in-place shape rebuild.+const COLLIDER_TYPES = [+ BoxCollider, CircleCollider, CapsuleCollider, SegmentCollider, PolygonCollider, ChainCollider,+] as const;++const JOINT_TYPES = [RevoluteJoint, DistanceJoint, PrismaticJoint, WeldJoint, WheelJoint] as const;++/** Bitmask of which collider components an entity currently has. @internal */+export function colliderSignature(world: App['world'], entity: Entity): number {+ let sig = 0;+ for (let i = 0; i < COLLIDER_TYPES.length; i++) {+ if (world.has(entity, COLLIDER_TYPES[i])) sig |= 1 << i;+ }+ return sig;+}++/** True if any present collider component changed since `sinceTick`. */+function collidersChangedSince(world: App['world'], entity: Entity, sinceTick: number): boolean {+ for (const C of COLLIDER_TYPES) {+ if (world.has(entity, C) && world.isChangedSince(entity, C, sinceTick)) return true;+ }+ return false;+}++/**+ * For a tracked joint entity (invariant: ≤1 joint component): whether its joint+ * was removed, or its definition changed since `sinceTick` — either way the old+ * Box2D joint must be destroyed (createPendingJoints re-adds it if still present).+ * @internal+ */+export function jointChangedOrGone(world: App['world'], entity: Entity, sinceTick: number): boolean {+ for (const J of JOINT_TYPES) {+ if (world.has(entity, J)) return world.isChangedSince(entity, J, sinceTick);+ }+ return true; // no joint component left → gone}/**@@ -588,31 +631,32 @@ export function registerPhysicsSystem(const entities = world.getEntitiesWithComponents([RigidBody, Transform]);const currentEntities = new Set<Entity>();+ // ── Unified body + collider reconcile ───────────────────────+ // Each entity's Box2D body is a reconciled projection of its+ // components: create on first enable, then bring the body in line+ // (enable/disable, props, shapes) with minimal in-place ops that+ // preserve simulation state — never destroy-and-rebuild.for (const entity of entities) {currentEntities.add(entity);+ const rb = world.get(entity, RigidBody) as RigidBodyData;if (!trackedEntities.has(entity)) {- const rb = world.get(entity, RigidBody) as RigidBodyData;- if (!rb.enabled) continue;+ if (!rb.enabled) continue; // lazy-create on first enableconst wt = world.get(entity, Transform) as TransformData;const hasParent = world.has(entity, Parent);const posX = hasParent ? wt.worldPosition.x : wt.position.x;const posY = hasParent ? wt.worldPosition.y : wt.position.y;const rot = hasParent ? wt.worldRotation : wt.rotation;- const angle = quatToAngleZ(rot);module._physics_createBody(entity, rb.bodyType,- posX * invPpu, posY * invPpu, angle,+ posX * invPpu, posY * invPpu, quatToAngleZ(rot),rb.gravityScale, rb.linearDamping, rb.angularDamping,- rb.fixedRotation ? 1 : 0, rb.bullet ? 1 : 0+ rb.fixedRotation ? 1 : 0, rb.bullet ? 1 : 0,);-addShapeForEntity(app, module, entity, config.collisionLayerMasks);trackedEntities.add(entity);- if (world.has(entity, Parent)) {- parentedBodies.add(entity);- }+ if (hasParent) parentedBodies.add(entity);cachedProps.set(entity, {bodyType: rb.bodyType,gravityScale: rb.gravityScale,@@ -620,57 +664,85 @@ export function registerPhysicsSystem(angularDamping: rb.angularDamping,fixedRotation: rb.fixedRotation,bullet: rb.bullet,+ enabled: true,+ colliderSig: colliderSignature(world, entity),});- } else {- if (world.isChangedSince(entity, RigidBody, lastEntitySyncTick)) {- const rb = world.get(entity, RigidBody) as RigidBodyData;- const prev = cachedProps.get(entity);- if (prev &&- (prev.bodyType !== rb.bodyType ||- prev.gravityScale !== rb.gravityScale ||- prev.linearDamping !== rb.linearDamping ||- prev.angularDamping !== rb.angularDamping ||- prev.fixedRotation !== rb.fixedRotation ||- prev.bullet !== rb.bullet)) {- module._physics_updateBodyProperties(- entity, rb.bodyType,- rb.gravityScale, rb.linearDamping, rb.angularDamping,- rb.fixedRotation ? 1 : 0, rb.bullet ? 1 : 0- );- prev.bodyType = rb.bodyType;- prev.gravityScale = rb.gravityScale;- prev.linearDamping = rb.linearDamping;- prev.angularDamping = rb.angularDamping;- prev.fixedRotation = rb.fixedRotation;- prev.bullet = rb.bullet;- }- }-- const cached = cachedProps.get(entity);- if (cached && cached.bodyType === BodyType.Kinematic) {- const wt = world.get(entity, Transform) as TransformData;- const angle = quatToAngleZ(wt.worldRotation);- module._physics_setBodyTransform(- entity,- wt.worldPosition.x * invPpu, wt.worldPosition.y * invPpu,- angle- );- }+ continue;}- }- lastEntitySyncTick = world.getWorldTick();+ const cached = cachedProps.get(entity)!;++ // 1. enabled toggle — in place (keeps shapes/velocity/joints).+ if (rb.enabled !== cached.enabled) {+ module._physics_setBodyEnabled(entity, rb.enabled ? 1 : 0);+ cached.enabled = rb.enabled;+ }+ // 2. body properties.+ if (world.isChangedSince(entity, RigidBody, lastEntitySyncTick) &&+ (cached.bodyType !== rb.bodyType ||+ cached.gravityScale !== rb.gravityScale ||+ cached.linearDamping !== rb.linearDamping ||+ cached.angularDamping !== rb.angularDamping ||+ cached.fixedRotation !== rb.fixedRotation ||+ cached.bullet !== rb.bullet)) {+ module._physics_updateBodyProperties(+ entity, rb.bodyType,+ rb.gravityScale, rb.linearDamping, rb.angularDamping,+ rb.fixedRotation ? 1 : 0, rb.bullet ? 1 : 0,+ );+ cached.bodyType = rb.bodyType;+ cached.gravityScale = rb.gravityScale;+ cached.linearDamping = rb.linearDamping;+ cached.angularDamping = rb.angularDamping;+ cached.fixedRotation = rb.fixedRotation;+ cached.bullet = rb.bullet;+ }++ // 3. colliders — rebuild shapes in place when the collider set+ // or any collider's fields change (body + velocity preserved).+ const sig = colliderSignature(world, entity);+ if (sig !== cached.colliderSig ||+ collidersChangedSince(world, entity, lastEntitySyncTick)) {+ module._physics_clearShapes(entity);+ addShapeForEntity(app, module, entity, config.collisionLayerMasks);+ cached.colliderSig = sig;+ }++ // 4. kinematic bodies are driven directly from their Transform.+ if (cached.bodyType === BodyType.Kinematic) {+ const wt = world.get(entity, Transform) as TransformData;+ module._physics_setBodyTransform(+ entity,+ wt.worldPosition.x * invPpu, wt.worldPosition.y * invPpu,+ quatToAngleZ(wt.worldRotation),+ );+ }+ }++ // Bodies whose entity left the query without firing onDespawn.for (const entity of trackedEntities) {if (!currentEntities.has(entity)) {module._physics_destroyBody(entity);trackedEntities.delete(entity);cachedProps.delete(entity);+ parentedBodies.delete(entity);}}+ // ── Joint reconcile ─────────────────────────────────────────+ // Destroy joints whose definition changed or whose component was+ // removed; createPendingJoints re-adds present+enabled ones.+ for (const entity of [...trackedJoints]) {+ if (jointChangedOrGone(world, entity, lastEntitySyncTick)) {+ module._physics_destroyJoint(entity);+ trackedJoints.delete(entity);+ }+ }createPendingJoints(world, module, trackedEntities, trackedJoints, invPpu);+ lastEntitySyncTick = world.getWorldTick();+if (trackedEntities.size > 0) {module._physics_step(fixedDt);}diff --git a/sdk/tests/physicsReconcile.test.ts b/sdk/tests/physicsReconcile.test.tsnew file mode 100644index 000000000..298390ad5--- /dev/null+++ b/sdk/tests/physicsReconcile.test.ts@@ -0,0 +1,64 @@+/**+ * @file Physics reconciler change-detection. The unified reconciler rebuilds+ * shapes / joints from these signals, so they're the load-bearing logic:+ * colliderSignature (which colliders are present → bitmask) and+ * jointChangedOrGone (a tracked joint's component removed or edited).+ */+import { describe, it, expect } from 'vitest';+import { World } from '../src/world';+import { createMockModule } from './mocks/wasm';+import {+ BoxCollider, CircleCollider, CapsuleCollider, RevoluteJoint,+} from '../src/physics/PhysicsComponents';+import { colliderSignature, jointChangedOrGone } from '../src/physics/PhysicsSystem';++function testWorld(): World {+ const mod = createMockModule();+ const world = new World();+ world.connectCpp(mod.getRegistry(), mod);+ return world;+}++describe('colliderSignature', () => {+ it('is 0 when the entity has no collider', () => {+ const world = testWorld();+ const e = world.spawn();+ expect(colliderSignature(world, e)).toBe(0);+ });++ it('sets one bit per present collider type (Box=bit0, Circle=bit1)', () => {+ const world = testWorld();+ const e = world.spawn();+ world.insert(e, BoxCollider, {} as never);+ expect(colliderSignature(world, e)).toBe(0b1);+ world.insert(e, CircleCollider, {} as never);+ expect(colliderSignature(world, e)).toBe(0b11);+ });++ it('changes when the collider set changes (drives shape rebuild)', () => {+ const world = testWorld();+ const e = world.spawn();+ world.insert(e, BoxCollider, {} as never);+ const before = colliderSignature(world, e);+ world.insert(e, CapsuleCollider, {} as never); // bit 2+ expect(colliderSignature(world, e)).not.toBe(before);+ expect(colliderSignature(world, e)).toBe(0b101);+ });+});++describe('jointChangedOrGone', () => {+ it('is true when the entity no longer has any joint component (gone)', () => {+ const world = testWorld();+ const e = world.spawn(); // no joint+ expect(jointChangedOrGone(world, e, 0)).toBe(true);+ });++ it('is false for a present joint not changed since the given tick', () => {+ const world = testWorld();+ const e = world.spawn();+ world.insert(e, RevoluteJoint, {} as never);+ // isChangedSince(currentTick) is false (it was last touched this tick),+ // so a present, unedited joint is left intact.+ expect(jointChangedOrGone(world, e, world.getWorldTick())).toBe(false);+ });+});diff --git a/src/esengine/bindings/PhysicsModuleEntry.cpp b/src/esengine/bindings/PhysicsModuleEntry.cppindex b104beb55..39cadfec9 100644--- a/src/esengine/bindings/PhysicsModuleEntry.cpp+++ b/src/esengine/bindings/PhysicsModuleEntry.cpp@@ -92,6 +92,20 @@ int physics_hasBody(uint32_t entityId) {return g_ctx.entityToBody.contains(entityId) ? 1 : 0;}+// Enable / disable a body in place (RigidBody.enabled). Unlike destroy, this keeps+// the body, its shapes, velocity, and joints — b2Body_Disable just removes it from+// simulation/broadphase — so the reconciler can toggle without losing state.+EMSCRIPTEN_KEEPALIVE+void physics_setBodyEnabled(uint32_t entityId, int enabled) {+ b2BodyId body = findValidBody(entityId);+ if (!b2Body_IsValid(body)) return;+ if (enabled) {+ b2Body_Enable(body);+ } else {+ b2Body_Disable(body);+ }+}+// SimulationEMSCRIPTEN_KEEPALIVEdiff --git a/src/esengine/bindings/PhysicsShapes.cpp b/src/esengine/bindings/PhysicsShapes.cppindex 2023e76af..6420b9f81 100644--- a/src/esengine/bindings/PhysicsShapes.cpp+++ b/src/esengine/bindings/PhysicsShapes.cpp@@ -174,4 +174,21 @@ void physics_addChainShape(uint32_t entityId, uintptr_t pointsPtr, int pointCounb2CreateChain(it->second, &chainDef);}+// Destroy all of an entity's shapes while KEEPING the body, so the reconciler can+// rebuild colliders in place (velocity, pose, contacts-elsewhere, and joints are+// preserved — far cheaper and less disruptive than destroying the whole body).+// Chain shapes (b2CreateChain) aren't tracked in entityToShapes and so aren't+// cleared here; chains are static level geometry and aren't runtime-rebuilt.+EMSCRIPTEN_KEEPALIVE+void physics_clearShapes(uint32_t entityId) {+ auto it = g_ctx.entityToShapes.find(entityId);+ if (it == g_ctx.entityToShapes.end()) return;+ for (b2ShapeId shapeId : it->second) {+ if (b2Shape_IsValid(shapeId)) {+ b2DestroyShape(shapeId, false); // mass is recomputed when shapes are re-added+ }+ }+ it->second.clear();+}+} // extern "C"