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.

perf(physics): batch composed static body poses across hosts

yhh5bf7ecabe6fd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index af1999a24..965d342f5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Fixed
+- **Moving static collision uses a shared batch pose channel.** The engine exports composed 2D poses for selected active entities and physics applies them in one call, skipping unchanged solver poses. Web modules copy populated rows between their heaps; native hosts use their shared arena. Batch rows share a generated C++ stride, lazy world fields are decomposed before export, temporary buffers are released on failure, and hosts without the new calls keep the scalar path.
+
- **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
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index b643fb7a0..36254e0cc 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5,7 +5,7 @@ Symbols: 115 public · 91 beta · 1581 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"73d45f32834f0b85"
+"0c84aca932384575"
```
## ANCHOR_AXES — const @experimental
@@ -5917,6 +5917,7 @@ _physics_setAwake: (entityId: number, awake: number) => void
_physics_setBodyEnabled: (entityId: number, enabled: number) => void
_physics_setBodyTargetTransform: (entityId: number, x: number, y: number, angle: number, dt: number) => void
_physics_setBodyTransform: (entityId: number, x: number, y: number, angle: number) => void
+_physics_setBodyTransforms: ((bufferPtr: number, count: number, ppu: number) => number) | undefined
_physics_setDistanceJointLength: (entityId: number, length: number) => void
_physics_setDistanceJointLimits: (entityId: number, minLength: number, maxLength: number) => void
_physics_setDistanceJointMaxMotorForce: (entityId: number, force: number) => void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index de48a80ed..f28111672 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5,7 +5,7 @@ Symbols: 115 public · 96 beta · 1600 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"73d45f32834f0b85"
+"0c84aca932384575"
```
## ANCHOR_AXES — const @experimental
@@ -6120,6 +6120,7 @@ _physics_setAwake: (entityId: number, awake: number) => void
_physics_setBodyEnabled: (entityId: number, enabled: number) => void
_physics_setBodyTargetTransform: (entityId: number, x: number, y: number, angle: number, dt: number) => void
_physics_setBodyTransform: (entityId: number, x: number, y: number, angle: number) => void
+_physics_setBodyTransforms: ((bufferPtr: number, count: number, ppu: number) => number) | undefined
_physics_setDistanceJointLength: (entityId: number, length: number) => void
_physics_setDistanceJointLimits: (entityId: number, minLength: number, maxLength: number) => void
_physics_setDistanceJointMaxMotorForce: (entityId: number, force: number) => void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index d11efadbc..e901abd71 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -5912,6 +5912,7 @@ _physics_setAwake: (entityId: number, awake: number) => void
_physics_setBodyEnabled: (entityId: number, enabled: number) => void
_physics_setBodyTargetTransform: (entityId: number, x: number, y: number, angle: number, dt: number) => void
_physics_setBodyTransform: (entityId: number, x: number, y: number, angle: number) => void
+_physics_setBodyTransforms: ((bufferPtr: number, count: number, ppu: number) => number) | undefined
_physics_setDistanceJointLength: (entityId: number, length: number) => void
_physics_setDistanceJointLimits: (entityId: number, minLength: number, maxLength: number) => void
_physics_setDistanceJointMaxMotorForce: (entityId: number, force: number) => void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index dc788226d..918ee3970 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -6205,6 +6205,7 @@ _physics_setAwake: (entityId: number, awake: number) => void
_physics_setBodyEnabled: (entityId: number, enabled: number) => void
_physics_setBodyTargetTransform: (entityId: number, x: number, y: number, angle: number, dt: number) => void
_physics_setBodyTransform: (entityId: number, x: number, y: number, angle: number) => void
+_physics_setBodyTransforms: ((bufferPtr: number, count: number, ppu: number) => number) | undefined
_physics_setDistanceJointLength: (entityId: number, length: number) => void
_physics_setDistanceJointLimits: (entityId: number, minLength: number, maxLength: number) => void
_physics_setDistanceJointMaxMotorForce: (entityId: number, force: number) => void
diff --git a/sdk/etc/physics.api.md b/sdk/etc/physics.api.md
index 97182bb84..5358df4f1 100644
--- a/sdk/etc/physics.api.md
+++ b/sdk/etc/physics.api.md
@@ -546,6 +546,7 @@ _physics_setAwake: (entityId: number, awake: number) => void
_physics_setBodyEnabled: (entityId: number, enabled: number) => void
_physics_setBodyTargetTransform: (entityId: number, x: number, y: number, angle: number, dt: number) => void
_physics_setBodyTransform: (entityId: number, x: number, y: number, angle: number) => void
+_physics_setBodyTransforms: ((bufferPtr: number, count: number, ppu: number) => number) | undefined
_physics_setDistanceJointLength: (entityId: number, length: number) => void
_physics_setDistanceJointLimits: (entityId: number, minLength: number, maxLength: number) => void
_physics_setDistanceJointMaxMotorForce: (entityId: number, force: number) => void
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 82d4ad145..cd5152dfb 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -408,6 +408,7 @@ registry_getCameraEntities: (registry: CppRegistry) => number[]
registry_getCanvasEntities: ((registry: CppRegistry) => number[]) | undefined
registry_getCanvasEntity: (registry: CppRegistry) => number
registry_getGeneration: (registry: CppRegistry, entity: number) => number
+registry_readWorldPoses2D: ((registry: CppRegistry, entitiesPtr: number, count: number, outputPtr: number) => number) | undefined
renderer_begin: (matrixPtr: number, targetHandle: number, clearFlags: number, r: number, g: number, b: number, a: number, clearX: number, clearY: number, clearW: number, clearH: number) => void
renderer_beginFrame: (elapsedSec: number) => void
renderer_beginScreenOverlay: ((projectionPtr: number, vpX: number, vpY: number, vpW: number, vpH: number) => void) | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index c1eb5852e..45bf4ab07 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -5919,6 +5919,7 @@ _physics_setAwake: (entityId: number, awake: number) => void
_physics_setBodyEnabled: (entityId: number, enabled: number) => void
_physics_setBodyTargetTransform: (entityId: number, x: number, y: number, angle: number, dt: number) => void
_physics_setBodyTransform: (entityId: number, x: number, y: number, angle: number) => void
+_physics_setBodyTransforms: ((bufferPtr: number, count: number, ppu: number) => number) | undefined
_physics_setDistanceJointLength: (entityId: number, length: number) => void
_physics_setDistanceJointLimits: (entityId: number, minLength: number, maxLength: number) => void
_physics_setDistanceJointMaxMotorForce: (entityId: number, force: number) => void
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index fea8afe99..b89c831e2 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -125,6 +125,7 @@ export interface NativeEngineApi {
registry_batchSyncPhysicsTransforms?(registry: unknown, bufferPtr: number, count: number, ppu: number): void;
registry_getCanvasEntity?(registry: unknown): number;
registry_getGeneration?(registry: unknown, entity: number): number;
+ registry_readWorldPoses2D?(registry: unknown, entitiesPtr: number, count: number, outputPtr: number): number;
renderer_begin?(matrixPtr: number, targetHandle: number, clearFlags: number, r: number, g: number, b: number, a: number, clearX: number, clearY: number, clearW: number, clearH: number): void;
renderer_beginFrame?(elapsedSec: number): void;
renderer_beginScreenOverlay?(projectionPtr: number, vpX: number, vpY: number, vpW: number, vpH: number): void;
@@ -416,6 +417,7 @@ export function createNativeEngineApi(
bind('registry_batchSyncPhysicsTransforms', 'es_registry_batchSyncPhysicsTransforms', true);
bind('registry_getCanvasEntity', 'es_registry_getCanvasEntity', true);
bind('registry_getGeneration', 'es_registry_getGeneration', true);
+ bind('registry_readWorldPoses2D', 'es_registry_readWorldPoses2D', true);
bind('renderer_begin', 'es_renderer_begin', false);
bind('renderer_beginFrame', 'es_renderer_beginFrame', false);
bind('renderer_beginScreenOverlay', 'es_renderer_beginScreenOverlay', false);
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 3b0cf2936..784dbca35 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BodyType, CanvasScaleMode, Cl
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '73d45f32834f0b85';
+export const ABI_LAYOUT_HASH = '0c84aca932384575';
/**
* One asset-valued field of a component: which field, and what kind of
diff --git a/sdk/src/physics/PhysicsModuleLoader.ts b/sdk/src/physics/PhysicsModuleLoader.ts
index 3e59a58ad..6d2d70dce 100644
--- a/sdk/src/physics/PhysicsModuleLoader.ts
+++ b/sdk/src/physics/PhysicsModuleLoader.ts
@@ -49,6 +49,8 @@ export interface PhysicsWasmModule {
_physics_step(dt: number): void;
_physics_setBodyTransform(entityId: number, x: number, y: number, angle: number): void;
+ /** Batch world-pixel poses; returns how many live bodies actually moved. */
+ _physics_setBodyTransforms?(bufferPtr: number, count: number, ppu: number): number;
_physics_setBodyTargetTransform(entityId: number, x: number, y: number, angle: number, dt: number): void;
_physics_getDynamicBodyCount(): number;
_physics_getBodyCount(): number;
diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.ts
index 1392736bd..233d811b5 100644
--- a/sdk/src/physics/PhysicsSystem.ts
+++ b/sdk/src/physics/PhysicsSystem.ts
@@ -45,6 +45,7 @@ import {
import { withMalloc } from '../wasm/wasmScratch';
import { engineApi, type EngineApi } from '../ecs/bridge/engineApi';
import { StaticBodyPoses2D } from './StaticBodyPoses2D';
+import { ENTITY_POSE_2D_WORDS } from '../wasm/constants.generated';
/**
* The engine surface this file drives. `getTransformPtr` is the web module's own
@@ -361,7 +362,7 @@ function syncOneWayPlatforms(
// =============================================================================
-const PHYSICS_BODY_STRIDE = 4; // u32 entity + 3x f32 (x, y, angle)
+const PHYSICS_BODY_STRIDE = ENTITY_POSE_2D_WORDS;
const PHYSICS_BODY_BYTES = PHYSICS_BODY_STRIDE * 4;
/**
diff --git a/sdk/src/physics/StaticBodyPoses2D.ts b/sdk/src/physics/StaticBodyPoses2D.ts
index 5d6803017..ba8ef9575 100644
--- a/sdk/src/physics/StaticBodyPoses2D.ts
+++ b/sdk/src/physics/StaticBodyPoses2D.ts
@@ -5,6 +5,7 @@ import type { World } from '../ecs/world';
import type { Entity } from '../types';
import type { PhysicsWasmModule } from './PhysicsModuleLoader';
import { quatToAngleZ } from './PhysicsTypes';
+import { batchStaticPoses2D } from './batchStaticPoses2D';
interface StaticPose { x: number; y: number; angle: number; parent: Entity | null }
@@ -18,6 +19,7 @@ export class StaticBodyPoses2D {
private epoch = -1;
private tick = -1;
private ppu = -1;
+ private legacyStale = false;
constructor(private readonly world: World) {}
@@ -76,27 +78,36 @@ export class StaticBodyPoses2D {
} 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);
+ const selected: Entity[] = [];
+ if (all) for (const entity of this.poses.keys()) selected.push(entity);
else {
- for (const parent of changedParents) for (const entity of this.groups.get(parent)!) sync(entity);
+ for (const parent of changedParents) for (const entity of this.groups.get(parent)!) selected.push(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);
+ if (pose && (pose.parent === null || !changedParents.has(pose.parent))) selected.push(entity);
+ }
+ }
+ if (batchStaticPoses2D(world, module, selected, ppu, enabled)) this.legacyStale = true;
+ else {
+ if (this.legacyStale) {
+ for (const pose of this.poses.values()) pose.x = NaN;
+ this.legacyStale = false;
}
+ 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;
+ }
+ };
+ for (const entity of selected) sync(entity);
}
}
this.epoch = world.transformEpoch();
diff --git a/sdk/src/physics/batchStaticPoses2D.ts b/sdk/src/physics/batchStaticPoses2D.ts
new file mode 100644
index 000000000..f09076cf3
--- /dev/null
+++ b/sdk/src/physics/batchStaticPoses2D.ts
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import type { Entity } from '../types';
+import type { World } from '../ecs/world';
+import { worldEngineApi } from '../ecs/bridge/engineApi';
+import { withMalloc } from '../wasm/wasmScratch';
+import { ENTITY_POSE_2D_WORDS } from '../wasm/constants.generated';
+import type { PhysicsWasmModule } from './PhysicsModuleLoader';
+
+/** Transfer composed candidates in one batch. The native host shares its arena;
+ * standalone wasm modules copy only the populated pose rows between heaps. */
+export function batchStaticPoses2D(world: World, module: PhysicsWasmModule, entities: readonly Entity[],
+ ppu: number, enabled: (entity: Entity) => boolean): boolean {
+ const core = worldEngineApi(world), registry = world.getCppRegistry();
+ if (!core?.registry_readWorldPoses2D || !core._malloc || !core._free || !core.HEAPU32 || !core.HEAPU8
+ || !module._physics_setBodyTransforms || !registry) return false;
+ if (!entities.length) return true;
+ const bytes = ENTITY_POSE_2D_WORDS * 4;
+ return withMalloc({ _malloc: core._malloc.bind(core), _free: core._free.bind(core) }, entities.length * (4 + bytes), ptr => {
+ if (!ptr) return false;
+ let count = 0;
+ for (const entity of entities) if (enabled(entity)) core.HEAPU32![(ptr >>> 2) + count++] = entity;
+ if (!count) return true;
+ const output = ptr + entities.length * 4;
+ const rows = core.registry_readWorldPoses2D!(registry, ptr, count, output);
+ if (!Number.isInteger(rows) || rows < 0 || rows > count) throw new Error('Invalid world pose batch length');
+ if (!rows) return true;
+ if (core.HEAPU8!.buffer === module.HEAPU8.buffer) {
+ module._physics_setBodyTransforms!(output, rows, ppu);
+ return true;
+ }
+ return withMalloc(module, rows * bytes, target => {
+ if (!target) return false;
+ module.HEAPU8.set(core.HEAPU8!.subarray(output, output + rows * bytes), target);
+ module._physics_setBodyTransforms!(target, rows, ppu);
+ return true;
+ });
+ });
+}
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 9fe2ec44c..82d87749a 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -686,6 +686,7 @@ export interface ESEngineModule {
getChildEntities(registry: CppRegistry, entity: number): number[];
registry_getGeneration(registry: CppRegistry, entity: number): number;
registry_batchSyncPhysicsTransforms(registry: CppRegistry, bufferPtr: number, count: number, ppu: number): void;
+ registry_readWorldPoses2D?(registry: CppRegistry, entitiesPtr: number, count: number, outputPtr: number): number;
// GL Debug API
gl_enableErrorCheck(enabled: boolean): void;
diff --git a/sdk/src/wasm/constants.generated.ts b/sdk/src/wasm/constants.generated.ts
index 8a6fd284c..b5cbafe98 100644
--- a/sdk/src/wasm/constants.generated.ts
+++ b/sdk/src/wasm/constants.generated.ts
@@ -14,6 +14,9 @@
/** C++ `CHUNK_SIZE` in `src/esengine/tilemap/TilemapSystem.hpp`. */
export const CHUNK_SIZE = 16;
+/** C++ `ENTITY_POSE_2D_WORDS` in `src/esengine/core/EntityPose2D.hpp`. */
+export const ENTITY_POSE_2D_WORDS = 4;
+
/** C++ `kColorLutSize` in `src/esengine/particle/ParticleSystem.hpp`. */
export const GRADIENT_LUT_SIZE = 32;
diff --git a/sdk/tests/physics-batch-poses-wasm.test.ts b/sdk/tests/physics-batch-poses-wasm.test.ts
new file mode 100644
index 000000000..ada94b7ef
--- /dev/null
+++ b/sdk/tests/physics-batch-poses-wasm.test.ts
@@ -0,0 +1,115 @@
+// 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, Disabled } 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 { batchStaticPoses2D } from '../src/physics/batchStaticPoses2D';
+import { ENTITY_POSE_2D_WORDS } from '../src/wasm/constants.generated';
+import type { ESEngineModule } from '../src/wasm';
+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';
+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';
+
+let core: ESEngineModule;
+const apps: App[] = [];
+afterEach(() => { for (const app of apps.splice(0)) app.quit(); vi.restoreAllMocks(); });
+
+async function scene(batch: boolean) {
+ core.setActiveContext(null);
+ const app = App.new(); apps.push(app);
+ app.connectCpp(new core.Registry(), core, { ownedRegistry: true });
+ const module = await loadSideModule<PhysicsWasmModule>('physics');
+ if (!batch) module._physics_setBodyTransforms = undefined;
+ const scalar = vi.spyOn(module, '_physics_setBodyTransform');
+ if (batch) vi.spyOn(module, '_physics_setBodyTransforms');
+ const bulk = batch ? vi.mocked(module._physics_setBodyTransforms!) : null;
+ app.addPlugin(new Physics2DPlugin('', { gravity: { x: 0, y: 0 }, fixedTimestep: 1 / 60 }, async () => module));
+ await app.getResource(Physics2DRuntime).initPromise;
+ const world = app.world, parent = world.spawn(), bodies: number[] = [];
+ world.insert(parent, Transform);
+ for (let i = 0; i < 32; 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(2, 1 / 60); scalar.mockClear(); bulk?.mockClear();
+ return { app, world, module, scalar, bulk, parent, bodies };
+}
+
+describe.skipIf(!HAS_WASM || !hasSideModule('physics'))('batched composed physics poses', () => {
+ beforeAll(async () => { core = await loadWasmModule(); });
+
+ it.each([false, true])('moves collision through a rotated parent without recreation (batch=%s)', async batch => {
+ const { app, world, module, scalar, bulk, parent, bodies } = await scene(batch);
+ const before = module._physics_getBodyCount(), angle = .37;
+ world.update(parent, Transform, tf => {
+ tf.position = { x: 17, y: 33, z: 5 };
+ tf.rotation = { x: 0, y: 0, z: Math.sin(angle / 2), w: Math.cos(angle / 2) };
+ });
+ await app.stepFrames(2, 1 / 60);
+ const direction = { x: -Math.sin(angle), y: Math.cos(angle) };
+ const hit = app.getResource(Physics2D).raycast({ x: 17 + direction.x * 20, y: 33 + direction.y * 20 },
+ { x: -direction.x, y: -direction.y }, 40).find(hit => hit.entity === bodies[0]);
+ expect(hit).toBeDefined();
+ expect(hit!.point.x).toBeCloseTo(17 + direction.x * 5, 3);
+ expect(hit!.point.y).toBeCloseTo(33 + direction.y * 5, 3);
+ expect(module._physics_getBodyCount()).toBe(before);
+ if (batch) {
+ expect(scalar).not.toHaveBeenCalled(); expect(bulk).toHaveBeenCalledOnce();
+ expect(bulk!.mock.results[0].value).toBe(bodies.length);
+ } else expect(scalar).toHaveBeenCalledTimes(bodies.length);
+ });
+
+ it('exports lazy composed fields and filters inactive, stale and transformless ids', async () => {
+ const { world, parent, bodies } = await scene(true), invalid = world.spawn(), bare = world.spawn();
+ world.despawn(invalid); world.insert(bodies[1], Disabled);
+ world.update(parent, Transform, tf => { tf.position.x = 123; }); world.ensureTransformsComposed();
+ const ids = [bodies[0], bodies[1], invalid, bare], input = core._malloc(ids.length * 4), output = core._malloc(ids.length * ENTITY_POSE_2D_WORDS * 4);
+ try {
+ core.HEAPU32.set(ids, input >>> 2);
+ expect(core.registry_readWorldPoses2D!(world.getCppRegistry()!, input, ids.length, output)).toBe(1);
+ expect(core.HEAPU32[output >>> 2]).toBe(bodies[0]);
+ expect(core.HEAPF32[(output >>> 2) + 1]).toBeCloseTo(123, 4);
+ expect(core.registry_readWorldPoses2D!(world.getCppRegistry()!, input, -1, output)).toBe(0);
+ expect(core.registry_readWorldPoses2D!(world.getCppRegistry()!, input, ids.length, core.HEAPU8.byteLength - 4)).toBe(0);
+ } finally { core._free(input); core._free(output); }
+ });
+
+ it('refreshes the legacy cache if batching becomes unavailable after a parent move', async () => {
+ const { app, world, module, parent, bodies, scalar } = await scene(true);
+ world.update(parent, Transform, tf => { tf.position.x = 30; }); await app.stepFrames(2, 1 / 60);
+ module._physics_setBodyTransforms = undefined;
+ world.update(bodies[0], Transform, tf => { tf.position.x = -30; }); await app.stepFrames(2, 1 / 60);
+ expect(scalar).toHaveBeenCalledOnce();
+ const hit = app.getResource(Physics2D).raycast({ x: -20, y: 0 }, { x: 1, y: 0 }, 40)
+ .find(hit => hit.entity === bodies[0]);
+ expect(hit?.point.x).toBeCloseTo(-5, 3);
+ });
+
+ it('skips unchanged solver poses and frees temporary buffers after a batch failure', async () => {
+ const { world, module, bodies } = await scene(true);
+ world.update(bodies[0], Transform, tf => { tf.position.x = 10; }); world.ensureTransformsComposed();
+ const allocations = vi.spyOn(core, '_malloc'), frees = vi.spyOn(core, '_free');
+ const physicsAlloc = vi.spyOn(module, '_malloc'), physicsFree = vi.spyOn(module, '_free');
+ expect(batchStaticPoses2D(world, module, bodies, 100, () => true)).toBe(true);
+ expect(batchStaticPoses2D(world, module, bodies, 100, () => true)).toBe(true);
+ const output = module._malloc(ENTITY_POSE_2D_WORDS * 4);
+ try {
+ const base = output >>> 2; module.HEAPU32[base] = bodies[0];
+ module.HEAPF32[base + 1] = 10; module.HEAPF32[base + 2] = 0; module.HEAPF32[base + 3] = 0;
+ expect(module._physics_setBodyTransforms!(output, 1, 100)).toBe(0);
+ expect(module._physics_setBodyTransforms!(output, 1, 0)).toBe(0);
+ module.HEAPF32[base + 1] = NaN;
+ expect(module._physics_setBodyTransforms!(output, 1, 100)).toBe(0);
+ } finally { module._free(output); }
+ vi.mocked(module._physics_setBodyTransforms!).mockImplementation(() => { throw Error('batch failed'); });
+ expect(() => batchStaticPoses2D(world, module, bodies, 100, () => true)).toThrow('batch failed');
+ expect(frees.mock.calls.map(([ptr]) => ptr).sort()).toEqual(allocations.mock.results.map(result => result.value).sort());
+ expect(physicsFree.mock.calls.map(([ptr]) => ptr).sort()).toEqual(physicsAlloc.mock.results.map(result => result.value).sort());
+ });
+});
diff --git a/sdk/tests/physics-batch-transfer.test.ts b/sdk/tests/physics-batch-transfer.test.ts
new file mode 100644
index 000000000..2330ab97c
--- /dev/null
+++ b/sdk/tests/physics-batch-transfer.test.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { expect, it, vi } from 'vitest';
+import { batchStaticPoses2D } from '../src/physics/batchStaticPoses2D';
+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';
+import type { World } from '../src/ecs/world';
+
+function heap() {
+ let used = 32;
+ const initial = new ArrayBuffer(64);
+ const value = {
+ HEAPU8: new Uint8Array(initial), HEAPU32: new Uint32Array(initial), HEAPF32: new Float32Array(initial),
+ grow(bytes: number) {
+ const buffer = new ArrayBuffer(bytes), u8 = new Uint8Array(buffer);
+ u8.set(value.HEAPU8); value.HEAPU8 = u8; value.HEAPU32 = new Uint32Array(buffer); value.HEAPF32 = new Float32Array(buffer);
+ },
+ _malloc: vi.fn((bytes: number) => { const ptr = used; used += bytes; if (used > value.HEAPU8.length) value.grow(used * 2); return ptr; }),
+ _free: vi.fn(),
+ };
+ return value;
+}
+function fixture(shared: boolean) {
+ const core = Object.assign(heap(), {
+ registry_readWorldPoses2D: vi.fn((_registry: unknown, input: number, count: number, output: number) => {
+ const ids = core.HEAPU32.slice(input >>> 2, (input >>> 2) + count);
+ for (let i = 0; i < count; i++) {
+ const base = (output >>> 2) + i * 4; core.HEAPU32[base] = ids[i];
+ core.HEAPF32[base + 1] = ids[i] * 10; core.HEAPF32[base + 2] = -ids[i] * 20; core.HEAPF32[base + 3] = .25;
+ }
+ return count;
+ }),
+ });
+ const physics = Object.assign(shared ? core : heap(), { _physics_setBodyTransforms: vi.fn((_ptr: number, _count: number, _ppu: number) => 1) });
+ const world = { getWasmModule: () => core, getCppRegistry: () => ({}) } as unknown as World;
+ return { core, physics, world };
+}
+
+it.each([false, true])('passes only enabled ids and populated pose rows (shared heap=%s)', shared => {
+ const { core, physics, world } = fixture(shared);
+ expect(batchStaticPoses2D(world, physics as unknown as PhysicsWasmModule, [7, 8], 200, id => id === 7)).toBe(true);
+ expect(core.registry_readWorldPoses2D).toHaveBeenCalledOnce();
+ const [ptr, count, ppu] = physics._physics_setBodyTransforms.mock.calls[0];
+ expect(count).toBe(1); expect(ppu).toBe(200);
+ expect(physics.HEAPU32[ptr >>> 2]).toBe(7);
+ expect([...physics.HEAPF32.subarray((ptr >>> 2) + 1, (ptr >>> 2) + 4)]).toEqual([70, -140, .25]);
+ expect(core._malloc).toHaveBeenCalledTimes(1); expect(core._free).toHaveBeenCalledTimes(1);
+ if (!shared) { expect(physics._malloc).toHaveBeenCalledOnce(); expect(physics._free).toHaveBeenCalledOnce(); }
+});
+
+it('reads fresh engine heap views after the physics allocation grows memory', () => {
+ const { core, physics, world } = fixture(false), allocate = physics._malloc.getMockImplementation()!;
+ physics._malloc.mockImplementation(bytes => { core.grow(core.HEAPU8.length * 2); return allocate(bytes); });
+ expect(batchStaticPoses2D(world, physics as unknown as PhysicsWasmModule, [7], 100, () => true)).toBe(true);
+ const ptr = physics._physics_setBodyTransforms.mock.calls[0][0];
+ expect(physics.HEAPF32[(ptr >>> 2) + 1]).toBe(70);
+});
+
+it('rejects an invalid row count and releases the engine allocation', () => {
+ const { core, physics, world } = fixture(false);
+ core.registry_readWorldPoses2D.mockReturnValue(2);
+ expect(() => batchStaticPoses2D(world, physics as unknown as PhysicsWasmModule, [7], 100, () => true)).toThrow('Invalid world pose batch length');
+ expect(core._free).toHaveBeenCalledOnce(); expect(physics._malloc).not.toHaveBeenCalled();
+});
+
+it('falls back cleanly when the new entry point or a temporary allocation is unavailable', () => {
+ const { core, physics, world } = fixture(false);
+ physics._malloc.mockReturnValue(0);
+ expect(batchStaticPoses2D(world, physics as unknown as PhysicsWasmModule, [7], 100, () => true)).toBe(false);
+ expect(core._free).toHaveBeenCalledOnce();
+ core.registry_readWorldPoses2D = undefined as never; core._malloc.mockClear();
+ expect(batchStaticPoses2D(world, physics as unknown as PhysicsWasmModule, [7], 100, () => true)).toBe(false);
+ expect(core._malloc).not.toHaveBeenCalled();
+});
diff --git a/sdk/tests/physics-static-sparse-wasm.test.ts b/sdk/tests/physics-static-sparse-wasm.test.ts
index 69e976123..d10ae4242 100644
--- a/sdk/tests/physics-static-sparse-wasm.test.ts
+++ b/sdk/tests/physics-static-sparse-wasm.test.ts
@@ -23,6 +23,8 @@ async function scene() {
app.connectCpp(new engine.Registry(), engine, { ownedRegistry: true });
const module = await loadSideModule<PhysicsWasmModule>('physics');
const move = vi.spyOn(module, '_physics_setBodyTransform');
+ vi.spyOn(module, '_physics_setBodyTransforms');
+ const bulk = vi.mocked(module._physics_setBodyTransforms!);
const plugin = new Physics2DPlugin('', { gravity: { x: 0, y: 0 }, fixedTimestep: 1 / 60 }, async () => module);
app.addPlugin(plugin);
await app.getResource(Physics2DRuntime).initPromise;
@@ -35,17 +37,17 @@ async function scene() {
world.insert(body, BoxCollider2D, { halfExtents: { x: .05, y: .05 }, radius: 0 });
world.setParent(body, parent);
}
- await app.stepFrames(3, 1 / 60); move.mockClear();
+ await app.stepFrames(3, 1 / 60); move.mockClear(); bulk.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 };
+ return { app, world, module, move, bulk, 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 { app, world, move, bulk, 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++; });
@@ -54,25 +56,29 @@ describe.skipIf(!HAS_WASM || !hasSideModule('physics'))('sparse static physics s
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();
+ expect(bulk).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);
+ expect(get.mock.calls.filter(([id, c]) => c === Transform && ids.has(id))).toHaveLength(0);
+ expect(move).not.toHaveBeenCalled(); expect(bulk).toHaveBeenCalledOnce();
+ expect(bulk.mock.calls[0][1]).toBe(1); expect(bulk.mock.results[0].value).toBe(1);
+ 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 { app, world, parent, bodies, move, bulk, 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();
+ await app.stepFrames(2, 1 / 60); move.mockClear(); bulk.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(move).not.toHaveBeenCalled(); expect(bulk).toHaveBeenCalledOnce();
+ expect(bulk.mock.results[0].value).toBe(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);
});
diff --git a/sdk/tests/physics-static-transform-wasm.test.ts b/sdk/tests/physics-static-transform-wasm.test.ts
index 83bd93aaf..078b69690 100644
--- a/sdk/tests/physics-static-transform-wasm.test.ts
+++ b/sdk/tests/physics-static-transform-wasm.test.ts
@@ -74,8 +74,11 @@ describe.skipIf(!HAS_WASM || !hasSideModule('physics'))('static Box2D transform
const driver = parented ? world.spawn() : body;
if (parented) { world.insert(driver, Transform, {}); world.setParent(body, driver); }
const move = vi.spyOn(module, '_physics_setBodyTransform');
+ vi.spyOn(module, '_physics_setBodyTransforms');
+ const bulk = vi.mocked(module._physics_setBodyTransforms!);
const create = vi.spyOn(module, '_physics_createBody');
await app.stepFrames(2, 1 / 30);
+ move.mockClear(); bulk.mockClear();
const api = app.getResource(Physics2D);
const hit = () => api.raycast({ x: -50, y: 0 }, { x: 1, y: 0 }, 200).find(value => value.entity === body)!;
const before = hit().point.x;
@@ -83,15 +86,18 @@ describe.skipIf(!HAS_WASM || !hasSideModule('physics'))('static Box2D transform
await app.stepFrames(2, 1 / 30);
expect(hit().point.x).toBeCloseTo(before + 30, 3);
expect(create).toHaveBeenCalledTimes(1);
- expect(move.mock.calls).toHaveLength(1);
- move.mockClear();
+ expect(move).not.toHaveBeenCalled(); expect(bulk).toHaveBeenCalledOnce();
+ expect(bulk.mock.results[0].value).toBe(1);
+ move.mockClear(); bulk.mockClear();
await app.stepFrames(20, 1 / 30);
expect(move).not.toHaveBeenCalled();
+ expect(bulk).not.toHaveBeenCalled();
expect(module._physics_hasBody(body)).toBe(1);
world.update(body, Transform, value => { value.position.x += 20; });
await app.stepFrames(2, 1 / 30);
expect(hit().point.x).toBeCloseTo(before + 50, 3);
- expect(move.mock.calls).toHaveLength(1);
+ expect(move).not.toHaveBeenCalled(); expect(bulk).toHaveBeenCalledOnce();
+ expect(bulk.mock.results[0].value).toBe(1);
});
it('keeps batched dynamic writeback when static bodies have parents', async () => {
const app = App.new(); apps.push(app);
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 993f03279..a0e99ebfa 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -23,6 +23,7 @@
#include "../ecs/Registry.hpp"
#include "../ecs/TransformSystem.hpp"
#include "../core/World.hpp"
+#include "../core/EntityPose2D.hpp"
#include "../ecs/components/Camera.hpp"
#include "../ecs/components/Canvas.hpp"
#include "../ecs/components/Transform.hpp"
@@ -1214,6 +1215,24 @@ u32 registry_getGeneration(ecs::Registry& registry, u32 entity) {
return Entity::fromRaw(entity).generation();
}
+int registry_readWorldPoses2D(ecs::Registry& registry, uintptr_t entitiesPtr, int count, uintptr_t outputPtr) {
+ if (count <= 0 || entitiesPtr % alignof(u32) || outputPtr % alignof(EntityPose2D)) return 0;
+ const auto* ids = boundarySpan<u32>(entitiesPtr, static_cast<u64>(count), "registry_readWorldPoses2D.entities");
+ auto* output = boundarySpanMut<EntityPose2D>(outputPtr, static_cast<u64>(count), "registry_readWorldPoses2D.output");
+ if (!ids || !output) return 0;
+ int written = 0;
+ for (int i = 0; i < count; ++i) {
+ const auto entity = Entity::fromRaw(ids[i]);
+ if (!registry.valid(entity) || !registry.isEntityActive(entity) || !registry.has<ecs::Transform>(entity)) continue;
+ auto& tf = registry.get<ecs::Transform>(entity);
+ tf.ensureDecomposed();
+ const auto& q = tf.worldRotation;
+ const f32 angle = std::atan2(2.0f * (q.w * q.z + q.x * q.y), 1.0f - 2.0f * (q.y * q.y + q.z * q.z));
+ output[written++] = {entity.id(), tf.worldPosition.x, tf.worldPosition.y, angle};
+ }
+ return written;
+}
+
void registry_batchSyncPhysicsTransforms(ecs::Registry& registry, uintptr_t bufferPtr, int count, float ppu) {
// Physics is a producer of transform INPUTS. The composed world fields are
// TransformSystem's, and writing them here made this a second author of them.
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index b63712ad1..6ba6ad041 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -319,6 +319,9 @@ emscripten::val registry_getCameraEntities(ecs::Registry& registry);
emscripten::val getChildEntities(ecs::Registry& registry, u32 entity);
#endif
u32 registry_getGeneration(ecs::Registry& registry, u32 entity);
+// Read composed world poses for valid, active entities with a Transform.
+// Output has room for count EntityPose2D rows; returns the number written.
+int registry_readWorldPoses2D(ecs::Registry& registry, uintptr_t entitiesPtr, int count, uintptr_t outputPtr);
void registry_batchSyncPhysicsTransforms(ecs::Registry& registry, uintptr_t bufferPtr, int count, float ppu);
} // namespace esengine
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index e5d87eb66..6bff22314 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -3674,7 +3674,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "73d45f32834f0b85";
+static const char* kEsAbiLayoutHash = "0c84aca932384575";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index d773f0b36..e1986ade3 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -781,6 +781,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("getChildEntities", &esengine::getChildEntities);
emscripten::function("registry_getGeneration", &esengine::registry_getGeneration);
emscripten::function("registry_batchSyncPhysicsTransforms", &esengine::registry_batchSyncPhysicsTransforms);
+ emscripten::function("registry_readWorldPoses2D", &esengine::registry_readWorldPoses2D);
emscripten::function("gl_enableErrorCheck", &esengine::gl_enableErrorCheck);
emscripten::function("gl_checkErrors", &esengine::gl_checkErrors);
diff --git a/src/esengine/bindings/modules/physics/PhysicsBindings.hpp b/src/esengine/bindings/modules/physics/PhysicsBindings.hpp
index 3fe975bb7..565750051 100644
--- a/src/esengine/bindings/modules/physics/PhysicsBindings.hpp
+++ b/src/esengine/bindings/modules/physics/PhysicsBindings.hpp
@@ -48,6 +48,8 @@ int physics_hasBody(uint32_t entityId);
void physics_setBodyEnabled(uint32_t entityId, int enabled);
void physics_step(float dt);
void physics_setBodyTransform(uint32_t entityId, float x, float y, float angle);
+// EntityPose2D rows in world pixels, converted with the live pixels-per-unit.
+int physics_setBodyTransforms(uintptr_t bufferPtr, int count, float ppu);
void physics_setBodyTargetTransform(uint32_t entityId, float x, float y, float angle, float dt);
int physics_getDynamicBodyCount();
// Resource-census counters: what physics is still holding, including the static
diff --git a/src/esengine/bindings/modules/physics/PhysicsModuleEntry.cpp b/src/esengine/bindings/modules/physics/PhysicsModuleEntry.cpp
index 5771d4e7a..cda36fcd2 100644
--- a/src/esengine/bindings/modules/physics/PhysicsModuleEntry.cpp
+++ b/src/esengine/bindings/modules/physics/PhysicsModuleEntry.cpp
@@ -2,6 +2,8 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
#include "./PhysicsContext.hpp"
#include "./PhysicsTaskPool.hpp"
+#include "../../BoundarySpan.hpp"
+#include "../../../core/EntityPose2D.hpp"
#include <algorithm>
#include <cmath>
@@ -261,6 +263,31 @@ void physics_setBodyTransform(uint32_t entityId, float x, float y, float angle)
b2Body_SetTransform(it->second, {x, y}, b2MakeRot(angle));
}
+EMSCRIPTEN_KEEPALIVE
+int physics_setBodyTransforms(uintptr_t bufferPtr, int count, float ppu) {
+ using namespace esengine;
+ if (count <= 0 || bufferPtr % alignof(EntityPose2D) || !std::isfinite(ppu) || ppu <= 0) return 0;
+ const auto* rows = boundarySpan<EntityPose2D>(bufferPtr, static_cast<u64>(count), "physics_setBodyTransforms");
+ if (!rows) return 0;
+ const double invPpu = 1.0 / static_cast<double>(ppu);
+ int changed = 0;
+ for (int i = 0; i < count; ++i) {
+ const auto& pose = rows[i];
+ if (!std::isfinite(pose.x) || !std::isfinite(pose.y) || !std::isfinite(pose.angle)) continue;
+ const auto it = g_ctx.entityToBody.find(pose.entity);
+ if (it == g_ctx.entityToBody.end() || !b2Body_IsValid(it->second)) continue;
+ const b2Vec2 next = {static_cast<float>(pose.x * invPpu), static_cast<float>(pose.y * invPpu)};
+ if (!b2IsValidVec2(next)) continue;
+ const b2Rot rotation = b2MakeRot(pose.angle);
+ const b2Vec2 position = b2Body_GetPosition(it->second);
+ const b2Rot current = b2Body_GetRotation(it->second);
+ if (position.x == next.x && position.y == next.y && current.c == rotation.c && current.s == rotation.s) continue;
+ b2Body_SetTransform(it->second, next, rotation);
+ ++changed;
+ }
+ return changed;
+}
+
// Drive a kinematic body toward a target pose over `dt`, deriving its
// linear+angular velocity from the delta (unlike setBodyTransform, which
// teleports with zero velocity). The velocity is what the contact solver uses
diff --git a/src/esengine/core/EntityPose2D.hpp b/src/esengine/core/EntityPose2D.hpp
new file mode 100644
index 000000000..6116c0a5c
--- /dev/null
+++ b/src/esengine/core/EntityPose2D.hpp
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+#pragma once
+#include "Types.hpp"
+#include "Reflection.hpp"
+
+namespace esengine {
+ES_CONST()
+static constexpr u32 ENTITY_POSE_2D_WORDS = 4;
+
+// Entity bits followed by world X/Y and Z rotation in radians. Units belong to
+// the caller: composition exports pixels; solver readback exports meters.
+struct EntityPose2D { u32 entity; f32 x; f32 y; f32 angle; };
+static_assert(sizeof(EntityPose2D) == ENTITY_POSE_2D_WORDS * sizeof(u32));
+} // namespace esengine
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 7d9ad8e6d..3a02ab497 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): batch composed static body poses across hosts':
+ { note: 'Moving static collision uses a shared batch pose channel.' },
'fix(physics): release static pose history while time is frozen':
{ note: 'Static physics synchronization skips unchanged body groups.' },
'perf(physics): synchronize only changed static body groups':