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.

26.2 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    Physics3DSystem.ts
 * @brief   Keeps the 3D world and the ECS saying the same thing.
 * @details Each fixed step: entities that gained a RigidBody3D get a body, ones
 *          that lost it give theirs back, the world advances, and what moved is
 *          written to its Transform.
 *
 *          Positions cross in METRES and land in world units, the same
 *          pixels-per-unit contract the 2D world uses: a solver tuned for metres
 *          behaves nothing like itself when a character is 180 units tall.
 */
import type { App } from '../app/app';
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,
    type RigidBody3DData, type BoxCollider3DData, type SphereCollider3DData,
    type CapsuleCollider3DData, type CharacterController3DData, type MeshCollider3DData,
    type ConvexCollider3DData,
} from './Physics3DComponents';
import { getMeshCollision } from '../asset/meshCollision';
import { isImplicitStatic } from './implicitStatic';
import { CompoundCollider3D, encodeCompoundParts } from './CompoundCollider3D';
import { breakJoints3D, syncJoints3D, type Joint3DMap } from './Physics3DJoints';
import type { Entity } from '../types';
import type { Physics3DWasmModule, Physics3DEventsData } from './Physics3DModule';
import { PHYSICS3D_TRANSFORM_STRIDE, drainPhysics3DEvents } from './Physics3DModule';
import type { CollisionGeometry, CollisionPiece } from '../runtime/collisionGeometry';

/** Body kinds, in the order the module reads them. */
const MOTION = { Static: 0, Kinematic: 1, Dynamic: 2 } as const;

export interface Physics3DConfig {
    /** Layer i collides with layer j when bit j of `layerMasks[i]` is set AND bit
     *  i of `layerMasks[j]` is. Absent leaves every layer colliding with all. */
    layerMasks?: number[];
    gravity: { x: number; y: number; z: number };
    fixedTimestep: number;
    collisionSteps: number;
    pixelsPerUnit: number;
    maxBodies: number;
    /** Solver passes; 0 keeps the backend's own (Jolt 10 / PhysX 1). */
    velocityIterations: number;
    /** 0 keeps the backend's own (Jolt 2 / PhysX 6). */
    positionIterations: number;
    /** Resting bodies stop being simulated until something touches them. */
    enableSleep: boolean;
    /** Slower impacts than this (m/s) do not bounce; 0 keeps the backend's own (Jolt 1 / PhysX 2). */
    bounceThreshold: number;
}

export const DEFAULT_PHYSICS3D_CONFIG: Physics3DConfig = {
    gravity: { x: 0, y: -9.81, z: 0 },
    fixedTimestep: 1 / 60,
    collisionSteps: 1,
    pixelsPerUnit: 100,
    maxBodies: 1024,
    velocityIterations: 0,
    positionIterations: 0,
    enableSleep: true,
    bounceThreshold: 0,
};

/** 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 }>;

/** Ground states, as CharacterVirtual reports them. */
const ON_GROUND = 0;

/**
 * Sweep every character, then write where each ended up.
 *
 * Characters are moved BEFORE the solver steps: a character reads the world as it
 * stands and the bodies then react to where it went, which is the order that keeps
 * a character from being pushed by the very body it just displaced.
 */
function moveCharacters(app: App, module: Physics3DWasmModule, characters: BodyMap,
                        config: Physics3DConfig): void {
    const ppu = config.pixelsPerUnit;
    const live = new Set<Entity>();
    for (const entity of app.world.queryEntities([CharacterController3D])) {
        const character = app.world.get(entity, CharacterController3D) as CharacterController3DData;
        if (!character.enabled) continue;
        live.add(entity);

        let id = characters.get(entity);
        if (id === undefined) {
            const t = app.world.get(entity, Transform) as TransformData | undefined;
            const p = t?.worldPosition ?? { x: 0, y: 0, z: 0 };
            id = module._physics3d_addCharacter(
                entity as number, character.radius / ppu, character.halfHeight / ppu,
                p.x / ppu, p.y / ppu, p.z / ppu, character.maxSlope, character.mass,
                character.layer, character.pushForce);
            if (id === 0) continue;
            characters.set(entity, id);
        }

        module._physics3d_moveCharacter(
            id, character.velocity.x / ppu, character.velocity.y / ppu,
            character.velocity.z / ppu, config.fixedTimestep,
            character.stepHeight / ppu, character.snapDown / ppu);

        const bytes = module._physics3d_queryResultBytes();
        if (bytes === 0) continue;
        const base = module._physics3d_queryResult() >> 2;
        const f32 = module.HEAPF32;
        character.isOnFloor = f32[base + 3] === ON_GROUND;
        character.floorNormal.x = f32[base + 4]!;
        character.floorNormal.y = f32[base + 5]!;
        character.floorNormal.z = f32[base + 6]!;
        character.realVelocity.x = f32[base + 7]! * ppu;
        character.realVelocity.y = f32[base + 8]! * ppu;
        character.realVelocity.z = f32[base + 9]! * ppu;
        app.world.set(entity, CharacterController3D, character);

        if (!app.world.has(entity, Transform)) continue;
        const t = app.world.get(entity, Transform) as TransformData;
        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) {
        if (live.has(entity) && app.world.valid(entity)) continue;
        module._physics3d_removeCharacter(id);
        characters.delete(entity);
    }
}

/**
 * @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
        : body.bodyType === 1 ? MOTION.Kinematic : MOTION.Dynamic;
}

/** Where a collider sits from the entity's origin, in metres. Absent means at the origin. */
function centreOf(center: { x: number; y: number; z: number } | undefined, ppu: number): [number, number, number] {
    return center ? [center.x / ppu, center.y / ppu, center.z / ppu] : [0, 0, 0];
}

/**
 * Create the body an entity's collider describes.
 * @returns the module's body id, or 0 when the entity carries no 3D collider.
 */
function createBody(app: App, module: Physics3DWasmModule, entity: Entity,
                    body: RigidBody3DData, ppu: number): number {
    const t = app.world.get(entity, Transform) as TransformData | undefined;
    const p = t?.worldPosition ?? { x: 0, y: 0, z: 0 };
    const r = t?.worldRotation ?? { x: 0, y: 0, z: 0, w: 1 };
    const px = p.x / ppu, py = p.y / ppu, pz = p.z / ppu;
    // How the body answers to the world, in the order the module reads it.
    const how = [motionOf(body), body.gravityScale, body.linearDamping,
                 body.angularDamping, body.fixedRotation ? 1 : 0, body.layer,
                 body.continuousCollision ? 1 : 0] as const;

    // `has` before `get`: a builtin read on an entity that does not carry the
    // 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) {
        return module._physics3d_addBox(
            entity as number, box.halfExtents.x / ppu, box.halfExtents.y / ppu,
            box.halfExtents.z / ppu, px, py, pz, r.x, r.y, r.z, r.w,
            ...how, box.friction, box.restitution, box.isSensor ? 1 : 0, ...centreOf(box.center, ppu));
    }
    const sphere = has(SphereCollider3D)
        ? app.world.get(entity, SphereCollider3D) as SphereCollider3DData : undefined;
    if (sphere?.enabled) {
        return module._physics3d_addSphere(
            entity as number, sphere.radius / ppu, px, py, pz, r.x, r.y, r.z, r.w,
            ...how, sphere.friction, sphere.restitution, sphere.isSensor ? 1 : 0, ...centreOf(sphere.center, ppu));
    }
    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, 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, t?.worldScale);
    }
    const capsule = has(CapsuleCollider3D)
        ? app.world.get(entity, CapsuleCollider3D) as CapsuleCollider3DData : undefined;
    if (capsule?.enabled) {
        return module._physics3d_addCapsule(
            entity as number, capsule.radius / ppu, capsule.halfHeight / ppu,
            px, py, pz, r.x, r.y, r.z, r.w,
            ...how, capsule.friction, capsule.restitution, capsule.isSensor ? 1 : 0, ...centreOf(capsule.center, ppu));
    }
    // A body with no shape has no extent to collide with, so it is not registered
    // at all — the alternative is an invisible point that falls forever.
    return 0;
}

/**
 * Hand a loaded mesh's triangles to the module, scaled into metres.
 *
 * They cross through the module's own heap: the positions have to be scaled
 * anyway, so a copy is made either way and this is the one the module can read.
 */
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, 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, scale);
}

/** Triangles in world units, scaled into metres on the module's heap, as one static body at (px, py, pz) in metres. */
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, 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]! * (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);
    } finally {
        module._free(vertexPtr);
        module._free(indexPtr);
    }
}

/** How far past a changed piece a resting body may stand and still have been resting on it, in world units. */
const PIECE_WAKE_MARGIN = 4;

/**
 * Wakes what may have rested on a piece that has just changed or gone. A solver does not look again at what sleeps, so a body whose ground was
 * dug out from under it would stay in the air. A force too small to matter is what both solvers wake a body for.
 */
function wakeOn(app: App, module: Physics3DWasmModule, bodies: BodyMap, piece: CollisionPiece, ppu: number): void {
    if (!module._physics3d_addForce || bodies.size === 0) return;
    const [ox, oy, oz] = piece.origin, p = piece.positions;
    let x0 = Infinity, y0 = Infinity, z0 = Infinity, x1 = -Infinity, y1 = -Infinity, z1 = -Infinity;
    for (let i = 0; i < p.length; i += 3) {
        x0 = Math.min(x0, p[i]!); y0 = Math.min(y0, p[i + 1]!); z0 = Math.min(z0, p[i + 2]!);
        x1 = Math.max(x1, p[i]!); y1 = Math.max(y1, p[i + 1]!); z1 = Math.max(z1, p[i + 2]!);
    }
    const m = PIECE_WAKE_MARGIN;
    for (const [entity, id] of bodies) {
        if (!app.world.valid(entity) || !app.world.has(entity, RigidBody3D) || !app.world.has(entity, Transform)) continue;
        if ((app.world.get(entity, RigidBody3D) as RigidBody3DData).bodyType !== MOTION.Dynamic) continue;
        const at = (app.world.get(entity, Transform) as TransformData).worldPosition;
        const x = at.x - ox, y = at.y - oy, z = at.z - oz;
        if (x < x0 - m || x > x1 + m || y < y0 - m || y > y1 + m || z < z0 - m || z > z1 + m) continue;
        module._physics3d_addForce(id, 0, -1e-6, 0, at.x / ppu, at.y / ppu, at.z / ppu);
    }
}

/** Follows the app's collision geometry: a static mesh body a piece, built again when its piece is replaced, removed with it. */
function syncPieces(app: App, module: Physics3DWasmModule, geometry: CollisionGeometry | null, pieces: PieceMap, bodies: BodyMap, ppu: number): void {
    if (!geometry && pieces.size === 0) return;
    const live = new Set<string>();
    if (geometry) {
        for (const [key, piece] of geometry.entries()) {
            live.add(key);
            const had = pieces.get(key);
            if (had?.piece === piece) continue;
            if (had) {
                module._physics3d_removeBody(had.id);
                wakeOn(app, module, bodies, had.piece, ppu);
            }
            const [ox, oy, oz] = piece.origin;
            const id = addTriangles(module, piece.owner, piece.positions, piece.indices,
                ox / ppu, oy / ppu, oz / ppu, { x: 0, y: 0, z: 0, w: 1 }, ppu, piece.layer, piece.friction, piece.restitution);
            if (id !== 0) pieces.set(key, { piece, id });
            else pieces.delete(key);
        }
    }
    for (const [key, had] of pieces) {
        if (live.has(key)) continue;
        module._physics3d_removeBody(had.id);
        wakeOn(app, module, bodies, had.piece, ppu);
        pieces.delete(key);
    }
}

/**
 * Hand a mesh's vertices over as a convex hull.
 *
 * Only the positions cross: Jolt builds the hull itself, so the triangles that
 * a mesh collider needs would be a copy nothing reads.
 */
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], scale?: Vec3,
): number {
    const geometry = getMeshCollision(collider.mesh);
    if (!geometry) return 0;
    const { positions } = geometry;
    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]! * (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,
            collider.friction, collider.restitution, collider.isSensor ? 1 : 0);
    } finally {
        module._free(vertexPtr);
    }
}

/** The colliders that make a static body on their own, with no RigidBody3D. */
const IMPLICIT_STATIC_COLLIDERS = [MeshCollider3D, BoxCollider3D, SphereCollider3D, CapsuleCollider3D, ConvexCollider3D, CompoundCollider3D];
/** Per body map: which of its bodies are static for having no RigidBody3D. */
const implicitBodies = new WeakMap<BodyMap, Set<Entity>>();
const IMPLICIT_STATIC: RigidBody3DData = {
    bodyType: 0, layer: 0, gravityScale: 0, linearDamping: 0, angularDamping: 0,
    fixedRotation: false, continuousCollision: false, enabled: true, mass: 0,
};
/** Per body map: the mass last given to each body that was given one, so a change in play reaches the world. */
const givenMasses = new WeakMap<BodyMap, Map<Entity, number>>();

/** Bring the world's population in line with the ECS, then step and read back. */
export function stepPhysics3D(app: App, module: Physics3DWasmModule,
                              bodies: BodyMap, config: Physics3DConfig,
                              characters: BodyMap = new Map(),
                              events?: Physics3DEventsData,
                              joints: Joint3DMap = new Map(),
                              pieces: PieceMap = new Map(),
                              geometry: CollisionGeometry | null = null): 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 poses = authoredPoses.get(bodies) ?? new Map<Entity, number[]>();
    authoredPoses.set(bodies, poses);
    app.world.ensureTransformsComposed();
    const live = new Set<Entity>();
    // A collider with no RigidBody3D is a static body, as in Unity: an imported level is collided against with a
    // MeshCollider3D on each mesh and nothing else. Its own `layer` (a mesh collider has one) is the body's.
    const bodied: Array<[Entity, RigidBody3DData]> = [];
    for (const entity of app.world.queryEntities([RigidBody3D])) {
        bodied.push([entity, app.world.get(entity, RigidBody3D) as RigidBody3DData]);
    }
    for (const collider of IMPLICIT_STATIC_COLLIDERS) {
        for (const entity of app.world.queryEntities([collider])) {
            if (!isImplicitStatic(app.world, entity)) continue;
            const layer = (app.world.get(entity, collider) as { layer?: number }).layer ?? 0;
            bodied.push([entity, { ...IMPLICIT_STATIC, layer }]);
        }
    }
    const implicit = implicitBodies.get(bodies) ?? new Set<Entity>();
    implicitBodies.set(bodies, implicit);
    const given = givenMasses.get(bodies) ?? new Map<Entity, number>();
    givenMasses.set(bodies, given);
    for (const [entity, body] of bodied) {
        if (!body.enabled || live.has(entity)) continue;
        live.add(entity);
        // A body that changed kind (its RigidBody3D came or went, the collider stayed) is made again as the new kind.
        const isImplicit = !app.world.has(entity, RigidBody3D);
        if (bodies.has(entity) && isImplicit !== implicit.has(entity)) {
            module._physics3d_removeBody(bodies.get(entity)!);
            bodies.delete(entity);
            poses.delete(entity);
        }
        if (isImplicit) implicit.add(entity); else implicit.delete(entity);
        const created = !bodies.has(entity);
        if (created) {
            const id = createBody(app, module, entity, body, ppu);
            if (id !== 0) bodies.set(entity, id);
            given.delete(entity);
        }
        // Its own mass where it says one; 0 leaves the one its shape gives. Read each step, as gravityScale is not:
        // what a thing weighs is something a game changes while it runs (a crate emptied, a barrel filled).
        const mass = body.mass ?? 0;
        if (bodies.has(entity) && body.bodyType === MOTION.Dynamic && mass > 0 && given.get(entity) !== mass) {
            module._physics3d_setMass?.(bodies.get(entity)!, mass);
            given.set(entity, mass);
        }
        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()) {
        if (!live.has(entity) || !app.world.valid(entity)) doomed.add(entity);
    }
    // Joints first, and told what is about to go: the module holds a constraint
    // against two bodies, so removing a body under a live joint leaves the solver
    // holding nothing.
    syncJoints3D(app, module, bodies, joints, ppu, doomed);
    for (const entity of doomed) {
        module._physics3d_removeBody(bodies.get(entity)!);
        bodies.delete(entity);
        poses.delete(entity);
        given.delete(entity);
    }

    syncPieces(app, module, geometry, pieces, bodies, ppu);

    // 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.
    if (events) drainPhysics3DEvents(module, events, ppu);
    // What gave way under this step: read now, while the step's force is the one the joint is reporting.
    breakJoints3D(app, module, joints, events?.jointBreaks);

    // Only bodies the solver moved are in the buffer, so this is the frame's
    // moving population rather than every body in the world.
    const bytes = module._physics3d_transformsBytes();
    if (bytes === 0) return;
    const base = module._physics3d_transforms() >> 2;
    const f32 = module.HEAPF32;
    const count = bytes / 4 / PHYSICS3D_TRANSFORM_STRIDE;
    for (let i = 0; i < count; i++) {
        const o = base + i * PHYSICS3D_TRANSFORM_STRIDE;
        const entity = f32[o] as Entity;
        if (!app.world.valid(entity) || !app.world.has(entity, Transform)) continue;
        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.
        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;
        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);
    }
}