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.

feat(physics): support compound colliders and scaled model geometry

yhh90024a4ef20d
diff --git a/sdk/src/physics3d/ColliderShape3D.ts b/sdk/src/physics3d/ColliderShape3D.ts
index dd1d63e3b..356209df5 100644
--- a/sdk/src/physics3d/ColliderShape3D.ts
+++ b/sdk/src/physics3d/ColliderShape3D.ts
@@ -30,20 +30,22 @@ import type {
RigidBody3DData, BoxCollider3DData, SphereCollider3DData, CapsuleCollider3DData,
MeshCollider3DData, ConvexCollider3DData, CharacterController3DData,
} from './Physics3DComponents';
+import { Transform } from '../ecs/component';
+import { CompoundCollider3D, encodeCompoundParts } from './CompoundCollider3D';
import { getMeshCollision } from '../asset/meshCollision';
/** Points per full circle in a sphere/capsule wireframe. */
export const COLLIDER3D_RING_SEGMENTS = 24;
/** A 3D collider's geometry in entity-local space, in world units. */
-export type Collider3DShape =
+export type Collider3DShape = { rotation?: Quat } & (
| { kind: 'box'; halfExtents: Vec3; center: Vec3 }
| { kind: 'sphere'; radius: number; center?: Vec3 }
- | { kind: 'capsule'; radius: number; halfHeight: number; center?: Vec3 };
+ | { kind: 'capsule'; radius: number; halfHeight: number; center?: Vec3 });
/** Which component authored a shape — the Inspector target behind a gizmo. */
export type Collider3DComponent =
- | 'BoxCollider3D' | 'SphereCollider3D' | 'CapsuleCollider3D'
+ | 'CompoundCollider3D' | 'BoxCollider3D' | 'SphereCollider3D' | 'CapsuleCollider3D'
| 'MeshCollider3D' | 'ConvexCollider3D' | 'CharacterController3D';
export interface Collider3DInstance {
@@ -66,7 +68,7 @@ export function rotateVec3ByQuat(rot: Quat, v: Vec3): Vec3 {
}
/** Local AABB of a loaded mesh's collision triangles, or null when nothing loaded them. */
-function meshBounds(handle: number): { center: Vec3; halfExtents: Vec3 } | null {
+function meshBounds(handle: number, scale: Vec3 = { x:1, y:1, z:1 }): { center: Vec3; halfExtents: Vec3 } | null {
const data = handle !== 0 ? getMeshCollision(handle) : null;
if (!data || data.positions.length < 3) return null;
const p = data.positions;
@@ -79,8 +81,8 @@ function meshBounds(handle: number): { center: Vec3; halfExtents: Vec3 } | null
if (z < minZ) minZ = z; else if (z > maxZ) maxZ = z;
}
return {
- center: { x: (minX + maxX) / 2, y: (minY + maxY) / 2, z: (minZ + maxZ) / 2 },
- halfExtents: { x: (maxX - minX) / 2, y: (maxY - minY) / 2, z: (maxZ - minZ) / 2 },
+ center: { x: (minX + maxX) / 2 * scale.x, y: (minY + maxY) / 2 * scale.y, z: (minZ + maxZ) / 2 * scale.z },
+ halfExtents: { x: (maxX - minX) / 2 * Math.abs(scale.x), y: (maxY - minY) / 2 * Math.abs(scale.y), z: (maxZ - minZ) / 2 * Math.abs(scale.z) },
};
}
@@ -97,6 +99,19 @@ export function readCollider3DShapes(world: World, entity: number): Collider3DIn
? world.get(entity, RigidBody3D) as RigidBody3DData : null;
const bodyLive = body !== null && on(body);
let taken = false;
+ if (world.has(entity, CompoundCollider3D)) {
+ const c = world.get(entity, CompoundCollider3D), scale = world.has(entity, Transform)
+ ? world.get(entity, Transform).worldScale : { x: 1, y: 1, z: 1 };
+ const packet = encodeCompoundParts(c.parts, scale, 1);
+ taken = on(c) && c.parts.length > 0;
+ for (let i = 0; i < c.parts.length; i++) {
+ const p = packet.subarray(i * 11, (i + 1) * 11);
+ const common = { center: { x: p[4]!, y: p[5]!, z: p[6]! }, rotation: { x: p[7]!, y: p[8]!, z: p[9]!, w: p[10]! } };
+ const shape: Collider3DShape = p[0] === 0 ? { ...common, kind: 'box', halfExtents: { x: p[1]!, y: p[2]!, z: p[3]! } }
+ : p[0] === 1 ? { ...common, kind: 'sphere', radius: p[1]! } : { ...common, kind: 'capsule', radius: p[1]!, halfHeight: p[2]! };
+ out.push({ component: 'CompoundCollider3D', shape, isSensor: c.isSensor, active: taken && bodyLive });
+ }
+ }
const box = world.has(entity, BoxCollider3D)
? world.get(entity, BoxCollider3D) as BoxCollider3DData : null;
@@ -131,7 +146,7 @@ export function readCollider3DShapes(world: World, entity: number): Collider3DIn
// mesh; whether that mesh loaded decides only if a body appears at all.
const chosen = !taken && on(mesh) && mesh.mesh !== 0;
if (chosen) taken = true;
- const bounds = meshBounds(mesh.mesh);
+ const bounds = meshBounds(mesh.mesh, world.has(entity, Transform) ? world.get(entity, Transform).worldScale : undefined);
if (bounds) {
out.push({
component: 'MeshCollider3D',
@@ -147,7 +162,7 @@ export function readCollider3DShapes(world: World, entity: number): Collider3DIn
if (hull) {
const chosen = !taken && on(hull) && hull.mesh !== 0;
if (chosen) taken = true;
- const bounds = meshBounds(hull.mesh);
+ const bounds = meshBounds(hull.mesh, world.has(entity, Transform) ? world.get(entity, Transform).worldScale : undefined);
if (bounds) {
out.push({
component: 'ConvexCollider3D',
@@ -220,6 +235,10 @@ function arc(radius: number, axis: 'xy' | 'zy', offset: Vec3, sign: 1 | -1, segm
* four caps and the four lines between them.
*/
export function collider3DWireframe(shape: Collider3DShape, segments = COLLIDER3D_RING_SEGMENTS): Vec3[][] {
+ if (shape.rotation) {
+ const lines = collider3DWireframe({ ...shape, rotation: undefined, center: ZERO }, segments);
+ return placeCollider3DWireframe(lines, shape.center ?? ZERO, shape.rotation);
+ }
const lines = centredWireframe(shape, segments);
const c = shape.kind === 'box' ? undefined : shape.center;
return c ? lines.map((line) => line.map((p) => ({ x: p.x + c.x, y: p.y + c.y, z: p.z + c.z }))) : lines;
@@ -301,6 +320,15 @@ const SOLID_SEGMENTS = 8;
export function collider3DTriangles(
shape: Collider3DShape,
): { positions: Float32Array; indices: Uint32Array } {
+ if (shape.rotation) {
+ const data = collider3DTriangles({ ...shape, rotation: undefined, center: ZERO });
+ const c = shape.center ?? ZERO;
+ for (let i = 0; i < data.positions.length; i += 3) {
+ const p = q.rotate(shape.rotation, { x: data.positions[i]!, y: data.positions[i + 1]!, z: data.positions[i + 2]! });
+ data.positions.set([p.x + c.x, p.y + c.y, p.z + c.z], i);
+ }
+ return data;
+ }
if (shape.kind === 'box') {
const { center: c, halfExtents: h } = shape;
const positions = new Float32Array(8 * 3);
diff --git a/sdk/src/physics3d/CompoundCollider3D.ts b/sdk/src/physics3d/CompoundCollider3D.ts
new file mode 100644
index 000000000..cbb82fbaa
--- /dev/null
+++ b/sdk/src/physics3d/CompoundCollider3D.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { defineComponent } from '../ecs/component';
+import type { Vec3, Quat } from '../types';
+
+export interface CompoundColliderPart3D {
+ kind: 'box' | 'sphere' | 'capsule';
+ position: Vec3;
+ rotation: Quat;
+ halfExtents?: Vec3;
+ radius?: number;
+ /** Cylinder half-height; total capsule height is 2 * (halfHeight + radius). */
+ halfHeight?: number;
+}
+
+export interface CompoundCollider3DData {
+ /** Local model units. The entity's composed scale applies to sizes and offsets. */
+ parts: CompoundColliderPart3D[];
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ mass: number;
+ enabled: boolean;
+}
+
+export const CompoundCollider3D = defineComponent<CompoundCollider3DData>('CompoundCollider3D', {
+ parts: [], friction: .3, restitution: 0, isSensor: false, mass: 1, enabled: true,
+});
+
+export const COMPOUND_PART_STRIDE = 11;
+
+/** The side module's bounded primitive packet, in metres, built only when a body is created. */
+export function encodeCompoundParts(parts: readonly CompoundColliderPart3D[], scale: Vec3, pixelsPerUnit: number): Float32Array {
+ if (!Number.isFinite(pixelsPerUnit) || pixelsPerUnit <= 0 || parts.length > 16384) throw Error('Invalid compound collider size or units');
+ if (![scale.x, scale.y, scale.z].every(v => Number.isFinite(v) && v > 0))
+ throw Error('Compound colliders require a finite positive placement scale');
+ const out = new Float32Array(parts.length * COMPOUND_PART_STRIDE);
+ const sx = Math.abs(scale.x) / pixelsPerUnit, sy = Math.abs(scale.y) / pixelsPerUnit, sz = Math.abs(scale.z) / pixelsPerUnit;
+ parts.forEach((part, i) => {
+ const at = i * COMPOUND_PART_STRIDE;
+ const q = part.rotation, length = Math.hypot(q.x, q.y, q.z, q.w);
+ if (!Number.isFinite(length) || length === 0) throw Error('Invalid compound collider rotation');
+ const uniform = Math.abs(sx - sy) < 1e-6 && Math.abs(sy - sz) < 1e-6;
+ if (!uniform && part.kind !== 'sphere' && Math.hypot(q.x, q.y, q.z) > 1e-6)
+ throw Error('Rotated compound primitives under non-uniform scale require baked collision geometry');
+ let dimensions: number[];
+ if (part.kind === 'box' && part.halfExtents) dimensions = [0, part.halfExtents.x * sx, part.halfExtents.y * sy, part.halfExtents.z * sz];
+ else if (part.kind === 'sphere') dimensions = [1, (part.radius ?? 0) * Math.max(sx, sy, sz), 0, 0];
+ else if (part.kind === 'capsule') dimensions = [2, (part.radius ?? 0) * Math.max(sx, sz), (part.halfHeight ?? 0) * sy, 0];
+ else throw Error('Unsupported compound collider primitive');
+ if (dimensions[1]! <= 0 || (part.kind === 'box' && (dimensions[2]! <= 0 || dimensions[3]! <= 0)) || dimensions[2]! < 0) {
+ throw Error('Compound collider dimensions must be positive');
+ }
+ out.set([...dimensions, part.position.x * scale.x / pixelsPerUnit, part.position.y * scale.y / pixelsPerUnit,
+ part.position.z * scale.z / pixelsPerUnit, q.x / length, q.y / length, q.z / length, q.w / length], at);
+ });
+ if (out.some(v => !Number.isFinite(v))) throw Error('Compound collider contains non-finite values');
+ return out;
+}
diff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.ts
index ae92a6944..4efcaf089 100644
--- a/sdk/src/physics3d/Physics3DModule.ts
+++ b/sdk/src/physics3d/Physics3DModule.ts
@@ -54,6 +54,12 @@ export interface Physics3DWasmModule {
continuous: number, friction: number, restitution: number,
isSensor: number): number;
_physics3d_removeBody(bodyId: number): void;
+ /** Optional for older binaries. Required by CompoundCollider3D, never silently approximated. */
+ _physics3d_addCompound?(entity: number, parts: number, count: number,
+ px: number, py: number, pz: number, qx: number, qy: number, qz: number, qw: number,
+ motion: number, gravityScale: number, linearDamping: number, angularDamping: number,
+ fixedRotation: number, layer: number, continuous: number, friction: number,
+ restitution: number, isSensor: number, mass: number): number;
_malloc(bytes: number): number;
_free(ptr: number): void;
diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.ts
index e7f71698d..7961b465c 100644
--- a/sdk/src/physics3d/Physics3DPlugin.ts
+++ b/sdk/src/physics3d/Physics3DPlugin.ts
@@ -84,7 +84,7 @@ export class Physics3DPlugin implements Plugin {
stepPhysics3D(app, module, runtime.bodies, this.config_,
runtime.characters, events, runtime.joints, runtime.pieces,
app.hasResource(CollisionGeometryRes) ? app.getResource(CollisionGeometryRes) : null);
- }));
+ }, { name: 'Physics3DStepSystem' }), { profileDomain: 'physics3d' });
// Installed with the world, drawn only once a game turns the resource
// on — a scene that never asks for it pays a resource and nothing else.
setupPhysics3DDebugDraw(app, () => events.contactEnters);
diff --git a/sdk/src/physics3d/Physics3DSystem.ts b/sdk/src/physics3d/Physics3DSystem.ts
index b1b9dd85f..ab5d25814 100644
--- a/sdk/src/physics3d/Physics3DSystem.ts
+++ b/sdk/src/physics3d/Physics3DSystem.ts
@@ -25,6 +25,7 @@ import {
type ConvexCollider3DData,
} from './Physics3DComponents';
import { getMeshCollision } from '../asset/meshCollision';
+import { CompoundCollider3D, encodeCompoundParts } from './CompoundCollider3D';
import { syncJoints3D, type Joint3DMap } from './Physics3DJoints';
import type { Entity } from '../types';
import type { Physics3DWasmModule, Physics3DEventsData } from './Physics3DModule';
@@ -55,6 +56,7 @@ export const DEFAULT_PHYSICS3D_CONFIG: Physics3DConfig = {
/** Which body an entity owns, so a removed component takes its body with it. */
type BodyMap = Map<Entity, number>;
+const authoredPoses = new WeakMap<BodyMap, Map<Entity, number[]>>();
/** The body each piece of collision geometry was built as, by its key, and the piece it was built from. */
export type PieceMap = Map<string, { piece: CollisionPiece; id: number }>;
@@ -184,6 +186,20 @@ function createBody(app: App, module: Physics3DWasmModule, entity: Entity,
// component answers with a default-constructed one, `enabled` and all — so
// every sphere, capsule, hull and mesh was built as the default box.
const has = (c: Parameters<typeof app.world.has>[1]) => app.world.has(entity, c);
+ if (has(CompoundCollider3D)) {
+ const collider = app.world.get(entity, CompoundCollider3D);
+ if (collider.enabled && collider.parts.length) {
+ if (!module._physics3d_addCompound) throw Error('CompoundCollider3D requires a rebuilt 3D physics module');
+ const data = encodeCompoundParts(collider.parts, t?.worldScale ?? { x: 1, y: 1, z: 1 }, ppu);
+ const ptr = module._malloc(data.byteLength);
+ try {
+ module.HEAPF32.set(data, ptr >> 2);
+ return module._physics3d_addCompound(entity, ptr, collider.parts.length,
+ px, py, pz, r.x, r.y, r.z, r.w, ...how,
+ collider.friction, collider.restitution, collider.isSensor ? 1 : 0, collider.mass);
+ } finally { module._free(ptr); }
+ }
+ }
const box = has(BoxCollider3D)
? app.world.get(entity, BoxCollider3D) as BoxCollider3DData : undefined;
if (box?.enabled) {
@@ -202,12 +218,12 @@ function createBody(app: App, module: Physics3DWasmModule, entity: Entity,
const meshCollider = has(MeshCollider3D)
? app.world.get(entity, MeshCollider3D) as MeshCollider3DData : undefined;
if (meshCollider?.enabled && meshCollider.mesh !== 0) {
- return addMeshBody(module, entity, meshCollider, px, py, pz, r, ppu, body.layer);
+ return addMeshBody(module, entity, meshCollider, px, py, pz, r, ppu, body.layer, t?.worldScale);
}
const hull = has(ConvexCollider3D)
? app.world.get(entity, ConvexCollider3D) as ConvexCollider3DData : undefined;
if (hull?.enabled && hull.mesh !== 0) {
- return addConvexBody(module, entity, hull, px, py, pz, r, ppu, how);
+ return addConvexBody(module, entity, hull, px, py, pz, r, ppu, how, t?.worldScale);
}
const capsule = has(CapsuleCollider3D)
? app.world.get(entity, CapsuleCollider3D) as CapsuleCollider3DData : undefined;
@@ -232,11 +248,11 @@ function addMeshBody(module: Physics3DWasmModule, entity: Entity,
collider: MeshCollider3DData,
px: number, py: number, pz: number,
r: { x: number; y: number; z: number; w: number },
- ppu: number, layer: number): number {
+ ppu: number, layer: number, scale?: Vec3): number {
const geometry = getMeshCollision(collider.mesh);
if (!geometry) return 0;
return addTriangles(module, entity, geometry.positions, geometry.indices, px, py, pz, r, ppu, layer,
- collider.friction, collider.restitution);
+ collider.friction, collider.restitution, scale);
}
/** Triangles in world units, scaled into metres on the module's heap, as one static body at (px, py, pz) in metres. */
@@ -244,13 +260,19 @@ function addTriangles(module: Physics3DWasmModule, entity: Entity,
positions: Float32Array, indices: Uint32Array,
px: number, py: number, pz: number,
r: { x: number; y: number; z: number; w: number },
- ppu: number, layer: number, friction: number, restitution: number): number {
+ ppu: number, layer: number, friction: number, restitution: number, scale?: Vec3): number {
const vertexPtr = module._malloc(positions.length * 4);
const indexPtr = module._malloc(indices.length * 4);
try {
const heapF32 = module.HEAPF32;
- for (let i = 0; i < positions.length; i++) heapF32[(vertexPtr >> 2) + i] = positions[i]! / ppu;
+ for (let i = 0; i < positions.length; i++) heapF32[(vertexPtr >> 2) + i] = positions[i]! * (scale ? (i % 3 === 0 ? scale.x : i % 3 === 1 ? scale.y : scale.z) : 1) / ppu;
module.HEAPU32.set(indices, indexPtr >> 2);
+ if (scale && scale.x * scale.y * scale.z < 0) {
+ for (let i = 0; i < indices.length; i += 3) {
+ module.HEAPU32[(indexPtr >> 2) + i + 1] = indices[i + 2]!;
+ module.HEAPU32[(indexPtr >> 2) + i + 2] = indices[i + 1]!;
+ }
+ }
return module._physics3d_addMeshBody(
entity as number, vertexPtr, positions.length / 3, indexPtr, indices.length,
px, py, pz, r.x, r.y, r.z, r.w, layer, friction, restitution);
@@ -294,7 +316,7 @@ function addConvexBody(module: Physics3DWasmModule, entity: Entity,
collider: ConvexCollider3DData, px: number, py: number, pz: number,
r: { x: number; y: number; z: number; w: number },
ppu: number,
- how: readonly [number, number, number, number, number, number, number],
+ how: readonly [number, number, number, number, number, number, number], scale?: Vec3,
): number {
const geometry = getMeshCollision(collider.mesh);
if (!geometry) return 0;
@@ -302,7 +324,7 @@ function addConvexBody(module: Physics3DWasmModule, entity: Entity,
const vertexPtr = module._malloc(positions.length * 4);
try {
const heapF32 = module.HEAPF32;
- for (let i = 0; i < positions.length; i++) heapF32[(vertexPtr >> 2) + i] = positions[i]! / ppu;
+ for (let i = 0; i < positions.length; i++) heapF32[(vertexPtr >> 2) + i] = positions[i]! * (scale ? (i % 3 === 0 ? scale.x : i % 3 === 1 ? scale.y : scale.z) : 1) / ppu;
return module._physics3d_addConvexBody(
entity as number, vertexPtr, positions.length / 3,
px, py, pz, r.x, r.y, r.z, r.w, ...how,
@@ -327,15 +349,27 @@ export function stepPhysics3D(app: App, module: Physics3DWasmModule,
app.world.ensureTransformsComposed();
moveCharacters(app, module, characters, config);
+ const poses = authoredPoses.get(bodies) ?? new Map<Entity, number[]>();
+ authoredPoses.set(bodies, poses);
+ app.world.ensureTransformsComposed();
const live = new Set<Entity>();
for (const entity of app.world.queryEntities([RigidBody3D])) {
const body = app.world.get(entity, RigidBody3D) as RigidBody3DData;
if (!body.enabled) continue;
live.add(entity);
- if (!bodies.has(entity)) {
+ const created = !bodies.has(entity);
+ if (created) {
const id = createBody(app, module, entity, body, ppu);
if (id !== 0) bodies.set(entity, id);
}
+ if (body.bodyType !== MOTION.Dynamic && bodies.has(entity) && app.world.has(entity, Transform)) {
+ const t = app.world.get(entity, Transform), p = t.worldPosition, r = t.worldRotation;
+ const pose = [p.x / ppu, p.y / ppu, p.z / ppu, r.x, r.y, r.z, r.w];
+ const previous = poses.get(entity);
+ if (!created && (!previous || pose.some((v, i) => v !== previous[i])))
+ module._physics3d_setTransform(bodies.get(entity)!, ...pose as [number, number, number, number, number, number, number]);
+ poses.set(entity, pose);
+ }
}
const doomed = new Set<Entity>();
for (const entity of bodies.keys()) {
@@ -348,6 +382,7 @@ export function stepPhysics3D(app: App, module: Physics3DWasmModule,
for (const entity of doomed) {
module._physics3d_removeBody(bodies.get(entity)!);
bodies.delete(entity);
+ poses.delete(entity);
}
syncPieces(module, geometry, pieces, ppu);
@@ -378,6 +413,12 @@ export function stepPhysics3D(app: App, module: Physics3DWasmModule,
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]! });
+ // The ECS stores float32. An unchanged solver pose must not dirty the
+ // hierarchy merely because JS division returned a wider approximation.
+ if (t.position.x === Math.fround(placed.position.x) && t.position.y === Math.fround(placed.position.y)
+ && t.position.z === Math.fround(placed.position.z) && t.rotation.x === Math.fround(placed.rotation!.x)
+ && t.rotation.y === Math.fround(placed.rotation!.y) && t.rotation.z === Math.fround(placed.rotation!.z)
+ && t.rotation.w === Math.fround(placed.rotation!.w)) continue;
t.position.x = placed.position.x;
t.position.y = placed.position.y;
t.position.z = placed.position.z;
diff --git a/sdk/src/physics3d/index.ts b/sdk/src/physics3d/index.ts
index 48ea7de50..4302c106b 100644
--- a/sdk/src/physics3d/index.ts
+++ b/sdk/src/physics3d/index.ts
@@ -69,6 +69,7 @@ export {
type ConvexCollider3DData,
type CharacterController3DData,
} from './Physics3DComponents';
+export { CompoundCollider3D, type CompoundCollider3DData, type CompoundColliderPart3D } from './CompoundCollider3D';
export {
PointJoint3D,
diff --git a/sdk/tests/compound-collider.test.ts b/sdk/tests/compound-collider.test.ts
new file mode 100644
index 000000000..8eb14cf53
--- /dev/null
+++ b/sdk/tests/compound-collider.test.ts
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe,it,expect } from 'vitest';
+import { encodeCompoundParts } from '../src/physics3d/CompoundCollider3D';
+import { collider3DWireframe,collider3DTriangles } from '../src/physics3d/ColliderShape3D';
+const rotation={x:0,y:0,z:0,w:1},position={x:2,y:3,z:4};
+describe('compound model units',()=>{
+ it('applies placement scale and unit conversion to offsets and shape dimensions once',()=>{
+ const packed=encodeCompoundParts([{kind:'box',position,rotation,halfExtents:{x:.5,y:1,z:2}}],{x:200,y:200,z:200},100);
+ expect([...packed]).toEqual([0,1,2,4,4,6,8,0,0,0,1]);
+ });
+ it('rejects invalid data and a sheared primitive instead of silently changing its shape',()=>{
+ expect(()=>encodeCompoundParts([{kind:'sphere',position,rotation,radius:NaN}],{x:1,y:1,z:1},100)).toThrow();
+ expect(()=>encodeCompoundParts([{kind:'box',position,rotation:{x:0,y:0,z:.707,w:.707},halfExtents:{x:1,y:1,z:1}}],{x:2,y:1,z:1},100)).toThrow(/non-uniform/);
+ });
+ it('rotates compound wires and navigation triangles around the local primitive centre',()=>{
+ const shape={kind:'box' as const,halfExtents:{x:1,y:2,z:1},center:{x:5,y:0,z:0},rotation:{x:0,y:0,z:Math.SQRT1_2,w:Math.SQRT1_2}};
+ const wire=collider3DWireframe(shape).flat(),solid=collider3DTriangles(shape).positions;
+ expect(Math.min(...wire.map(p=>p.x))).toBeCloseTo(3);expect(Math.max(...wire.map(p=>p.x))).toBeCloseTo(7);
+ expect(Math.min(...Array.from(solid).filter((_,i)=>i%3===0))).toBeCloseTo(3);
+ });
+});
diff --git a/sdk/tests/physics3d-ecs.test.ts b/sdk/tests/physics3d-ecs.test.ts
index 19263eebf..7f256ed40 100644
--- a/sdk/tests/physics3d-ecs.test.ts
+++ b/sdk/tests/physics3d-ecs.test.ts
@@ -9,7 +9,7 @@
* falling through a floor 0.1m thick — every number still "works", and nothing
* behaves.
*/
-import { describe, it, expect, beforeEach } from 'vitest';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
import { Transform } from '../src/ecs/component';
import type { TransformData } from '../src/ecs/component.generated';
import {
@@ -196,6 +196,27 @@ describe('the 3D world and the ECS', () => {
const called = (name: string) => module.calls.filter((c) => c.name === name);
+ it('syncs changed authored static and kinematic poses without writes on stable frames', () => {
+ const e=spawn();world.insert(e,BoxCollider3D);world.insert(e,RigidBody3D,{bodyType:1});
+ stepPhysics3D(app,module,bodies,DEFAULT_PHYSICS3D_CONFIG);
+ stepPhysics3D(app,module,bodies,DEFAULT_PHYSICS3D_CONFIG);
+ expect(called('setTransform')).toHaveLength(0);
+ const transform=world.get(e,Transform) as TransformData;transform.worldPosition.x=250;
+ stepPhysics3D(app,module,bodies,DEFAULT_PHYSICS3D_CONFIG);
+ expect(called('setTransform')[0].args.slice(1,4)).toEqual([2.5,0,0]);
+ stepPhysics3D(app,module,bodies,DEFAULT_PHYSICS3D_CONFIG);
+ expect(called('setTransform')).toHaveLength(1);
+ });
+
+ it('does not dirty the ECS for an unchanged native body readback', () => {
+ const e=spawn();world.insert(e,BoxCollider3D);world.insert(e,RigidBody3D,{bodyType:2});
+ module.publish([e,0,0,0,0,0,0,1]);
+ const writes=vi.spyOn(world,'set');
+ stepPhysics3D(app,module,bodies,DEFAULT_PHYSICS3D_CONFIG);
+ stepPhysics3D(app,module,bodies,DEFAULT_PHYSICS3D_CONFIG);
+ expect(writes.mock.calls.filter(c=>c[1]===Transform)).toHaveLength(0);
+ });
+
it('registers a body for each shape a scene authors', () => {
const box = spawn();
world.insert(box, BoxCollider3D);
diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjs
index c48a49c57..cde7535ac 100644
--- a/sdk/tests/physics3d-smoke.mjs
+++ b/sdk/tests/physics3d-smoke.mjs
@@ -759,6 +759,34 @@ step(180);
const offsetRest = bodyState(offsetBall);
check('a box centred above its body holds a ball at the shape, not the origin', offsetRest && near(offsetRest.y, 4, 0.05), `y=${offsetRest?.y.toFixed(3)}`);
+
+// Compound shape gap, local rotation, mass and trigger use the same public ABI on both backends.
+function compound(entity, records, motion = STATIC, sensor = 0, mass = 7) {
+ const ptr = m._malloc(records.length * 4);
+ m.HEAPF32.set(records, ptr >> 2);
+ try { return m._physics3d_addCompound(entity, ptr, records.length / 11, 6200, 10, 0,
+ ...IDENTITY, ...FREE(motion), .5, 0, sensor, mass); } finally { m._free(ptr); }
+}
+const bar = [0, .5, 2, .5, -3, 0, 0, ...IDENTITY, 0, .5, 2, .5, 3, 0, 0, ...IDENTITY];
+const pair = compound(8100, bar);
+check('compound creates one body', pair !== 0);
+check('compound leaves its middle gap empty', !raycast(6200, 15, 0, 0, -10, 0));
+check('compound left offset shape participates in queries', raycast(6197,15,0,0,-10,0)?.entity === 8100);
+check('compound right offset shape participates in queries', raycast(6203,15,0,0,-10,0)?.entity === 8100);
+const rotated = compound(8101, [0, .25, 2, .25, 0, 5, 0, 0, 0, Math.SQRT1_2, Math.SQRT1_2]);
+check('compound local rotation is preserved', raycast(6201.5,20,0,0,-10,0)?.entity === 8101);
+m._physics3d_removeBody(rotated); m._physics3d_removeBody(pair);
+const movingCompound = compound(8102, [1,.5,0,0, -1,0,0,...IDENTITY, 1,.5,0,0,1,0,0,...IDENTITY], DYNAMIC);
+check('dynamic compound reports explicit mass', m._physics3d_getBodyDynamics(movingCompound) === 1 && near(m.HEAPF32[m._physics3d_queryResult() >> 2],7,.01));
+step(30); check('dynamic compound falls as one body', bodyState(movingCompound)?.y < 9);
+check('invalid compound data rejected', compound(8103, [0,-1,1,1,0,0,0,...IDENTITY]) === 0);
+m._physics3d_removeBody(movingCompound);
+const sensorCompound = compound(8104,[1,2,0,0,0,0,0,...IDENTITY],KINEMATIC,1);
+const visitor = m._physics3d_addSphere(8105,.5,6200,10,0,...IDENTITY,...FREE(DYNAMIC),.5,0,0);
+step(1);
+check('compound sensor reports overlap', m._physics3d_sensorEntersBytes() > 0);
+m._physics3d_removeBody(visitor); m._physics3d_removeBody(sensorCompound);
+
m._physics3d_shutdown();
check('the world reports itself gone', m._physics3d_isReady() === 0);
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp b/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp
index 12eec9a0b..a624be1a2 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp
@@ -38,6 +38,11 @@ void physics3d_optimize();
void physics3d_setLayerMask(uint32_t layer, uint32_t mask);
// Bodies
+uint32_t physics3d_addCompound(uint32_t entity, uintptr_t partsPtr, uint32_t count,
+ float px, float py, float pz, float qx, float qy, float qz, float qw,
+ int motion, float gravityScale, float linearDamping, float angularDamping,
+ int fixedRotation, uint32_t layer, int continuous,
+ float friction, float restitution, int isSensor, float mass);
uint32_t physics3d_addBox(uint32_t entity, float hx, float hy, float hz,
float px, float py, float pz,
float qx, float qy, float qz, float qw,
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
index 2170a880b..7bdcf0bbf 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
@@ -25,6 +25,7 @@
#include <Jolt/Physics/Collision/Shape/MeshShape.h>
#include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
#include <Jolt/Physics/Collision/Shape/SphereShape.h>
+#include <Jolt/Physics/Collision/Shape/StaticCompoundShape.h>
#include <Jolt/Physics/Character/CharacterVirtual.h>
#include <Jolt/Physics/Collision/CollideShape.h>
#include <Jolt/Physics/Collision/CollisionCollectorImpl.h>
@@ -34,6 +35,7 @@
#include <Jolt/RegisterTypes.h>
#include <cstddef>
+#include <cmath>
using namespace JPH;
using esengine::physics3d::Context;
@@ -157,7 +159,7 @@ ContactRecorder& recorder() {
uint32_t addBody(uint32_t entity, const Ref<Shape>& shape, float px, float py, float pz,
float qx, float qy, float qz, float qw, const BodyMotion& how,
float friction, float restitution, int isSensor,
- float cx = 0.0f, float cy = 0.0f, float cz = 0.0f) {
+ float cx = 0.0f, float cy = 0.0f, float cz = 0.0f, float mass = 0.0f) {
if (!g().isValid()) return 0;
// A collider off the entity's origin: the shape is carried by a translated wrapper, so the body (and what a dynamic one rotates about)
// stays at the entity.
@@ -176,6 +178,10 @@ uint32_t addBody(uint32_t entity, const Ref<Shape>& shape, float px, float py, f
settings.mGravityFactor = how.gravityScale;
settings.mLinearDamping = how.linearDamping;
settings.mAngularDamping = how.angularDamping;
+ if (mass > 0.0f && std::isfinite(mass) && motionType != EMotionType::Static) {
+ settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
+ settings.mMassPropertiesOverride.mMass = mass;
+ }
// What keeps a character upright: the solver may move it and never turn it.
if (how.fixedRotation != 0) {
settings.mAllowedDOFs = EAllowedDOFs::TranslationX | EAllowedDOFs::TranslationY
@@ -305,6 +311,40 @@ void physics3d_optimize() {
// Bodies
+/// Each primitive is 11 floats: kind, dimensions.xyz, offset.xyz, rotation.xyzw.
+/// The compound remains ONE body, so children cannot separate under gravity.
+EMSCRIPTEN_KEEPALIVE
+uint32_t physics3d_addCompound(uint32_t entity, uintptr_t partsPtr, uint32_t count,
+ float px, float py, float pz, float qx, float qy, float qz, float qw,
+ int motion, float gravityScale, float linearDamping, float angularDamping,
+ int fixedRotation, uint32_t layer, int continuous,
+ float friction, float restitution, int isSensor, float mass) {
+ if (!g().isValid() || partsPtr == 0 || count == 0 || count > 16384) return 0;
+ const float* parts = reinterpret_cast<const float*>(partsPtr);
+ StaticCompoundShapeSettings settings;
+ for (uint32_t i = 0; i < count; ++i) {
+ const float* p = parts + i * 11;
+ for (uint32_t j = 0; j < 11; ++j) if (!std::isfinite(p[j])) return 0;
+ Ref<Shape> shape;
+ if (p[0] == 0 && p[1] > 0 && p[2] > 0 && p[3] > 0) {
+ const float convex = std::min(0.05f, std::min(p[1], std::min(p[2], p[3])) * 0.1f);
+ shape = new BoxShape(Vec3(p[1], p[2], p[3]), convex);
+ } else if (p[0] == 1 && p[1] > 0) shape = new SphereShape(p[1]);
+ else if (p[0] == 2 && p[1] > 0 && p[2] >= 0) {
+ if (p[2] == 0) shape = new SphereShape(p[1]);
+ else shape = new CapsuleShape(p[2], p[1]);
+ } else return 0;
+ Quat rotation(p[7], p[8], p[9], p[10]);
+ if (rotation.LengthSq() < 1.0e-12f) return 0;
+ settings.AddShape(Vec3(p[4], p[5], p[6]), rotation.Normalized(), shape);
+ }
+ const auto result = settings.Create();
+ if (result.HasError()) return 0;
+ return addBody(entity, result.Get(), px, py, pz, qx, qy, qz, qw,
+ {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer, continuous},
+ friction, restitution, isSensor, 0, 0, 0, mass);
+}
+
EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addBox(uint32_t entity, float hx, float hy, float hz,
float px, float py, float pz,
diff --git a/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp b/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp
index e2bd20727..d062a3a94 100644
--- a/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp
+++ b/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp
@@ -396,6 +396,60 @@ void physics3d_optimize() {
// Bodies
+EMSCRIPTEN_KEEPALIVE
+uint32_t physics3d_addCompound(uint32_t entity, uintptr_t partsPtr, uint32_t count,
+ float px, float py, float pz, float qx, float qy, float qz, float qw,
+ int motion, float gravityScale, float linearDamping, float angularDamping,
+ int fixedRotation, uint32_t layer, int continuous,
+ float friction, float restitution, int isSensor, float mass) {
+ if (!g().isValid() || partsPtr == 0 || count == 0 || count > 16384) return 0;
+ const float* parts = reinterpret_cast<const float*>(partsPtr);
+ for (uint32_t i = 0; i < count; ++i) {
+ const float* p = parts + i * 11;
+ for (uint32_t j = 0; j < 11; ++j) if (!std::isfinite(p[j])) return 0;
+ if (!(p[1] > 0) || (p[0] == 0 && !(p[2] > 0 && p[3] > 0))
+ || (p[0] == 2 && p[2] < 0) || (p[0] != 0 && p[0] != 1 && p[0] != 2)
+ || PxQuat(p[7], p[8], p[9], p[10]).magnitudeSquared() < 1.0e-12f) return 0;
+ }
+ uint32_t id = 0;
+ const PxShapeFlags flags = isSensor != 0
+ ? PxShapeFlags(PxShapeFlag::eTRIGGER_SHAPE | PxShapeFlag::eSCENE_QUERY_SHAPE)
+ : PxShapeFlags(PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eSCENE_QUERY_SHAPE);
+ for (uint32_t i = 0; i < count; ++i) {
+ const float* p = parts + i * 11;
+ PxGeometryHolder geometry;
+ PxQuat rotation = quat(p[7], p[8], p[9], p[10]);
+ if (p[0] == 0) geometry.storeAny(PxBoxGeometry(p[1], p[2], p[3]));
+ else if (p[0] == 1 || p[2] == 0) geometry.storeAny(PxSphereGeometry(p[1]));
+ else { geometry.storeAny(PxCapsuleGeometry(p[1], p[2])); rotation = rotation * capsuleUpright(); }
+ const PxTransform local(PxVec3(p[4], p[5], p[6]), rotation);
+ if (i == 0) {
+ id = addBody(entity, geometry.any(), local, px, py, pz, qx, qy, qz, qw,
+ {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer, continuous},
+ friction, restitution, isSensor);
+ if (id == 0) return 0;
+ } else {
+ PxShape* shape = gPhysics->createShape(geometry.any(), *material(friction, restitution), true, flags);
+ if (!shape) { physics3d_removeBody(id); return 0; }
+ shape->setLocalPose(local);
+ shape->setContactOffset(CONTACT_OFFSET);
+ shape->setRestOffset(0.0f);
+ shape->setSimulationFilterData(filterData(layer, 0));
+ shape->setQueryFilterData(filterData(layer, 0));
+ const bool attached = g().body(id)->actor->attachShape(*shape);
+ shape->release();
+ if (!attached) { physics3d_removeBody(id); return 0; }
+ }
+ }
+ if (auto* dynamic = dynamicOf(id)) {
+ if (!isSensor) {
+ if (mass > 0 && std::isfinite(mass)) PxRigidBodyExt::setMassAndUpdateInertia(*dynamic, mass);
+ else PxRigidBodyExt::updateMassAndInertia(*dynamic, DENSITY);
+ }
+ }
+ return id;
+}
+
EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addBox(uint32_t entity, float hx, float hy, float hz,
float px, float py, float pz,