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.

fix(physics3d): the solver answers in world space, and it was written as local

esengine414dfb5de77c
diff --git a/sdk/src/physics3d/Physics3DSystem.ts b/sdk/src/physics3d/Physics3DSystem.ts
index e7a4d07db..5030e442a 100644
--- a/sdk/src/physics3d/Physics3DSystem.ts
+++ b/sdk/src/physics3d/Physics3DSystem.ts
@@ -12,8 +12,11 @@
* behaves nothing like itself when a character is 180 units tall.
*/
import type { App } from '../app/app';
-import { Transform } from '../ecs/component';
-import type { TransformData } from '../ecs/component.generated';
+import { Parent, Transform } from '../ecs/component';
+import type { ParentData, TransformData } from '../ecs/component.generated';
+import { q } from '../math/quat';
+import { v3 } from '../math/vec3';
+import type { Quat, Vec3 } from '../types';
import {
RigidBody3D, BoxCollider3D, SphereCollider3D, CapsuleCollider3D, CharacterController3D,
MeshCollider3D, ConvexCollider3D,
@@ -103,9 +106,12 @@ function moveCharacters(app: App, module: Physics3DWasmModule, characters: BodyM
if (!app.world.has(entity, Transform)) continue;
const t = app.world.get(entity, Transform) as TransformData;
- t.position.x = f32[base]! * ppu;
- t.position.y = f32[base + 1]! * ppu;
- t.position.z = f32[base + 2]! * ppu;
+ const placed = localFromWorld(app, entity, {
+ x: f32[base]! * ppu, y: f32[base + 1]! * ppu, z: f32[base + 2]! * ppu,
+ });
+ t.position.x = placed.position.x;
+ t.position.y = placed.position.y;
+ t.position.z = placed.position.z;
app.world.set(entity, Transform, t);
}
for (const [entity, id] of characters) {
@@ -115,6 +121,35 @@ function moveCharacters(app: App, module: Physics3DWasmModule, characters: BodyM
}
}
+/**
+ * @brief The local pose that composes to `world` under this entity's parent
+ * @details A body goes to the solver at its composed WORLD pose, so what comes
+ * back is one too, and under a parent that transform has to come back
+ * out or composing adds it twice. Non-uniform parent scale keeps the
+ * translation exact; the rotation carries the skew the docs name.
+ */
+function localFromWorld(app: App, entity: Entity, world: Vec3, rotation?: Quat):
+{ position: Vec3; rotation?: Quat } {
+ const link = app.world.has(entity, Parent)
+ ? (app.world.get(entity, Parent) as ParentData) : null;
+ const parent = link?.entity;
+ if (parent === undefined || !app.world.valid(parent) || !app.world.has(parent, Transform)) {
+ return { position: world, rotation };
+ }
+ const p = app.world.get(parent, Transform) as TransformData;
+ const inverse = q.conjugate(p.worldRotation as Quat);
+ const offset = q.rotate(inverse, v3.sub(world, p.worldPosition as Vec3));
+ const s = p.worldScale as Vec3;
+ return {
+ position: {
+ x: s.x !== 0 ? offset.x / s.x : offset.x,
+ y: s.y !== 0 ? offset.y / s.y : offset.y,
+ z: s.z !== 0 ? offset.z / s.z : offset.z,
+ },
+ rotation: rotation ? q.mul(inverse, rotation) : undefined,
+ };
+}
+
function motionOf(body: RigidBody3DData): number {
// BodyType is the 2D enum, reused: static/kinematic/dynamic mean the same here.
return body.bodyType === 0 ? MOTION.Static
@@ -234,6 +269,10 @@ export function stepPhysics3D(app: App, module: Physics3DWasmModule,
events?: Physics3DEventsData,
joints: Joint3DMap = new Map()): void {
const ppu = config.pixelsPerUnit;
+ // Both directions read a parent's COMPOSED transform — the pose a body is
+ // created at, and the local pose its answer is turned back into — so the
+ // composition is made current first. O(1) when nothing moved.
+ app.world.ensureTransformsComposed();
moveCharacters(app, module, characters, config);
const live = new Set<Entity>();
@@ -259,6 +298,10 @@ export function stepPhysics3D(app: App, module: Physics3DWasmModule,
bodies.delete(entity);
}
+ // Characters have just written local poses of their own, and a body may be
+ // parented to one.
+ app.world.ensureTransformsComposed();
+
module._physics3d_step(config.fixedTimestep, config.collisionSteps);
// Drained immediately after the step that produced them: the module's buffers
// hold one step's worth and the next step clears them.
@@ -278,13 +321,16 @@ export function stepPhysics3D(app: App, module: Physics3DWasmModule,
const t = app.world.get(entity, Transform) as TransformData;
// Position and rotation are the solver's; scale is the scene's and is
// left alone, the same division of ownership the 2D path makes.
- t.position.x = f32[o + 1]! * ppu;
- t.position.y = f32[o + 2]! * ppu;
- t.position.z = f32[o + 3]! * ppu;
- t.rotation.x = f32[o + 4]!;
- t.rotation.y = f32[o + 5]!;
- t.rotation.z = f32[o + 6]!;
- t.rotation.w = f32[o + 7]!;
+ const placed = localFromWorld(app, entity, {
+ x: f32[o + 1]! * ppu, y: f32[o + 2]! * ppu, z: f32[o + 3]! * ppu,
+ }, { x: f32[o + 4]!, y: f32[o + 5]!, z: f32[o + 6]!, w: f32[o + 7]! });
+ t.position.x = placed.position.x;
+ t.position.y = placed.position.y;
+ t.position.z = placed.position.z;
+ t.rotation.x = placed.rotation!.x;
+ t.rotation.y = placed.rotation!.y;
+ t.rotation.z = placed.rotation!.z;
+ t.rotation.w = placed.rotation!.w;
app.world.set(entity, Transform, t);
}
}
diff --git a/sdk/tests/physics3d-ecs.test.ts b/sdk/tests/physics3d-ecs.test.ts
index cd7603d9a..824e58771 100644
--- a/sdk/tests/physics3d-ecs.test.ts
+++ b/sdk/tests/physics3d-ecs.test.ts
@@ -152,6 +152,10 @@ function fakeWorld() {
edit(value as T);
},
valid(e: Entity): boolean { return store.has(e); },
+ // Nothing composes here, so this is the honest answer for a store with no
+ // composer: what the solver's world pose becomes under a PARENT is
+ // checked against the real one in physics3d-transform-space.
+ ensureTransformsComposed(): void {},
queryEntities(defs: unknown[]): Entity[] {
return [...store.entries()]
.filter(([, comps]) => defs.every((d) => comps.has(d)))
diff --git a/sdk/tests/physics3d-transform-space.test.ts b/sdk/tests/physics3d-transform-space.test.ts
new file mode 100644
index 000000000..153b92422
--- /dev/null
+++ b/sdk/tests/physics3d-transform-space.test.ts
@@ -0,0 +1,252 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Which SPACE the 3D solver's answer arrives in.
+ *
+ * A body is handed to the solver at its composed WORLD pose, so what comes back
+ * is a world pose too. `Transform.position` is the local input the composer
+ * builds that world pose FROM — writing one into the other adds the parent's
+ * transform a second time. These run against the real composer, so the
+ * round-trip is a checked claim rather than a reading of the arithmetic.
+ */
+import { describe, it, expect, beforeAll } from 'vitest';
+import { App } from '../src/app/app';
+import { Transform } from '../src/ecs/component';
+import type { TransformData } from '../src/ecs/component.generated';
+import {
+ RigidBody3D, BoxCollider3D, CharacterController3D,
+} from '../src/physics3d/Physics3DComponents';
+import { stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG } from '../src/physics3d/Physics3DSystem';
+import type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';
+import type { Entity } from '../src/types';
+import type { CppRegistry, ESEngineModule } from '../src/wasm';
+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
+
+const PPU = DEFAULT_PHYSICS3D_CONFIG.pixelsPerUnit;
+
+/** The solver, reduced to what it publishes: body poses and a character result. */
+function poseSource() {
+ const heap = new Float32Array(4096);
+ const query = heap.subarray(1024);
+ let bodyBytes = 0;
+ let queryBytes = 0;
+ const id = (() => { let n = 0; return () => ++n; })();
+ return {
+ publishBodies(records: number[]) { heap.set(records, 0); bodyBytes = records.length * 4; },
+ publishCharacter(records: number[]) { query.set(records, 0); queryBytes = records.length * 4; },
+ module: {
+ HEAPF32: heap,
+ HEAPU32: new Uint32Array(heap.buffer),
+ _physics3d_isReady: () => 1,
+ _physics3d_step: () => 0,
+ _physics3d_addBox: () => id(),
+ _physics3d_addCharacter: () => id(),
+ _physics3d_moveCharacter: () => 0,
+ _physics3d_removeBody: () => 0,
+ _physics3d_removeCharacter: () => 0,
+ _physics3d_setTransform: () => 0,
+ _physics3d_transforms: () => 0,
+ _physics3d_transformsBytes: () => bodyBytes,
+ _physics3d_queryResult: () => 1024 * 4,
+ _physics3d_queryResultBytes: () => queryBytes,
+ _physics3d_contactEntersBytes: () => 0,
+ _physics3d_contactExitsBytes: () => 0,
+ _physics3d_sensorEntersBytes: () => 0,
+ _physics3d_sensorExitsBytes: () => 0,
+ _malloc: () => 0,
+ _free: () => {},
+ } as unknown as Physics3DWasmModule,
+ };
+}
+
+describe.skipIf(!HAS_WASM)('the 3D solver answers in world space', () => {
+ let engine: ESEngineModule;
+ beforeAll(async () => { engine = await loadWasmModule(); });
+
+ function scene() {
+ const app = App.new();
+ app.connectCpp(new engine.Registry() as unknown as CppRegistry, engine);
+ return { app, world: app.world };
+ }
+ const local = (app: App, e: Entity) => (app.world.get(e, Transform) as TransformData).position;
+ const composed = (app: App, e: Entity) => {
+ app.world.ensureTransformsComposed();
+ return (app.world.get(e, Transform) as TransformData).worldPosition;
+ };
+ const composedRotation = (app: App, e: Entity) => {
+ app.world.ensureTransformsComposed();
+ return (app.world.get(e, Transform) as TransformData).worldRotation;
+ };
+
+ function body(app: App, e: Entity) {
+ app.world.insert(e, RigidBody3D, { bodyType: 2 });
+ app.world.insert(e, BoxCollider3D, { halfExtents: { x: 0.5, y: 0.5, z: 0.5 } });
+ }
+
+ it('a parented body: the solver pose is world, and the local input is solved for', () => {
+ const { app, world } = scene();
+ const parent = world.spawn('parent');
+ world.insert(parent, Transform, { position: { x: 100, y: 0, z: 0 } });
+ const child = world.spawn('child');
+ world.insert(child, Transform, { position: { x: 5, y: 0, z: 0 } });
+ world.setParent(child, parent);
+ body(app, child);
+ world.ensureTransformsComposed();
+
+ const src = poseSource();
+ src.publishBodies([child as number, 130 / PPU, 0, 0, 0, 0, 0, 1]);
+ stepPhysics3D(app, src.module, new Map(), DEFAULT_PHYSICS3D_CONFIG);
+
+ expect(local(app, child).x).toBeCloseTo(30, 3);
+ expect(composed(app, child).x).toBeCloseTo(130, 3);
+ world.disconnectCpp();
+ });
+
+ it('a parented body under a rotated parent round-trips position and rotation', () => {
+ const { app, world } = scene();
+ const h = Math.PI / 4; // a quarter turn about Z
+ const parent = world.spawn('parent');
+ world.insert(parent, Transform, {
+ position: { x: 100, y: 0, z: 0 },
+ rotation: { w: Math.cos(h), x: 0, y: 0, z: Math.sin(h) },
+ });
+ const child = world.spawn('child');
+ world.insert(child, Transform, { position: { x: 0, y: 0, z: 0 } });
+ world.setParent(child, parent);
+ body(app, child);
+ world.ensureTransformsComposed();
+
+ const src = poseSource();
+ // World (130, 0, 0), unrotated: the parent's turn has to come out of both.
+ src.publishBodies([child as number, 130 / PPU, 0, 0, 0, 0, 0, 1]);
+ stepPhysics3D(app, src.module, new Map(), DEFAULT_PHYSICS3D_CONFIG);
+
+ expect(local(app, child).x).toBeCloseTo(0, 3);
+ expect(local(app, child).y).toBeCloseTo(-30, 3);
+ expect(composed(app, child).x).toBeCloseTo(130, 3);
+ expect(composed(app, child).y).toBeCloseTo(0, 3);
+ // Identity in world, so the local rotation is the parent's turn undone.
+ const r = composedRotation(app, child);
+ expect(r.z).toBeCloseTo(0, 3);
+ expect(Math.abs(r.w)).toBeCloseTo(1, 3);
+ world.disconnectCpp();
+ });
+
+ it('a root body is unchanged: its local pose IS its world pose', () => {
+ const { app, world } = scene();
+ const e = world.spawn('root');
+ world.insert(e, Transform, { position: { x: 7, y: 0, z: 0 } });
+ body(app, e);
+ world.ensureTransformsComposed();
+
+ const src = poseSource();
+ src.publishBodies([e as number, 250 / PPU, 3 / PPU, 0, 0, 0, 0, 1]);
+ stepPhysics3D(app, src.module, new Map(), DEFAULT_PHYSICS3D_CONFIG);
+
+ expect(local(app, e).x).toBeCloseTo(250, 3);
+ expect(local(app, e).y).toBeCloseTo(3, 3);
+ expect(composed(app, e).x).toBeCloseTo(250, 3);
+ world.disconnectCpp();
+ });
+
+ it('a body handed to the solver and handed back unchanged has not moved', () => {
+ const { app, world } = scene();
+ const h = Math.PI / 6;
+ const parent = world.spawn('parent');
+ world.insert(parent, Transform, {
+ position: { x: 40, y: -12, z: 7 },
+ rotation: { w: Math.cos(h), x: 0, y: Math.sin(h), z: 0 },
+ });
+ const child = world.spawn('child');
+ world.insert(child, Transform, {
+ position: { x: 9, y: 4, z: -3 },
+ rotation: { w: Math.cos(h), x: 0, y: 0, z: Math.sin(h) },
+ });
+ world.setParent(child, parent);
+ body(app, child);
+ world.ensureTransformsComposed();
+
+ const before = { ...composed(app, child) };
+ const beforeR = { ...composedRotation(app, child) };
+ // What `createBody` sends is the composed world pose; the solver is asked
+ // for nothing, so what it publishes back is the same pose.
+ const src = poseSource();
+ src.publishBodies([child as number, before.x / PPU, before.y / PPU, before.z / PPU,
+ beforeR.x, beforeR.y, beforeR.z, beforeR.w]);
+ stepPhysics3D(app, src.module, new Map(), DEFAULT_PHYSICS3D_CONFIG);
+
+ const after = composed(app, child);
+ expect(after.x).toBeCloseTo(before.x, 3);
+ expect(after.y).toBeCloseTo(before.y, 3);
+ expect(after.z).toBeCloseTo(before.z, 3);
+ world.disconnectCpp();
+ });
+
+ it('a uniformly scaled parent scales the offset back out', () => {
+ const { app, world } = scene();
+ const parent = world.spawn('parent');
+ world.insert(parent, Transform, {
+ position: { x: 100, y: 0, z: 0 }, scale: { x: 2, y: 2, z: 2 },
+ });
+ const child = world.spawn('child');
+ world.insert(child, Transform, { position: { x: 0, y: 0, z: 0 } });
+ world.setParent(child, parent);
+ body(app, child);
+ world.ensureTransformsComposed();
+
+ const src = poseSource();
+ src.publishBodies([child as number, 130 / PPU, 0, 0, 0, 0, 0, 1]);
+ stepPhysics3D(app, src.module, new Map(), DEFAULT_PHYSICS3D_CONFIG);
+
+ // Thirty world units under a parent twice life size is fifteen local ones.
+ expect(local(app, child).x).toBeCloseTo(15, 3);
+ expect(composed(app, child).x).toBeCloseTo(130, 3);
+ world.disconnectCpp();
+ });
+
+ it('non-uniform parent scale still puts the body where the solver said', () => {
+ // The known limit is the skew between rotation and scale, which the
+ // Transforms doc already names. WHERE the body is has an exact answer
+ // under any scale, and it is the one this returns.
+ const { app, world } = scene();
+ const parent = world.spawn('parent');
+ world.insert(parent, Transform, {
+ position: { x: 10, y: -4, z: 2 }, scale: { x: 3, y: 0.5, z: 2 },
+ });
+ const child = world.spawn('child');
+ world.insert(child, Transform, { position: { x: 0, y: 0, z: 0 } });
+ world.setParent(child, parent);
+ body(app, child);
+ world.ensureTransformsComposed();
+
+ const src = poseSource();
+ src.publishBodies([child as number, 130 / PPU, 20 / PPU, -6 / PPU, 0, 0, 0, 1]);
+ stepPhysics3D(app, src.module, new Map(), DEFAULT_PHYSICS3D_CONFIG);
+
+ const at = composed(app, child);
+ expect(at.x).toBeCloseTo(130, 3);
+ expect(at.y).toBeCloseTo(20, 3);
+ expect(at.z).toBeCloseTo(-6, 3);
+ world.disconnectCpp();
+ });
+
+ it('a parented character controller lands where the solver put it', () => {
+ const { app, world } = scene();
+ const parent = world.spawn('parent');
+ world.insert(parent, Transform, { position: { x: 100, y: 0, z: 0 } });
+ const child = world.spawn('walker');
+ world.insert(child, Transform, { position: { x: 5, y: 0, z: 0 } });
+ world.setParent(child, parent);
+ world.insert(child, CharacterController3D, { enabled: true });
+ world.ensureTransformsComposed();
+
+ const src = poseSource();
+ // [x, y, z, onGround, normal…, velocity…] in the module's layout.
+ src.publishCharacter([130 / PPU, 0, 0, 0, 0, 1, 0, 0, 0, 0]);
+ stepPhysics3D(app, src.module, new Map(), DEFAULT_PHYSICS3D_CONFIG, new Map());
+
+ expect(local(app, child).x).toBeCloseTo(30, 3);
+ expect(composed(app, child).x).toBeCloseTo(130, 3);
+ world.disconnectCpp();
+ });
+});
diff --git a/sdk/tests/physics3d-wireframe.test.ts b/sdk/tests/physics3d-wireframe.test.ts
index 2e078f4e5..90ddcbc0c 100644
--- a/sdk/tests/physics3d-wireframe.test.ts
+++ b/sdk/tests/physics3d-wireframe.test.ts
@@ -81,6 +81,10 @@ function fakeWorld() {
get(e: Entity, def: unknown): unknown { return store.get(e)?.get(def); },
has(e: Entity, def: unknown): boolean { return store.get(e)?.has(def) ?? false; },
valid(e: Entity): boolean { return store.has(e); },
+ // Nothing composes here, so this is the honest answer for a store with no
+ // composer: what the solver's world pose becomes under a PARENT is
+ // checked against the real one in physics3d-transform-space.
+ ensureTransformsComposed(): void {},
queryEntities(defs: unknown[]): Entity[] {
return [...store.entries()]
.filter(([, comps]) => defs.every((d) => comps.has(d)))