Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Free the physics world on failed setup, check live poses, add bake parity test (#771)

Nguyen Xuan An71ed649019ba
diff --cc README.md
index 149908e6,e29c7598..da1e41f2
--- a/README.md
+++ b/README.md
@@@ -140,7 -140,8 +140,9 @@@ Each addon is a separate import, so a p
| Physics | `67js/addons/physics` | [Rapier contacts and joints](docs/physics.md) recorded into a timeline |
| Live games | `67js/addons/runtime` | [Game loop](docs/runtime.md) with fixed or variable steps and pluggable systems |
| Live games | `67js/addons/input` | [Input](docs/input.md): keyboard, mouse, gamepad and custom sources mapped to named actions and axes |
+| Live games | `67js/addons/physics-runtime` | [Live physics](docs/physics-runtime.md): a physics world stepped in the game loop, contact and sensor events, ray, shape and overlap queries |
+ | Live games | `67js/addons/animation-graph` | [Animation graph](docs/animation-graph.md): states, 1D and 2D blend spaces, parameter transitions with crossfades and masked layers for any rig |
+ | Live games | `67js/addons/player` | [Player](docs/player.md): character controller, follow, first-person and top-down camera rigs, swappable at runtime |
| Modeling | `67js/addons/mesh`, `67js/addons/modeling`, `67js/addons/sculpt` | [Mesh editing](docs/mesh.md), [modeling](docs/modeling.md) and [sculpt brushes](https://67js.codepawl.com/sculpt.md) |
| Offline light | `67js/addons/path-tracer`, `67js/addons/light-bake` | [Path-traced stills](https://67js.codepawl.com/path-tracer.md) and [baked lightmaps](https://67js.codepawl.com/light-bake.md) |
| Post passes | `67js/addons/user-pass` | [Your own full-screen GLSL passes](docs/user-passes.md): dither, pixel downscale, quantise |
diff --cc docs/physics-runtime.md
index a89169d2,00000000..99869364
mode 100644,000000..100644
--- a/docs/physics-runtime.md
+++ b/docs/physics-runtime.md
@@@ -1,88 -1,0 +1,90 @@@
+# Live physics
+
+`67js/addons/physics-runtime` steps a physics world inside the [game loop](runtime.md). The recorded bake in [physics.md](physics.md) renders a film; this is for a browser game, where code pushes bodies, reads contacts and casts rays every frame. Both paths build the world with the same function, so a scene behaves the same on either.
+
+```js
+import { Renderer67 } from '67js';
+import { createRuntime } from '67js/addons/runtime';
+import { createPhysicsSystem } from '67js/addons/physics-runtime';
+
+const physics = await createPhysicsSystem({
+ bodies: [
+ { name: 'floor', type: 'fixed', translation: [0, -0.5, 0] },
+ { name: 'crate', translation: [0, 3, 0] },
+ ],
+ colliders: [
+ { name: 'ground', body: 'floor', shape: 'cuboid', halfExtents: [10, 0.5, 10] },
+ { name: 'crate', body: 'crate', shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 },
+ ],
+});
+physics.bind('crate', cratePart);
+physics.on('contact', event => event.started && playThud(event.bodyA, event.bodyB));
+
+const runtime = createRuntime(renderer, { fixedStepSeconds: physics.timestep, systems: [physics] });
+runtime.start();
+```
+
+The definition is the one `createPhysicsScene` takes, without `events` (a live game has no tick script; call the methods below instead). Joints, force fields, sensors, collision groups and masks work as in [physics.md](physics.md).
+
+## Options
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `adapter` | `rapierAdapter` | The engine, see below |
+| `timestep` | `1/60` | Seconds per step. The runtime's `fixedStepSeconds` must equal it; a mismatch throws and says which value to pass. |
+| `bindings` | `[]` | `[{ body, part }]`, same as `physics.bind` |
+| `name` | `'physics'` | The runtime system name |
+| `solverIterations`, `maxBodies`, `maxColliders`, `maxJoints` | as in physics.md | Bounds and solver quality |
+
+Put the system after input and before animation and game code in `systems`.
+
+## Control
+
+- `setKinematicPose(body, { translation, rotation })` moves a `kinematic` body; the world sees the move in the next step, and dynamic bodies resting on it are carried.
+- `applyImpulse(body, impulse, point?)` and `setLinearVelocity(body, velocity)` act on a `dynamic` body.
+- `getPose(body)` returns `{ translation, rotation }` as of the last step.
+- `bind(body, part)` writes the body's pose to `part.matrix` (a retained `Float32Array(16)`, scale is kept). In `'both'` mode the pose is interpolated with `context.alpha`, so a 30 Hz simulation looks smooth on a 144 Hz screen.
+
+## Events
+
+`physics.on('contact', listener)` and `physics.on('sensor', listener)` return an unsubscribe function. After each step the listeners get, per pair:
+
+```js
+{ step, kind: 'contact' | 'sensor', started, colliderA, colliderB, bodyA, bodyB }
+```
+
+`started` is `true` when two colliders begin touching and `false` when they stop. A pair with a sensor collider is `'sensor'`. Within a pair `colliderA` is the lower collider index, and a step's events are sorted by `(colliderA, colliderB, started first)`, so every adapter fires the same sequence. `physics.events` holds the last step's events; `physics.eventsTruncated` is set if more than `maxContactEvents` (4096) arrived in one step.
+
+## Queries
+
+They read the world as the last step left it. Every query takes optional `{ mask, excludeBody, includeSensors }`: `mask` is a collision-group mask (0 to 65535), `excludeBody` skips one body (for example the player), and sensors are skipped unless `includeSensors` is `true`.
+
+- `raycast(origin, direction, { maxDistance = 1000 })` returns the first hit or `null`: `{ body, collider, distance, point, normal }`. The direction need not be a unit vector.
+- `shapeCast(shape, translation, direction, { maxDistance, rotation })` sweeps a shape and returns the first hit in the same form; `distance` is how far the shape's centre travelled.
+- `overlap(shape, translation, { rotation })` returns the sorted names of the bodies that touch the shape.
+
+A shape is `{ type: 'ball', radius }`, `{ type: 'cuboid', halfExtents }` or `{ type: 'capsule', halfHeight, radius }`.
+
+## Engines
+
+An adapter is `{ name, load?(), createWorld(prepared) }`. `prepared` is the validated scene (bodies, colliders, joints, fields, gravity). `createWorld` returns:
+
+```js
+{
+ step(stepSeconds, elapsedSeconds), readPose(bodyIndex, out7), free(),
+ setKinematicPose(bodyIndex, translation, rotation), setLinearVelocity(bodyIndex, velocity), applyImpulse(bodyIndex, impulse, point),
+ drainEvents(callback(colliderIndexA, colliderIndexB, started)),
+ raycast(origin, unitDirection, maxDistance, filter), shapeCast(shape, translation, rotation, unitDirection, maxDistance, filter),
+ overlap(shape, translation, rotation, filter),
+}
+```
+
+Bodies and colliders are addressed by their index in the definition; the system maps indices to names, validates every argument and orders events. `rapierAdapter` (Rapier, already a dependency of the physics addon) is the one adapter shipped today. The tests run the system over a scripted adapter to prove it reads nothing else.
+
+## Limits
+
+At most 64 listeners per kind, 4096 bound parts, 1024 overlap results and a query distance up to 1,000,000. Counts of bodies, colliders and joints follow physics.md. `dispose()` (the runtime calls it) frees the world.
+
- Measured on one machine, 500 dynamic boxes settling on a floor with Rapier: about 3 ms per step (`tests/physics-runtime.test.js` prints the figure). Other engines are not shipped yet.
++After every step the system checks each pose like the bake does: a non-finite position or a quaternion that is not unit length throws a `RangeError` naming the body and the step, so a bad pose never reaches a bound part. If setup throws (an unknown body in `bindings`, say), the engine world is freed before the error propagates.
++
++Steps for 500 dynamic boxes settling on a floor were seen at about 3 ms on one machine with Rapier; the test prints the figure but asserts no timing. Only Rapier ships, so no step time is recorded for a second engine and event parity between two real engines is not shown. Issue #771 stays open for both.
diff --cc package.json
index 69817da6,2767290b..6c8b7bda
--- a/package.json
+++ b/package.json
@@@ -43,7 -43,8 +43,9 @@@
"docs/physics.md",
"docs/runtime.md",
"docs/input.md",
+ "docs/physics-runtime.md",
+ "docs/animation-graph.md",
+ "docs/player.md",
"docs/scene-query.md",
"docs/user-passes.md",
"docs/skeleton-pose.md",
@@@ -121,7 -122,8 +123,9 @@@
"./addons/cloth": "./build/cloth.js",
"./addons/runtime": "./build/runtime.js",
"./addons/input": "./build/input.js",
+ "./addons/physics-runtime": "./build/physics-runtime.js",
+ "./addons/animation-graph": "./build/animation-graph.js",
+ "./addons/player": "./build/player.js",
"./addons/update-part-vertices": "./build/update-part-vertices.js",
"./package.json": "./package.json"
},
diff --cc scripts/prepare-release.mjs
index 3b90ba6d,6256aa22..871cfc2a
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@@ -53,7 -53,7 +53,7 @@@ const sourceDocuments =
'vehicle.md',
'vegetation.md', 'terrain.md', 'grass.md', 'clutter.md', 'light-bake.md', 'path-tracer.md', 'gaussian-splats.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
- 'runtime.md', 'input.md', 'physics-runtime.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
- 'runtime.md', 'input.md', 'player.md', 'animation-graph.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
++ 'runtime.md', 'input.md', 'physics-runtime.md', 'player.md', 'animation-graph.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
];
for (const name of sourceDocuments) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
diff --cc src/docs-live.js
index 62a28728,36cb15a8..0684a4ca
--- a/src/docs-live.js
+++ b/src/docs-live.js
@@@ -64,7 -64,7 +64,8 @@@ const addonLoaders = import.meta.glob(
'./cloth.js',
'./runtime.js',
'./input.js',
+ './physics-runtime.js',
+ './player.js',
'./update-part-vertices.js',
]);
const moduleCache = new Map();
diff --cc src/physics-runtime.js
index f6c0d9ae,00000000..052c9d38
mode 100644,000000..100644
--- a/src/physics-runtime.js
+++ b/src/physics-runtime.js
@@@ -1,421 -1,0 +1,455 @@@
+// Live physics as a runtime system. One small interface (bodies, colliders, joints, forces, ray, shape and overlap
+// queries, contact and sensor events) sits over a physics engine adapter, and the system steps it in fixedUpdate and
+// writes the body poses to scene parts. The Rapier adapter wraps the world builder the recorded bake in physics.js uses,
+// so the bake path and the live path share one adapter. Another engine plugs in as an object with the same shape as
+// `rapierAdapter`; see docs/physics-runtime.md. Nothing here touches the film path.
+import { mat4, quat } from 'gl-matrix';
+import { applyForceFieldImpulses, createRapierWorld, loadPhysicsEngine, prepareLivePhysics, requireRapier } from './physics.js';
+
+export const PHYSICS_RUNTIME_LIMITS = Object.freeze({
+ maximumListeners: 64,
+ maximumBindings: 4096,
+ maximumOverlaps: 1024,
+ maximumQueryDistance: 1e6,
+});
+
+const SHAPE_TYPES = ['ball', 'cuboid', 'capsule'];
+const MAX_GROUP_BITS = 0xffff;
+const STEP_TOLERANCE = 1e-9;
+const POSE_STRIDE = 7;
+
+function describe(value) {
+ return value === null ? 'null' : typeof value;
+}
+
+function finiteVector(value, length, label) {
+ if (!(Array.isArray(value) || ArrayBuffer.isView(value)) || value.length !== length || !Array.from(value).every(Number.isFinite)) {
+ throw new TypeError(`${label} must be an array of ${length} finite numbers, got ${Array.isArray(value) ? JSON.stringify(value) : describe(value)}.`);
+ }
+ return Array.from(value);
+}
+
+function unitDirection(value, label) {
+ const direction = finiteVector(value, 3, label);
+ const length = Math.hypot(...direction);
+ if (!(length > 0)) throw new RangeError(`${label} must not be the zero vector; pass a direction such as [0, -1, 0].`);
+ return direction.map(component => component / length);
+}
+
+function queryDistance(value, label) {
+ if (typeof value !== 'number' || !(value > 0) || value > PHYSICS_RUNTIME_LIMITS.maximumQueryDistance) {
+ throw new RangeError(`${label} must be a number above 0 and up to ${PHYSICS_RUNTIME_LIMITS.maximumQueryDistance}, got ${String(value)}.`);
+ }
+ return value;
+}
+
+function positiveNumber(value, label) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
+ throw new RangeError(`${label} must be a number above 0, got ${String(value)}.`);
+ }
+ return value;
+}
+
+function validateShape(shape, label) {
+ if (shape === null || typeof shape !== 'object' || !SHAPE_TYPES.includes(shape.type)) {
+ const got = shape === null || typeof shape !== 'object' ? describe(shape) : String(shape.type);
+ throw new TypeError(`${label} must be { type: ${SHAPE_TYPES.map(type => `"${type}"`).join(' | ')}, ... }, got ${got}.`);
+ }
+ if (shape.type === 'ball') return { type: 'ball', radius: positiveNumber(shape.radius, `${label}.radius`) };
+ if (shape.type === 'capsule') {
+ return { type: 'capsule', halfHeight: positiveNumber(shape.halfHeight, `${label}.halfHeight`), radius: positiveNumber(shape.radius, `${label}.radius`) };
+ }
+ const halfExtents = finiteVector(shape.halfExtents, 3, `${label}.halfExtents`);
+ halfExtents.forEach((extent, axis) => positiveNumber(extent, `${label}.halfExtents[${axis}]`));
+ return { type: 'cuboid', halfExtents };
+}
+
+function validateRotation(value, label) {
+ if (value === undefined) return [0, 0, 0, 1];
+ const rotation = finiteVector(value, 4, label);
+ const length = Math.hypot(...rotation);
+ if (!(length > 0)) throw new RangeError(`${label} must not be the zero quaternion; pass [x, y, z, w] such as [0, 0, 0, 1].`);
+ return rotation.map(component => component / length);
+}
+
+const xyz = array => ({ x: array[0], y: array[1], z: array[2] });
+const xyzw = array => ({ ...xyz(array), w: array[3] });
+
+/** The Rapier adapter: a world built by the same function the recorded bake uses. */
+export const rapierAdapter = Object.freeze({
+ name: 'rapier',
+ load: loadPhysicsEngine,
+ createWorld(prepared) {
+ const rapier = requireRapier();
+ const { world, bodies, colliderIndices } = createRapierWorld(rapier, prepared);
+ const eventQueue = new rapier.EventQueue(true);
+
+ function queryFilter(filter) {
+ const flags = filter.includeSensors ? undefined : rapier.QueryFilterFlags.EXCLUDE_SENSORS;
+ const groups = ((MAX_GROUP_BITS << 16) | filter.mask) >>> 0;
+ const excludedBody = filter.excludeBody === undefined ? undefined : bodies[filter.excludeBody];
+ return [flags, groups, undefined, excludedBody];
+ }
+
+ function rapierShape(shape) {
+ if (shape.type === 'ball') return new rapier.Ball(shape.radius);
+ if (shape.type === 'capsule') return new rapier.Capsule(shape.halfHeight, shape.radius);
+ return new rapier.Cuboid(...shape.halfExtents);
+ }
+
+ return {
+ step(stepSeconds, elapsedSeconds) {
+ world.timestep = stepSeconds;
+ if (prepared.fields.length) applyForceFieldImpulses({ ...prepared, timestep: stepSeconds }, bodies, elapsedSeconds);
+ world.step(eventQueue);
+ },
+ readPose(bodyIndex, output) {
+ const position = bodies[bodyIndex].translation();
+ const rotation = bodies[bodyIndex].rotation();
+ output[0] = position.x;
+ output[1] = position.y;
+ output[2] = position.z;
+ output[3] = rotation.x;
+ output[4] = rotation.y;
+ output[5] = rotation.z;
+ output[6] = rotation.w;
+ },
+ setKinematicPose(bodyIndex, translation, rotation) {
+ if (translation) bodies[bodyIndex].setNextKinematicTranslation(xyz(translation));
+ if (rotation) bodies[bodyIndex].setNextKinematicRotation(xyzw(rotation));
+ },
+ setLinearVelocity(bodyIndex, velocity) {
+ bodies[bodyIndex].setLinvel(xyz(velocity), true);
+ },
+ applyImpulse(bodyIndex, impulse, point) {
+ if (point) bodies[bodyIndex].applyImpulseAtPoint(xyz(impulse), xyz(point), true);
+ else bodies[bodyIndex].applyImpulse(xyz(impulse), true);
+ },
+ drainEvents(callback) {
+ eventQueue.drainCollisionEvents((firstHandle, secondHandle, started) => {
+ callback(colliderIndices.get(firstHandle), colliderIndices.get(secondHandle), started);
+ });
+ },
+ raycast(origin, direction, maxDistance, filter) {
+ const ray = new rapier.Ray(xyz(origin), xyz(direction));
+ const hit = world.castRayAndGetNormal(ray, maxDistance, true, ...queryFilter(filter));
+ if (!hit) return null;
+ return { collider: colliderIndices.get(hit.collider.handle), distance: hit.timeOfImpact, normal: [hit.normal.x, hit.normal.y, hit.normal.z] };
+ },
+ shapeCast(shape, translation, rotation, direction, maxDistance, filter) {
+ const hit = world.castShape(xyz(translation), xyzw(rotation), xyz(direction), rapierShape(shape), 0, maxDistance, true, ...queryFilter(filter));
+ if (!hit) return null;
+ return { collider: colliderIndices.get(hit.collider.handle), distance: hit.time_of_impact, normal: [hit.normal1.x, hit.normal1.y, hit.normal1.z] };
+ },
+ overlap(shape, translation, rotation, filter) {
+ const found = [];
+ world.intersectionsWithShape(xyz(translation), xyzw(rotation), rapierShape(shape), collider => {
+ found.push(colliderIndices.get(collider.handle));
+ return found.length < PHYSICS_RUNTIME_LIMITS.maximumOverlaps;
+ }, ...queryFilter(filter));
+ return found;
+ },
+ free() {
+ eventQueue.free();
+ world.free();
+ },
+ };
+ },
+});
+
+function validateAdapter(adapter) {
+ if (adapter === null || typeof adapter !== 'object' || typeof adapter.createWorld !== 'function' || typeof adapter.name !== 'string') {
+ throw new TypeError('createPhysicsSystem adapter must be an object like { name, load?(), createWorld(prepared) }, such as rapierAdapter.');
+ }
+ return adapter;
+}
+
+function validateFilter(filter, bodyIndices) {
+ if (filter === null || typeof filter !== 'object') throw new TypeError('A physics query options value must be an object like { mask, excludeBody, includeSensors } or left out.');
+ const mask = filter.mask ?? MAX_GROUP_BITS;
+ if (!Number.isInteger(mask) || mask < 0 || mask > MAX_GROUP_BITS) {
+ throw new RangeError(`A physics query mask must be an integer from 0 to ${MAX_GROUP_BITS}, got ${String(filter.mask)}.`);
+ }
+ let excludeBody;
+ if (filter.excludeBody !== undefined) {
+ excludeBody = bodyIndices.get(filter.excludeBody);
+ if (excludeBody === undefined) throw new RangeError(`A physics query excludeBody names no body: "${String(filter.excludeBody)}". Present: ${[...bodyIndices.keys()].join(', ')}.`);
+ }
+ return { mask, excludeBody, includeSensors: filter.includeSensors === true };
+}
+
+function partScale(matrix) {
+ return [Math.hypot(matrix[0], matrix[1], matrix[2]), Math.hypot(matrix[4], matrix[5], matrix[6]), Math.hypot(matrix[8], matrix[9], matrix[10])];
+}
+
+/**
+ * Build a live physics system for a runtime. Await it: the adapter may load a wasm engine first.
+ * `definition` is the recorded-physics definition without tick events (docs/physics.md). Options: adapter (default
+ * rapierAdapter), timestep (default 1/60; give the runtime the same fixedStepSeconds), name, bindings, solverIterations.
+ */
+export async function createPhysicsSystem(definition, options = {}) {
+ if (options === null || typeof options !== 'object') throw new TypeError('createPhysicsSystem options must be an object or left out.');
+ const { adapter: requestedAdapter, name, bindings: initialBindings, ...engineOptions } = options;
+ const adapter = validateAdapter(requestedAdapter ?? rapierAdapter);
+ const timestep = engineOptions.timestep ?? 1 / 60;
+ const prepared = prepareLivePhysics(definition, { ...engineOptions, timestep });
+ await adapter.load?.();
+ const world = adapter.createWorld(prepared);
+
+ const bodyNames = Object.freeze(prepared.bodies.map(body => body.name));
+ const bodyIndices = new Map(bodyNames.map((bodyName, index) => [bodyName, index]));
+ let previousPoses = new Float32Array(bodyNames.length * POSE_STRIDE);
+ let currentPoses = new Float32Array(bodyNames.length * POSE_STRIDE);
+ const bindings = [];
+ const listeners = { contact: new Set(), sensor: new Set() };
+ let stepEvents = [];
+ let eventsTruncated = false;
+ let stepCount = 0;
+ let disposed = false;
+
+ function readPoses() {
+ for (let bodyIndex = 0; bodyIndex < bodyNames.length; bodyIndex++) {
+ world.readPose(bodyIndex, currentPoses.subarray(bodyIndex * POSE_STRIDE, (bodyIndex + 1) * POSE_STRIDE));
+ }
+ }
- readPoses();
- previousPoses.set(currentPoses);
++ // The wasm world is only freed by dispose(), so a setup that throws before the system exists must free it here.
++ function freeWorldOnFailure(action) {
++ try {
++ return action();
++ } catch (error) {
++ world.free();
++ throw error;
++ }
++ }
++
++ // The bake rejects non-finite poses and non-unit quaternions after each step; the live step does the same.
++ function assertPosesSound() {
++ for (let bodyIndex = 0; bodyIndex < bodyNames.length; bodyIndex++) {
++ const offset = bodyIndex * POSE_STRIDE;
++ let quaternionLengthSquared = 0;
++ for (let component = 0; component < POSE_STRIDE; component++) {
++ const value = currentPoses[offset + component];
++ if (!Number.isFinite(value)) {
++ throw new RangeError(`Body "${bodyNames[bodyIndex]}" has a non-finite pose at step ${stepCount}. Apply smaller velocities and impulses.`);
++ }
++ if (component >= 3) quaternionLengthSquared += value * value;
++ }
++ if (Math.abs(Math.sqrt(quaternionLengthSquared) - 1) > 1e-3) {
++ throw new RangeError(`Body "${bodyNames[bodyIndex]}" has a non-unit rotation at step ${stepCount}. Apply smaller velocities and impulses.`);
++ }
++ }
++ }
++
++ freeWorldOnFailure(() => {
++ readPoses();
++ assertPosesSound();
++ previousPoses.set(currentPoses);
++ });
+
+ function assertAlive() {
+ if (disposed) throw new Error('This physics system was disposed. Call createPhysicsSystem again.');
+ }
+
+ function bodyIndexOf(bodyName, action) {
+ const index = bodyIndices.get(bodyName);
+ if (index === undefined) throw new RangeError(`${action} names no body: "${String(bodyName)}". Present: ${bodyNames.join(', ')}.`);
+ return index;
+ }
+
+ function requireBodyType(bodyName, action, type) {
+ const index = bodyIndexOf(bodyName, action);
+ const actual = prepared.bodies[index].type;
+ if (actual !== type) throw new TypeError(`${action} needs a ${type} body; "${bodyName}" is ${actual}.`);
+ return index;
+ }
+
+ const colliderBodyName = colliderIndex => bodyNames[prepared.colliders[colliderIndex].body];
+
+ function describeHit(hit, origin, unit) {
+ return {
+ body: colliderBodyName(hit.collider),
+ collider: prepared.colliders[hit.collider].name,
+ distance: hit.distance,
+ point: origin.map((component, axis) => component + unit[axis] * hit.distance),
+ normal: hit.normal,
+ };
+ }
+
+ function collectEvents() {
+ const collected = [];
+ eventsTruncated = false;
+ world.drainEvents((first, second, started) => {
+ if (collected.length >= prepared.maxContactEvents) {
+ eventsTruncated = true;
+ return;
+ }
+ const [colliderA, colliderB] = first < second ? [first, second] : [second, first];
+ const sensor = prepared.colliders[colliderA].sensor || prepared.colliders[colliderB].sensor;
+ collected.push(Object.freeze({
+ step: stepCount,
+ kind: sensor ? 'sensor' : 'contact',
+ started,
+ colliderA,
+ colliderB,
+ bodyA: colliderBodyName(colliderA),
+ bodyB: colliderBodyName(colliderB),
+ }));
+ });
+ // Engines report events in their own order; sorting makes every adapter fire the same sequence.
+ collected.sort((first, second) => first.colliderA - second.colliderA || first.colliderB - second.colliderB || Number(second.started) - Number(first.started));
+ return collected;
+ }
+
+ function writeBindings(alpha) {
+ for (const binding of bindings) {
+ const offset = binding.index * POSE_STRIDE;
+ for (let axis = 0; axis < 3; axis++) {
+ binding.position[axis] = previousPoses[offset + axis] + (currentPoses[offset + axis] - previousPoses[offset + axis]) * alpha;
+ }
+ for (let component = 0; component < 4; component++) {
+ binding.start[component] = previousPoses[offset + 3 + component];
+ binding.end[component] = currentPoses[offset + 3 + component];
+ }
+ quat.slerp(binding.rotation, binding.start, binding.end, alpha);
+ mat4.fromRotationTranslationScale(binding.part.matrix, binding.rotation, binding.position, binding.scale);
+ }
+ }
+
+ function bind(bodyName, part) {
+ assertAlive();
+ const index = bodyIndexOf(bodyName, 'bind');
+ const matrix = part?.matrix;
+ if (!(matrix instanceof Float32Array) || matrix.length !== 16) {
+ throw new TypeError(`bind("${bodyName}") needs a part with a retained Float32Array(16) matrix, got ${describe(matrix)}.`);
+ }
+ if (bindings.length >= PHYSICS_RUNTIME_LIMITS.maximumBindings) {
+ throw new RangeError(`A physics system binds at most ${PHYSICS_RUNTIME_LIMITS.maximumBindings} parts.`);
+ }
+ if (bindings.some(binding => binding.part.matrix === matrix)) throw new RangeError(`bind("${bodyName}") got a part whose matrix is already bound.`);
+ const scale = partScale(matrix);
+ if (!scale.every(size => size > 0 && Number.isFinite(size))) {
+ throw new RangeError(`bind("${bodyName}") needs a part matrix with a positive scale, such as the identity matrix.`);
+ }
+ bindings.push({ part, index, scale, position: new Float32Array(3), rotation: quat.create(), start: quat.create(), end: quat.create() });
+ writeBindings(1);
+ return system;
+ }
+
+ function on(kind, listener) {
+ assertAlive();
+ if (!(kind in listeners)) throw new RangeError(`on() kind must be "contact" or "sensor", got ${String(kind)}.`);
+ if (typeof listener !== 'function') throw new TypeError(`on("${kind}") needs a listener function, got ${describe(listener)}.`);
+ if (listeners[kind].size >= PHYSICS_RUNTIME_LIMITS.maximumListeners) {
+ throw new RangeError(`A physics system holds at most ${PHYSICS_RUNTIME_LIMITS.maximumListeners} listeners per kind.`);
+ }
+ listeners[kind].add(listener);
+ return () => listeners[kind].delete(listener);
+ }
+
+ const system = {
+ name: name ?? 'physics',
+ adapter: adapter.name,
+ timestep,
+ bodyNames,
+ get stepCount() { return stepCount; },
+ /** The contact and sensor events of the last step, sorted by collider pair. */
+ get events() { return stepEvents; },
+ get eventsTruncated() { return eventsTruncated; },
+ on,
+ bind,
+
+ // Runtime hooks.
+ fixedUpdate(stepSeconds, context) {
+ assertAlive();
+ if (Math.abs(stepSeconds - timestep) > STEP_TOLERANCE * Math.max(1, timestep)) {
+ throw new RangeError(`The runtime fixed step is ${stepSeconds} s but this physics system was built with timestep ${timestep} s. Create the runtime with fixedStepSeconds: physics.timestep, or pass timestep: ${stepSeconds} to createPhysicsSystem.`);
+ }
+ world.step(stepSeconds, stepCount * stepSeconds);
+ stepCount += 1;
+ [previousPoses, currentPoses] = [currentPoses, previousPoses];
+ readPoses();
++ assertPosesSound();
+ stepEvents = collectEvents();
+ // In 'both' mode update() writes the interpolated pose; otherwise this step is the only writer.
+ if (context?.mode !== 'both') writeBindings(1);
+ for (const event of stepEvents) {
+ for (const listener of listeners[event.kind]) listener(event);
+ }
+ },
+ update(_delta, context) {
+ if (context?.mode === 'both') writeBindings(context.alpha);
+ },
+ dispose() {
+ if (disposed) return;
+ disposed = true;
+ world.free();
+ bindings.length = 0;
+ },
+
+ // Control. Kinematic bodies are driven by code; dynamic bodies take impulses and velocities.
+ setKinematicPose(bodyName, pose) {
+ assertAlive();
+ const index = requireBodyType(bodyName, 'setKinematicPose', 'kinematic');
+ if (pose === null || typeof pose !== 'object' || (pose.translation === undefined && pose.rotation === undefined)) {
+ throw new TypeError('setKinematicPose needs { translation, rotation } with at least one of them.');
+ }
+ const translation = pose.translation === undefined ? undefined : finiteVector(pose.translation, 3, 'setKinematicPose translation');
+ const rotation = pose.rotation === undefined ? undefined : validateRotation(pose.rotation, 'setKinematicPose rotation');
+ world.setKinematicPose(index, translation, rotation);
+ return system;
+ },
+ setLinearVelocity(bodyName, velocity) {
+ assertAlive();
+ const index = requireBodyType(bodyName, 'setLinearVelocity', 'dynamic');
+ world.setLinearVelocity(index, finiteVector(velocity, 3, 'setLinearVelocity velocity'));
+ return system;
+ },
+ applyImpulse(bodyName, impulse, point) {
+ assertAlive();
+ const index = requireBodyType(bodyName, 'applyImpulse', 'dynamic');
+ world.applyImpulse(index, finiteVector(impulse, 3, 'applyImpulse impulse'), point === undefined ? undefined : finiteVector(point, 3, 'applyImpulse point'));
+ return system;
+ },
+ /** Pose of a body after the last step: { translation, rotation }. */
+ getPose(bodyName) {
+ assertAlive();
+ const offset = bodyIndexOf(bodyName, 'getPose') * POSE_STRIDE;
+ return { translation: Array.from(currentPoses.subarray(offset, offset + 3)), rotation: Array.from(currentPoses.subarray(offset + 3, offset + POSE_STRIDE)) };
+ },
+
+ // Queries read the world as the last step left it.
+ /** First hit along a ray, or null: { body, collider, distance, point, normal }. */
+ raycast(origin, direction, queryOptions = {}) {
+ assertAlive();
+ const start = finiteVector(origin, 3, 'raycast origin');
+ const unit = unitDirection(direction, 'raycast direction');
+ const maximumDistance = queryDistance(queryOptions.maxDistance ?? 1000, 'raycast maxDistance');
+ const hit = world.raycast(start, unit, maximumDistance, validateFilter(queryOptions, bodyIndices));
+ return hit ? describeHit(hit, start, unit) : null;
+ },
+ /** Sweep a ball, cuboid or capsule along a direction and return the first hit, or null: { body, collider, distance, point, normal }. */
+ shapeCast(shape, translation, direction, queryOptions = {}) {
+ assertAlive();
+ const validShape = validateShape(shape, 'shapeCast shape');
+ const start = finiteVector(translation, 3, 'shapeCast translation');
+ const unit = unitDirection(direction, 'shapeCast direction');
+ const maximumDistance = queryDistance(queryOptions.maxDistance ?? 1000, 'shapeCast maxDistance');
+ const rotation = validateRotation(queryOptions.rotation, 'shapeCast rotation');
+ const hit = world.shapeCast(validShape, start, rotation, unit, maximumDistance, validateFilter(queryOptions, bodyIndices));
+ return hit ? describeHit(hit, start, unit) : null;
+ },
+ /** Names of the bodies whose colliders touch a ball, cuboid or capsule placed in the world, sorted. */
+ overlap(shape, translation, queryOptions = {}) {
+ assertAlive();
+ const validShape = validateShape(shape, 'overlap shape');
+ const start = finiteVector(translation, 3, 'overlap translation');
+ const rotation = validateRotation(queryOptions.rotation, 'overlap rotation');
+ const found = world.overlap(validShape, start, rotation, validateFilter(queryOptions, bodyIndices));
+ return [...new Set(found.map(colliderBodyName))].sort();
+ },
+ };
- for (const binding of initialBindings ?? []) bind(binding.body, binding.part);
++ freeWorldOnFailure(() => {
++ for (const binding of initialBindings ?? []) bind(binding.body, binding.part);
++ });
+ return system;
+}
diff --cc tests/physics-runtime.test.js
index 107bb880,00000000..2303c2ec
mode 100644,000000..100644
--- a/tests/physics-runtime.test.js
+++ b/tests/physics-runtime.test.js
@@@ -1,194 -1,0 +1,255 @@@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createPhysicsSystem, rapierAdapter } from '../src/physics-runtime.js';
+import { createRuntime } from '../src/runtime.js';
+
+const STEP = 1 / 60;
+
+function worldDefinition() {
+ return {
+ bodies: [
+ { name: 'floor', type: 'fixed', translation: [0, -0.5, 0] },
+ { name: 'box', translation: [0, 2, 0] },
+ { name: 'zone', type: 'fixed', translation: [4, 1, 0] },
+ { name: 'platform', type: 'kinematic', translation: [-4, 1, 0] },
+ ],
+ colliders: [
+ { name: 'ground', body: 'floor', shape: 'cuboid', halfExtents: [10, 0.5, 10] },
+ { name: 'crate', body: 'box', shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 },
+ { name: 'trigger', body: 'zone', shape: 'cuboid', halfExtents: [1, 1, 1], sensor: true },
+ { name: 'lift', body: 'platform', shape: 'cuboid', halfExtents: [1, 0.1, 1] },
+ ],
+ };
+}
+
+function stepMany(system, count) {
+ for (let step = 0; step < count; step++) system.fixedUpdate(STEP, { mode: 'fixed' });
+}
+
+test('a live world steps in fixedUpdate and a box falls onto the floor', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ assert.equal(physics.adapter, 'rapier');
+ stepMany(physics, 120);
+ const { translation } = physics.getPose('box');
+ assert.ok(Math.abs(translation[1] - 0.5) < 0.05, `box rests on the floor, y = ${translation[1]}`);
+ assert.equal(physics.stepCount, 120);
+ physics.dispose();
+});
+
+test('contact events fire once on start, sorted, with body names', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ const heard = [];
+ physics.on('contact', event => heard.push(event));
+ stepMany(physics, 120);
+ const started = heard.filter(event => event.started);
+ assert.equal(started.length, 1);
+ assert.deepEqual([started[0].bodyA, started[0].bodyB], ['floor', 'box']);
+ assert.equal(started[0].kind, 'contact');
+ assert.ok(started[0].step > 0 && started[0].step < 60);
+ physics.dispose();
+});
+
+test('sensor events report a body entering and leaving a trigger', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ const heard = [];
+ physics.on('sensor', event => heard.push(`${event.started ? 'enter' : 'exit'} ${event.bodyA}/${event.bodyB}`));
+ physics.applyImpulse('box', [4, 0, 0]);
+ stepMany(physics, 60);
+ assert.ok(heard.includes('enter box/zone') || heard.includes('enter zone/box'), heard.join(', '));
+ physics.setLinearVelocity('box', [-6, 0, 0]);
+ stepMany(physics, 60);
+ assert.ok(heard.some(entry => entry.startsWith('exit')), heard.join(', '));
+ physics.dispose();
+});
+
+test('a kinematic body follows setKinematicPose and carries the world', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ physics.setKinematicPose('platform', { translation: [-4, 3, 0] });
+ stepMany(physics, 2);
+ assert.ok(Math.abs(physics.getPose('platform').translation[1] - 3) < 1e-4);
+ assert.throws(() => physics.setKinematicPose('box', { translation: [0, 0, 0] }), /needs a kinematic body; "box" is dynamic/);
+ physics.dispose();
+});
+
+test('raycast, shapeCast and overlap read the world', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ stepMany(physics, 120);
+ const ray = physics.raycast([0, 5, 0], [0, -1, 0]);
+ assert.equal(ray.body, 'box');
+ assert.equal(ray.collider, 'crate');
+ assert.ok(Math.abs(ray.distance - 4) < 0.05, `distance ${ray.distance}`);
+ assert.ok(Math.abs(ray.normal[1] - 1) < 1e-4);
+ assert.ok(Math.abs(ray.point[1] - 1) < 0.05);
+ assert.equal(physics.raycast([0, 5, 0], [0, -1, 0], { excludeBody: 'box' }).body, 'floor');
+ assert.equal(physics.raycast([0, 5, 0], [0, 1, 0]), null);
+ assert.equal(physics.raycast([0, 5, 0], [0, -1, 0], { maxDistance: 1 }), null);
+ assert.equal(physics.raycast([4, 5, 0], [0, -1, 0]).body, 'floor', 'a ray ignores sensors by default');
+ assert.equal(physics.raycast([4, 5, 0], [0, -1, 0], { includeSensors: true }).body, 'zone');
+ assert.equal(physics.raycast([0, 5, 0], [0, -1, 0], { mask: 0 }), null);
+
+ const sweep = physics.shapeCast({ type: 'ball', radius: 0.25 }, [0, 5, 0], [0, -1, 0]);
+ assert.equal(sweep.body, 'box');
+ assert.ok(Math.abs(sweep.distance - 3.75) < 0.05, `sweep ${sweep.distance}`);
+
+ assert.deepEqual(physics.overlap({ type: 'ball', radius: 1 }, [0, 0.5, 0]), ['box', 'floor']);
+ assert.deepEqual(physics.overlap({ type: 'cuboid', halfExtents: [0.2, 0.2, 0.2] }, [0, 8, 0]), []);
+ assert.deepEqual(physics.overlap({ type: 'ball', radius: 0.5 }, [-9, 0, 0]), ['floor']);
+ physics.dispose();
+});
+
+test('errors name the field and what to pass', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ assert.throws(() => physics.raycast([0, 0], [0, -1, 0]), /raycast origin must be an array of 3 finite numbers/);
+ assert.throws(() => physics.raycast([0, 0, 0], [0, 0, 0]), /raycast direction must not be the zero vector/);
+ assert.throws(() => physics.raycast([0, 0, 0], [0, -1, 0], { maxDistance: -1 }), /raycast maxDistance must be a number above 0/);
+ assert.throws(() => physics.raycast([0, 0, 0], [0, -1, 0], { excludeBody: 'nope' }), /excludeBody names no body: "nope"/);
+ assert.throws(() => physics.overlap({ type: 'sphere' }, [0, 0, 0]), /overlap shape must be \{ type: "ball"/);
+ assert.throws(() => physics.applyImpulse('floor', [0, 1, 0]), /needs a dynamic body; "floor" is fixed/);
+ assert.throws(() => physics.getPose('ghost'), /getPose names no body: "ghost"\. Present: floor, box/);
+ assert.throws(() => physics.on('bump', () => {}), /kind must be "contact" or "sensor"/);
+ assert.throws(() => physics.fixedUpdate(1 / 30, { mode: 'fixed' }), /fixedStepSeconds: physics\.timestep/);
+ physics.dispose();
+ assert.throws(() => physics.getPose('box'), /disposed/);
+ await assert.rejects(createPhysicsSystem({ ...worldDefinition(), events: [{ tick: 0, type: 'impulse', body: 'box', impulse: [1, 0, 0] }] }), /takes no events/);
+ await assert.rejects(createPhysicsSystem(worldDefinition(), { adapter: {} }), /adapter must be an object/);
+});
+
+test('the system runs inside the runtime and writes interpolated part matrices', async () => {
+ const physics = await createPhysicsSystem(worldDefinition());
+ const part = { matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]) };
+ physics.bind('box', part);
+ const runtime = createRuntime({ render() {} }, {
+ systems: [physics],
+ fixedStepSeconds: physics.timestep,
+ mode: 'both',
+ scheduler: { request: () => 1, cancel() {} },
+ clock: () => 0,
+ visibility: { hidden: false, subscribe: () => () => {} },
+ });
+ runtime.step(1000 / 60 * 0.5);
+ assert.equal(physics.stepCount, 0);
+ for (let frame = 0; frame < 10; frame++) runtime.step(100);
+ assert.ok(physics.stepCount >= 59);
+ assert.ok(part.matrix[13] < 2 && part.matrix[13] > 0.4, `box y ${part.matrix[13]}`);
+ runtime.dispose();
+ assert.throws(() => physics.getPose('box'), /disposed/);
+});
+
- test('a 500-box scene runs live and records the step time', async () => {
++// Step time is printed for information only; no timing is asserted and no second engine is compared (issue #771 stays open).
++test('a 500-box scene runs live', async () => {
+ const bodies = [{ name: 'floor', type: 'fixed', translation: [0, -0.5, 0] }];
+ const colliders = [{ name: 'ground', body: 'floor', shape: 'cuboid', halfExtents: [20, 0.5, 20] }];
+ for (let index = 0; index < 500; index++) {
+ const name = `box${index}`;
+ const column = index % 10;
+ const row = Math.floor(index / 10) % 10;
+ const layer = Math.floor(index / 100);
+ bodies.push({ name, translation: [(column - 4.5) * 1.2, 0.5 + layer * 1.1, (row - 4.5) * 1.2] });
+ colliders.push({ name, body: name, shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 });
+ }
+ const physics = await createPhysicsSystem({ bodies, colliders }, { maxBodies: 512, maxColliders: 512 });
+ stepMany(physics, 10);
+ const steps = 120;
+ const start = performance.now();
+ stepMany(physics, steps);
+ const millisecondsPerStep = (performance.now() - start) / steps;
+ console.log(`physics-runtime 500 boxes (${physics.adapter}): ${millisecondsPerStep.toFixed(2)} ms per step`);
+ assert.equal(physics.bodyNames.length, 501);
+ assert.ok(Math.abs(physics.getPose('box0').translation[1] - 0.5) < 0.1);
+ physics.dispose();
+});
+
+// A scripted engine with no physics: it proves the system reads only the adapter interface.
+test('another adapter plugs in and its events are normalised the same way', async () => {
+ const calls = [];
+ const scripted = {
+ name: 'scripted',
+ createWorld(prepared) {
+ assert.equal(prepared.bodies.length, 4);
+ return {
+ step(stepSeconds, elapsedSeconds) { calls.push(['step', stepSeconds, elapsedSeconds]); },
+ readPose(index, output) { output.set([index, 0, 0, 0, 0, 0, 1]); },
+ drainEvents(callback) { callback(3, 1, true); callback(2, 1, false); callback(0, 1, true); },
+ raycast: () => ({ collider: 1, distance: 2, normal: [0, 1, 0] }),
+ free() { calls.push(['free']); },
+ };
+ },
+ };
+ const physics = await createPhysicsSystem(worldDefinition(), { adapter: scripted });
+ assert.equal(physics.adapter, 'scripted');
+ physics.fixedUpdate(STEP, { mode: 'fixed' });
+ assert.deepEqual(physics.events.map(event => [event.kind, event.started, event.bodyA, event.bodyB]), [
+ ['contact', true, 'floor', 'box'],
+ ['sensor', false, 'box', 'zone'],
+ ['contact', true, 'box', 'platform'],
+ ]);
+ assert.deepEqual(physics.getPose('zone').translation, [2, 0, 0]);
+ assert.equal(physics.raycast([0, 0, 0], [0, 1, 0]).body, 'box');
+ physics.dispose();
+ assert.deepEqual(calls.at(-1), ['free']);
+});
+
++function scriptedAdapter(overrides = {}) {
++ const calls = [];
++ return {
++ calls,
++ adapter: {
++ name: 'scripted',
++ createWorld() {
++ return {
++ step() {},
++ readPose(index, output) { output.set([index, 0, 0, 0, 0, 0, 1]); },
++ drainEvents() {},
++ free() { calls.push('free'); },
++ ...overrides,
++ };
++ },
++ },
++ };
++}
++
++test('a setup that throws frees the engine world', async () => {
++ const { adapter, calls } = scriptedAdapter();
++ await assert.rejects(createPhysicsSystem(worldDefinition(), { adapter, bindings: [{ body: 'nobody', part: { matrix: new Float32Array(16) } }] }), /names no body/);
++ assert.deepEqual(calls, ['free']);
++
++ const unreadable = scriptedAdapter({ readPose() { throw new Error('engine failed'); } });
++ await assert.rejects(createPhysicsSystem(worldDefinition(), { adapter: unreadable.adapter }), /engine failed/);
++ assert.deepEqual(unreadable.calls, ['free']);
++});
++
++test('a step that produces a non-finite or non-unit pose throws and names the body and step', async () => {
++ let poison = null;
++ const { adapter } = scriptedAdapter({
++ readPose(index, output) {
++ output.set(index === 1 && poison ? poison : [index, 0, 0, 0, 0, 0, 1]);
++ },
++ });
++ const physics = await createPhysicsSystem(worldDefinition(), { adapter });
++ physics.fixedUpdate(STEP, { mode: 'fixed' });
++ poison = [Number.NaN, 0, 0, 0, 0, 0, 1];
++ assert.throws(() => physics.fixedUpdate(STEP, { mode: 'fixed' }), /Body "box" has a non-finite pose at step 2/);
++ poison = [0, 0, 0, 0, 0, 0, 3];
++ assert.throws(() => physics.fixedUpdate(STEP, { mode: 'fixed' }), /Body "box" has a non-unit rotation at step 3/);
++ physics.dispose();
++});
++
++test('a huge impulse never writes a bad pose into a bound part', async () => {
++ const physics = await createPhysicsSystem(worldDefinition());
++ const part = { matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]) };
++ physics.bind('box', part);
++ physics.applyImpulse('box', [1e30, 1e30, 1e30]);
++ try {
++ stepMany(physics, 5);
++ } catch (error) {
++ assert.ok(error instanceof RangeError, String(error));
++ assert.match(error.message, /Body "box"/);
++ }
++ assert.ok(part.matrix.every(Number.isFinite), 'the bound matrix stays finite');
++ physics.dispose();
++});
++
+test('the rapier adapter is frozen and named', () => {
+ assert.equal(rapierAdapter.name, 'rapier');
+ assert.ok(Object.isFrozen(rapierAdapter));
+});
diff --cc tests/physics.test.js
index d48afcc6,d48afcc6..7bf77d6a
--- a/tests/physics.test.js
+++ b/tests/physics.test.js
@@@ -1,3 -1,3 +1,4 @@@
++import { createHash } from 'node:crypto';
import test from 'node:test';
import assert from 'node:assert/strict';
import { mat4, vec3 } from 'gl-matrix';
@@@ -673,3 -673,3 +674,30 @@@ test('cylinder and cone colliders, spri
joints: [{ name: 'j', type: 'fixed', bodyA: 'a', bodyB: 'b', stiffness: 10 }],
}), /spring joint/);
});
++
++// The hash was recorded from the bake on main before createRapierWorld and applyForceFieldImpulses were extracted.
++test('a force-field and spring bake matches the output recorded before the live-physics refactor', async () => {
++ const definition = {
++ gravity: [0, 0, 0],
++ fields: [{ type: 'wind', direction: [1, 0, 0], strength: 4 }],
++ bodies: [
++ { name: 'anchor', type: 'fixed', translation: [0, 0, 0] },
++ { name: 'cyl', type: 'dynamic', translation: [0, -2, 0] },
++ { name: 'cone', type: 'dynamic', translation: [2, 0, 0] },
++ ],
++ colliders: [
++ { name: 'anchor', body: 'anchor', shape: 'cylinder', radius: 0.5, halfHeight: 0.5 },
++ { name: 'cyl', body: 'cyl', shape: 'cylinder', radius: 0.4, halfHeight: 0.6, mass: 1 },
++ { name: 'cone', body: 'cone', shape: 'cone', radius: 0.5, halfHeight: 0.8, mass: 1 },
++ ],
++ joints: [{ name: 'spring', type: 'spring', bodyA: 'anchor', bodyB: 'cyl', restLength: 1, stiffness: 20, damping: 2 }],
++ };
++ const frameCount = 61;
++ const scene = await createPhysicsScene(definition, { frameCount });
++ const hash = createHash('sha256');
++ for (let frame = 0; frame < frameCount; frame++) {
++ hash.update(Buffer.from(new Float32Array(scene.sample(frame / 60)).buffer));
++ }
++ scene.dispose();
++ assert.equal(hash.digest('hex'), '0ca9567131bd01531d04580283f2ea10009cc2180e1f08c60b1d3bd523e8fb1c');
++});
diff --cc vite.lib.config.js
index 5bb2d35e,0bb2c083..32dd1406
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@@ -107,7 -107,8 +107,9 @@@ export default defineConfig(
cloth: 'src/cloth.js',
runtime: 'src/runtime.js',
input: 'src/input.js',
+ 'physics-runtime': 'src/physics-runtime.js',
+ 'animation-graph': 'src/animation-graph.js',
+ player: 'src/player.js',
'update-part-vertices':'src/update-part-vertices.js',
'replace-textured-parts': 'src/replace-textured-parts.js',
// Page of the MCP preview. It imports the engine chunks above instead of bundling its own copy.