Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Physics and scene queries: Rapier in a wasm32 crate, a three.js-style surface, bodies move objects without the script (ROADMAP § 6 step 7) (#1)

Yujia7b94dcd8c620
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 393ae15..642578b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -31,9 +31,14 @@ jobs:
workspaces: |
renderer
renderer/voxel-core
+ renderer/physics-core
- run: cd renderer && cargo build --release --locked
# The voxel engine's core builds for the browser (wasm32: players run the game there) and passes its tests.
- run: rustup target add wasm32-unknown-unknown
- run: cd renderer/voxel-core && cargo build --release --locked --target wasm32-unknown-unknown && cargo test --release --locked
# Its edits are deterministic: the same script natively and in wasm32 leaves the same voxels (ROADMAP § 6 step 6).
- run: node tools/voxel-determinism.ts
+ # The physics core (Rapier) builds for the browser too, passes its tests, and steps to the same bits natively and
+ # in wasm32 (ROADMAP § 6 step 7).
+ - run: cd renderer/physics-core && cargo build --release --locked --target wasm32-unknown-unknown && cargo test --release --locked
+ - run: node tools/physics-determinism.ts
diff --git a/README.md b/README.md
index 7c7484e..ccc6f8d 100644
--- a/README.md
+++ b/README.md
@@ -17,7 +17,7 @@ Mirror: [`doodlewind/ThreeRT`](https://github.com/doodlewind/ThreeRT).
| Dir | What |
|---|---|
-| `renderer/` | The engine: Rust + wgpu path tracer, live viewport, denoiser, post, embedded QuickJS (`threert-render`); `renderer/voxel-core` (also builds for wasm32) |
+| `renderer/` | The engine: Rust + wgpu path tracer, live viewport, denoiser, post, embedded QuickJS (`threert-render`); `renderer/voxel-core` and `renderer/physics-core` (Rapier; both also build for wasm32); `renderer/third_party/glamx` (a patched dependency of Rapier's, see its PATCH.md) |
| `packages/scene` | The Three-like scene DSL (`@threert/scene`) |
| `packages/gameplay` | Games: state, transactional handlers, frame scripts (`@threert/gameplay`) |
| `packages/voxel` | The voxel engine's TypeScript side (`@threert/voxel`) |
@@ -76,7 +76,8 @@ npm run test:render # the render test suite on the GPU
`.github/workflows/ci.yml` runs on every push and PR:
- `npm run typecheck`, `npm test`;
- the renderer's release build;
-- the voxel core's wasm32 build and tests, and native / wasm32 edit determinism.
+- the voxel core's wasm32 build and tests, and native / wasm32 edit determinism;
+- the physics core's wasm32 build and tests, and native / wasm32 determinism (a script and 1,000 random worlds).
The GPU checks (`test:render`, the perf smoke, the benches) run on a Mac, per [`docs/WORKFLOW.md`](docs/WORKFLOW.md).
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 5a004f1..7482eb0 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -3589,15 +3589,155 @@ benchmark level. The order follows the dependencies; a step that meets a further
edit; quads no longer merge across chunks) or a BLAS per chunk (changes the trace cost of the whole level). It
needs its own measurements and gate.
7. **[ThreeRT] Physics and scene queries.** Rigid bodies, contacts, joints; ray, overlap and sweep queries for game
- code. Native, a shape interface the engine can extend. Prototype on Rapier.
+ code. Native, a shape interface the engine can extend. On Rapier.
- Acceptance: stacking and joint tests against expected results; zero cost to scenes without bodies; the CPU split
in the frame log.
+ - **Done** (branch `physics`). A contract of ThreeRT for every kind of game; the voxel shape and debris bodies are
+ step 8.
+ - **The world is the engine's.** Rapier 0.36 behind `renderer/physics-core` (its own crate: no GPU, file system,
+ clock or thread; CI builds it for `wasm32-unknown-unknown` and runs its 34 tests): dynamic, fixed and kinematic
+ bodies; box, sphere, capsule, convex hull and static triangle-mesh colliders; fixed, hinge, slider, ball and
+ rope joints with limits and motors; contact events; ray (first hit or all), overlap and sweep queries; a shape
+ trait for the engine's own colliders (`CustomShape`: step 8's voxel shape). It is stepped at a fixed 1 / 60 s,
+ at most 5 ticks a frame, after the frame script; scripts cannot step it and never see Rapier.
+ - **The bridge** (`physics-core/src/bridge.rs`, also wasm32): scene code's calls (JSON; ids chosen by the
+ caller) and the scene objects that bodies drive, against a `Scene` trait the renderer's `World` implements. A
+ body's move goes from the world to the object's transform to its TLAS instance without passing through the
+ script: a mesh a body drives is an instance of its own BLAS (`move_instances`), one added while the game runs
+ is placed in place and moves the same way (no rebuild), and so does a new material without textures.
+ - **The script's surface is three.js's** (`packages/scene`). `mesh.physics = "dynamic"` (or `{ type, shape,
+ density | mass, friction, restitution, damping, ccd, sensor, contacts }`); in the scene the object has its body,
+ out of it none, whether the scene began with it or a script adds it. The collider is the geometry's: a box, a
+ sphere, a capsule, else the convex hull, or the triangles for a fixed body. `position` / `quaternion` /
+ `rotation` read the body's pose when read (one typed array for every body a frame, then each object its own
+ seven numbers, on first access); writing them moves the body (a kinematic one is driven there). `applyImpulse`,
+ `applyForce`, `setLinearVelocity`, ... are methods of the object. `HingeJoint`, `SliderJoint`, `BallJoint`,
+ `RopeJoint`, `FixedJoint` are objects that hold while they and their two objects are in the scene.
+ `Raycaster.intersectPhysics()` and `Shapecaster` (`overlap`, `sweep`) ask the world. Contacts come once a frame
+ as a batch: `contactstart` / `contactend` on the objects, `contacts` on the scene.
+ - **Expected numbers** (physics-core's tests): free fall by Rapier's own law (a tick in 4 substeps: g dt² (n² / 2
+ + n / 8) after n ticks, within 1 mm); five 1 m boxes rest as a column within 2 mm a contact; a box on a 20°
+ slope holds at friction 0.6 and slides at g (sin - mu cos) at 0.1; a weight on a hinge passes the bottom at
+ sqrt(2 g L) within 2 % and stays 1 m from it within 5 mm; a hinge stops at its limit (0.5 rad within 0.03); a
+ slider keeps its axis, reaches its motor's 1.5 m/s and stops at its limit; a rope holds at its length (2 m
+ within 2 cm), ball and fixed joints keep their anchors; joints join bodies as they are turned (a bar turned a
+ quarter is not wrenched into line); contact events; queries; kinematic bodies push. The
+ bridge's: a body drives its object (under a parent too), poses by slot, a force lasts its frame's ticks,
+ impulses at a point, what a call refuses, limits. Layer A: `physics/box-rest` (5 nits where the box rests; also
+ live), `physics/stack` (the strip above a three-box column: 0), `physics/hinge` (5 nits at the limit),
+ `physics/instance-live` (a body's box against a still one: 1.005).
+ - **What a script can do to it** (2026-11-10, after a review of physics-core: game scripts are untrusted and call
+ `__engine.physics` directly, so the checks are in the world, not the binding; a panic in a tick is a crashed
+ renderer natively and a trap in wasm32).
+ - Every number of a body, collider, joint, call and query has a bound (`physics_core::limits`; the table is in
+ RUNTIME.md), and what is outside is refused with its reason. Rotations and axes of any finite size are
+ directions (1e20 squared overflowed into a zero quaternion).
+ - A trimesh is for fixed bodies and static colliders (an open one gave a dynamic body 60 mg with its centre of
+ mass far away); a joint joins two different bodies; a capsule under 1 mm long is its sphere; a hull with no
+ volume is refused.
+ - After a tick, a body whose pose or velocity went non-finite (Rapier disables it, and a joint on it would
+ panic a later tick), one whose collider did, and one past 1,000 km are taken out of the world with their
+ colliders and joints. The call `faults` reports each once with its kind, `state` answers `{ removed: why }`,
+ and the binding leaves the object in the scene without a body. A body that left the world is an ordinary
+ thing in a game (it fell off the level: 42 minutes of free fall, Rapier capping a body at 400 m/s): its
+ object gets an `outofworld` event and nothing is thrown. One
+ that went non-finite is an error: the next sync throws once, naming it.
+ - A frame script or sync that throws no longer costs the world a frame: `GameSession::frame` makes the
+ frame's ticks and commit all the same and returns the error after (before, both were skipped and the
+ frame's time was lost), and the node host syncs the scene as the script left it, so the binding knows the
+ world stepped (the next frame reads fresh poses). A `serve` job with frames still fails with the error, as
+ with any script error.
+ - A call that is refused changes nothing: everything is checked before any of it acts.
+ - Memory: contacts nobody takes are held to 8,192 (the oldest go, counted); a trimesh to 1 M triangles, the
+ world's shapes to 4 M points and triangles; queries take no trimesh.
+ - Also: objects are placed at the body's own pose (not the call's numbers); a frame owing exactly 5 ticks keeps
+ its remainder (12.5 fps made 562 ticks in 10 s); a body asleep when its object is removed goes with it.
+ - The review's fuzz (random calls, ordinary and absurd numbers; a small version is in the crate's tests):
+ 611 panics in 120,000 runs at its two mildest levels before, none in 210,000 runs at all five after.
+ - **Determinism:** the same bits natively and in wasm32, in physics-core's own build and in the renderer's, on
+ what is checked: the script (`113d50eb06a47636`), 1,000 random worlds (tumbling convex hulls, bodies of
+ several colliders, hinges and sliders with limits and motors, a rope; `check::case`, folded hash
+ `9e16a6771fa8f317`), each compared (`tools/physics-determinism.ts`, CI), and 32,000 runs of the review's
+ random calls. It takes three things:
+ - Rapier's `enhanced-determinism` (on in physics-core): without it none of the 1,000 worlds agree (the
+ script: `dfdc13fb0be5cd0b` natively). It costs 1–3 % on the script (0.029 ms a tick) and 3–5 % on a pile of
+ 1,000 boxes (0.35 → 0.36 ms a tick), natively.
+ - **A patched glamx** (`renderer/third_party/glamx`, PATCH.md). Rapier 0.36, parry 0.31 and glamx 0.3 call
+ sin, cos and acos with method syntax, which on an f32 is the type's own method, the platform's libm, in
+ every crate graph with `std` in it (any dependency that turns on `num-traits/std`: the renderer has several),
+ whatever `enhanced-determinism` or their own `std` feature say. The eigen decomposition behind the mass
+ properties of convex hulls and of bodies of several colliders is the one that showed: 48 of the 1,000
+ worlds ended in other bits natively (macOS arm64, whose acos differs from libm's on 8.8 % of inputs, its sin
+ and cos on 0.012 %) than in wasm32. The first version of the check passed because its one hull happens to
+ agree. Rapier is also built without its `std` (it needs `alloc` only), which costs nothing measurable natively (ms
+ a tick, best / median of 30 runs, two rounds alternated: the script 0.0285–0.0287 / 0.0290–0.0292 without
+ `std` against 0.0287–0.0288 / 0.0290–0.0294 with; a pile of 1,000 boxes 0.349–0.355 / 0.353–0.357 against
+ 0.351–0.356 / 0.354–0.358). It is enough for physics-core's own build and not for the renderer's: the check now runs
+ both ways (`std-in-graph`), and the renderer has a test of its own. `[patch.crates-io]` is read from the
+ manifest of the crate being built only, so every crate that depends on physics-core repeats it and has that
+ test (PATCH.md): the web build's wasm crate will be the next.
+ - **Hinge limits centred.** Rapier takes the sine and cosine of a quarter of (min + max) the same way; the
+ world hands it limits about 0, [-h, h] (of 0 they are exact), and turns the centre into the joint's frame
+ with libm.
+ - The other such calls on a 3D world's path are tested to change nothing on the platform the tests run on:
+ the broad phase's BVH optimizer takes a log2 that depends on the collider count alone (every count checked),
+ a convex hull's feature lookup the sine and cosine of one constant.
+ - Platforms measured: macOS arm64 natively (where the hashes were recorded), Linux x86-64 natively (CI:
+ `tools/physics-determinism.ts` there compares Linux's native build, wasm32 and the hashes recorded on macOS,
+ all three equal), and wasm32 under Node's V8 on both. Not measured: Windows, Linux arm64, a browser's own
+ wasm engine (the same wasm32 module; wasm's float arithmetic is specified, so no difference is expected),
+ and iOS / Android natively.
+ - What this does not give: a proof for platforms the tests have not run on, or for another version of Rapier,
+ parry or glamx (the calls were found by reading their sources: an update repeats that, and the recorded
+ hashes show a change). The complete fix is theirs: those calls made through simba. Step 9's replay rests on
+ this for one build of the engine.
+ - **Hello world** (`games/physics/hello.game.ts`, catalog `physics-hello`; `threert-render play` to click in a
+ window, `tools/physics-hello.ts` for the same game with scripted clicks): a click's ray is cast into the world
+ (`Raycaster.intersectPhysics`); on something fixed (a triangle-mesh ground and rock, a wall, a ramp) a box with
+ `physics = "dynamic"` is added off the surface and falls onto what is there; on a box, the box is kicked. The
+ scripted run adds 4 boxes (three end as a column at 0.250, 0.748 and 1.248 m), kicks one at 3 m/s (it slides
+ 0.913 m; v² / 2 mu g = 0.917) and ends with every box asleep. A click's chain: the pick 0.001–0.004 ms, the
+ script (handler, frame script, binding) 0.30–0.54 ms of which the world's calls 0.007–0.053 ms, the commit
+ 0.39–0.57 ms in place, the next frame submitted 3.8–4.1 ms after the click. The first box of a scene without
+ instances rebuilds it once (15–22 ms here: the kernel variant with instances).
+ - **What the boundary costs a frame** (`tools/bench-physics.ts`; every body moving every tick, the most it can
+ cost; M5 Pro, means of 120 frames, one run):
+
+ | bodies | step (Rapier) | sync to objects | commit (records, TLAS) | script, reads none | script, reads all |
+ | --- | --- | --- | --- | --- | --- |
+ | 0 | 0.007 ms | 0.0001 | 0.001 | 0.085 | 0.097 |
+ | 100 | 0.035 | 0.011 | 0.116 | 0.090 | 0.141 |
+ | 1,000 | 0.258 | 0.173 | 0.780 | 0.166 | 0.741 |
+ | 10,000 | 2.126 | 1.696 | 4.518 | 0.217 | 5.445 |
+
+ A script that reads nothing pays nothing for the bodies (the same scene without bodies: 0.079 / 0.090 / 0.339 ms
+ at 100 / 1,000 / 10,000 meshes). Reading a body's position and quaternion costs 0.5 µs, of which 0.28 µs is
+ reading the two properties of any object in QuickJS. Bodies asleep cost nothing natively (a pile of 10,000 at
+ rest: step 0.03 ms, sync 0.0003 ms, commit 0.003 ms).
+ - The frame log has `physics: { ticks, step, sync, bodies, moved }` and `commit`.
+ - **Open:** the first instance of a scene rebuilds it; a sleeping body does not follow a parent of its object that
+ moves; a query sees a collider from the tick after it was added; reading every body's pose every frame at
+ 10,000 bodies is 5 ms of script (the typed array itself is not handed to scripts yet); a body made anew
+ (`physics` set again, the object re-parented or rescaled) starts at rest; where physics is authoritative, the
+ node or the room, is step 9's.
+ - **Open, before game code from outside runs here:** a tick has no time bound. The limits are on counts (20,000
+ bodies), not on what a tick costs: N one-metre dynamic boxes made at one point take 62 ms for their first tick
+ at 250, 0.46 s at 500, 2.8 s at 1,000 and 45 s at 2,000 (M5 Pro, one run). It belongs to the security review
+ before the cloud opens.
8. **[engine] Voxel bodies.** The voxel collision shape and debris as bodies.
- Acceptance: about a hundred debris bodies within the frame budget on the level, with the CPU split recorded.
- Then the decision: keep Rapier or write our own.
9. **[ThreeRT] World data and command replay.** Binary world blocks on the node outside the JSON game state, changed by
deterministic commands the room logs and replays to late joiners.
- Acceptance: a room replayed from its log gives bit-identical world data.
+ - From step 7, for the physics' part of the log:
+ - It rests on step 7's determinism, which holds for one build of the engine on the platforms checked; a new
+ platform or a new Rapier runs `tools/physics-determinism.ts` first.
+ - The log needs the tick each call was made at, and the syncs: a frame makes 0 to 5 ticks from the wall clock's
+ `dt`, and a force lasts "the ticks of its frame", so the calls alone do not replay.
+ - A body that drives an object starts at `Scene::world_pose`, which is the renderer's own glam arithmetic (not
+ under `enhanced-determinism`): the log should carry the pose the body was made at, as it should carry a voxel
+ command's fixed-point shape (step 6).
10. **[engine] The game API and effects.**
- `packages/voxel`: voxel edits, bodies, joints, lights, scene queries and effects.
- Fire and smoke on the existing volume and particle paths.
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 30ad256..4718638 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -47,7 +47,8 @@ runtime, and drives the engine directly, the way a UE game drives its actors:
| Scene runtime | `renderer/src/script.rs` `ScriptHost` | QuickJS (rquickjs) with no I/O (no fs, network or timers). Loads a bundle (one script) or ES modules (`game.js` + `threert-runtime.js`, the cloud layout). Memory capped at 1 GiB. Time budgets: setup 120 s, event 1 s, frame 50 ms; the interrupt handler aborts overruns. A prelude adds `TextEncoder`, `structuredClone`, `atob` and `console`. |
| Node host | `packages/gameplay/src/node-host.ts` | `globalThis.__threert`: `setup(room, seed)`, `event(type, payload, ts)` (local authority: execute + commit), `commit(writes, seq)` / `setState(state, seq)` (room authority), `state()`, `frame(dt, now)`, and the editor's `outline()`, `inspect(name)`, `edit(name, path, value)`. |
| Frame scripts | `packages/gameplay/src/frame.ts` | `FrameContext`: `time`, `dt`, `snap`, `now`, read-only `state`, `scene`, `camera`, `object(id)`, `random()`. |
-| Game session | `renderer/src/script.rs` `GameSession` | A runtime + its live view: events, clicks (CPU pick → `click {target, point}`, with `instanceId` on an `InstancedMesh`), frame script, editor edits, each followed by a commit. Shared by `play`, `live` and the playground. |
+| Game session | `renderer/src/script.rs` `GameSession` | A runtime + its live view: events, clicks (CPU pick → `click {target, point, ray: {origin, direction}}`, with `instanceId` on an `InstancedMesh`; `ray` is the view ray, for a `Raycaster`), frame script, the physics world's ticks, editor edits, each followed by a commit. Shared by `play`, `live` and the playground. |
+| Physics | `renderer/physics-core` (`Physics` on Rapier, `bridge::Bridge`), `renderer/src/physics.rs`, `packages/scene` (`Object3D.physics`, joints, `Raycaster.intersectPhysics`, `Shapecaster`) | The session's physics world, made by the first physics call (none: nothing runs). The engine steps it at 1 / 60 s after the frame script (at most 5 ticks a frame; offline renders step to their scene time) and places the objects of the bodies that moved: instances, so a move is a TLAS transform. Scripts cannot step it. See "Physics" below. |
## Entry points
@@ -70,6 +71,85 @@ The playground runs the opened scene the same way: its host holds the `GameSessi
catalog, the selection, the undo stack (Details edits as `{node, path, before, after}`) and the Play flow. Stop
re-runs setup and replays the editor's edits (UE PIE: Play changes are discarded).
+## Physics
+
+Scene code describes bodies on objects, three.js style; the engine owns the world (ROADMAP § 6 step 7).
+
+```ts
+const crate = new Mesh(new BoxGeometry(0.5, 0.5, 0.5), wood);
+crate.position.set(0, 3, 0);
+crate.physics = "dynamic"; // or { type, shape, density | mass, friction, restitution, ccd, ... }
+scene.add(crate); // in the scene it has its body; scene.remove(crate) ends it
+
+const frame = new Mesh(new BoxGeometry(0.1, 2, 0.1), wood), door = new Mesh(new BoxGeometry(1, 2, 0.05), wood);
+frame.physics = "fixed";
+door.physics = "dynamic";
+door.position.set(0.55, 0, 0);
+scene.add(frame, door, new HingeJoint(frame, door, { anchorA: new Vector3(0.05, 0, 0), anchorB: new Vector3(-0.5, 0, 0), limits: [-1.5, 1.5] }));
+
+raycaster.set(origin, direction); // or setFromCamera
+const hit = raycaster.intersectPhysics()[0]; // { object, point, normal, distance }
+if (hit) hit.object.applyImpulse(new Vector3(0, 40, 0), hit.point);
+crate.position.y; // the body's pose, read when asked
+crate.position.set(0, 5, 0); // a write moves the body there
+```
+
+- Bodies: `"dynamic"`, `"fixed"`, `"kinematic"` (moved by the script through its `position` / `quaternion`; it pushes
+ dynamic bodies). The collider comes from the mesh's geometry (`BoxGeometry` a box, `SphereGeometry` a sphere,
+ `CapsuleGeometry` a capsule, any other its convex hull, or its triangles for a fixed body) and the object's scale;
+ `shape` overrides it. An object that is not a mesh takes a shape with sizes. A hidden object keeps its body.
+- Methods of the object: `applyImpulse(impulse, point?)`, `applyTorqueImpulse`, `applyForce` / `applyTorque` (for the
+ frame's ticks: call them every frame they act), `setLinearVelocity`, `setAngularVelocity`, `getLinearVelocity`,
+ `getAngularVelocity`, `sleeping`. `scene.gravity` is the world's.
+- Joints are objects: `FixedJoint`, `HingeJoint`, `SliderJoint`, `BallJoint`, `RopeJoint` (`anchorA` / `anchorB` in
+ each object's space, `axis` in the first object's, `limits`, `motor`, `length`). They hold while they and both their
+ objects are in the scene, and join the objects as they are turned when made (limits count from there).
+- A `physics` no body can be made from (a flat geometry's hull, a size of 0, a number out of its bounds) throws from
+ the sync once, names the object, and leaves it without a body until `physics` is set again.
+- Game code is untrusted, so the engine checks every number (in `physics-core`, whoever calls it) and refuses a call
+ with one outside its bounds, with the reason:
+
+ | what | bound |
+ | --- | --- |
+ | positions (bodies, static colliders, joint anchors, impulse points, query origins, trimesh vertices) | within ±100 km |
+ | sizes (half extents, radii) | 1 mm to 10 km; a capsule under 1 mm long is its sphere |
+ | a collider's offset on its body, a convex hull's points | within ±10 km; a hull holds at least 1 mm³ |
+ | velocities set by a call | 10 km/s, 1,000 rad/s (Rapier itself caps what a body reaches at 400 m/s) |
+ | impulses, forces | 10⁶ N s (N m s), 10⁸ N (N m) |
+ | a collider's mass, density | 0, or 1 g to 10,000 t; 0, or 1 g/m³ to 100 t/m³ |
+ | gravity scale, gravity | ±100, ±1,000 m/s² a component |
+ | damping, friction, restitution | 0 to 1,000, 0 to 1,000, 0 to 1 |
+ | joint limits, a rope's length | within ±100 km (rad for a hinge), min ≤ max; 0 to 100 km |
+ | a motor | ±10 km/s (rad/s), damping 0 to 10⁹, a force from 0 |
+ | rotations, axes, directions | finite and not zero (any size: they are normalized) |
+ | a query's reach | cut to 1,000 km |
+ | counts | 20,000 bodies, 40,000 colliders and joints; a trimesh 1 M triangles, a hull 4,096 points, all shapes 4 M points and triangles; 256 hits a ray; 8,192 contacts held between frames (the oldest go) |
+
+ A triangle mesh is for fixed bodies only; a joint joins two different bodies; queries take a box, sphere or capsule.
+- What the simulation itself drives out of bounds is taken out of the physics world after a tick, with its colliders
+ and joints. The object stays in the scene where its body last put it, without a body until its `physics` is set
+ again:
+ - A body more than 1,000 km from the origin left the world (it fell off the level; free fall gets there in 42
+ minutes, Rapier capping a body at 400 m/s). Nothing is wrong: its object gets an `outofworld` event (before the frame
+ script, as contacts do), and the game decides: `scene.remove(object)`, or put it back and set `physics` again.
+ - A body whose pose or velocity is no longer finite is an error (the simulation blew up): the next sync throws once,
+ naming the object and why.
+- A frame script (or its sync) that throws does not stop the world: in a window and in `live` the error is printed,
+ the scene is synced as the script left it, and that frame's physics ticks and commit are made all the same (so the
+ next frame reads the bodies' new poses). A `serve` job with frames fails with the error.
+- A call the engine refuses changes nothing (an impulse with a torque whose point is out of bounds applies neither).
+- A tick has no time bound yet: thousands of bodies made at one point take seconds (ROADMAP § 6 step 7, Open).
+- Queries: `Raycaster.intersectPhysics({ exclude })` (every body the ray passes through, nearest first, with the
+ surface's normal) and `Shapecaster` (`overlap()`, `sweep(direction)`) for a box, sphere or capsule. They see the
+ world as of its last tick.
+- Contacts (`physics.contacts`): once a frame, before the frame script, `contactstart` / `contactend` events on the two
+ objects (`event.other`) and one `contacts` event on the scene with the whole batch.
+- Cost: a body moves its object in the engine; no script runs for it. Poses reach the script only when read: the first
+ read of a frame fetches one typed array of every body's pose, each object then takes its seven numbers on its own
+ first read. Numbers: ROADMAP § 6 step 7.
+- The engine call under it is `__engine.physics(op, args)` (JSON; `renderer/physics-core/src/bridge.rs` lists the
+ calls, `faults` and `state`'s `{ removed }` among them) and `__engine.physicsPoses()`.
+
## Correctness
* `threert-render edit-check` builds the GPU tables both ways for a list of events: edited in place, and built fresh
diff --git a/docs/VOXEL.md b/docs/VOXEL.md
index baf619f..05e8775 100644
--- a/docs/VOXEL.md
+++ b/docs/VOXEL.md
@@ -39,9 +39,9 @@ What the research below sorts into each layer:
- Incremental structure: adding or removing objects and replacing geometry without the full rebuild
(`World::set_geometry` sets `structural`, `renderer/src/world.rs:242`; `LiveCore::rebuild` reloads the whole scene,
`renderer/src/live.rs:1548`; ~0.7 s on Kabukichō, ROADMAP § 4).
- - Physics and scene queries: rigid bodies, contacts, joints, ray / overlap / sweep queries, native (Rust). Today
- there is no physics at all, and the only CPU ray cast is the click pick over every triangle
- (`LiveCore::pick`, `renderer/src/live.rs:2142`).
+ - Physics and scene queries: rigid bodies, contacts, joints, ray / overlap / sweep queries, native (Rust). Done
+ (ROADMAP § 6 step 7): `renderer/physics-core` on Rapier, the three.js-style surface in `packages/scene`
+ (`mesh.physics`, joints as objects, `Raycaster.intersectPhysics`, `Shapecaster`).
- Dynamic emission: any geometry can start or stop emitting without a rebuild. Today a material may only become
emissive if it already had emitter triangles (`renderer/src/tables.rs:144`).
- World data outside the replicated JSON game state: binary blocks on the node, changed by deterministic commands
@@ -465,8 +465,17 @@ Where it runs (the user, 2026-11-10):
what reaches no anchor becomes a new object (a body from step 8 on; until then it falls and rests).
- An edited object is meshed and uploaded again whole; by chunk is open.
- **Physics:**
- - Native, on the node, in ThreeRT's physics module. The frame script's 50 ms QuickJS budget cannot hold it.
- - The voxel collision shape is the engine's.
+ - Native, on the node, in ThreeRT's physics module (`renderer/physics-core`, ROADMAP § 6 step 7). The frame script's
+ 50 ms QuickJS budget cannot hold it: the engine owns the world and steps it at 1 / 60 s; a body moves its object's
+ instance without the script; the script sets `physics` on objects, reads their poses when it wants them, and asks
+ rays and shapes of the world.
+ - physics-core and its bridge to scene objects build for wasm32. The same bits natively and in the browser on what
+ is checked (a script, 1,000 random worlds, in physics-core's build and the renderer's), with Rapier's
+ `enhanced-determinism` (1–5 % slower natively), a patched glamx and hinge limits handed over centred: Rapier's
+ crates otherwise take some math functions from the platform (ROADMAP § 6 step 7 has what is and is not shown).
+ - Game scripts cannot crash it: every number a call carries is bounded, and a body whose state goes non-finite is
+ taken out of the world and reported (RUNTIME.md, Physics).
+ - The voxel collision shape is the engine's: physics-core's `CustomShape` is where it plugs in (step 8).
- The prototype is Rapier / Parry's `Voxels` shape (dynamic voxel bodies, `setVoxel` edits, since 2025). Whether to
keep it or write our own (TGS substepping, grid contacts) is decided by its measured cost on the benchmark.
- **Assets:**
diff --git a/games/physics/bench.game.ts b/games/physics/bench.game.ts
new file mode 100644
index 0000000..b8409e3
--- /dev/null
+++ b/games/physics/bench.game.ts
@@ -0,0 +1,63 @@
+// The cost of the boundary between the physics world and gameplay (ROADMAP § 6 step 7; tools/bench-physics.ts): N boxes
+// with dynamic bodies that all move every tick (weightless, turning, never asleep: every body's object is placed and
+// its instance moved every frame, the most the boundary can cost for N bodies), and a frame script that reads either
+// nothing or every box's position and quaternion (the `read` event switches). The room id gives N: "n1000". A room id
+// "pile1000" drops the boxes onto the ground instead: a pile that comes to rest and falls asleep, where the boundary
+// costs nothing. "s1000": the same boxes without bodies (what the scene's objects cost the script by themselves).
+import { BoxGeometry, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera, Scene, SkyAtmosphere, Vector3 } from "@threert/scene";
+import { defineGame } from "@threert/gameplay";
+
+interface State { read: boolean }
+
+const boxes: Mesh[] = [];
+let sum = 0;
+
+export default defineGame<State>({
+ state: { read: false },
+ setup: (ctx) => {
+ const m = /^(n|pile|s)(\d+)$/.exec(ctx.roomId);
+ const [pile, still, n] = [m?.[1] === "pile", m?.[1] === "s", Math.min(Number(m?.[2] ?? 100), 20000)];
+ const scene = new Scene();
+ const sun = new DirectionalLight(0xffffff, 90000);
+ sun.setSunAngles(50, 215);
+ scene.add(sun);
+ scene.environment = new SkyAtmosphere({ sun });
+ const side = Math.max(Math.ceil(Math.sqrt(pile ? n / 4 : n)), 1);
+ const camera = new PerspectiveCamera(50, 16 / 9, 0.1, 500);
+ camera.position.set(0, side * 0.5 + 4, side * 0.75 + 6);
+ camera.lookAt(0, 1, 0);
+ camera.setManualExposure(14);
+ scene.add(camera);
+ const ground = new Mesh(new BoxGeometry(side + 40, 1, side + 40), new MeshStandardMaterial({ name: "ground", color: 0x6f7468, roughness: 0.95 }));
+ ground.position.set(0, -0.5, 0);
+ ground.physics = "fixed";
+ scene.add(ground);
+ const geometry = new BoxGeometry(0.3, 0.3, 0.3), material = new MeshStandardMaterial({ name: "box", color: 0xc8553d, roughness: 0.7 });
+ boxes.length = 0;
+ for (let k = 0; k < n; k++) {
+ const box = new Mesh(geometry, material);
+ const [i, j, layer] = [k % side, Math.floor(k / side) % side, Math.floor(k / (side * side))];
+ box.position.set((i - side / 2) * 0.6, pile ? 0.5 + layer * 0.5 : 1.5, (j - side / 2) * 0.6);
+ if (!still) box.physics = pile ? "dynamic" : { type: "dynamic", gravityScale: 0, canSleep: false };
+ if (!pile && !still) box.setAngularVelocity(new Vector3(0.3 + (k % 7) * 0.1, 1, 0.2));
+ scene.add(box);
+ boxes.push(box);
+ }
+ return { scene, camera, options: { name: "physics-bench", width: 1280, height: 720, preset: "cinematic" as const } };
+ },
+ frame(f) {
+ if (!f.state.read) return;
+ // Every body's pose: one table fetched from the engine, then each object's own numbers.
+ let s = 0;
+ for (let k = 0; k < boxes.length; k++) s += boxes[k].position.y + boxes[k].quaternion.w;
+ sum = s;
+ },
+ handlers: {
+ read(tx) {
+ tx.state.read = !tx.state.read;
+ },
+ sum() {
+ console.log(`sum ${sum}`);
+ },
+ },
+});
diff --git a/games/physics/hello.game.ts b/games/physics/hello.game.ts
new file mode 100644
index 0000000..1c1911c
--- /dev/null
+++ b/games/physics/hello.game.ts
@@ -0,0 +1,123 @@
+// Physics hello world (ROADMAP § 6 step 7): click to add a box; click a box to kick it. A click's view ray is cast into
+// the physics world (`Raycaster.intersectPhysics`). Where it meets something that stands still (the ground, the wall,
+// the ramp, the rock), a box with `physics = "dynamic"` is added to the scene 1.5 m off that surface along its normal:
+// it falls, lands on what is fixed and piles up with the boxes before it (click the same spot of the wall again and
+// they stack). Where it meets a box, the box is kicked along the ground, away from the camera.
+// The chain is the engine's whole path for gameplay physics: click -> the `click` handler records it in the game state
+// -> the frame script (run again right after the commit) casts the ray and calls `scene.add` -> the binding makes the
+// object and its body in the engine -> the engine steps the world and moves the object; nothing runs per object per
+// frame in the script. The scene: a ground plane and a rock that are triangle-mesh colliders, a wall and a ramp that
+// are boxes.
+// node tools/bundle-game.ts games/physics/hello.game.ts -o out/bundles/physics-hello.js
+// renderer/target/release/threert-render play out/bundles/physics-hello.js (a window: click; R reports)
+// node tools/physics-hello.ts (the same game, scripted clicks, numbers)
+import {
+ BoxGeometry, DirectionalLight, IcosahedronGeometry, Mesh, MeshStandardMaterial, type Object3D, PerspectiveCamera, PlaneGeometry, Raycaster, Scene, SkyAtmosphere, Vector3,
+} from "@threert/scene";
+import { defineGame } from "@threert/gameplay";
+
+/** The camera (the scripted test projects its clicks with it). */
+export const CAMERA = { position: [0, 4.5, 9] as const, target: [0, 1, 0] as const, fov: 45, width: 1280, height: 720 };
+/** The wall's front face (z, m) and how far off a clicked surface a box appears. */
+export const WALL_Z = -1.8;
+export const OFF = 1.5;
+/** A box: its edge (m), its density (kg / m³: 50 kg), and the speed a kick gives it (m/s). */
+export const BOX = 0.5;
+export const DENSITY = 400;
+export const KICK = 3;
+
+interface State {
+ /** The clicks so far, and the last one's view ray. */
+ clicks: number;
+ ray: { origin: [number, number, number]; direction: [number, number, number] } | null;
+ /** Asks the frame script for a report (R). */
+ reports: number;
+}
+
+const COLOURS = [0xc8553d, 0x3d7ec8, 0x58a05c, 0xd9a441, 0x8a5cc8, 0x4fb3b3];
+const geometry = new BoxGeometry(BOX, BOX, BOX);
+const materials = COLOURS.map((color, k) => new MeshStandardMaterial({ name: `box${k}`, color, roughness: 0.7 }));
+const raycaster = new Raycaster();
+const boxes: Mesh[] = [];
+let seen = 0, reported = 0, kicks = 0;
+
+/** A mesh that stands still: a fixed body, its collider from its geometry (a box for a box, else its triangles). */
+function fixed(name: string, mesh: Mesh, at: [number, number, number]): Mesh {
+ mesh.name = name;
+ mesh.position.set(...at);
+ mesh.physics = "fixed";
+ return mesh;
+}
+
+export default defineGame<State>({
+ state: { clicks: 0, ray: null, reports: 0 },
+ keys: { R: "report" },
+ setup: () => {
+ // (Setup may run again in one runtime, the playground's Stop: the boxes of the scene before are not this one's.)
+ boxes.length = 0;
+ [seen, reported, kicks] = [0, 0, 0];
+ const scene = new Scene();
+ const sun = new DirectionalLight(0xffffff, 90000);
+ sun.setSunAngles(50, 215);
+ scene.add(sun);
+ scene.environment = new SkyAtmosphere({ sun });
+ const camera = new PerspectiveCamera(CAMERA.fov, CAMERA.width / CAMERA.height, 0.1, 200);
+ camera.position.set(...CAMERA.position);
+ camera.lookAt(...CAMERA.target);
+ camera.setManualExposure(14);
+ scene.add(camera);
+ const stone = new MeshStandardMaterial({ name: "stone", color: 0x8c8c88, roughness: 0.9 });
+ const ground = fixed("ground", new Mesh(new PlaneGeometry(40, 40), new MeshStandardMaterial({ name: "ground", color: 0x6f7468, roughness: 0.95 })), [0, 0, 0]);
+ ground.rotation.x = -Math.PI / 2;
+ const wall = fixed("wall", new Mesh(new BoxGeometry(8, 3, 0.4), stone), [0, 1.5, WALL_Z - 0.2]);
+ const ramp = fixed("ramp", new Mesh(new BoxGeometry(2.4, 0.2, 1.6), stone), [3.4, 0.45, 1.2]);
+ ramp.rotation.z = 0.35;
+ const rock = fixed("rock", new Mesh(new IcosahedronGeometry(0.7, 1), stone), [-3.2, 0.35, 1.4]);
+ scene.add(ground, wall, ramp, rock);
+ return { scene, camera, options: { name: "physics-hello", width: CAMERA.width, height: CAMERA.height, preset: "cinematic" as const } };
+ },
+ frame(f) {
+ if (f.snap) {
+ // (The state was set, not changed: nothing to act on.)
+ seen = f.state.clicks;
+ reported = f.state.reports;
+ }
+ if (f.state.clicks !== seen && f.state.ray) {
+ seen = f.state.clicks;
+ const origin = new Vector3(...f.state.ray.origin), direction = new Vector3(...f.state.ray.direction);
+ raycaster.set(origin, direction);
+ const hit = raycaster.intersectPhysics()[0];
+ if (hit && hit.object.physics?.type === "fixed" && hit.normal) {
+ // Something that stands still: a new box off its surface. In the scene, it has its body.
+ const box = new Mesh(geometry, materials[boxes.length % materials.length]);
+ box.name = `box${boxes.length}`;
+ box.position.copy(hit.point).addScaledVector(hit.normal, OFF);
+ box.physics = { type: "dynamic", density: DENSITY };
+ f.scene.add(box);
+ boxes.push(box);
+ console.log(`hello ${JSON.stringify({ click: seen, add: box.name, on: hit.object.name, at: box.position.toArray() })}`);
+ } else if (hit) {
+ // A box: kicked along the ground, away from the camera.
+ const push = new Vector3(direction.x, 0, direction.z).normalize().multiplyScalar(KICK * DENSITY * BOX ** 3);
+ hit.object.applyImpulse(push);
+ kicks++;
+ console.log(`hello ${JSON.stringify({ click: seen, kick: hit.object.name, from: hit.object.position.toArray(), impulse: push.toArray() })}`);
+ } else console.log(`hello ${JSON.stringify({ click: seen, miss: true })}`);
+ }
+ if (f.state.reports !== reported) {
+ reported = f.state.reports;
+ const row = (o: Object3D) => ({ name: o.name, at: o.position.toArray().map((v) => Math.round(v * 1e4) / 1e4), speed: Math.round(o.getLinearVelocity().length() * 1e3) / 1e3, asleep: o.sleeping });
+ console.log(`report ${JSON.stringify({ boxes: boxes.map(row), kicks })}`);
+ }
+ },
+ handlers: {
+ click(tx, ev: { ray?: State["ray"] }) {
+ tx.decide(!!ev.ray, "a click without its view ray");
+ tx.state.ray = ev.ray!;
+ tx.state.clicks++;
+ },
+ report(tx) {
+ tx.state.reports++;
+ },
+ },
+});
diff --git a/packages/gameplay/src/node-host.ts b/packages/gameplay/src/node-host.ts
index ca65ccc..131c2c6 100644
--- a/packages/gameplay/src/node-host.ts
+++ b/packages/gameplay/src/node-host.ts
@@ -50,6 +50,7 @@ export function installNodeHost(game: GameDefinition<unknown>, engine?: Engine):
/** The scene follows the state (dt 0; `snap`: settled, no transitions), then the engine follows the scene. */
const refresh = (now: number, snap = false) => {
const { frames, binding } = live();
+ binding.deliverPhysicsEvents();
frames.run(0, now, snap);
binding.sync();
};
@@ -118,8 +119,25 @@ export function installNodeHost(game: GameDefinition<unknown>, engine?: Engine):
frame(dt, now) {
const { frames, binding } = live();
- frames.run(dt, now);
- binding.sync();
+ // The contacts of the ticks since the last frame, to their listeners, before the frame script.
+ binding.deliverPhysicsEvents();
+ // A frame script that throws does not stop the engine (it steps the physics and draws the frame all the same),
+ // so the engine still follows the scene as the script left it: the binding learns that the world stepped (objects
+ // read their bodies' poses afresh next frame) and what listeners did reaches the engine. The script's error is
+ // the one thrown; the sync's own, if it has one too, is logged.
+ let failed: { error: unknown } | null = null;
+ try {
+ frames.run(dt, now);
+ } catch (error) {
+ failed = { error };
+ }
+ try {
+ binding.sync();
+ } catch (error) {
+ if (!failed) throw error;
+ console.error(error);
+ }
+ if (failed) throw failed.error;
},
seek(time, now) {
diff --git a/packages/gameplay/test/frame.test.ts b/packages/gameplay/test/frame.test.ts
index 9d7c025..c8fdebc 100644
--- a/packages/gameplay/test/frame.test.ts
+++ b/packages/gameplay/test/frame.test.ts
@@ -120,3 +120,30 @@ test("game keys default to the conventional handlers and must name a handler", (
assert.deepEqual(gameKeys(g), { L: "lights", R: "rain" });
assert.throws(() => defineGame({ ...coinGame, keys: { X: "nope" } }), /unknown handler "nope"/);
});
+
+test("a frame script that throws: the engine still follows the scene, and the script's error is the one thrown", () => {
+ // (Counted from the first frame after setup, which runs the frame script too.)
+ let counting = false, frame = 0;
+ const game = defineGame({
+ ...coinGame,
+ frame(f) {
+ if (counting) frame++;
+ (f.object("coin_a") as Mesh).power = 10 + frame;
+ if (frame > 0 && frame % 2 === 0) throw new Error(`frame ${frame} threw`);
+ },
+ });
+ const engine = new RecordingEngine();
+ const host = installNodeHost(game, engine);
+ host.setup("node");
+ engine.take();
+ counting = true;
+ host.frame(1 / 60, 0);
+ assert.deepEqual(engine.take().map((c) => [c[0], c[2]]), [["power", 11]]);
+ // The frame that throws: what the script did before it threw reaches the engine in that frame (the engine steps the
+ // physics and draws the frame all the same; the binding's sync is also what tells objects to read their bodies'
+ // poses afresh), and the error is the script's.
+ assert.throws(() => host.frame(1 / 60, 0), /frame 2 threw/);
+ assert.deepEqual(engine.take().map((c) => [c[0], c[2]]), [["power", 12]]);
+ host.frame(1 / 60, 0);
+ assert.deepEqual(engine.take().map((c) => [c[0], c[2]]), [["power", 13]]);
+});
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts
index fbd78ba..ee03a65 100644
--- a/packages/scene/src/core.ts
+++ b/packages/scene/src/core.ts
@@ -50,6 +50,188 @@ export function compatNotes(): string[] {
return [...compat];
}
+// ---------------------------------------------------------------------------------------------
+// Physics (ROADMAP § 6 step 7)
+//
+// An object with `physics` has a rigid body in the engine's physics world from the moment it is in the scene
+// (`scene.add`) until it leaves it (`scene.remove`), whether the scene began with it or a script adds it later:
+//
+// const crate = new Mesh(new BoxGeometry(0.5, 0.5, 0.5), wood);
+// crate.physics = "dynamic"; // or { type, shape, density, friction, ... }; "fixed" for what stands still
+// scene.add(crate); // it falls, collides, can be hit by a ray and pushed
+// crate.applyImpulse(new Vector3(0, 40, 0));
+//
+// The world is the engine's: it steps it 60 times a second, and scene code can neither step it nor reach into it.
+// A body moves its object in the engine, straight to what is drawn; nothing runs in the script for it. `position`,
+// `quaternion` and `rotation` of such an object read the body's pose when they are read (one call fetches every
+// body's pose for the frame, then each object takes its own on its first read); writing them moves the body there (a
+// kinematic body is driven there through the next tick and pushes what is in the way). Joints are objects too
+// (`HingeJoint`, ...: in the scene, they hold). `Raycaster.intersectPhysics` and `Shapecaster` ask the world.
+
+/** A collider's shape: from the mesh's geometry by name, or given (sizes in the object's own units). */
+export type PhysicsShape =
+ | "box" | "sphere" | "capsule" | "hull" | "mesh"
+ | { type: "box"; halfExtents: readonly [number, number, number] }
+ | { type: "sphere"; radius: number }
+ | { type: "capsule"; halfHeight: number; radius: number };
+
+export interface PhysicsDesc {
+ /** "dynamic" (default): moved by forces and contacts. "fixed": stands still. "kinematic": moved by the script. */
+ type?: "dynamic" | "fixed" | "kinematic";
+ /**
+ * Default: from the mesh's geometry. A `BoxGeometry` is a box, a `SphereGeometry` a sphere, a `CapsuleGeometry` a
+ * capsule (the last two under a uniform scale); any other geometry is its convex hull, or for a fixed body its
+ * triangles ("mesh"). "box" / "sphere" / "capsule" by name are the geometry's bounding box and what fits it. An
+ * object that is not a mesh needs a shape with sizes.
+ */
+ shape?: PhysicsShape;
+ /** kg / m³ (default 1000, water), or the body's mass in kg. */
+ density?: number;
+ mass?: number;
+ /** Default 0.5. */
+ friction?: number;
+ /** Default 0: no bounce. */
+ restitution?: number;
+ linearDamping?: number;
+ angularDamping?: number;
+ /** Default 1. */
+ gravityScale?: number;
+ /** Continuous collision detection, for small fast bodies. */
+ ccd?: boolean;
+ /** Default true: a body at rest sleeps (costs nothing) until something wakes it. */
+ canSleep?: boolean;
+ /** Touches without pushing: it reports contacts only. */
+ sensor?: boolean;
+ /** Report its contacts: "contactstart" / "contactend" events on the object, "contacts" on the scene. */
+ contacts?: boolean;
+}
+
+/** An event of an object (`addEventListener`). */
+export interface ObjectEvent {
+ type: string;
+ target?: Object3D;
+ [key: string]: unknown;
+}
+
+/** What a body's contact reports: on each of the two objects ("contactstart" / "contactend") with the other one. */
+export interface ContactEvent extends ObjectEvent {
+ other: Object3D;
+}
+
+/** @internal An object's body in the engine, kept on the object by the binding. */
+export interface BoundBody {
+ id: number;
+ /** Its place in the engine's table of poses (-1: none, a fixed body). */
+ slot: number;
+ /** The physics epoch its pose was last read in. */
+ epoch: number;
+ /** The binding's record of the transform the engine has (position, quaternion, scale). */
+ trs: Float64Array;
+ /** `rotation` is behind `quaternion` (set when a pose is read; `rotation` catches up when it is read). */
+ euler: boolean;
+}
+
+/** @internal A call on an object's body, sent at the binding's next sync (the body may not exist before it). */
+export interface PhysicsCommand {
+ op: "impulse" | "force" | "velocity";
+ object: Object3D;
+ args: Record<string, unknown>;
+}
+
+interface PhysicsEngine {
+ physics(op: string, args: object): string;
+ physicsPoses?(): Float32Array;
+}
+
+const physicsQueue: PhysicsCommand[] = [];
+/** @internal Body id -> its object (queries and contacts report bodies). */
+export const physicsBodies = new Map<number, Object3D>();
+let physicsEngine: PhysicsEngine | null = null;
+// The engine steps the world after each sync: poses read before it are stale after it.
+let physicsEpoch = 0;
+let poses: Float32Array | null = null;
+let posesEpoch = -1;
+
+/** @internal The engine whose world queries ask and poses come from (the binding's). */
+export function usePhysicsEngine(e: PhysicsEngine): void {
+ physicsEngine = e;
+}
+
+/** @internal The engine may have stepped the world: poses are read again. */
+export function physicsStepped(): void {
+ physicsEpoch++;
+}
+
+/** @internal The queued calls, taken (the binding's sync sends them). */
+export function takePhysicsCommands(): PhysicsCommand[] {
+ return physicsQueue.length ? physicsQueue.splice(0) : physicsQueue;
+}
+
+function physicsCommand(c: PhysicsCommand): void {
+ // (Calls on objects that never reach a scene are not kept without bound.)
+ if (physicsQueue.length >= 65536) physicsQueue.shift();
+ physicsQueue.push(c);
+}
+
+/** @internal A query answered now, against the world as of its last tick; null where there is no engine. */
+export function physicsQuery(op: "state" | "ray" | "overlap" | "sweep" | "contacts" | "hash", args: Record<string, unknown> = {}): unknown {
+ return physicsEngine ? JSON.parse(physicsEngine.physics(op, args)) : null;
+}
+
+/** The body's pose into the object's position and quaternion (and the binding's record: reading is not a write). */
+function pullPose(b: BoundBody, p: TrackedVector3, q: Quaternion): void {
+ b.epoch = physicsEpoch;
+ if (posesEpoch !== physicsEpoch) {
+ posesEpoch = physicsEpoch;
+ poses = physicsEngine?.physicsPoses?.() ?? null;
+ }
+ const at = b.slot * 7;
+ if (!poses || b.slot < 0 || at + 7 > poses.length) return;
+ const t = b.trs;
+ p._x = t[0] = poses[at];
+ p._y = t[1] = poses[at + 1];
+ p._z = t[2] = poses[at + 2];
+ q._x = t[3] = poses[at + 3];
+ q._y = t[4] = poses[at + 4];
+ q._z = t[5] = poses[at + 5];
+ q._w = t[6] = poses[at + 6];
+ b.euler = true;
+}
+
+/**
+ * @internal The object has body `b` in the engine. One that physics moves (a slot) reads its pose from it: `position`,
+ * `quaternion` and `rotation` become accessors of this object alone (objects without a body keep plain properties and
+ * pay nothing).
+ */
+export function bindBody(o: Object3D, b: BoundBody): void {
+ Object.defineProperty(o, "_body", { value: b, configurable: true, writable: true });
+ physicsBodies.set(b.id, o);
+ if (b.slot < 0) return;
+ const p = o.position as TrackedVector3, q = o.quaternion, r = o.rotation;
+ Object.defineProperty(o, "position", { configurable: true, enumerable: true, get: () => (b.epoch !== physicsEpoch && pullPose(b, p, q), p) });
+ Object.defineProperty(o, "quaternion", { configurable: true, enumerable: true, get: () => (b.epoch !== physicsEpoch && pullPose(b, p, q), q) });
+ Object.defineProperty(o, "rotation", {
+ configurable: true, enumerable: true,
+ get: () => {
+ if (b.epoch !== physicsEpoch) pullPose(b, p, q);
+ if (b.euler) {
+ b.euler = false;
+ r.setFromQuaternion(q, false);
+ }
+ return r;
+ },
+ });
+}
+
+/** @internal The object's body is gone: it keeps the pose it had, in plain properties again. */
+export function unbindBody(o: Object3D): void {
+ const b = o._body;
+ if (!b) return;
+ if (physicsBodies.get(b.id) === o) physicsBodies.delete(b.id);
+ if (b.slot >= 0) for (const k of ["position", "quaternion", "rotation"] as const) Object.defineProperty(o, k, { value: o[k], configurable: true, enumerable: true, writable: true });
+ o._body = undefined;
+}
+
function restructured(): void {
for (const t of trackers) t.structure = true;
}
@@ -109,7 +291,7 @@ export interface SwayDesc {
let objectIds = 0;
/** What `Object3D.copy` does not take over as it is (transforms are copied by value, children cloned). */
-const COPY_SKIP = new Set(["parent", "children", "position", "quaternion", "rotation", "scale", "up", "matrix", "matrixWorld", "userData", "tags", "_id", "_autoId", "uuid"]);
+const COPY_SKIP = new Set(["parent", "children", "position", "quaternion", "rotation", "scale", "up", "matrix", "matrixWorld", "userData", "tags", "_id", "_autoId", "uuid", "_body", "_listeners"]);
export class Object3D {
readonly isObject3D = true;
@@ -149,6 +331,93 @@ export class Object3D {
get id(): string | number {
return this._id ?? this._autoId;
}
+ declare private _physics: Readonly<PhysicsDesc> | null | undefined;
+ /** @internal */
+ declare _body: BoundBody | undefined;
+ declare private _listeners: Map<string, ((e: ObjectEvent) => void)[]> | undefined;
+
+ /**
+ * The object's rigid body (see "Physics" above): a description, or just its type. In the scene, the object has the
+ * body; out of it, or with `physics` null, it has none. To change a body, set `physics` again (the body is made
+ * anew).
+ */
+ get physics(): Readonly<PhysicsDesc> | null {
+ return this._physics ?? null;
+ }
+ set physics(v: PhysicsDesc | "dynamic" | "fixed" | "kinematic" | null) {
+ this._physics = v == null ? null : Object.freeze(typeof v === "string" ? { type: v } : { ...v });
+ touched(this);
+ }
+
+ /** An impulse (N s, world space) at the body's centre of mass, or at a point of the world (it then turns it too). */
+ applyImpulse(impulse: Vector3, point?: Vector3): this {
+ physicsCommand({ op: "impulse", object: this, args: { impulse: impulse.toArray(), ...(point ? { point: point.toArray() } : {}) } });
+ return this;
+ }
+ /** An angular impulse (N m s, world space). */
+ applyTorqueImpulse(torque: Vector3): this {
+ physicsCommand({ op: "impulse", object: this, args: { torque: torque.toArray() } });
+ return this;
+ }
+ /** A force (N, world space) on the body through the ticks of the frame that follows: call it every frame it acts. */
+ applyForce(force: Vector3): this {
+ physicsCommand({ op: "force", object: this, args: { force: force.toArray() } });
+ return this;
+ }
+ /** A torque (N m, world space) through the ticks of the frame that follows. */
+ applyTorque(torque: Vector3): this {
+ physicsCommand({ op: "force", object: this, args: { torque: torque.toArray() } });
+ return this;
+ }
+ /** The body's velocity (m/s, world space) set. */
+ setLinearVelocity(v: Vector3): this {
+ physicsCommand({ op: "velocity", object: this, args: { linvel: v.toArray() } });
+ return this;
+ }
+ /** The body's angular velocity (rad/s, world space) set. */
+ setAngularVelocity(v: Vector3): this {
+ physicsCommand({ op: "velocity", object: this, args: { angvel: v.toArray() } });
+ return this;
+ }
+ /** The body's velocity as of the last tick (zero without a body, or for one the engine has just taken out). */
+ getLinearVelocity(target = new Vector3()): Vector3 {
+ const s = this._body ? (physicsQuery("state", { body: this._body.id }) as { linvel?: number[] } | null) : null;
+ return s?.linvel ? target.fromArray(s.linvel) : target.set(0, 0, 0);
+ }
+ getAngularVelocity(target = new Vector3()): Vector3 {
+ const s = this._body ? (physicsQuery("state", { body: this._body.id }) as { angvel?: number[] } | null) : null;
+ return s?.angvel ? target.fromArray(s.angvel) : target.set(0, 0, 0);
+ }
+ /** The body is at rest and asleep (false without a body). */
+ get sleeping(): boolean {
+ const s = this._body ? (physicsQuery("state", { body: this._body.id }) as { sleeping: boolean } | null) : null;
+ return s?.sleeping ?? false;
+ }
+
+ /**
+ * three.js's EventDispatcher. The engine's events: "contactstart" / "contactend" (`physics.contacts`), and
+ * "outofworld" when the object's body got more than 1,000 km from the origin and was taken out of the physics world
+ * (the object stays in the scene, without a body until its `physics` is set again).
+ */
+ addEventListener(type: string, listener: (e: ObjectEvent) => void): void {
+ const all = (this._listeners ??= new Map());
+ const l = all.get(type);
+ if (!l) all.set(type, [listener]);
+ else if (!l.includes(listener)) l.push(listener);
+ }
+ hasEventListener(type: string, listener: (e: ObjectEvent) => void): boolean {
+ return this._listeners?.get(type)?.includes(listener) ?? false;
+ }
+ removeEventListener(type: string, listener: (e: ObjectEvent) => void): void {
+ const l = this._listeners?.get(type);
+ if (l?.includes(listener)) l.splice(l.indexOf(listener), 1);
+ }
+ dispatchEvent(event: ObjectEvent): void {
+ const l = this._listeners?.get(event.type);
+ if (!l?.length) return;
+ event.target = this;
+ for (const f of [...l]) f(event);
+ }
set id(v: string | number | undefined) {
this._id = v === undefined ? undefined : String(v);
}
@@ -481,9 +750,122 @@ export class Group extends Object3D {
override type = "Group";
}
+/** A joint's motor: it drives the joint toward `velocity` (rad/s, or m/s for a slider) with at most `maxForce`. */
+export interface JointMotor {
+ velocity: number;
+ /** How hard it holds the velocity (default 1e4). */
+ damping?: number;
+ /** N m (or N); default: no limit. */
+ maxForce?: number;
+}
+
+export interface JointParameters {
+ /** Where the joint holds each object, in the object's own space (default: its origin). */
+ anchorA?: Vector3;
+ anchorB?: Vector3;
+ /** The hinge's or slider's axis, in `bodyA`'s space. */
+ axis?: Vector3;
+ /** The hinge's angles (radians) or the slider's travel (m), from how the two objects are when joined: [min, max]. */
+ limits?: readonly [number, number] | null;
+ motor?: JointMotor | null;
+ /** A rope's length, m. */
+ length?: number;
+}
+
+/**
+ * A joint between two objects with bodies: an object itself, so it holds while it is in the scene (`scene.add(joint)`)
+ * and both its objects are, and lets go when it is removed. It joins the objects as they are turned when it is made (a
+ * door that stands open stays open; its anchors are pulled together if they are apart). After changing one that is in
+ * the scene, set `needsUpdate`.
+ */
+export class Joint extends Object3D {
+ readonly isJoint = true;
+ override type = "Joint";
+ bodyA: Object3D | null;
+ bodyB: Object3D | null;
+ readonly anchorA = new Vector3();
+ readonly anchorB = new Vector3();
+ constructor(bodyA?: Object3D, bodyB?: Object3D, params: JointParameters = {}) {
+ super();
+ this.bodyA = bodyA ?? null;
+ this.bodyB = bodyB ?? null;
+ if (params.anchorA) this.anchorA.copy(params.anchorA);
+ if (params.anchorB) this.anchorB.copy(params.anchorB);
+ }
+ set needsUpdate(v: boolean) {
+ if (v) touched(this);
+ }
+ /** @internal The engine's description of it, less its bodies and anchors. */
+ jointDesc(): Record<string, unknown> {
+ return { type: "fixed" };
+ }
+}
+
+/** Holds the two objects rigidly together at the anchors. */
+export class FixedJoint extends Joint {
+ override type = "FixedJoint";
+}
+
+/** A hinge: the objects turn about `axis` through the anchors (a door, a wheel). */
+export class HingeJoint extends Joint {
+ override type = "HingeJoint";
+ readonly axis = new Vector3(0, 1, 0);
+ limits: readonly [number, number] | null;
+ motor: JointMotor | null;
+ constructor(bodyA?: Object3D, bodyB?: Object3D, params: JointParameters = {}) {
+ super(bodyA, bodyB, params);
+ if (params.axis) this.axis.copy(params.axis);
+ this.limits = params.limits ?? null;
+ this.motor = params.motor ?? null;
+ }
+ override jointDesc(): Record<string, unknown> {
+ return { type: "revolute", axis: this.axis.toArray(), ...(this.limits ? { limits: [...this.limits] } : {}), ...(this.motor ? { motor: { ...this.motor } } : {}) };
+ }
+}
+
+/** A slider: `bodyB` moves along `axis` (a drawer, a lift). */
+export class SliderJoint extends Joint {
+ override type = "SliderJoint";
+ readonly axis = new Vector3(1, 0, 0);
+ limits: readonly [number, number] | null;
+ motor: JointMotor | null;
+ constructor(bodyA?: Object3D, bodyB?: Object3D, params: JointParameters = {}) {
+ super(bodyA, bodyB, params);
+ if (params.axis) this.axis.copy(params.axis);
+ this.limits = params.limits ?? null;
+ this.motor = params.motor ?? null;
+ }
+ override jointDesc(): Record<string, unknown> {
+ return { type: "prismatic", axis: this.axis.toArray(), ...(this.limits ? { limits: [...this.limits] } : {}), ...(this.motor ? { motor: { ...this.motor } } : {}) };
+ }
+}
+
+/** A ball joint: the anchors stay together, the objects turn freely about them. */
+export class BallJoint extends Joint {
+ override type = "BallJoint";
+ override jointDesc(): Record<string, unknown> {
+ return { type: "spherical" };
+ }
+}
+
+/** A rope: the anchors are never further apart than `length`. */
+export class RopeJoint extends Joint {
+ override type = "RopeJoint";
+ length: number;
+ constructor(bodyA?: Object3D, bodyB?: Object3D, params: JointParameters = {}) {
+ super(bodyA, bodyB, params);
+ this.length = params.length ?? 1;
+ }
+ override jointDesc(): Record<string, unknown> {
+ return { type: "rope", length: this.length };
+ }
+}
+
export class Scene extends Object3D {
readonly isScene = true;
override type = "Scene";
+ /** The physics world's gravity, m/s². */
+ readonly gravity = new Vector3(0, -9.81, 0);
/** Sky / image based lighting. Defaults to a physical atmosphere when a sun is present. */
environment: Environment | null = null;
/** three.js: what camera rays that miss show (a colour, sRGB as given; null: the environment). It lights nothing. */
diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.ts
index 75efac0..5c5d676 100644
--- a/packages/scene/src/engine.ts
+++ b/packages/scene/src/engine.ts
@@ -10,10 +10,11 @@
import {
AmbientLight, compatNote, DirectionalLight, Fog, FogExp2, GLTFModel, HDRIEnvironment, HemisphereLight, InstancedMesh, Light, MeshBasicMaterial, MaterialFunction, Mesh, MeshPhysicalMaterial, type MeshStandardMaterial, Object3D,
type ParticleBinding, type ParticleFunction, Particles, GpuParticles, type ParticleProgram, type ParticleProgramBinding, type VolumeBinding, type VolumeFunction, VolumeMesh, type DensityGrid, type GridProgram, type GridProgramBinding, ProceduralMesh, ProceduralGeometry,
- DataTexture, PerspectiveCamera, PointLight, RectAreaLight, Scene, SkyAtmosphere, SkyColor, SkyGradient, SpotLight, Texture, trackChanges, vec3,
- type SceneChanges, type ShaderBinding, type SwayDesc,
+ DataTexture, PerspectiveCamera, PointLight, RectAreaLight, Scene, SkyAtmosphere, SkyColor, SkyGradient, SpotLight, Texture, trackChanges, vec3, takePhysicsCommands,
+ bindBody, unbindBody, usePhysicsEngine, physicsStepped, physicsBodies, Joint,
+ type SceneChanges, type ShaderBinding, type SwayDesc, type PhysicsDesc, type BoundBody,
} from "./core.ts";
-import { BufferGeometry } from "./geometry.ts";
+import { BoxGeometry, BufferGeometry, CapsuleGeometry, SphereGeometry } from "./geometry.ts";
import { Matrix4, Quaternion, Vector3 } from "./math.ts";
export type Vec2 = [number, number];
@@ -145,8 +146,13 @@ export interface TextureDesc {
offset: Vec2;
}
-/** `movable`: UE Mobility "Movable" (present when true). */
-export type ObjectDesc =
+/**
+ * `movable`: UE Mobility "Movable" (present when true). `body` (present when true, any kind): a rigid body will drive
+ * the object (`Engine.physics`).
+ */
+export type ObjectDesc = { body?: boolean } & ObjectKindDesc;
+
+type ObjectKindDesc =
| { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "group" }
/** `materials`: one per geometry group (three.js's material array; `material` is the first). */
| { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "mesh"; geometry: number; material: number; materials?: number[]; dynamicGeometry?: boolean }
@@ -195,6 +201,14 @@ export interface Engine {
particlesSpawn(id: number, data: Float32Array): void;
/** A volume function's WGSL (`fn vf_<name>`; pathtrace.wgsl `volume_function`). */
volumeFunction(name: string, code: string, helpers: string): void;
+ /**
+ * A call on the physics world (renderer/physics-core/src/bridge.rs: body, collider, joint, remove, impulse, force,
+ * velocity, follow, gravity; queries state, ray, overlap, sweep, contacts, hash): its answer as JSON ("null" for
+ * commands). Ids of bodies, colliders and joints are the caller's. The engine steps the world; no call does.
+ */
+ physics(op: string, args: object): string;
+ /** The poses of the objects bodies drive, by the body's `slot`: 7 numbers each (position, quaternion xyzw). */
+ physicsPoses?(): Float32Array;
/** A grid program's WGSL (`fn gp_<name>`; renderer/shaders/grid_sim.wgsl). */
gridProgram(name: string, code: string, helpers: string): void;
/** A density grid: its cells, the numbers a cell in `data` (1 or 4; null: zeros, or unchanged), its program. */
@@ -264,6 +278,10 @@ interface Bound {
inst: { count: number; m: [unknown, number]; c: [unknown, number]; d: [unknown, number] } | null;
/** Sync that last reached it in a walk of the graph. */
epoch: number;
+ /** Its rigid body in the engine, and what it was made from (a change makes it anew). */
+ body: (BoundBody & { desc: Readonly<PhysicsDesc>; scale: Vec3; geometry: BufferGeometry | null; version: number; contacts: boolean }) | null;
+ /** The `physics` no body could be made from (not tried again until it is set again). */
+ bodyFailed: Readonly<PhysicsDesc> | null;
}
interface BoundMaterial {
@@ -331,6 +349,21 @@ export class SceneBinding {
private readonly changes: SceneChanges = { objects: new Set(), structure: true };
private readonly untrack: () => void;
private epoch = 0;
+ // Physics: ids of bodies (a body's collider has its id) and joints, the slots of the engine's pose table, the joints
+ // in the scene with what the engine has of each, how many bodies report contacts, the gravity last sent.
+ private nextBody = 1;
+ private nextSlot = 0;
+ private readonly freeSlots: number[] = [];
+ private bodies = 0;
+ private contactBodies = 0;
+ private readonly joints = new Map<Joint, { id: number; key: string } | null>();
+ /** A joint or a body came, went or changed: the joints are looked at again. */
+ private jointsDirty = false;
+ /** The first body of this sync that could not be made: thrown when the sync is done (the scene stays bound). */
+ private bodyError: unknown = null;
+ /** Objects with bodies under a parent scaled anew in this sync: checked once every transform is sent. */
+ private rescaled = new Set<Object3D>();
+ private gravity = "0,-9.81,0";
constructor(engine: Engine, scene: Scene, camera: PerspectiveCamera, options: RenderOptions = {}) {
this.engine = engine;
@@ -381,6 +414,8 @@ export class SceneBinding {
if (this.objects.get(this.camera)?.epoch !== epoch) visit(this.camera, null);
for (const [o, b] of this.objects) {
if (b.epoch === epoch) continue;
+ this.dropBody(o, b);
+ if (o instanceof Joint) this.dropJoint(o);
this.engine.remove(b.id);
this.objects.delete(o);
this.byName.delete(b.name);
@@ -436,6 +471,14 @@ export class SceneBinding {
this.engine.environment(env);
stats.updated++;
}
+ // (After every transform: a body made anew is placed where the renderer has its object, and an ancestor of it
+ // may have moved in this sync too.)
+ for (const r of this.rescaled) {
+ const b = this.objects.get(r);
+ if (b && (r.physics || b.body)) this.syncBody(r, b, stats);
+ }
+ this.rescaled.clear();
+ this.syncPhysics(stats);
const o = this.options;
const settings: SettingsDesc = {
name: o.name ?? (this.scene.name || "scene"), preset: o.preset ?? "cinematic", width: o.width ?? 1280, height: o.height ?? 720,
@@ -447,6 +490,11 @@ export class SceneBinding {
this.engine.settings(settings);
stats.updated++;
}
+ if (this.bodyError !== null) {
+ const e = this.bodyError;
+ this.bodyError = null;
+ throw e;
+ }
return stats;
}
@@ -477,7 +525,7 @@ export class SceneBinding {
const created = !b;
if (!b) {
const name = this.uniqueName(o);
- b = { id: this.nextId++, name, parent, kind, trs: new Float64Array(10).fill(NaN), visible: true, power: 1, custom: "0,0,0,0", sway: "", light: null, camera: "", anim: null, inst: null, epoch: 0 };
+ b = { id: this.nextId++, name, parent, kind, trs: new Float64Array(10).fill(NaN), visible: true, power: 1, custom: "0,0,0,0", sway: "", light: null, camera: "", anim: null, inst: null, epoch: 0, body: null, bodyFailed: null };
this.objects.set(o, b);
this.byName.set(name, o);
if (o instanceof Light) this.lights.set(o, b);
@@ -485,6 +533,8 @@ export class SceneBinding {
}
b.parent = parent;
b.kind = kind;
+ // (Made anew in the engine: its body, if it has one, goes with the old one and is made again below.)
+ this.dropBody(o, b);
this.engine.object(b.id, this.objectDesc(o, b));
b.light = o instanceof Light ? lightValues(o, this.scratch).slice(0, LIGHT_VALUES) : null;
b.camera = o instanceof PerspectiveCamera ? JSON.stringify(this.cameraDesc(o)) : "";
@@ -498,7 +548,10 @@ export class SceneBinding {
if (created) stats.created++;
else stats.updated++;
}
- this.sendTransform(o, b, stats);
+ // A new scale changes the size of the bodies below it too (their colliders and joint anchors are made at the
+ // object's scale in the world): those under it are made anew at the new size, once the sync has sent every
+ // transform.
+ if (this.sendTransform(o, b, stats)) this.rescaleBodiesBelow(o);
if (o.visible !== b.visible) {
b.visible = o.visible;
this.engine.visible(b.id, o.visible);
@@ -533,6 +586,11 @@ export class SceneBinding {
stats.updated++;
}
}
+ if (o.physics || b.body) this.syncBody(o, b, stats);
+ if (o instanceof Joint) {
+ if (!this.joints.has(o)) this.joints.set(o, null);
+ this.jointsDirty = true;
+ }
if (o instanceof InstancedMesh) this.sendInstances(o, b, stats);
if (o instanceof VolumeMesh && o.grid) {
const g = o.grid;
@@ -593,23 +651,261 @@ export class SceneBinding {
}
}
- private sendTransform(o: Object3D, b: Bound, stats: SyncStats): void {
+ /** Sends the object's transform if it changed. True if its scale did (and it had been sent before). */
+ private sendTransform(o: Object3D, b: Bound, stats: SyncStats): boolean {
const q = resolveOrientation(o);
const t = this.trs;
t[0] = o.position.x; t[1] = o.position.y; t[2] = o.position.z;
t[3] = q.x; t[4] = q.y; t[5] = q.z; t[6] = q.w;
t[7] = o.scale.x; t[8] = o.scale.y; t[9] = o.scale.z;
- let moved = false;
- for (let k = 0; k < 10; k++) if (b.trs[k] !== t[k]) { moved = true; b.trs[k] = t[k]; }
+ let moved = false, posed = false, scaled = false;
+ for (let k = 0; k < 10; k++) {
+ if (b.trs[k] !== t[k]) {
+ moved = true;
+ posed ||= k < 7;
+ // (NaN: never sent; the objects below are bound after it anyway.)
+ scaled ||= k >= 7 && !Number.isNaN(b.trs[k]);
+ b.trs[k] = t[k];
+ }
+ }
if (moved) {
this.engine.transform(b.id, t);
+ // Scene code moved an object that has a body: the body goes there (a kinematic one through the next tick).
+ if (posed && b.body) this.engine.physics("follow", { body: b.body.id });
stats.updated++;
}
+ return scaled;
+ }
+
+ /** The objects with bodies below `o`, to be checked against their scale in the world at the end of the sync
+ * (`syncBody` makes anew only those whose size changed). */
+ private rescaleBodiesBelow(o: Object3D): void {
+ if (!this.bodies) return;
+ for (const c of o.children) {
+ c.traverse((d) => {
+ const bd = this.objects.get(d);
+ if (bd?.body || (bd && d.physics)) this.rescaled.add(d);
+ });
+ }
+ }
+
+ // -------------------------------------------------------------------------------------------- physics
+
+ /** The object's rigid body: made when the object has `physics` and none yet, made anew when what it was made from
+ * changed (the description, the object's scale in the world, the geometry its shape is from), removed without. */
+ private syncBody(o: Object3D, b: Bound, stats: SyncStats): void {
+ const d = o.physics;
+ const scale = worldScale(o);
+ const g = o instanceof Mesh ? o.geometry : null;
+ const bb = b.body;
+ if (bb && d === bb.desc && g === bb.geometry && (g?.version ?? 0) === bb.version && scale[0] === bb.scale[0] && scale[1] === bb.scale[1] && scale[2] === bb.scale[2]) return;
+ this.dropBody(o, b);
+ if (!d) {
+ b.bodyFailed = null;
+ return;
+ }
+ if (b.bodyFailed === d) return;
+ // A `physics` no body can be made from (a shape that cannot be, numbers that are not finite) leaves the object
+ // without one and nothing of it in the engine; the error is thrown once the whole scene is synced.
+ const id = this.nextBody++;
+ const kind = d.type ?? "dynamic";
+ const slot = kind === "fixed" ? -1 : (this.freeSlots.pop() ?? this.nextSlot++);
+ let made = false;
+ try {
+ const { shape, position } = this.colliderShape(o, d, scale, b.name);
+ for (const [k, v] of Object.entries(d)) if (typeof v === "number" && !Number.isFinite(v)) throw new TypeError(`${b.name}: physics.${k} must be a finite number`);
+ usePhysicsEngine(this.engine);
+ this.engine.physics("body", {
+ id, kind, object: b.id, ...(slot >= 0 ? { slot } : {}),
+ ...(d.linearDamping !== undefined ? { linearDamping: d.linearDamping } : {}), ...(d.angularDamping !== undefined ? { angularDamping: d.angularDamping } : {}),
+ ...(d.gravityScale !== undefined ? { gravityScale: d.gravityScale } : {}), ...(d.canSleep === false ? { canSleep: false } : {}), ...(d.ccd ? { ccd: true } : {}),
+ });
+ made = true;
+ this.engine.physics("collider", {
+ id, body: id, shape, ...(position ? { position } : {}),
+ ...(d.mass !== undefined ? { mass: d.mass } : d.density !== undefined ? { density: d.density } : {}),
+ ...(d.friction !== undefined ? { friction: d.friction } : {}), ...(d.restitution !== undefined ? { restitution: d.restitution } : {}),
+ ...(d.sensor ? { sensor: true } : {}), ...(d.contacts ? { events: true } : {}),
+ });
+ } catch (e) {
+ // (The body without its collider goes: it would move the object, and the engine would refuse the object another.)
+ if (made) this.engine.physics("remove", { body: id });
+ if (slot >= 0) this.freeSlots.push(slot);
+ b.bodyFailed = d;
+ this.bodyError ??= e;
+ return;
+ }
+ b.bodyFailed = null;
+ b.body = { id, slot, epoch: 0, trs: b.trs, euler: false, desc: d, scale, geometry: g, version: g?.version ?? 0, contacts: !!d.contacts };
+ bindBody(o, b.body);
+ this.jointsDirty = true;
+ this.bodies++;
+ if (d.contacts) this.contactBodies++;
+ stats.updated++;
+ }
+
+ private dropBody(o: Object3D, b: Bound): void {
+ const bb = b.body;
+ if (!bb) return;
+ this.engine.physics("remove", { body: bb.id });
+ if (bb.slot >= 0) this.freeSlots.push(bb.slot);
+ unbindBody(o);
+ b.body = null;
+ this.jointsDirty = true;
+ this.bodies--;
+ if (bb.contacts) this.contactBodies--;
+ }
+
+ private dropJoint(j: Joint): void {
+ const bj = this.joints.get(j);
+ if (bj) this.engine.physics("remove", { joint: bj.id });
+ this.joints.delete(j);
+ }
+
+ /** The collider of an object's body: the engine's shape description and where it sits in the body. */
+ private colliderShape(o: Object3D, d: Readonly<PhysicsDesc>, scale: Vec3, name: string): { shape: Record<string, unknown>; position?: Vec3 } {
+ const fixed = d.type === "fixed";
+ const size = [Math.abs(scale[0]), Math.abs(scale[1]), Math.abs(scale[2])];
+ const uniform = Math.abs(size[0] - size[1]) <= 1e-6 * size[0] && Math.abs(size[0] - size[2]) <= 1e-6 * size[0];
+ let s = d.shape;
+ if (s !== undefined && typeof s !== "string") {
+ // Given sizes, in the object's units.
+ if (s.type === "box") return { shape: { type: "box", halfExtents: [s.halfExtents[0] * size[0], s.halfExtents[1] * size[1], s.halfExtents[2] * size[2]] } };
+ const k = Math.max(size[0], size[1], size[2]);
+ if (s.type === "sphere") return { shape: { type: "sphere", radius: s.radius * k } };
+ if (s.type === "capsule") return { shape: { type: "capsule", halfHeight: s.halfHeight * size[1], radius: s.radius * Math.max(size[0], size[2]) } };
+ throw new TypeError(`${name}: physics.shape must be "box", "sphere", "capsule", "hull", "mesh" or a box / sphere / capsule with sizes`);
+ }
+ if (!(o instanceof Mesh)) throw new TypeError(`${name}: physics on an object that is not a mesh needs a shape with sizes ({ type: "box", halfExtents }, ...)`);
+ const g = o.geometry;
+ s ??= g instanceof BoxGeometry ? "box" : g instanceof SphereGeometry && uniform ? "sphere" : g instanceof CapsuleGeometry && uniform ? "capsule" : fixed ? "mesh" : "hull";
+ if (s === "hull" || s === "mesh") {
+ if (s === "mesh" && !fixed) throw new TypeError(`${name}: a "mesh" shape (the geometry's triangles) is for fixed bodies; a body that moves takes "hull" or a box / sphere / capsule`);
+ return { shape: { type: s === "hull" ? "convexHull" : "trimesh", geometry: this.geometryId(g), scale } };
+ }
+ // The geometry's bounding box, and what fits it.
+ if (!g.boundingBox) g.computeBoundingBox();
+ const { min, max } = g.boundingBox!;
+ const position: Vec3 = [(min.x + max.x) / 2 * scale[0], (min.y + max.y) / 2 * scale[1], (min.z + max.z) / 2 * scale[2]];
+ // (A flat geometry, a plane, is a thin box.)
+ const h = [Math.max((max.x - min.x) / 2 * size[0], 1e-3), Math.max((max.y - min.y) / 2 * size[1], 1e-3), Math.max((max.z - min.z) / 2 * size[2], 1e-3)];
+ const centred = position.every((v) => Math.abs(v) < 1e-9);
+ const at = centred ? {} : { position };
+ if (s === "box") return { shape: { type: "box", halfExtents: h }, ...at };
+ if (s === "sphere") return { shape: { type: "sphere", radius: Math.max(h[0], h[1], h[2]) }, ...at };
+ if (s === "capsule") {
+ const radius = Math.max(h[0], h[2]);
+ return h[1] - radius > 1e-6 ? { shape: { type: "capsule", halfHeight: h[1] - radius, radius }, ...at } : { shape: { type: "sphere", radius }, ...at };
+ }
+ throw new TypeError(`${name}: physics.shape must be "box", "sphere", "capsule", "hull", "mesh" or a box / sphere / capsule with sizes`);
+ }
+
+ /** Gravity, the joints, and the calls scene code queued on objects' bodies, now that the bodies exist. */
+ private syncPhysics(stats: SyncStats): void {
+ const gv = this.scene.gravity;
+ const gravity = `${gv.x},${gv.y},${gv.z}`;
+ if (gravity !== this.gravity) {
+ if (![gv.x, gv.y, gv.z].every(Number.isFinite)) throw new TypeError("scene.gravity must be finite numbers");
+ this.gravity = gravity;
+ this.engine.physics("gravity", { gravity: [gv.x, gv.y, gv.z] });
+ stats.updated++;
+ }
+ // A joint holds while it and both its objects' bodies are in the scene; whatever it was made from changing (a body
+ // made anew included) makes it anew.
+ const joints = this.jointsDirty ? this.joints : [];
+ this.jointsDirty = false;
+ for (const [j, bj] of joints) {
+ const a = j.bodyA ? this.objects.get(j.bodyA) : undefined, b = j.bodyB ? this.objects.get(j.bodyB) : undefined;
+ let key = "";
+ let desc: Record<string, unknown> | null = null;
+ if (a?.body && b?.body) {
+ const [sa, sb] = [a.body.scale, b.body.scale];
+ desc = {
+ ...j.jointDesc(), a: a.body.id, b: b.body.id,
+ anchor1: [j.anchorA.x * sa[0], j.anchorA.y * sa[1], j.anchorA.z * sa[2]], anchor2: [j.anchorB.x * sb[0], j.anchorB.y * sb[1], j.anchorB.z * sb[2]],
+ };
+ key = JSON.stringify(desc);
+ }
+ if (key === (bj?.key ?? "")) continue;
+ if (bj) this.engine.physics("remove", { joint: bj.id });
+ if (desc) {
+ const id = this.nextBody++;
+ this.engine.physics("joint", { id, ...desc });
+ this.joints.set(j, { id, key });
+ } else this.joints.set(j, null);
+ stats.updated++;
+ }
+ for (const c of takePhysicsCommands()) {
+ const body = this.objects.get(c.object)?.body;
+ // (An object without a body, or out of the scene by now: nothing to act on.)
+ if (!body) continue;
+ this.engine.physics(c.op, { body: body.id, ...c.args });
+ stats.updated++;
+ }
+ // The engine steps the world after a sync: objects read their bodies' poses afresh.
+ if (this.bodies) physicsStepped();
+ }
+
+ /**
+ * The contacts since the last call, to their listeners: "contactstart" / "contactend" on each of the two objects
+ * (`other`: the other one), then "contacts" on the scene with the whole batch (`contacts`: { a, b, started } in the
+ * order they happened). One engine call, and none while no body in the scene reports contacts; before it, the bodies
+ * the engine took out (`takeFaults`: one call while the scene has bodies; "outofworld" on an object whose body left
+ * the world). The host calls it before the frame script.
+ */
+ deliverPhysicsEvents(): void {
+ if (this.bodies) this.takeFaults();
+ if (!this.contactBodies) return;
+ const list = JSON.parse(this.engine.physics("contacts", {})) as { bodyA: number | null; bodyB: number | null; started: boolean }[] | null;
+ if (!list?.length) return;
+ const contacts: { a: Object3D; b: Object3D; started: boolean }[] = [];
+ for (const c of list) {
+ const a = c.bodyA === null ? undefined : physicsBodies.get(c.bodyA), b = c.bodyB === null ? undefined : physicsBodies.get(c.bodyB);
+ if (!a || !b) continue;
+ contacts.push({ a, b, started: c.started });
+ const type = c.started ? "contactstart" : "contactend";
+ a.dispatchEvent({ type, other: b });
+ b.dispatchEvent({ type, other: a });
+ }
+ if (contacts.length) this.scene.dispatchEvent({ type: "contacts", contacts });
+ }
+
+ /**
+ * The bodies the engine took out after a tick, their colliders and joints with them. Each object stays in the scene
+ * where its body last put it, without a body until its `physics` is set again.
+ * - One past the world's edge (1,000 km: it fell off the level) is nothing wrong: its object gets an "outofworld"
+ * event, and the game removes it, or puts it back and sets its `physics` again.
+ * - One whose pose or velocity went non-finite is an error (bad numbers, or a simulation that blew up): the next
+ * sync throws once, naming the objects.
+ */
+ private takeFaults(): void {
+ const list = JSON.parse(this.engine.physics("faults", {})) as { body: number; kind?: string; reason: string }[] | null;
+ if (!list?.length) return;
+ const names: string[] = [], left: Object3D[] = [];
+ for (const f of list) {
+ const o = physicsBodies.get(f.body);
+ const b = o && this.objects.get(o);
+ const bb = b?.body;
+ if (!o || !b || !bb || bb.id !== f.body) continue;
+ // (Gone in the engine already: only the binding's side is undone.)
+ if (bb.slot >= 0) this.freeSlots.push(bb.slot);
+ unbindBody(o);
+ b.body = null;
+ b.bodyFailed = o.physics;
+ this.jointsDirty = true;
+ this.bodies--;
+ if (bb.contacts) this.contactBodies--;
+ if (f.kind === "leftWorld") left.push(o);
+ else names.push(`${b.name} (${f.reason})`);
+ }
+ if (names.length) this.bodyError ??= new Error(`physics: the engine took out the bodies of ${names.join(", ")}; each stays without one until its physics is set again`);
+ // (After the binding's side is in order: a listener may remove the object or give it a body again.)
+ for (const o of left) o.dispatchEvent({ type: "outofworld" });
}
/** What the object is: a change re-creates it in the engine. */
private kindKey(o: Object3D): string {
- return `${this.kindOf(o)}${o.movable ? ":movable" : ""}`;
+ return `${this.kindOf(o)}${o.movable ? ":movable" : ""}${drivenByBody(o) ? ":body" : ""}`;
}
private kindOf(o: Object3D): string {
@@ -632,7 +928,7 @@ export class SceneBinding {
}
private objectDesc(o: Object3D, b: Bound): ObjectDesc {
- const base = { name: b.name, parent: b.parent, castShadow: o.castShadow, ...(o.movable ? { movable: true } : {}) };
+ const base = { name: b.name, parent: b.parent, castShadow: o.castShadow, ...(o.movable ? { movable: true } : {}), ...(drivenByBody(o) ? { body: true } : {}) };
if (o instanceof InstancedMesh) {
const g = o.geometry;
const geometry = g instanceof ProceduralGeometry ? this.proceduralId(g) : this.geometryId(g);
@@ -1169,6 +1465,24 @@ export function lightDesc(l: Light): LightDesc {
throw new Error(`unsupported light ${l.type}`);
}
+/** A rigid body moves the object: it has `physics` that is not a fixed body's. */
+function drivenByBody(o: Object3D): boolean {
+ const d = o.physics;
+ return d !== null && d.type !== "fixed";
+}
+
+/** The object's scale in the world: its own times its ancestors' (as if none of them turned a non-uniform one). */
+function worldScale(o: Object3D): Vec3 {
+ let x = 1, y = 1, z = 1;
+ for (let c: Object3D | null = o; c; c = c.parent) {
+ const s = c.scale;
+ x *= s.x;
+ y *= s.y;
+ z *= s.z;
+ }
+ return [x, y, z];
+}
+
/** Local quaternion; targeted lights are re-aimed so that their local -Z points at the target. */
function resolveOrientation(o: Object3D): Quaternion {
if (!((o instanceof DirectionalLight || o instanceof SpotLight) && o.target)) return o.quaternion;
@@ -1203,6 +1517,7 @@ export class RecordingEngine implements Engine {
particleProgram(...a: Parameters<Engine["particleProgram"]>) { this.calls.push(["particleProgram", ...a]); }
particlesSpawn(...a: Parameters<Engine["particlesSpawn"]>) { this.calls.push(["particlesSpawn", ...a]); }
volumeFunction(...a: Parameters<Engine["volumeFunction"]>) { this.calls.push(["volumeFunction", ...a]); }
+ physics(...a: Parameters<Engine["physics"]>) { this.calls.push(["physics", ...a]); return "null"; }
gridProgram(...a: Parameters<Engine["gridProgram"]>) { this.calls.push(["gridProgram", ...a]); }
densityGrid(...a: Parameters<Engine["densityGrid"]>) { this.calls.push(["densityGrid", ...a]); }
gridSources(...a: Parameters<Engine["gridSources"]>) { this.calls.push(["gridSources", ...a]); }
diff --git a/packages/scene/src/math.ts b/packages/scene/src/math.ts
index 3040b54..d82b940 100644
--- a/packages/scene/src/math.ts
+++ b/packages/scene/src/math.ts
@@ -41,6 +41,9 @@ export class Vector3 {
subVectors(a: Vector3, b: Vector3): this {
return this.set(a.x - b.x, a.y - b.y, a.z - b.z);
}
+ addScaledVector(v: Vector3, s: number): this {
+ return this.set(this.x + v.x * s, this.y + v.y * s, this.z + v.z * s);
+ }
multiplyScalar(s: number): this {
return this.set(this.x * s, this.y * s, this.z * s);
}
diff --git a/packages/scene/src/raycaster.ts b/packages/scene/src/raycaster.ts
index 7442323..f84fa72 100644
--- a/packages/scene/src/raycaster.ts
+++ b/packages/scene/src/raycaster.ts
@@ -3,8 +3,12 @@
// click's `target` and `instanceId`) is the same Moller-Trumbore test over the built scene; scene code has the scene
// graph, not the GPU scene. Meshes (several materials included), instanced meshes (`instanceId`) and procedural meshes
// (their boxes) are hit; as in three.js, hidden objects too, and back faces only of double-sided materials.
-import { InstancedMesh, Mesh, type Object3D, type PerspectiveCamera, ProceduralGeometry, ProceduralMesh } from "./core.ts";
-import { Box3, Matrix4, Ray, Vector2, Vector3 } from "./math.ts";
+//
+// The physics world answers too (ROADMAP § 6 step 7): `Raycaster.intersectPhysics` is the ray against the colliders of
+// the objects with `physics`, in the engine (its tree of them, not a walk over triangles here), and `Shapecaster` asks
+// what a shape overlaps or meets when moved. Both see the world as of its last tick.
+import { InstancedMesh, Mesh, type Object3D, type PerspectiveCamera, physicsBodies, physicsQuery, ProceduralGeometry, ProceduralMesh } from "./core.ts";
+import { Box3, Matrix4, Quaternion, Ray, Vector2, Vector3 } from "./math.ts";
import type { BufferGeometry } from "./geometry.ts";
export interface Intersection {
@@ -16,6 +20,30 @@ export interface Intersection {
faceIndex: number | null;
uv?: Vector2;
instanceId?: number;
+ /** The surface's normal at the point, in the world (hits of the physics world). */
+ normal?: Vector3;
+}
+
+/** What a query of the physics world leaves out: an object (the one that asks: its own body). */
+export interface PhysicsQueryOptions {
+ exclude?: Object3D;
+}
+
+interface PhysicsHit {
+ body: number | null;
+ distance: number;
+ point: [number, number, number];
+ normal: [number, number, number];
+}
+
+function physicsIntersection(h: PhysicsHit): Intersection | null {
+ const object = h.body === null ? undefined : physicsBodies.get(h.body);
+ return object ? { distance: h.distance, point: new Vector3(...h.point), object, face: null, faceIndex: null, normal: new Vector3(...h.normal) } : null;
+}
+
+function skipOf(o: PhysicsQueryOptions): { skip?: number } {
+ const id = o.exclude?._body?.id;
+ return id === undefined ? {} : { skip: id };
}
export class Raycaster {
@@ -44,6 +72,21 @@ export class Raycaster {
this.camera = camera;
}
+ /**
+ * The objects with `physics` the ray passes through, nearest first, between `near` and `far` (at most 10 km): the
+ * ray against their colliders in the physics world, with the point and the surface's normal there.
+ */
+ intersectPhysics(options: PhysicsQueryOptions = {}): Intersection[] {
+ const o = this.ray.origin, d = this.ray.direction;
+ const hits = physicsQuery("ray", { origin: [o.x, o.y, o.z], direction: [d.x, d.y, d.z], max: Math.min(this.far, 1e4), all: true, ...skipOf(options) }) as PhysicsHit[] | null;
+ const out: Intersection[] = [];
+ for (const h of hits ?? []) {
+ const i = h.distance >= this.near ? physicsIntersection(h) : null;
+ if (i) out.push(i);
+ }
+ return out;
+ }
+
intersectObject(object: Object3D, recursive = true, intersects: Intersection[] = []): Intersection[] {
this.visit(object, recursive, intersects);
return intersects.sort((a, b) => a.distance - b.distance);
@@ -119,3 +162,57 @@ export class Raycaster {
if (best) out.push({ distance: best.distance, point: best.point, object, face: null, faceIndex: best.k });
}
}
+
+/** A shape to ask the physics world with (sizes in metres). */
+export type QueryShape =
+ | { type: "box"; halfExtents: readonly [number, number, number] }
+ | { type: "sphere"; radius: number }
+ | { type: "capsule"; halfHeight: number; radius: number };
+
+/**
+ * A shape placed in the physics world, as `Raycaster` is a ray: `overlap()` is the objects with `physics` whose
+ * colliders it touches where it is, `sweep(direction)` the first it meets when moved along a direction.
+ */
+export class Shapecaster {
+ shape: QueryShape;
+ readonly position = new Vector3();
+ readonly quaternion = new Quaternion();
+ /** How far `sweep` moves the shape, m. */
+ far: number;
+ constructor(shape: QueryShape, position?: Vector3, quaternion?: Quaternion, far = 1e4) {
+ this.shape = shape;
+ if (position) this.position.copy(position);
+ if (quaternion) this.quaternion.copy(quaternion);
+ this.far = far;
+ }
+
+ set(position: Vector3, quaternion?: Quaternion): void {
+ this.position.copy(position);
+ if (quaternion) this.quaternion.copy(quaternion);
+ }
+
+ private at(): Record<string, unknown> {
+ const p = this.position, q = this.quaternion;
+ return { shape: this.shape, position: [p.x, p.y, p.z], rotation: [q.x, q.y, q.z, q.w] };
+ }
+
+ /** The objects whose colliders the shape overlaps (each once). */
+ overlap(options: PhysicsQueryOptions = {}): Object3D[] {
+ const hits = physicsQuery("overlap", { ...this.at(), ...skipOf(options) }) as { body: number | null }[] | null;
+ const out = new Set<Object3D>();
+ for (const h of hits ?? []) {
+ const o = h.body === null ? undefined : physicsBodies.get(h.body);
+ if (o) out.add(o);
+ }
+ return [...out];
+ }
+
+ /**
+ * The first object the shape meets moved along `direction` by at most `far`: `distance` is how far it gets, `point`
+ * and `normal` where it touches. Null if the way is clear.
+ */
+ sweep(direction: Vector3, options: PhysicsQueryOptions = {}): Intersection | null {
+ const h = physicsQuery("sweep", { ...this.at(), direction: [direction.x, direction.y, direction.z], max: Math.min(this.far, 1e4), ...skipOf(options) }) as PhysicsHit | null;
+ return h ? physicsIntersection(h) : null;
+ }
+}
diff --git a/packages/scene/test/physics.test.ts b/packages/scene/test/physics.test.ts
new file mode 100644
index 0000000..952ab0f
--- /dev/null
+++ b/packages/scene/test/physics.test.ts
@@ -0,0 +1,456 @@
+// Physics in the DSL (ROADMAP § 6 step 7): what `Object3D.physics`, joints and the queries send to the engine, and how
+// objects read their bodies' poses. The engine here records the calls and answers the queries from a table.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ BoxGeometry, CapsuleGeometry, Group, HingeJoint, IcosahedronGeometry, Mesh, type Object3D, PerspectiveCamera, PlaneGeometry, Raycaster, RecordingEngine, RopeJoint, Scene, SceneBinding,
+ Shapecaster, SphereGeometry, Vector3, type ContactEvent, type ObjectDesc,
+} from "../src/index.ts";
+
+type Call = [string, ...unknown[]];
+
+/** A recording engine with a pose table and query answers. */
+class PhysicsEngine extends RecordingEngine {
+ poses = new Float32Array(0);
+ fetched = 0;
+ answers: Record<string, unknown> = {};
+ /** Colliders of this shape are refused, as the engine refuses one it cannot build. */
+ refuse = "";
+ override physics(op: string, args: object): string {
+ this.calls.push(["physics", op, args]);
+ if (op === "collider" && (args as { shape: { type: string } }).shape.type === this.refuse) throw new TypeError("physics: the collider's shape cannot be built");
+ return JSON.stringify(this.answers[op] ?? null);
+ }
+ physicsPoses(): Float32Array {
+ this.fetched++;
+ return this.poses;
+ }
+ /** Body `slot`'s pose in the table. */
+ put(slot: number, p: [number, number, number], q: [number, number, number, number] = [0, 0, 0, 1]) {
+ if (this.poses.length < (slot + 1) * 7) {
+ const grown = new Float32Array((slot + 1) * 7);
+ grown.set(this.poses);
+ this.poses = grown;
+ }
+ this.poses.set([...p, ...q], slot * 7);
+ }
+}
+
+function world() {
+ const scene = new Scene(), camera = new PerspectiveCamera();
+ scene.add(camera);
+ const engine = new PhysicsEngine();
+ const binding = new SceneBinding(engine, scene, camera);
+ const physics = () => (engine.take().filter((c) => c[0] === "physics") as Call[]).map((c) => [c[1], c[2]] as [string, Record<string, unknown>]);
+ return { scene, camera, engine, binding, physics };
+}
+
+test("an object with physics has a body while it is in the scene", () => {
+ const { scene, engine, binding, physics } = world();
+ const box = new Mesh(new BoxGeometry(1, 2, 0.5));
+ box.position.set(0, 3, 0);
+ box.physics = "dynamic";
+ const ground = new Mesh(new PlaneGeometry(10, 10));
+ ground.physics = { type: "fixed", friction: 0.9 };
+ scene.add(box, ground);
+ binding.sync();
+ const calls = engine.take();
+ const objects = Object.fromEntries((calls.filter((c) => c[0] === "object") as [string, number, ObjectDesc][]).map((c) => [c[2].name, c]));
+ assert.equal(objects.mesh_1[2].body, true, "a body will drive it");
+ assert.equal(objects.mesh_2[2].body, undefined, "a fixed body drives nothing");
+ const ph = (calls.filter((c) => c[0] === "physics") as Call[]).map((c) => [c[1], c[2]]);
+ assert.deepEqual(ph, [
+ ["body", { id: 1, kind: "dynamic", object: objects.mesh_1[1], slot: 0 }],
+ ["collider", { id: 1, body: 1, shape: { type: "box", halfExtents: [0.5, 1, 0.25] } }],
+ ["body", { id: 2, kind: "fixed", object: objects.mesh_2[1] }],
+ // A fixed mesh that is not a box: its triangles.
+ ["collider", { id: 2, body: 2, shape: { type: "trimesh", geometry: (calls.find((c) => c[0] === "geometry" && c[1] !== (objects.mesh_1[2] as { geometry: number }).geometry) as Call)[1], scale: [1, 1, 1] }, friction: 0.9 }],
+ ]);
+ // Nothing changes: nothing is sent.
+ binding.sync();
+ assert.deepEqual(physics(), []);
+ // Out of the scene: the body goes. Back in: a new one (the slot is taken again).
+ scene.remove(box);
+ binding.sync();
+ assert.deepEqual(physics(), [["remove", { body: 1 }]]);
+ scene.add(box);
+ binding.sync();
+ assert.deepEqual(physics().map((c) => [c[0], c[1].id, c[1].slot]), [["body", 3, 0], ["collider", 3, undefined]]);
+ // `physics` set again makes the body anew; null removes it (and the object is no longer one a body drives).
+ box.physics = { type: "dynamic", density: 500, ccd: true };
+ binding.sync();
+ assert.deepEqual(physics().map((c) => c[0]), ["remove", "body", "collider"]);
+ box.physics = null;
+ binding.sync();
+ const end = engine.take();
+ assert.deepEqual(end.filter((c) => c[0] === "physics").map((c) => c[1]), ["remove"]);
+ assert.equal((end.find((c) => c[0] === "object") as [string, number, ObjectDesc])[2].body, undefined);
+});
+
+test("colliders come from the geometry, its bounding box and the object's scale in the world", () => {
+ const { scene, binding, physics } = world();
+ const group = new Group();
+ group.scale.set(2, 2, 2);
+ const sphere = new Mesh(new SphereGeometry(0.5));
+ sphere.physics = "dynamic";
+ const capsule = new Mesh(new CapsuleGeometry(0.25, 1));
+ capsule.physics = "kinematic";
+ const rock = new Mesh(new IcosahedronGeometry(1));
+ rock.physics = { type: "dynamic", mass: 80 };
+ const stretched = new Mesh(new SphereGeometry(0.5));
+ stretched.scale.set(1, 3, 1);
+ stretched.physics = "dynamic";
+ const offset = new Mesh(new BoxGeometry(1, 1, 1).translate(0, 0.5, 0));
+ offset.physics = { type: "dynamic", shape: "sphere" };
+ const trigger = new Group();
+ trigger.physics = { type: "fixed", shape: { type: "box", halfExtents: [1, 0.5, 1] }, sensor: true, contacts: true };
+ group.add(sphere, capsule, rock, stretched, offset, trigger);
+ scene.add(group);
+ binding.sync();
+ const colliders = physics().filter((c) => c[0] === "collider").map((c) => c[1]);
+ const round = (v: unknown) => JSON.parse(JSON.stringify(v, (_, x) => (typeof x === "number" ? Math.round(x * 1e4) / 1e4 : x)));
+ assert.deepEqual(round(colliders[0].shape), { type: "sphere", radius: 1 });
+ assert.deepEqual(round(colliders[1].shape), { type: "capsule", halfHeight: 1, radius: 0.5 });
+ assert.equal((colliders[2].shape as { type: string }).type, "convexHull");
+ assert.deepEqual([(colliders[2].shape as { scale: number[] }).scale, colliders[2].mass, colliders[2].density], [[2, 2, 2], 80, undefined]);
+ assert.equal((colliders[3].shape as { type: string }).type, "convexHull", "a sphere scaled unevenly is its hull");
+ assert.deepEqual(round([colliders[4].shape, colliders[4].position]), [{ type: "sphere", radius: 1 }, [0, 1, 0]], "the bounding box's centre, scaled");
+ assert.deepEqual([colliders[5].shape, colliders[5].sensor, colliders[5].events], [{ type: "box", halfExtents: [2, 1, 2] }, true, true]);
+ // What cannot be: a moving mesh collider, an object that is not a mesh without sizes. The sync throws once it is done,
+ // and the object is left without a body until its `physics` is set again.
+ const bad = new Mesh(new IcosahedronGeometry(1));
+ bad.physics = { type: "dynamic", shape: "mesh" };
+ scene.add(bad);
+ assert.throws(() => binding.sync(), /"mesh" shape .* is for fixed bodies/);
+ binding.sync();
+ assert.deepEqual(physics(), []);
+ scene.remove(bad);
+ const empty = new Group();
+ empty.physics = "dynamic";
+ scene.add(empty);
+ assert.throws(() => binding.sync(), /needs a shape with sizes/);
+});
+
+test("a body the engine cannot give a collider leaves nothing behind", () => {
+ const { scene, engine, binding, physics } = world();
+ engine.refuse = "convexHull";
+ // A flat geometry has no hull: the engine refuses the collider after it made the body.
+ const flat = new Mesh(new PlaneGeometry(1, 1)), box = new Mesh(new BoxGeometry(1, 1, 1));
+ flat.physics = "dynamic";
+ box.physics = "dynamic";
+ scene.add(flat, box);
+ assert.throws(() => binding.sync(), /cannot be built/);
+ // The body is removed again, its slot is free for the next, and the objects after it in the scene are bound.
+ assert.deepEqual(physics().map((c) => [c[0], c[1].id ?? c[1].body, c[1].slot]), [["body", 1, 0], ["collider", 1, undefined], ["remove", 1, undefined], ["body", 2, 0], ["collider", 2, undefined]]);
+ assert.equal(binding.objectNamed("mesh_2"), box);
+ // Nothing is tried again by itself: later syncs are quiet and do not throw.
+ binding.sync();
+ flat.position.y = 1;
+ binding.sync();
+ assert.deepEqual(physics(), []);
+ // `physics` set again is tried again.
+ flat.physics = { type: "dynamic", shape: "box" };
+ binding.sync();
+ assert.deepEqual(physics().map((c) => [c[0], c[1].id, c[1].slot]), [["body", 3, 1], ["collider", 3, undefined]]);
+});
+
+test("objects read their bodies' poses when asked, from one table a frame; writing moves the body", () => {
+ const { scene, engine, binding, physics } = world();
+ const boxes = [0, 1, 2].map((k) => {
+ const b = new Mesh(new BoxGeometry(1, 1, 1));
+ b.position.set(k, 5, 0);
+ b.physics = k === 2 ? "kinematic" : "dynamic";
+ return b;
+ });
+ const wall = new Mesh(new BoxGeometry(1, 1, 1));
+ wall.physics = "fixed";
+ scene.add(...boxes, wall);
+ binding.sync();
+ engine.take();
+ // The engine steps: the bodies have moved. Nothing is fetched until a pose is read.
+ engine.put(0, [0, 4, 0]);
+ engine.put(1, [1, 4.5, 0], [0, 0.5, 0, Math.sqrt(0.75)]);
+ engine.put(2, [2, 5, 0]);
+ assert.equal(engine.fetched, 0);
+ assert.equal(boxes[0].position.y, 4);
+ assert.equal(boxes[1].position.y, 4.5);
+ assert.ok(Math.abs(boxes[1].rotation.y - Math.PI / 3) < 1e-6, "rotation follows the quaternion read");
+ assert.ok(Math.abs(boxes[1].quaternion.w - Math.sqrt(0.75)) < 1e-7);
+ assert.equal(engine.fetched, 1, "one fetch for every body's pose");
+ assert.equal(wall.position.y, 0, "a fixed body's object is a plain object");
+ // Reading is not writing: the sync sends no transform, and nothing for the bodies.
+ binding.sync();
+ assert.deepEqual(engine.take().map((c) => c[0]), []);
+ // The next frame: the table again, once, on the first read.
+ engine.put(0, [0, 3, 0]);
+ assert.equal(boxes[0].getWorldPosition().y, 3, "through the object's matrices too");
+ assert.equal(engine.fetched, 2);
+ // A write is a teleport: the object's transform, then the body told to follow it; where the script did not read first,
+ // the pose it adds to is the body's.
+ engine.put(1, [1, 2, 0]);
+ boxes[0].position.y = 10;
+ boxes[1].position.x += 5;
+ boxes[2].rotation.y = 1;
+ binding.sync();
+ const calls = engine.take();
+ assert.deepEqual(calls.map((c) => c[0]), ["transform", "physics", "transform", "physics", "transform", "physics"]);
+ assert.deepEqual([...(calls[2][2] as number[]).slice(0, 3)], [6, 2, 0], "x += 5 on the pose of this frame");
+ assert.deepEqual(calls.filter((c) => c[0] === "physics").map((c) => [c[1], c[2]]), [["follow", { body: 1 }], ["follow", { body: 2 }], ["follow", { body: 3 }]]);
+ // A script that reads nothing fetches nothing.
+ const before = engine.fetched;
+ binding.sync();
+ binding.sync();
+ assert.equal(engine.fetched, before);
+ assert.deepEqual(physics(), []);
+ // The body gone: the object keeps the pose it had, as plain properties.
+ engine.put(0, [0, 1, 0]);
+ boxes[0].physics = null;
+ binding.sync();
+ assert.equal(boxes[0].position.y, 1);
+ engine.put(0, [0, -50, 0]);
+ binding.sync();
+ assert.equal(boxes[0].position.y, 1);
+});
+
+test("impulses, forces and velocities are calls on the object, sent once it has its body", () => {
+ const { scene, engine, binding, physics } = world();
+ const ball = new Mesh(new SphereGeometry(0.5));
+ ball.physics = "dynamic";
+ // Before it is in the scene: kept, sent after the body exists, in order.
+ ball.setLinearVelocity(new Vector3(1, 0, 0)).applyImpulse(new Vector3(0, 5, 0), new Vector3(0, 0, 0.5));
+ scene.add(ball);
+ binding.sync();
+ assert.deepEqual(physics().map((c) => [c[0], { ...c[1], shape: undefined, object: undefined }]), [
+ ["body", { id: 1, kind: "dynamic", slot: 0, shape: undefined, object: undefined }],
+ ["collider", { id: 1, body: 1, shape: undefined, object: undefined }],
+ ["velocity", { body: 1, linvel: [1, 0, 0], shape: undefined, object: undefined }],
+ ["impulse", { body: 1, impulse: [0, 5, 0], point: [0, 0, 0.5], shape: undefined, object: undefined }],
+ ]);
+ ball.applyForce(new Vector3(0, 9.81, 0)).applyTorque(new Vector3(0, 1, 0)).applyTorqueImpulse(new Vector3(1, 0, 0)).setAngularVelocity(new Vector3(0, 0, 2));
+ binding.sync();
+ assert.deepEqual(physics(), [
+ ["force", { body: 1, force: [0, 9.81, 0] }], ["force", { body: 1, torque: [0, 1, 0] }], ["impulse", { body: 1, torque: [1, 0, 0] }], ["velocity", { body: 1, angvel: [0, 0, 2] }],
+ ]);
+ // Its state, asked of the engine.
+ engine.answers.state = { linvel: [1, 2, 3], angvel: [0, 0, 2], sleeping: true };
+ assert.deepEqual([ball.getLinearVelocity().toArray(), ball.getAngularVelocity().toArray(), ball.sleeping], [[1, 2, 3], [0, 0, 2], true]);
+ assert.deepEqual(physics(), [["state", { body: 1 }], ["state", { body: 1 }], ["state", { body: 1 }]]);
+ // An object without a body: nothing is sent, and it reads as at rest.
+ const ghost = new Mesh(new SphereGeometry(0.5));
+ ghost.applyImpulse(new Vector3(1, 0, 0));
+ scene.add(ghost);
+ binding.sync();
+ assert.deepEqual(physics(), []);
+ assert.deepEqual([ghost.getLinearVelocity().toArray(), ghost.sleeping], [[0, 0, 0], false]);
+});
+
+test("a body the engine takes out after a tick leaves its object without one, and the sync says so once", () => {
+ const { scene, engine, binding, physics } = world();
+ const post = new Mesh(new BoxGeometry(0.2, 2, 0.2));
+ post.physics = "fixed";
+ const crate = new Mesh(new BoxGeometry(1, 1, 1));
+ crate.physics = { type: "dynamic", contacts: true };
+ scene.add(post, crate, new HingeJoint(post, crate));
+ binding.sync();
+ const made = physics();
+ const crateBody = made.filter((c) => c[0] === "body")[1][1].id as number;
+ // The engine took the crate's body out (its colliders and joint with it) and reports it once.
+ engine.answers.faults = [{ body: crateBody, object: 2, kind: "nonFinite", reason: "its pose or velocity went non-finite" }];
+ let event = false;
+ crate.addEventListener("outofworld", () => (event = true));
+ engine.answers.state = { removed: "its pose or velocity went non-finite" };
+ assert.deepEqual(crate.getLinearVelocity().toArray(), [0, 0, 0], "a removed body reads as none");
+ binding.deliverPhysicsEvents();
+ engine.answers.faults = [];
+ physics();
+ assert.throws(() => binding.sync(), /took out the bodies of mesh_2 \(its pose or velocity went non-finite\)/);
+ assert.equal(event, false, "an error, not a body that left the world");
+ // Nothing is sent for it (no removal: the engine has none; no body made again), and the crate reads as without one.
+ assert.deepEqual(physics().filter((c) => c[0] !== "remove" || c[1].joint === undefined), [], "the joint's removal is the only call");
+ crate.applyImpulse(new Vector3(0, 1, 0));
+ binding.sync();
+ assert.deepEqual(physics(), [], "an impulse on an object without a body goes nowhere");
+ assert.equal(crate.sleeping, false);
+ physics();
+ // Its physics set again: a body again, and the joint on it.
+ crate.physics = { type: "dynamic" };
+ binding.sync();
+ assert.deepEqual(physics().map((c) => c[0]), ["body", "collider", "joint"]);
+});
+
+test("an object whose body leaves the world gets an event, and nothing is thrown", () => {
+ const { scene, engine, binding, physics } = world();
+ const ball = new Mesh(new SphereGeometry(0.5)), other = new Mesh(new SphereGeometry(0.5));
+ ball.physics = "dynamic";
+ other.physics = "dynamic";
+ scene.add(ball, other);
+ binding.sync();
+ const ids = physics().filter((c) => c[0] === "body").map((c) => c[1].id as number);
+ // It fell off the level: past the world's edge the engine takes the body out (an ordinary thing in a game).
+ const seen: string[] = [];
+ ball.addEventListener("outofworld", (e) => seen.push(`${e.type} ${e.target === ball}`));
+ other.addEventListener("outofworld", () => scene.remove(other));
+ engine.answers.faults = ids.map((body) => ({ body, object: 1, kind: "leftWorld", reason: "it left the world (past 1e6 m from the origin)" }));
+ binding.deliverPhysicsEvents();
+ engine.answers.faults = [];
+ assert.deepEqual(seen, ["outofworld true"]);
+ physics();
+ // No error; the ball is still in the scene, without a body (nothing is sent for it: the engine has none); the
+ // other one's listener removed it from the scene.
+ binding.sync();
+ assert.deepEqual(physics(), []);
+ assert.ok(scene.children.includes(ball) && !scene.children.includes(other));
+ ball.applyImpulse(new Vector3(0, 1, 0));
+ binding.sync();
+ assert.deepEqual(physics(), [], "no body: the impulse goes nowhere");
+ // Put back with its physics set again: a body again.
+ ball.position.set(0, 2, 0);
+ ball.physics = "dynamic";
+ binding.sync();
+ assert.deepEqual(physics().map((c) => c[0]), ["body", "collider"]);
+});
+
+test("a parent scaled anew makes the bodies below it anew at their new size, and their joints", () => {
+ const { scene, engine, binding, physics } = world();
+ const post = new Mesh(new BoxGeometry(0.2, 2, 0.2));
+ post.physics = "fixed";
+ const group = new Group();
+ const inner = new Group();
+ const ball = new Mesh(new SphereGeometry(0.5));
+ ball.physics = "dynamic";
+ inner.add(ball);
+ group.add(inner);
+ const rope = new RopeJoint(post, ball, { length: 2, anchorB: new Vector3(0, 0.5, 0) });
+ scene.add(post, group, rope);
+ binding.sync();
+ physics();
+ // Moved, not scaled: nothing made anew.
+ group.position.set(1, 0, 0);
+ binding.sync();
+ assert.deepEqual(physics().filter((c) => c[0] !== "follow"), []);
+ // Scaled two levels up: the ball's body and collider made anew at twice the size, the rope anew with its anchor.
+ group.scale.set(2, 2, 2);
+ binding.sync();
+ const made = physics();
+ assert.deepEqual(made.map((c) => c[0]), ["remove", "body", "collider", "remove", "joint"]);
+ assert.deepEqual(made[2][1].shape, { type: "sphere", radius: 1 });
+ assert.deepEqual(made[4][1].anchor2, [0, 1, 0]);
+ binding.sync();
+ assert.deepEqual(physics(), []);
+ // Scaled while an object between them moves (changed after it, so synced after it): the ball's body is made once
+ // that move is sent, where the renderer then has the ball.
+ group.scale.set(3, 3, 3);
+ inner.position.set(0, 2, 0);
+ binding.sync();
+ const calls = engine.take();
+ const innerId = (calls.find((c) => c[0] === "transform" && (c[2] as number[])[1] === 2) as [string, number] | undefined)?.[1];
+ const moved = calls.findIndex((c) => c[0] === "transform" && c[1] === innerId);
+ const body = calls.findIndex((c) => c[0] === "physics" && c[1] === "body");
+ assert.ok(innerId !== undefined && moved >= 0 && body > moved, `the inner group's move (call ${moved}) before the ball's new body (call ${body})`);
+});
+
+test("a joint holds while it and both its objects are in the scene", () => {
+ const { scene, binding, physics } = world();
+ const post = new Mesh(new BoxGeometry(0.2, 2, 0.2));
+ post.physics = "fixed";
+ const door = new Mesh(new BoxGeometry(1, 2, 0.1));
+ door.scale.set(2, 1, 1);
+ door.physics = "dynamic";
+ const hinge = new HingeJoint(post, door, { anchorA: new Vector3(0.1, 0, 0), anchorB: new Vector3(-0.5, 0, 0), limits: [-1.5, 1.5], motor: { velocity: 1, maxForce: 50 } });
+ scene.add(post, hinge);
+ binding.sync();
+ assert.deepEqual(physics().map((c) => c[0]), ["body", "collider"], "the door is not in the scene yet: no joint");
+ scene.add(door);
+ binding.sync();
+ const made = physics();
+ assert.deepEqual(made.map((c) => c[0]), ["body", "collider", "joint"]);
+ // (Anchors are in the objects' own spaces: the door's is scaled with it.)
+ assert.deepEqual(made[2][1], { type: "revolute", axis: [0, 1, 0], limits: [-1.5, 1.5], motor: { velocity: 1, maxForce: 50 }, a: 1, b: 2, anchor1: [0.1, 0, 0], anchor2: [-1, 0, 0], id: 3 });
+ binding.sync();
+ assert.deepEqual(physics(), []);
+ // Changed in the scene: made anew.
+ hinge.motor = null;
+ hinge.needsUpdate = true;
+ binding.sync();
+ assert.deepEqual(physics().map((c) => [c[0], c[1].joint ?? c[1].motor]), [["remove", 3], ["joint", undefined]]);
+ // The door's body made anew: so is the joint, on the new body.
+ door.physics = { type: "dynamic", density: 300 };
+ binding.sync();
+ const again = physics();
+ assert.deepEqual(again.map((c) => c[0]), ["remove", "body", "collider", "remove", "joint"]);
+ assert.equal(again[4][1].b, again[1][1].id);
+ // The joint removed: it lets go; a rope joins the same two.
+ scene.remove(hinge);
+ scene.add(new RopeJoint(post, door, { length: 2 }));
+ binding.sync();
+ const swapped = physics();
+ assert.deepEqual(swapped.map((c) => [c[0], c[1].type]), [["remove", undefined], ["joint", "rope"]]);
+ assert.equal(swapped[1][1].length, 2);
+ // An end leaves the scene: the joint's object stays, the joint is gone until it is back.
+ scene.remove(door);
+ binding.sync();
+ assert.deepEqual(physics().map((c) => Object.keys(c[1])[0]), ["body", "joint"]);
+});
+
+test("rays and shapes ask the physics world; contacts arrive as events, in batches", () => {
+ const { scene, engine, binding, physics } = world();
+ const a = new Mesh(new BoxGeometry(1, 1, 1)), b = new Mesh(new BoxGeometry(1, 1, 1));
+ a.name = "a";
+ b.name = "b";
+ a.physics = { type: "dynamic", contacts: true };
+ b.physics = "fixed";
+ scene.add(a, b);
+ binding.sync();
+ engine.take();
+ // A ray: the engine's hits (bodies by id) come back as intersections with their objects.
+ engine.answers.ray = [
+ { collider: 1, body: 1, object: 7, distance: 0.5, point: [0, 0, 0.5], normal: [0, 0, 1] },
+ { collider: 2, body: 2, object: 8, distance: 2, point: [0, 0, 2], normal: [0, 1, 0] },
+ { collider: 9, body: null, object: null, distance: 3, point: [0, 0, 3], normal: [0, 1, 0] },
+ ];
+ const ray = new Raycaster(new Vector3(0, 0, 0), new Vector3(0, 0, 1), 1, 50);
+ const hits = ray.intersectPhysics({ exclude: b });
+ assert.deepEqual(physics(), [["ray", { origin: [0, 0, 0], direction: [0, 0, 1], max: 50, all: true, skip: 2 }]]);
+ assert.deepEqual(hits.map((h) => [h.object.name, h.distance, h.point.toArray(), h.normal?.toArray(), h.face]), [["b", 2, [0, 0, 2], [0, 1, 0], null]], "nearer than `near` and of no object: left out");
+ // A shape: what it overlaps, and what it meets when moved.
+ engine.answers.overlap = [{ collider: 1, body: 1, object: 7 }, { collider: 5, body: 1, object: 7 }];
+ engine.answers.sweep = { collider: 2, body: 2, object: 8, distance: 1.25, point: [0, 1, 0], normal: [0, 1, 0] };
+ const probe = new Shapecaster({ type: "sphere", radius: 0.5 }, new Vector3(0, 3, 0));
+ probe.far = 10;
+ assert.deepEqual(probe.overlap().map((o) => o.name), ["a"], "each object once");
+ const met = probe.sweep(new Vector3(0, -1, 0), { exclude: a });
+ assert.deepEqual([met?.object.name, met?.distance], ["b", 1.25]);
+ assert.deepEqual(physics().map((c) => [c[0], c[1].max, c[1].skip]), [["overlap", undefined, undefined], ["sweep", 10, 1]]);
+ // Contacts: one call a frame while a body in the scene reports them, dispatched to both objects and, whole, to the
+ // scene.
+ const seen: string[] = [];
+ const note = (who: Object3D) => (e: { type: string }) => seen.push(`${who.name} ${e.type} ${(e as ContactEvent).other.name}`);
+ a.addEventListener("contactstart", note(a));
+ a.addEventListener("contactend", note(a));
+ b.addEventListener("contactstart", note(b));
+ let batch: unknown[] = [];
+ scene.addEventListener("contacts", (e) => (batch = e.contacts as unknown[]));
+ engine.answers.contacts = [{ a: 1, b: 2, bodyA: 1, bodyB: 2, started: true }, { a: 1, b: 2, bodyA: 1, bodyB: 2, started: false }, { a: 1, b: 9, bodyA: 1, bodyB: null, started: true }];
+ binding.deliverPhysicsEvents();
+ assert.deepEqual(seen, ["a contactstart b", "b contactstart a", "a contactend b"]);
+ assert.equal(batch.length, 2);
+ assert.deepEqual(physics(), [["faults", {}], ["contacts", {}]]);
+ // No body reports contacts: no call for them (the faults' one stays while there are bodies).
+ a.physics = "dynamic";
+ binding.sync();
+ engine.take();
+ binding.deliverPhysicsEvents();
+ assert.deepEqual(physics(), [["faults", {}]]);
+});
+
+test("a scene without physics makes no physics call; gravity is sent when it is not the default", () => {
+ const { scene, engine, binding, physics } = world();
+ scene.add(new Mesh(new BoxGeometry(1, 1, 1)));
+ binding.sync();
+ binding.sync();
+ assert.deepEqual(engine.take().filter((c) => c[0] === "physics"), []);
+ assert.equal(engine.fetched, 0);
+ scene.gravity.set(0, -1.62, 0);
+ binding.sync();
+ assert.deepEqual(physics(), [["gravity", { gravity: [0, -1.62, 0] }]]);
+});
diff --git a/renderer/Cargo.lock b/renderer/Cargo.lock
index 86815fa..117138d 100644
--- a/renderer/Cargo.lock
+++ b/renderer/Cargo.lock
@@ -83,6 +83,15 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+[[package]]
+name = "approx"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "arrayref"
version = "0.3.9"
@@ -467,6 +476,12 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
+[[package]]
+name = "downcast-rs"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"
+
[[package]]
name = "dpi"
version = "0.1.2"
@@ -657,6 +672,27 @@ dependencies = [
"bytemuck",
]
+[[package]]
+name = "glam"
+version = "0.33.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37bfe73dc8ec21f54d181e5a60554327ec3f1c600c455a75ccbfc65d2106a6c4"
+dependencies = [
+ "approx",
+ "libm",
+]
+
+[[package]]
+name = "glamx"
+version = "0.3.1"
+dependencies = [
+ "approx",
+ "glam 0.33.12",
+ "nalgebra",
+ "num-traits",
+ "simba",
+]
+
[[package]]
name = "glow"
version = "0.17.0"
@@ -744,6 +780,15 @@ dependencies = [
"zerocopy",
]
+[[package]]
+name = "hash32"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606"
+dependencies = [
+ "byteorder",
+]
+
[[package]]
name = "hashbrown"
version = "0.16.1"
@@ -766,6 +811,16 @@ dependencies = [
"foldhash",
]
+[[package]]
+name = "heapless"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
+dependencies = [
+ "hash32",
+ "stable_deref_trait",
+]
+
[[package]]
name = "hermit-abi"
version = "0.5.3"
@@ -796,6 +851,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown 0.17.1",
+ "serde",
+ "serde_core",
]
[[package]]
@@ -1068,6 +1125,33 @@ dependencies = [
"thiserror 2.0.21",
]
+[[package]]
+name = "nalgebra"
+version = "0.35.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "adc43a60c217b0c6ff46e47f26911015ad8d2e5a8be1af668c67e370d99a4346"
+dependencies = [
+ "approx",
+ "glam 0.33.12",
+ "nalgebra-macros",
+ "num-complex",
+ "num-rational",
+ "num-traits",
+ "simba",
+ "typenum",
+]
+
+[[package]]
+name = "nalgebra-macros"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "973e7178a678cfd059ccec50887658d482ce16b0aa9da3888ddeab5cd5eb4889"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "ndk"
version = "0.9.0"
@@ -1108,6 +1192,36 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "num-derive"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4e98dc3b890f6c23a0f9d3d491a2823d0dea0fa656302a13dd225fa924112a8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "num-integer"
+version = "0.1.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-rational"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -1491,6 +1605,32 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "parry3d"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b626edc0b497dba4bdf6e1e0797895294ed9f61dac2bd28cb5d34d37ad2ca7e"
+dependencies = [
+ "approx",
+ "arrayvec",
+ "bitflags 2.13.2",
+ "downcast-rs 2.0.2",
+ "either",
+ "foldhash",
+ "glamx",
+ "hashbrown 0.17.1",
+ "indexmap",
+ "log",
+ "num-derive",
+ "num-traits",
+ "ordered-float",
+ "rstar",
+ "simba",
+ "smallvec",
+ "static_assertions",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "paste"
version = "1.0.15"
@@ -1503,6 +1643,15 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+[[package]]
+name = "physics-core"
+version = "0.1.0"
+dependencies = [
+ "libm",
+ "rapier3d",
+ "serde_json",
+]
+
[[package]]
name = "pin-project"
version = "1.1.13"
@@ -1618,6 +1767,19 @@ name = "profiling"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
+dependencies = [
+ "profiling-procmacros",
+]
+
+[[package]]
+name = "profiling-procmacros"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
[[package]]
name = "pulp"
@@ -1684,6 +1846,28 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"
+[[package]]
+name = "rapier3d"
+version = "0.36.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "033e2edc815d61ab97bd74ed5d1cbea5ebe575218774a7cfedbd3551f0033317"
+dependencies = [
+ "approx",
+ "arrayvec",
+ "bitflags 2.13.2",
+ "glamx",
+ "log",
+ "nalgebra",
+ "num-traits",
+ "parry3d",
+ "profiling",
+ "serde",
+ "simba",
+ "static_assertions",
+ "thiserror 2.0.21",
+ "wide",
+]
+
[[package]]
name = "raw-cpuid"
version = "11.6.0"
@@ -1808,6 +1992,17 @@ dependencies = [
"cc",
]
+[[package]]
+name = "rstar"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "90e7279515baf3838062fa9c495a408bc2f3abbf9cd2ac8c2d4108b90fa29b89"
+dependencies = [
+ "heapless",
+ "num-traits",
+ "smallvec",
+]
+
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -1855,6 +2050,15 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+[[package]]
+name = "safe_arch"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42c6efa15875e6ecb39ca61fb0b0c1a40b84fac5a5ffe71eef7d1000c8eb3f5f"
+dependencies = [
+ "bytemuck",
+]
+
[[package]]
name = "same-file"
version = "1.0.6"
@@ -1955,6 +2159,19 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+[[package]]
+name = "simba"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1a7200d82ff1c7b4235efd12f11e2537a402c91cf83a5cb97ce80eef787fde7"
+dependencies = [
+ "approx",
+ "libm",
+ "num-complex",
+ "num-traits",
+ "wide",
+]
+
[[package]]
name = "simd-adler32"
version = "0.3.10"
@@ -2041,6 +2258,12 @@ dependencies = [
"bitflags 2.13.2",
]
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
[[package]]
name = "static_assertions"
version = "1.1.0"
@@ -2130,11 +2353,12 @@ version = "0.1.0"
dependencies = [
"anyhow",
"bytemuck",
- "glam",
+ "glam 0.30.10",
"gltf",
"half",
"image",
"oidn",
+ "physics-core",
"pollster",
"rayon",
"rquickjs",
@@ -2353,7 +2577,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"
dependencies = [
"cc",
- "downcast-rs",
+ "downcast-rs 1.2.1",
"rustix 1.1.6",
"scoped-tls",
"smallvec",
@@ -2648,6 +2872,16 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "wide"
+version = "1.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d920ac99c3c8edce110cb8d07dbb324d6d026011dce85b1e9355b70f0adacc4f"
+dependencies = [
+ "bytemuck",
+ "safe_arch",
+]
+
[[package]]
name = "winapi-util"
version = "0.1.11"
diff --git a/renderer/Cargo.toml b/renderer/Cargo.toml
index 9a1f4ff..55296d8 100644
--- a/renderer/Cargo.toml
+++ b/renderer/Cargo.toml
@@ -6,6 +6,7 @@ description = "Native renderer for ThreeRT games: embedded scene runtime, GPU pa
[dependencies]
voxel-core = { path = "voxel-core" }
+physics-core = { path = "physics-core" }
wgpu = "30"
pollster = "0.4"
bytemuck = { version = "1", features = ["derive"] }
@@ -35,3 +36,10 @@ lto = "thin"
[profile.dev]
opt-level = 2
+
+# glamx with its eigen decomposition's acos / cos called through simba (libm on every platform): the physics' bits must
+# not depend on the platform's math functions (third_party/glamx/PATCH.md). physics-core's own manifest has the same
+# table, but cargo only reads the one of the crate it builds: this one is what the renderer gets
+# (src/physics.rs `the_renderers_physics_steps_to_the_recorded_bits` fails without it).
+[patch.crates-io]
+glamx = { path = "third_party/glamx" }
diff --git a/renderer/physics-core/Cargo.lock b/renderer/physics-core/Cargo.lock
new file mode 100644
index 0000000..e983201
--- /dev/null
+++ b/renderer/physics-core/Cargo.lock
@@ -0,0 +1,495 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "approx"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "arrayvec"
+version = "0.7.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "bytemuck"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+
+[[package]]
+name = "byteorder"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+
+[[package]]
+name = "downcast-rs"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"
+
+[[package]]
+name = "either"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
+
+[[package]]
+name = "equivalent"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
+
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "glam"
+version = "0.33.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37bfe73dc8ec21f54d181e5a60554327ec3f1c600c455a75ccbfc65d2106a6c4"
+dependencies = [
+ "approx",
+ "libm",
+]
+
+[[package]]
+name = "glamx"
+version = "0.3.1"
+dependencies = [
+ "approx",
+ "glam",
+ "nalgebra",
+ "num-traits",
+ "simba",
+]
+
+[[package]]
+name = "hash32"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606"
+dependencies = [
+ "byteorder",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "heapless"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
+dependencies = [
+ "hash32",
+ "stable_deref_trait",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
+
+[[package]]
+name = "libm"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+
+[[package]]
+name = "log"
+version = "0.4.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "nalgebra"
+version = "0.35.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "adc43a60c217b0c6ff46e47f26911015ad8d2e5a8be1af668c67e370d99a4346"
+dependencies = [
+ "approx",
+ "glam",
+ "nalgebra-macros",
+ "num-complex",
+ "num-rational",
+ "num-traits",
+ "simba",
+ "typenum",
+]
+
+[[package]]
+name = "nalgebra-macros"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "973e7178a678cfd059ccec50887658d482ce16b0aa9da3888ddeab5cd5eb4889"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "num-complex"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-derive"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4e98dc3b890f6c23a0f9d3d491a2823d0dea0fa656302a13dd225fa924112a8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.10",
+]
+
+[[package]]
+name = "num-integer"
+version = "0.1.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-rational"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+ "libm",
+]
+
+[[package]]
+name = "ordered-float"
+version = "5.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "parry3d"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b626edc0b497dba4bdf6e1e0797895294ed9f61dac2bd28cb5d34d37ad2ca7e"
+dependencies = [
+ "approx",
+ "arrayvec",
+ "bitflags",
+ "downcast-rs",
+ "either",
+ "foldhash",
+ "glamx",
+ "hashbrown",
+ "indexmap",
+ "log",
+ "num-derive",
+ "num-traits",
+ "ordered-float",
+ "rstar",
+ "simba",
+ "smallvec",
+ "static_assertions",
+ "thiserror",
+]
+
+[[package]]
+name = "physics-core"
+version = "0.1.0"
+dependencies = [
+ "libm",
+ "num-traits",
+ "rapier3d",
+ "serde_json",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "profiling"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
+dependencies = [
+ "profiling-procmacros",
+]
+
+[[package]]
+name = "profiling-procmacros"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "rapier3d"
+version = "0.36.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "033e2edc815d61ab97bd74ed5d1cbea5ebe575218774a7cfedbd3551f0033317"
+dependencies = [
+ "approx",
+ "arrayvec",
+ "bitflags",
+ "glamx",
+ "log",
+ "nalgebra",
+ "num-traits",
+ "parry3d",
+ "profiling",
+ "serde",
+ "simba",
+ "static_assertions",
+ "thiserror",
+ "wide",
+]
+
+[[package]]
+name = "rstar"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "90e7279515baf3838062fa9c495a408bc2f3abbf9cd2ac8c2d4108b90fa29b89"
+dependencies = [
+ "heapless",
+ "num-traits",
+ "smallvec",
+]
+
+[[package]]
+name = "safe_arch"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42c6efa15875e6ecb39ca61fb0b0c1a40b84fac5a5ffe71eef7d1000c8eb3f5f"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.10",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.154"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "simba"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1a7200d82ff1c7b4235efd12f11e2537a402c91cf83a5cb97ce80eef787fde7"
+dependencies = [
+ "approx",
+ "libm",
+ "num-complex",
+ "num-traits",
+ "wide",
+]
+
+[[package]]
+name = "smallvec"
+version = "1.16.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.10",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "wide"
+version = "1.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d920ac99c3c8edce110cb8d07dbb324d6d026011dce85b1e9355b70f0adacc4f"
+dependencies = [
+ "bytemuck",
+ "safe_arch",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/renderer/physics-core/Cargo.toml b/renderer/physics-core/Cargo.toml
new file mode 100644
index 0000000..f61686e
--- /dev/null
+++ b/renderer/physics-core/Cargo.toml
@@ -0,0 +1,49 @@
+[package]
+name = "physics-core"
+version = "0.1.0"
+edition = "2021"
+description = "ThreeRT's physics: rigid bodies, colliders, joints, contact events and scene queries on Rapier, stepped at a fixed tick. No GPU, file system or threads: it builds for wasm32 (players run the game in the browser)."
+license = "MIT"
+publish = false
+
+[features]
+default = ["enhanced-determinism"]
+# Rapier's cross-platform determinism (software math functions instead of the platform's): the same bits natively and
+# in wasm32. On by default: without it the two differ (docs/ROADMAP.md § 6 step 7, with what it costs; build with
+# --no-default-features to compare).
+enhanced-determinism = ["rapier3d/enhanced-determinism"]
+# For the determinism check only (tools/physics-determinism.ts): puts `std` into the crate graph the way a larger
+# program's other dependencies do (the renderer's turn on `num-traits/std`), which is what brought the platform's math
+# functions into Rapier's crates (third_party/glamx/PATCH.md). The bits must be the same with it.
+std-in-graph = ["dep:num-traits"]
+
+[dependencies]
+# Without Rapier's `std` (`alloc` is all it needs here), on purpose: with `std`, Rapier, parry and glamx call f32's own
+# sin / cos / acos / asin, the platform's, whatever `enhanced-determinism` says (it only reroutes the calls made
+# through simba and glam). Without it those calls go through simba, so through libm on every platform. The first to
+# differ was the eigen decomposition behind the mass properties of convex hulls and of bodies of several colliders
+# (glamx's eigen3.rs): 48 of 1,000 random worlds ended in other bits natively than in wasm32. `check::cases` and
+# tools/physics-determinism.ts hold it; a per-tick cost was not measurable.
+rapier3d = { version = "0.36.1", default-features = false, features = ["dim3", "f32", "alloc"] }
+# The bridge's calls carry JSON.
+serde_json = "1"
+# The math functions the world itself calls (a hinge's limits, world.rs), the same bits on every platform.
+libm = "0.2"
+num-traits = { version = "0.2", features = ["std"], optional = true }
+
+# The determinism check (physics_core::check): the same script natively and as a wasm32 module (compared by
+# tools/physics-determinism.ts).
+[[example]]
+name = "determinism"
+
+[[example]]
+name = "determinism_wasm"
+crate-type = ["cdylib"]
+
+# glamx with its eigen decomposition's acos / cos called through simba (libm on every platform): the physics' bits must
+# not depend on the platform's math functions (third_party/glamx/PATCH.md).
+# NOTE: this table only works when physics-core itself is what cargo builds. A crate that depends on physics-core must
+# repeat it in its own manifest (the renderer's does), or it silently gets crates.io's glamx; and it needs a test that
+# steps `check::script` and `check::cases` to the recorded hashes, which is what shows a patch left out (PATCH.md).
+[patch.crates-io]
+glamx = { path = "../third_party/glamx" }
diff --git a/renderer/physics-core/examples/determinism.rs b/renderer/physics-core/examples/determinism.rs
new file mode 100644
index 0000000..f8eac0f
--- /dev/null
+++ b/renderer/physics-core/examples/determinism.rs
@@ -0,0 +1,33 @@
+//! Prints the hash the determinism script leaves after 600 ticks (physics_core::check), natively.
+//! examples/determinism_wasm.rs gives the hash in wasm32 (tools/physics-determinism.ts compares them).
+//! `--cases`: the hash of every random case of physics_core::check instead (hulls, bodies of several colliders, joints).
+//! `--bench`: times it instead (the best and the median of 30 runs of the script, and of `check::pile(1000)`: a
+//! thousand boxes dropped in a heap, 300 ticks), ms per tick.
+fn main() {
+ if std::env::args().any(|a| a == "--bench") {
+ let time = |f: &dyn Fn() -> u64, ticks: f64| {
+ let mut ms: Vec<f64> = (0..30)
+ .map(|_| {
+ let t = std::time::Instant::now();
+ std::hint::black_box(f());
+ t.elapsed().as_secs_f64() * 1e3 / ticks
+ })
+ .collect();
+ ms.sort_by(|a, b| a.total_cmp(b));
+ (ms[0], ms[15])
+ };
+ let (s, p) = (time(&|| physics_core::check::script(600), 600.0), time(&|| physics_core::check::pile(1000, 300), 300.0));
+ println!("script: best {:.4} median {:.4} ms/tick; pile of 1000: best {:.3} median {:.3} ms/tick", s.0, s.1, p.0, p.1);
+ return;
+ }
+ // `--cases`: every random case's hash, a line each ("kind seed hash").
+ if std::env::args().any(|a| a == "--cases") {
+ for (kind, &(_, n)) in physics_core::check::KINDS.iter().enumerate() {
+ for seed in 0..n {
+ println!("{kind} {seed} {:016x}", physics_core::check::case(kind as u32, seed));
+ }
+ }
+ return;
+ }
+ println!("{:016x}", physics_core::check::script(600));
+}
diff --git a/renderer/physics-core/examples/determinism_wasm.rs b/renderer/physics-core/examples/determinism_wasm.rs
new file mode 100644
index 0000000..3e04981
--- /dev/null
+++ b/renderer/physics-core/examples/determinism_wasm.rs
@@ -0,0 +1,12 @@
+//! The determinism script's hash (physics_core::check) as a wasm32 module's export: the same code as the native
+//! examples/determinism.rs, built for `wasm32-unknown-unknown` and run by Node (tools/physics-determinism.ts).
+#[no_mangle]
+pub extern "C" fn physics_determinism(ticks: u32) -> u64 {
+ physics_core::check::script(ticks)
+}
+
+/// One random case's hash (physics_core::check::case).
+#[no_mangle]
+pub extern "C" fn physics_determinism_case(kind: u32, seed: u32) -> u64 {
+ physics_core::check::case(kind, seed)
+}
diff --git a/renderer/physics-core/src/bridge.rs b/renderer/physics-core/src/bridge.rs
new file mode 100644
index 0000000..c8d4d40
--- /dev/null
+++ b/renderer/physics-core/src/bridge.rs
@@ -0,0 +1,935 @@
+//! Between scene code and the world (ROADMAP § 6 step 7): the calls a game's binding makes (bodies, colliders, joints,
+//! impulses, forces, queries, contacts; JSON in, JSON out), and the scene objects the bodies drive. The engine owns a
+//! `Bridge`, steps it at the fixed tick and lets it place the objects of the bodies that moved; scene code never steps
+//! it and never sees the world. The scene is whatever implements `Scene` (the renderer's world natively; the browser's
+//! the same way), so this layer has no GPU, file system, clock or thread in it either: it builds for wasm32.
+//!
+//! Ids of bodies, colliders and joints are the caller's (the binding chooses them, as it does for geometries and
+//! objects), so creating one needs no answer. A body that drives an object may take a `slot`: `poses()` is then the
+//! table of every such object's position and rotation as the last sync left them, one copy for a whole frame's reads.
+
+use crate::{limits, BodyDesc, BodyId, BodyKind, ColliderDesc, ColliderId, Hit, JointDesc, JointId, Limits, Motor, Physics, Shape, TICK};
+use serde_json::{json, Value};
+use std::collections::BTreeMap;
+
+/// The most a session may hold (game code is untrusted), and the most ticks one frame makes up.
+pub const MAX_BODIES: usize = 20_000;
+pub const MAX_COLLIDERS: usize = 40_000;
+pub const MAX_JOINTS: usize = 40_000;
+pub const MAX_MESH_VERTICES: usize = 1 << 20;
+pub const MAX_HULL_POINTS: usize = 4096;
+pub const MAX_TICKS: u32 = 5;
+/// The most hits one ray reports.
+pub const MAX_HITS: usize = 256;
+/// Floats a slot of `poses()` holds: position xyz, rotation xyzw.
+pub const POSE: usize = 7;
+
+/// The scene whose objects bodies drive, by the engine's object and geometry ids.
+pub trait Scene {
+ /// An object's position and rotation (xyzw) in the world; None if there is no such object.
+ fn world_pose(&self, object: u32) -> Option<([f32; 3], [f32; 4])>;
+ /// Places an object at a pose of the world, its scale kept. Returns the position and rotation it has for scene code
+ /// (in its parent's space); None if the object is gone.
+ fn place(&mut self, object: u32, position: [f32; 3], rotation: [f32; 4]) -> Option<([f32; 3], [f32; 4])>;
+ /// A body moves the object from now on (the renderer keeps such an object apart, so a move is cheap).
+ fn drive(&mut self, object: u32);
+ /// A geometry's positions (three numbers a vertex) and triangle indices.
+ fn geometry(&self, id: u32) -> Option<(&[f32], &[u32])>;
+}
+
+pub struct Bridge {
+ core: Physics,
+ /// Caller id -> the world's, and back for what queries and contacts report.
+ bodies: BTreeMap<u32, BodyId>,
+ body_ids: BTreeMap<BodyId, u32>,
+ colliders: BTreeMap<u32, ColliderId>,
+ /// The world's collider -> the caller's id of it and of its body.
+ collider_ids: BTreeMap<ColliderId, (u32, Option<u32>)>,
+ joints: BTreeMap<u32, JointId>,
+ /// Body (the world's id) -> the scene object it drives and its slot in `poses`.
+ drives: BTreeMap<BodyId, (u32, Option<u32>)>,
+ /// The objects that have a body and the slots that are taken (an object has one body, a slot one object).
+ driven: std::collections::BTreeSet<u32>,
+ slots: std::collections::BTreeSet<u32>,
+ /// `POSE` floats a slot: the driven objects' poses as scene code reads them.
+ poses: Vec<f32>,
+ /// Bodies awake after any tick since the last sync, and those awake at the last sync (one that fell asleep in the
+ /// first tick after it still moved in that tick).
+ moved: Vec<BodyId>,
+ awake: Vec<BodyId>,
+ /// Bodies with forces: cleared once a frame's ticks are done.
+ forced: Vec<BodyId>,
+ /// A tick was made since the last sync.
+ ticked: bool,
+ /// Time not yet stepped, s.
+ behind: f64,
+ /// Bodies the world took out after a tick (`Physics::step`), by the caller's id, with the object they drove,
+ /// whether they left the world (or went non-finite) and why: those not yet reported by "faults", and (for
+ /// "state") the last `MAX_FAULTS` of them.
+ faults: Vec<(u32, Option<u32>, bool, &'static str)>,
+ faulted: BTreeMap<u32, &'static str>,
+}
+
+/// The most faults "faults" holds until it is called, and "state" remembers.
+pub const MAX_FAULTS: usize = 1024;
+
+fn nums<const N: usize>(v: &Value) -> Option<[f32; N]> {
+ let a = v.as_array().filter(|a| a.len() == N)?;
+ let mut out = [0.0f32; N];
+ for (o, x) in out.iter_mut().zip(a) {
+ *o = x.as_f64().filter(|x| x.is_finite())? as f32;
+ }
+ Some(out)
+}
+
+fn vec3(a: &Value, key: &str, default: [f32; 3]) -> Result<[f32; 3], String> {
+ match &a[key] {
+ Value::Null => Ok(default),
+ v => nums::<3>(v).ok_or_else(|| format!("physics: {key} must be three finite numbers")),
+ }
+}
+
+fn quat(a: &Value, key: &str) -> Result<[f32; 4], String> {
+ match &a[key] {
+ Value::Null => Ok([0.0, 0.0, 0.0, 1.0]),
+ v => nums::<4>(v).ok_or_else(|| format!("physics: {key} must be a quaternion (x, y, z, w)")),
+ }
+}
+
+fn num(a: &Value, key: &str, default: f32) -> Result<f32, String> {
+ match &a[key] {
+ Value::Null => Ok(default),
+ v => v.as_f64().filter(|x| x.is_finite()).map(|x| x as f32).ok_or_else(|| format!("physics: {key} must be a finite number")),
+ }
+}
+
+fn id(a: &Value, key: &str) -> Result<u32, String> {
+ a[key].as_u64().filter(|&x| x <= u32::MAX as u64).map(|x| x as u32).ok_or_else(|| format!("physics: {key} must be an id"))
+}
+
+fn opt_id(a: &Value, key: &str) -> Result<Option<u32>, String> {
+ if a[key].is_null() {
+ Ok(None)
+ } else {
+ id(a, key).map(Some)
+ }
+}
+
+impl Default for Bridge {
+ fn default() -> Self {
+ Bridge {
+ core: Physics::default(),
+ bodies: BTreeMap::new(),
+ body_ids: BTreeMap::new(),
+ colliders: BTreeMap::new(),
+ collider_ids: BTreeMap::new(),
+ joints: BTreeMap::new(),
+ drives: BTreeMap::new(),
+ driven: Default::default(),
+ slots: Default::default(),
+ poses: vec![],
+ moved: vec![],
+ awake: vec![],
+ forced: vec![],
+ ticked: false,
+ behind: 0.0,
+ faults: vec![],
+ faulted: BTreeMap::new(),
+ }
+ }
+}
+
+impl Bridge {
+ /// A shape from its description: `{type: "box", halfExtents}`, `{type: "sphere", radius}`, `{type: "capsule",
+ /// halfHeight, radius}` (along y), `{type: "convexHull", points: [x, y, z, ...]}`, `{type: "trimesh", vertices: [...],
+ /// indices: [...]}`; or the last two from a geometry the scene holds: `{type: "convexHull" | "trimesh", geometry: id,
+ /// scale?: [x, y, z]}`.
+ fn shape(scene: &impl Scene, s: &Value) -> Result<Shape, String> {
+ let floats = |key: &str| -> Result<Vec<[f32; 3]>, String> {
+ let a = s[key].as_array().filter(|a| a.len() % 3 == 0 && a.len() / 3 <= MAX_MESH_VERTICES).ok_or_else(|| format!("physics: shape {key} must be numbers, three a point, at most {MAX_MESH_VERTICES} points"))?;
+ a.chunks(3).map(|c| nums::<3>(&Value::Array(c.to_vec())).ok_or_else(|| format!("physics: shape {key} must be finite numbers"))).collect()
+ };
+ let geometry = |hull: bool| -> Result<(Vec<[f32; 3]>, Vec<[u32; 3]>), String> {
+ let gid = id(s, "geometry")?;
+ let (positions, indices) = scene.geometry(gid).ok_or_else(|| format!("physics: unknown geometry {gid}"))?;
+ let k = vec3(s, "scale", [1.0; 3])?;
+ if positions.len() / 3 > MAX_MESH_VERTICES || (!hull && indices.len() / 3 > limits::MAX_MESH_TRIANGLES) {
+ return Err(format!("physics: geometry {gid} has more than {MAX_MESH_VERTICES} vertices or {} triangles", limits::MAX_MESH_TRIANGLES));
+ }
+ let mut points: Vec<[f32; 3]> = positions.chunks_exact(3).map(|p| [p[0] * k[0], p[1] * k[1], p[2] * k[2]]).collect();
+ if hull && points.len() > MAX_HULL_POINTS {
+ // Every n-th vertex: a hull of a dense mesh needs few of them.
+ let step = points.len().div_ceil(MAX_HULL_POINTS);
+ points = points.into_iter().step_by(step).collect();
+ }
+ Ok((points, indices.chunks_exact(3).map(|t| [t[0], t[1], t[2]]).collect()))
+ };
+ Ok(match s["type"].as_str() {
+ Some("box") => Shape::Box(nums::<3>(&s["halfExtents"]).ok_or("physics: a box needs halfExtents [x, y, z]")?),
+ Some("sphere") => Shape::Sphere(num(s, "radius", f32::NAN)?),
+ Some("capsule") => Shape::Capsule { half_height: num(s, "halfHeight", f32::NAN)?, radius: num(s, "radius", f32::NAN)? },
+ Some("convexHull") if !s["geometry"].is_null() => Shape::ConvexHull(geometry(true)?.0),
+ Some("convexHull") => {
+ let p = floats("points")?;
+ if p.len() > MAX_HULL_POINTS {
+ return Err(format!("physics: a convex hull takes at most {MAX_HULL_POINTS} points"));
+ }
+ Shape::ConvexHull(p)
+ }
+ Some("trimesh") if !s["geometry"].is_null() => {
+ let (vertices, indices) = geometry(false)?;
+ Shape::Trimesh { vertices, indices }
+ }
+ Some("trimesh") => {
+ let vertices = floats("vertices")?;
+ let idx = s["indices"].as_array().filter(|a| a.len() % 3 == 0 && a.len() / 3 <= limits::MAX_MESH_TRIANGLES).ok_or_else(|| format!("physics: a trimesh needs indices, three a triangle, at most {} triangles", limits::MAX_MESH_TRIANGLES))?;
+ // (An index past u32 is refused, not cut: 4294967296 is not vertex 0.)
+ let index = |x: &Value| x.as_u64().filter(|&i| i <= u32::MAX as u64).map(|i| i as u32);
+ let indices = idx.chunks(3).map(|t| Some([index(&t[0])?, index(&t[1])?, index(&t[2])?])).collect::<Option<Vec<_>>>().ok_or("physics: trimesh indices must be whole numbers below 2^32")?;
+ Shape::Trimesh { vertices, indices }
+ }
+ other => return Err(format!("physics: shape type {other:?} is none of box, sphere, capsule, convexHull, trimesh")),
+ })
+ }
+
+ /// One call from scene code. Returns its answer (a state, hits, contacts) as JSON; null for a command.
+ pub fn call(&mut self, scene: &mut impl Scene, op: &str, a: &Value) -> Result<Value, String> {
+ Ok(match op {
+ "gravity" => {
+ self.core.set_gravity(vec3(a, "gravity", [0.0, -9.81, 0.0])?)?;
+ Value::Null
+ }
+ // {id, kind, object?, slot?, position?, rotation?, linvel?, angvel?, linearDamping?, angularDamping?,
+ // gravityScale?, canSleep?, ccd?}: a body; with `object`, it drives that scene object (and starts where it
+ // is, unless a position is given), and with `slot` the object's pose is in `poses()` there.
+ "body" => {
+ if self.core.bodies() >= MAX_BODIES {
+ return Err(format!("physics: more than {MAX_BODIES} bodies"));
+ }
+ let bid = id(a, "id")?;
+ if self.bodies.contains_key(&bid) {
+ return Err(format!("physics: body {bid} exists"));
+ }
+ let kind = match a["kind"].as_str() {
+ None | Some("dynamic") => BodyKind::Dynamic,
+ Some("fixed") => BodyKind::Fixed,
+ Some("kinematic") => BodyKind::Kinematic,
+ Some(other) => return Err(format!("physics: body kind \"{other}\" is none of dynamic, fixed, kinematic")),
+ };
+ let object = opt_id(a, "object")?;
+ let slot = opt_id(a, "slot")?;
+ let (mut position, mut rotation) = ([0.0; 3], [0.0, 0.0, 0.0, 1.0]);
+ if let Some(o) = object {
+ (position, rotation) = scene.world_pose(o).ok_or_else(|| format!("physics: unknown object {o}"))?;
+ if self.driven.contains(&o) {
+ return Err(format!("physics: object {o} already has a body"));
+ }
+ }
+ if let Some(s) = slot {
+ if object.is_none() || s as usize >= MAX_BODIES || self.slots.contains(&s) {
+ return Err(format!("physics: slot {s} is taken, past {MAX_BODIES}, or of a body without an object"));
+ }
+ }
+ let d = BodyDesc {
+ kind,
+ position: vec3(a, "position", position)?,
+ rotation: if a["rotation"].is_null() { rotation } else { quat(a, "rotation")? },
+ linvel: vec3(a, "linvel", [0.0; 3])?,
+ angvel: vec3(a, "angvel", [0.0; 3])?,
+ linear_damping: num(a, "linearDamping", 0.0)?,
+ angular_damping: num(a, "angularDamping", 0.0)?,
+ gravity_scale: num(a, "gravityScale", 1.0)?,
+ can_sleep: a["canSleep"].as_bool().unwrap_or(true),
+ ccd: a["ccd"].as_bool().unwrap_or(false),
+ };
+ let b = self.core.add_body(&d)?;
+ self.bodies.insert(bid, b);
+ self.body_ids.insert(b, bid);
+ self.faulted.remove(&bid);
+ if let Some(o) = object {
+ if kind != BodyKind::Fixed {
+ scene.drive(o);
+ }
+ self.drives.insert(b, (o, slot));
+ self.driven.insert(o);
+ if let Some(s) = slot {
+ self.slots.insert(s);
+ let end = (s as usize + 1) * POSE;
+ if self.poses.len() < end {
+ self.poses.resize(end, 0.0);
+ }
+ }
+ // (Where the body is: its rotation normalized, as the world keeps it.)
+ self.place_at_body(scene, b);
+ }
+ Value::Null
+ }
+ // {id, body?, shape, position?, rotation?, density? | mass?, friction?, restitution?, sensor?, events?}: a
+ // collider on a body, or a static one in the world.
+ "collider" => {
+ if self.colliders.len() >= MAX_COLLIDERS {
+ return Err(format!("physics: more than {MAX_COLLIDERS} colliders"));
+ }
+ let cid = id(a, "id")?;
+ if self.colliders.contains_key(&cid) {
+ return Err(format!("physics: collider {cid} exists"));
+ }
+ let owner = opt_id(a, "body")?;
+ let body = match owner {
+ Some(b) => Some(*self.bodies.get(&b).ok_or_else(|| format!("physics: unknown body {b}"))?),
+ None => None,
+ };
+ let d = ColliderDesc {
+ shape: Self::shape(scene, &a["shape"])?,
+ position: vec3(a, "position", [0.0; 3])?,
+ rotation: quat(a, "rotation")?,
+ density: num(a, "density", 1000.0)?,
+ mass: if a["mass"].is_null() { None } else { Some(num(a, "mass", 0.0)?) },
+ friction: num(a, "friction", 0.5)?,
+ restitution: num(a, "restitution", 0.0)?,
+ sensor: a["sensor"].as_bool().unwrap_or(false),
+ events: a["events"].as_bool().unwrap_or(false),
+ };
+ let c = self.core.add_collider(body, &d)?;
+ self.colliders.insert(cid, c);
+ self.collider_ids.insert(c, (cid, owner));
+ Value::Null
+ }
+ // {id, a, b, type, anchor1?, anchor2?, axis?, limits?: [min, max], motor?: {velocity, damping, maxForce},
+ // length?}: a joint between two bodies.
+ "joint" => {
+ if self.joints.len() >= MAX_JOINTS {
+ return Err(format!("physics: more than {MAX_JOINTS} joints"));
+ }
+ let jid = id(a, "id")?;
+ if self.joints.contains_key(&jid) {
+ return Err(format!("physics: joint {jid} exists"));
+ }
+ let (anchor1, anchor2) = (vec3(a, "anchor1", [0.0; 3])?, vec3(a, "anchor2", [0.0; 3])?);
+ let limits = match &a["limits"] {
+ Value::Null => None,
+ v => Some(nums::<2>(v).map(|l| Limits { min: l[0], max: l[1] }).ok_or("physics: limits must be [min, max]")?),
+ };
+ let motor = match &a["motor"] {
+ Value::Null => None,
+ m => Some(Motor { velocity: num(m, "velocity", 0.0)?, damping: num(m, "damping", 1e4)?, max_force: num(m, "maxForce", f32::MAX)? }),
+ };
+ let d = match a["type"].as_str() {
+ Some("fixed") => JointDesc::Fixed { anchor1, anchor2 },
+ Some("revolute") => JointDesc::Revolute { anchor1, anchor2, axis: vec3(a, "axis", [0.0, 1.0, 0.0])?, limits, motor },
+ Some("prismatic") => JointDesc::Prismatic { anchor1, anchor2, axis: vec3(a, "axis", [1.0, 0.0, 0.0])?, limits, motor },
+ Some("spherical") => JointDesc::Spherical { anchor1, anchor2 },
+ Some("rope") => JointDesc::Rope { anchor1, anchor2, length: num(a, "length", f32::NAN)? },
+ other => return Err(format!("physics: joint type {other:?} is none of fixed, revolute, prismatic, spherical, rope")),
+ };
+ let (ba, bb) = (self.body(a, "a")?, self.body(a, "b")?);
+ let j = self.core.add_joint(ba, bb, &d)?;
+ self.joints.insert(jid, j);
+ Value::Null
+ }
+ "remove" => {
+ // (All three read before any is removed: a call that is refused changes nothing.)
+ let (body, collider, joint) = (opt_id(a, "body")?, opt_id(a, "collider")?, opt_id(a, "joint")?);
+ if let Some(b) = body.and_then(|b| self.bodies.get(&b).copied()) {
+ self.forget_body(b);
+ }
+ if let Some(c) = collider.and_then(|c| self.colliders.remove(&c)) {
+ self.core.remove_collider(c);
+ self.collider_ids.remove(&c);
+ }
+ if let Some(j) = joint.and_then(|j| self.joints.remove(&j)) {
+ self.core.remove_joint(j);
+ }
+ Value::Null
+ }
+ // {body, impulse?, point?, torque?}: an impulse at the centre of mass, or at a point of the world; an angular
+ // one.
+ "impulse" => {
+ let b = self.body(a, "body")?;
+ let (j, t) = (vec3(a, "impulse", [0.0; 3])?, vec3(a, "torque", [0.0; 3])?);
+ if a["point"].is_null() {
+ self.core.apply_impulse(b, j, t)?;
+ } else {
+ self.core.apply_impulse_at(b, j, vec3(a, "point", [0.0; 3])?, t)?;
+ }
+ Value::Null
+ }
+ // {body, force?, torque?}: a force and a torque through the ticks of this frame (until the next `sync`).
+ "force" => {
+ let b = self.body(a, "body")?;
+ self.core.add_force(b, vec3(a, "force", [0.0; 3])?, vec3(a, "torque", [0.0; 3])?)?;
+ if !self.forced.contains(&b) {
+ self.forced.push(b);
+ }
+ Value::Null
+ }
+ // {body, linvel?, angvel?}: either velocity set, the other kept.
+ "velocity" => {
+ let b = self.body(a, "body")?;
+ let opt = |key: &str| -> Result<Option<[f32; 3]>, String> { if a[key].is_null() { Ok(None) } else { vec3(a, key, [0.0; 3]).map(Some) } };
+ self.core.set_velocity(b, opt("linvel")?, opt("angvel")?)?;
+ Value::Null
+ }
+ "pose" => {
+ let b = self.body(a, "body")?;
+ let (p, q) = (vec3(a, "position", [0.0; 3])?, quat(a, "rotation")?);
+ self.core.set_pose(b, p, q)?;
+ self.place_at_body(scene, b);
+ Value::Null
+ }
+ // Where a kinematic body is after the next tick.
+ "target" => {
+ self.core.set_kinematic_target(self.body(a, "body")?, vec3(a, "position", [0.0; 3])?, quat(a, "rotation")?)?;
+ Value::Null
+ }
+ // {body}: scene code moved the body's object. The body goes where the object is: at once (its velocity
+ // kept), or, a kinematic one, through the next tick, pushing what is in its way.
+ "follow" => {
+ let b = self.body(a, "body")?;
+ if let Some((p, q)) = self.drives.get(&b).and_then(|&(o, _)| scene.world_pose(o)) {
+ if self.core.is_kinematic(b) {
+ self.core.set_kinematic_target(b, p, q)?;
+ self.note_pose(scene, b);
+ } else {
+ self.core.set_pose(b, p, q)?;
+ self.place_at_body(scene, b);
+ }
+ }
+ Value::Null
+ }
+ // {body}: its pose, velocities, sleeping and mass; for a body the world took out after a tick, {removed: why}.
+ "state" => {
+ if let Some(why) = id(a, "body").ok().filter(|b| !self.bodies.contains_key(b)).and_then(|b| self.faulted.get(&b)) {
+ return Ok(json!({ "removed": why }));
+ }
+ let b = self.body(a, "body")?;
+ match (self.core.pose(b), self.core.velocity(b)) {
+ (Some((p, q)), Some((v, av))) => json!({ "position": p, "rotation": q, "linvel": v, "angvel": av, "sleeping": self.core.sleeping(b), "mass": self.core.mass(b) }),
+ _ => Value::Null,
+ }
+ }
+ // Queries, against the world as of the last tick. {origin, direction, max?, skip?, all?}: the first hit (or
+ // null), or with `all` every hit, nearest first.
+ "ray" => {
+ let (o, d, max, skip) = (vec3(a, "origin", [0.0; 3])?, vec3(a, "direction", [0.0; 3])?, num(a, "max", 1e4)?, self.skip(a)?);
+ if a["all"].as_bool().unwrap_or(false) {
+ Value::Array(self.core.cast_ray_all(o, d, max, skip, MAX_HITS)?.into_iter().map(|h| self.hit(Some(h))).collect())
+ } else {
+ self.hit(self.core.cast_ray(o, d, max, skip)?)
+ }
+ }
+ // The colliders a shape overlaps: [{collider, body, object}].
+ "overlap" => {
+ let s = Self::shape(scene, &a["shape"])?;
+ let hits = self.core.overlap(&s, vec3(a, "position", [0.0; 3])?, quat(a, "rotation")?, self.skip(a)?)?;
+ Value::Array(hits.iter().filter_map(|c| self.collider_ids.get(c)).map(|&(c, b)| json!({ "collider": c, "body": b, "object": self.object_of(b) })).collect())
+ }
+ "sweep" => {
+ let s = Self::shape(scene, &a["shape"])?;
+ let h = self.core.sweep(&s, vec3(a, "position", [0.0; 3])?, quat(a, "rotation")?, vec3(a, "direction", [0.0; 3])?, num(a, "max", 1e4)?, self.skip(a)?)?;
+ self.hit(h)
+ }
+ // The contacts begun and ended since the last call (colliders with `events`), in the order they happened:
+ // [{a, b, bodyA, bodyB, started}].
+ "contacts" => Value::Array(
+ self.core
+ .take_contacts()
+ .into_iter()
+ .filter_map(|c| {
+ let (&(a, ba), &(b, bb)) = (self.collider_ids.get(&c.a)?, self.collider_ids.get(&c.b)?);
+ Some(if a <= b { json!({ "a": a, "b": b, "bodyA": ba, "bodyB": bb, "started": c.started }) } else { json!({ "a": b, "b": a, "bodyA": bb, "bodyB": ba, "started": c.started }) })
+ })
+ .collect(),
+ ),
+ // The world's hash and ticks (16 hex digits): the same calls at the same ticks give the same one.
+ "hash" => json!({ "hash": format!("{:016x}", self.core.hash()), "ticks": self.core.ticks(), "bodies": self.core.bodies(), "contactsDropped": self.core.contacts_dropped() }),
+ // The bodies the world took out after a tick since the last call (`Physics::step`), with the object each
+ // drove and why: [{body, object, kind, reason}]. `kind` is "leftWorld" for a body past the world's edge (it
+ // fell off the level: nothing is wrong) and "nonFinite" for one whose pose, velocity or shape went
+ // non-finite (an error). Their colliders and joints went with them; "state" on one answers {removed: why}.
+ "faults" => Value::Array(std::mem::take(&mut self.faults).into_iter().map(|(b, o, left, why)| json!({ "body": b, "object": o, "kind": if left { "leftWorld" } else { "nonFinite" }, "reason": why })).collect()),
+ other => return Err(format!("physics: unknown call \"{other}\"")),
+ })
+ }
+
+ /// The world's body of the caller's id in `a[key]`.
+ fn body(&self, a: &Value, key: &str) -> Result<BodyId, String> {
+ let b = id(a, key)?;
+ self.bodies.get(&b).copied().ok_or_else(|| format!("physics: unknown body {b}"))
+ }
+
+ /// A query's `skip`: the body whose colliders it passes through.
+ fn skip(&self, a: &Value) -> Result<Option<BodyId>, String> {
+ Ok(opt_id(a, "skip")?.and_then(|b| self.bodies.get(&b).copied()))
+ }
+
+ /// The scene object the body of caller id `b` drives.
+ fn object_of(&self, b: Option<u32>) -> Option<u32> {
+ self.drives.get(self.bodies.get(&b?)?).map(|d| d.0)
+ }
+
+ /// Removes a body (the world's id) with its colliders and joints, and their ids.
+ fn forget_body(&mut self, b: BodyId) {
+ let gone = self.core.remove_body(b);
+ self.forget_ids(b, &gone);
+ }
+
+ /// Forgets the ids of a body the world no longer has (the world's id), of the colliders that went with it and of
+ /// its joints.
+ fn forget_ids(&mut self, b: BodyId, colliders: &[ColliderId]) {
+ for c in colliders {
+ if let Some((id, _)) = self.collider_ids.remove(c) {
+ self.colliders.remove(&id);
+ }
+ }
+ if let Some((o, slot)) = self.drives.remove(&b) {
+ self.driven.remove(&o);
+ if let Some(s) = slot {
+ self.slots.remove(&s);
+ }
+ }
+ if let Some(id) = self.body_ids.remove(&b) {
+ self.bodies.remove(&id);
+ }
+ // (Its joints went with it: those the world no longer has.)
+ if !self.joints.is_empty() {
+ let core = &self.core;
+ self.joints.retain(|_, j| core.has_joint(*j));
+ }
+ }
+
+ fn hit(&self, h: Option<Hit>) -> Value {
+ match h {
+ Some(h) => json!({
+ "collider": self.collider_ids.get(&h.collider).map(|c| c.0), "body": h.body.and_then(|b| self.body_ids.get(&b)), "object": h.body.and_then(|b| self.drives.get(&b)).map(|d| d.0),
+ "distance": h.distance, "point": h.point, "normal": h.normal,
+ }),
+ None => Value::Null,
+ }
+ }
+
+ /// The object body `b` drives, placed at the body's pose, and its slot of `poses` written. False if the object is
+ /// gone (the body goes with it).
+ fn place(&mut self, scene: &mut impl Scene, b: BodyId, position: [f32; 3], rotation: [f32; 4]) -> bool {
+ let Some(&(o, slot)) = self.drives.get(&b) else { return true };
+ let Some((p, q)) = scene.place(o, position, rotation) else {
+ self.forget_body(b);
+ return false;
+ };
+ if let Some(s) = slot {
+ let at = s as usize * POSE;
+ self.poses[at..at + 3].copy_from_slice(&p);
+ self.poses[at + 3..at + POSE].copy_from_slice(&q);
+ }
+ true
+ }
+
+ /// The object body `b` drives placed where the body is (`place`).
+ fn place_at_body(&mut self, scene: &mut impl Scene, b: BodyId) {
+ if let Some((p, q)) = self.core.pose(b) {
+ self.place(scene, b, p, q);
+ }
+ }
+
+ /// The scene removed these objects: the bodies that drove them go too (an awake body would find out when it next
+ /// placed its object; a sleeping one never would, and the object's id may be used again).
+ pub fn objects_removed(&mut self, objects: &[u32]) {
+ if self.driven.is_empty() {
+ return;
+ }
+ let doomed: Vec<BodyId> = objects.iter().filter(|o| self.driven.contains(o)).filter_map(|o| self.drives.iter().find(|(_, d)| d.0 == *o).map(|(&b, _)| b)).collect();
+ for b in doomed {
+ self.forget_body(b);
+ }
+ }
+
+ /// A kinematic body's object was moved by scene code: its slot of `poses` is where the object is now.
+ fn note_pose(&mut self, scene: &mut impl Scene, b: BodyId) {
+ if let Some(&(o, Some(s))) = self.drives.get(&b) {
+ if let Some((p, q)) = scene.world_pose(o).and_then(|(p, q)| scene.place(o, p, q)) {
+ let at = s as usize * POSE;
+ self.poses[at..at + 3].copy_from_slice(&p);
+ self.poses[at + 3..at + POSE].copy_from_slice(&q);
+ }
+ }
+ }
+
+ /// The driven objects' poses by slot (`POSE` floats each: position, rotation xyzw, in the object's parent's space),
+ /// as of the last sync. A slot no body holds keeps what it had.
+ pub fn poses(&self) -> &[f32] {
+ &self.poses
+ }
+
+ /// One tick.
+ pub fn tick(&mut self) {
+ self.core.step();
+ for f in self.core.take_faults() {
+ self.fault(f);
+ }
+ self.core.awake(&mut self.moved);
+ // (Made unique once it holds the bodies a few times over: an offline settle makes up to 36,000 ticks before
+ // its one sync, and 20,000 awake bodies would add 720 million entries.)
+ if self.moved.len() > 4 * self.core.bodies() + 1024 {
+ self.moved.sort_unstable();
+ self.moved.dedup();
+ }
+ self.ticked = true;
+ }
+
+ /// What the world took out after a tick: its ids forgotten, and the body reported ("faults", "state").
+ fn fault(&mut self, f: crate::Fault) {
+ let Some(b) = f.body else {
+ self.forget_colliders(&f.colliders);
+ return;
+ };
+ let caller = self.body_ids.get(&b).copied();
+ let object = self.drives.get(&b).map(|d| d.0);
+ self.forget_ids(b, &f.colliders);
+ let Some(caller) = caller else { return };
+ if self.faults.len() == MAX_FAULTS {
+ self.faults.remove(0);
+ }
+ self.faults.push((caller, object, f.left_world, f.reason));
+ if self.faulted.len() == MAX_FAULTS {
+ self.faulted.pop_first();
+ }
+ self.faulted.insert(caller, f.reason);
+ }
+
+ fn forget_colliders(&mut self, colliders: &[ColliderId]) {
+ for c in colliders {
+ if let Some((id, _)) = self.collider_ids.remove(c) {
+ self.colliders.remove(&id);
+ }
+ }
+ }
+
+ /// After a frame's ticks (none, at a frame rate above the tick rate): places the objects of the bodies that moved
+ /// in them, where they are now, and ends the frame's forces. Returns how many bodies moved.
+ pub fn sync(&mut self, scene: &mut impl Scene) -> usize {
+ let mut n = 0;
+ if std::mem::take(&mut self.ticked) {
+ // Those awake after any of the ticks, and those awake before the first (one that came to rest and fell
+ // asleep in a tick moved in it).
+ let mut moved = std::mem::take(&mut self.moved);
+ moved.append(&mut self.awake);
+ moved.sort_unstable();
+ moved.dedup();
+ for &b in &moved {
+ if let Some((p, q)) = self.core.pose(b) {
+ self.place(scene, b, p, q);
+ }
+ }
+ n = moved.len();
+ self.core.awake(&mut self.awake);
+ }
+ // A force lasts the ticks of the frame it was applied in: scene code applies it again every frame it acts, at
+ // any frame rate.
+ for b in std::mem::take(&mut self.forced) {
+ self.core.clear_forces(b);
+ }
+ n
+ }
+
+ /// The whole ticks a frame of `dt` seconds makes (at most `MAX_TICKS`: a longer frame slows the world down rather
+ /// than stepping without bound).
+ pub fn due(&mut self, dt: f64) -> u32 {
+ self.behind += if dt.is_finite() { dt.clamp(0.0, 0.25) } else { 0.0 };
+ // (A frame of exactly one tick is one tick, whatever its f32 rounds to.)
+ let due = ((self.behind + 1e-6) / TICK as f64).floor() as u32;
+ // (What a frame owing more than `MAX_TICKS` leaves is dropped; one owing exactly that many keeps its remainder,
+ // or a steady 12 fps would lose a fifth of its time.)
+ let ticks = due.min(MAX_TICKS);
+ self.behind = if due > MAX_TICKS { 0.0 } else { (self.behind - ticks as f64 * TICK as f64).max(0.0) };
+ ticks
+ }
+
+ /// The ticks left until the world has made `ticks` in all (an offline render at a scene time: the world as it is
+ /// after that long; at most 36,000). A world already past that makes none: it cannot go back.
+ pub fn due_until(&self, ticks: u32) -> u32 {
+ ticks.min(36_000).saturating_sub(self.core.ticks().min(u32::MAX as u64) as u32)
+ }
+
+ pub fn bodies(&self) -> usize {
+ self.core.bodies()
+ }
+
+ /// The world's hash (`Physics::hash`).
+ pub fn hash(&self) -> u64 {
+ self.core.hash()
+ }
+}
+
+#[cfg(test)]
+#[path = "robustness.rs"]
+mod robustness;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A scene of objects with a position, a rotation and maybe a parent (parents here only move, they do not turn).
+ #[derive(Default)]
+ struct Objects {
+ at: BTreeMap<u32, ([f32; 3], [f32; 4], Option<u32>)>,
+ driven: Vec<u32>,
+ geometries: BTreeMap<u32, (Vec<f32>, Vec<u32>)>,
+ placed: usize,
+ }
+
+ impl Objects {
+ fn offset(&self, o: u32) -> [f32; 3] {
+ match self.at.get(&o).and_then(|x| x.2) {
+ Some(p) => {
+ let (a, b) = (self.at[&p].0, self.offset(p));
+ [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
+ }
+ None => [0.0; 3],
+ }
+ }
+ }
+
+ impl Scene for Objects {
+ fn world_pose(&self, o: u32) -> Option<([f32; 3], [f32; 4])> {
+ let (p, q, _) = *self.at.get(&o)?;
+ let d = self.offset(o);
+ Some(([p[0] + d[0], p[1] + d[1], p[2] + d[2]], q))
+ }
+ fn place(&mut self, o: u32, p: [f32; 3], q: [f32; 4]) -> Option<([f32; 3], [f32; 4])> {
+ let d = self.offset(o);
+ let e = self.at.get_mut(&o)?;
+ (e.0, e.1) = ([p[0] - d[0], p[1] - d[1], p[2] - d[2]], q);
+ self.placed += 1;
+ Some((e.0, e.1))
+ }
+ fn drive(&mut self, o: u32) {
+ self.driven.push(o);
+ }
+ fn geometry(&self, id: u32) -> Option<(&[f32], &[u32])> {
+ self.geometries.get(&id).map(|(p, i)| (p.as_slice(), i.as_slice()))
+ }
+ }
+
+ const Q: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
+
+ fn scene() -> Objects {
+ let mut s = Objects::default();
+ // 1: the ground (top at y = 0), 2: a box 2 m up, 3: a group at (10, 0, 0), 4: a box under it.
+ s.at.insert(1, ([0.0, -0.5, 0.0], Q, None));
+ s.at.insert(2, ([0.0, 2.0, 0.0], Q, None));
+ s.at.insert(3, ([10.0, 0.0, 0.0], Q, None));
+ s.at.insert(4, ([0.0, 1.0, 0.0], Q, Some(3)));
+ s
+ }
+
+ fn run(b: &mut Bridge, s: &mut Objects, ticks: u32) -> usize {
+ (0..ticks).map(|_| {
+ b.tick();
+ b.sync(s)
+ })
+ .sum()
+ }
+
+ fn ground(b: &mut Bridge, s: &mut Objects) {
+ b.call(s, "body", &json!({ "id": 1, "kind": "fixed", "object": 1 })).unwrap();
+ b.call(s, "collider", &json!({ "id": 1, "body": 1, "shape": { "type": "box", "halfExtents": [20, 0.5, 20] } })).unwrap();
+ }
+
+ /// A body drives its object: the box falls onto the ground and rests on it, the object where the body is; one under
+ /// a parent is placed in the parent's space; `poses` holds them by slot; nothing is placed once they sleep.
+ #[test]
+ fn bodies_drive_objects() {
+ let (mut b, mut s) = (Bridge::default(), scene());
+ ground(&mut b, &mut s);
+ for (id, slot) in [(2, 0), (4, 3)] {
+ b.call(&mut s, "body", &json!({ "id": id, "object": id, "slot": slot })).unwrap();
+ b.call(&mut s, "collider", &json!({ "id": id, "body": id, "shape": { "type": "box", "halfExtents": [0.25, 0.25, 0.25] } })).unwrap();
+ }
+ assert_eq!(s.driven, vec![2, 4], "the fixed ground is not driven");
+ assert_eq!(b.poses().len(), 4 * POSE);
+ assert_eq!(b.poses()[..3], [0.0, 2.0, 0.0]);
+ assert_eq!(b.poses()[3 * POSE..3 * POSE + 3], [0.0, 1.0, 0.0], "in its parent's space");
+ let moved = run(&mut b, &mut s, 240);
+ assert!(moved > 60 && moved < 400, "placed while they moved only: {moved}");
+ let rest = s.at[&2].0;
+ // (A flat drop of 2 m ends within a centimetre of where it began sideways: the solver's own noise.)
+ assert!(rest[0].abs() < 1e-2 && (rest[1] - 0.25).abs() < 3e-3 && rest[2].abs() < 1e-2, "{rest:?}");
+ let under = s.at[&4].0;
+ assert!((under[0]).abs() < 1e-2 && (under[1] - 0.25).abs() < 3e-3, "local to the group at x = 10: {under:?}");
+ assert_eq!(b.poses()[..3], rest);
+ assert_eq!(b.poses()[3 * POSE..3 * POSE + 3], under);
+ let st = b.call(&mut s, "state", &json!({ "body": 4 })).unwrap();
+ assert!((st["position"][0].as_f64().unwrap() - 10.0).abs() < 1e-2 && st["sleeping"] == true, "{st}");
+ // Asleep: ticks place nothing.
+ let before = s.placed;
+ assert_eq!(run(&mut b, &mut s, 30), 0);
+ assert_eq!(s.placed, before);
+ // An impulse wakes it; it moves again.
+ b.call(&mut s, "impulse", &json!({ "body": 2, "impulse": [0, 300, 0] })).unwrap();
+ assert!(run(&mut b, &mut s, 10) >= 10);
+ assert!(s.at[&2].0[1] > 0.5);
+ }
+
+ /// Scene code moves a body's object: a dynamic body is there at once with its velocity; a kinematic one goes there
+ /// through the next tick and pushes what is in its way.
+ #[test]
+ fn bodies_follow_objects_scene_code_moved() {
+ let (mut b, mut s) = (Bridge::default(), scene());
+ ground(&mut b, &mut s);
+ b.call(&mut s, "body", &json!({ "id": 2, "object": 2, "slot": 0, "linvel": [1, 0, 0] })).unwrap();
+ b.call(&mut s, "collider", &json!({ "id": 2, "body": 2, "shape": { "type": "sphere", "radius": 0.25 } })).unwrap();
+ s.at.get_mut(&2).unwrap().0 = [3.0, 5.0, 0.0];
+ b.call(&mut s, "follow", &json!({ "body": 2 })).unwrap();
+ let st = b.call(&mut s, "state", &json!({ "body": 2 })).unwrap();
+ assert_eq!((st["position"][0].as_f64(), st["position"][1].as_f64(), st["linvel"][0].as_f64()), (Some(3.0), Some(5.0), Some(1.0)));
+ assert_eq!(b.poses()[..3], [3.0, 5.0, 0.0]);
+ // A kinematic paddle (object 4, under the group) pushed into a resting ball.
+ let mut s = scene();
+ let mut b = Bridge::default();
+ ground(&mut b, &mut s);
+ s.at.get_mut(&2).unwrap().0 = [10.0, 0.25, 1.0];
+ s.at.get_mut(&4).unwrap().0 = [0.0, 0.25, 0.0];
+ b.call(&mut s, "body", &json!({ "id": 2, "object": 2 })).unwrap();
+ b.call(&mut s, "collider", &json!({ "id": 2, "body": 2, "shape": { "type": "sphere", "radius": 0.25 } })).unwrap();
+ b.call(&mut s, "body", &json!({ "id": 4, "object": 4, "kind": "kinematic", "slot": 1 })).unwrap();
+ b.call(&mut s, "collider", &json!({ "id": 4, "body": 4, "shape": { "type": "box", "halfExtents": [0.5, 0.25, 0.25] } })).unwrap();
+ for k in 1..=30 {
+ s.at.get_mut(&4).unwrap().0 = [0.0, 0.25, k as f32 * 0.02];
+ b.call(&mut s, "follow", &json!({ "body": 4 })).unwrap();
+ assert_eq!(b.poses()[POSE + 2], k as f32 * 0.02, "what scene code wrote is what it reads");
+ run(&mut b, &mut s, 1);
+ }
+ let st = b.call(&mut s, "state", &json!({ "body": 4 })).unwrap();
+ assert!((st["position"][2].as_f64().unwrap() - 0.6).abs() < 1e-4 && (st["position"][0].as_f64().unwrap() - 10.0).abs() < 1e-4, "{st}");
+ assert!(s.at[&2].0[2] > 1.05, "pushed: {:?}", s.at[&2].0);
+ }
+
+ /// Queries report the caller's ids and the scene objects (the world as of the last tick: a collider is seen from
+ /// the tick after it was added); a force acts through one frame's ticks only; contacts come in the order they
+ /// happened with their bodies.
+ #[test]
+ fn queries_forces_and_contacts() {
+ let (mut b, mut s) = (Bridge::default(), scene());
+ ground(&mut b, &mut s);
+ // (Weightless, so it stays where the queries expect it.)
+ b.call(&mut s, "body", &json!({ "id": 7, "object": 2, "gravityScale": 0 })).unwrap();
+ b.call(&mut s, "collider", &json!({ "id": 70, "body": 7, "shape": { "type": "box", "halfExtents": [0.25, 0.25, 0.25] }, "events": true })).unwrap();
+ assert!(b.call(&mut s, "ray", &json!({ "origin": [0, 10, 0], "direction": [0, -1, 0] })).unwrap().is_null(), "before a tick");
+ run(&mut b, &mut s, 1);
+ let h = b.call(&mut s, "ray", &json!({ "origin": [0, 10, 0], "direction": [0, -1, 0] })).unwrap();
+ assert_eq!((h["collider"].as_u64(), h["body"].as_u64(), h["object"].as_u64()), (Some(70), Some(7), Some(2)));
+ assert!((h["distance"].as_f64().unwrap() - 7.75).abs() < 1e-4 && h["normal"][1] == 1.0);
+ let all = b.call(&mut s, "ray", &json!({ "origin": [0, 10, 0], "direction": [0, -1, 0], "all": true })).unwrap();
+ assert_eq!(all.as_array().unwrap().iter().map(|h| h["object"].as_u64().unwrap()).collect::<Vec<_>>(), vec![2, 1], "nearest first");
+ let skipped = b.call(&mut s, "ray", &json!({ "origin": [0, 10, 0], "direction": [0, -1, 0], "skip": 7 })).unwrap();
+ assert_eq!(skipped["object"].as_u64(), Some(1));
+ assert!(b.call(&mut s, "ray", &json!({ "origin": [5, 10, 0], "direction": [0, 1, 0] })).unwrap().is_null());
+ let o = b.call(&mut s, "overlap", &json!({ "shape": { "type": "sphere", "radius": 0.5 }, "position": [0, 2.2, 0] })).unwrap();
+ assert_eq!(o, json!([{ "collider": 70, "body": 7, "object": 2 }]));
+ let w = b.call(&mut s, "sweep", &json!({ "shape": { "type": "sphere", "radius": 0.5 }, "position": [0, 6, 0], "direction": [0, -1, 0] })).unwrap();
+ assert!((w["distance"].as_f64().unwrap() - 3.25).abs() < 1e-3 && w["object"] == 2, "{w}");
+ // A force of 600 N on its 125 kg through one frame's tick: 0.08 m/s more; the next frame has no force.
+ let m = b.call(&mut s, "state", &json!({ "body": 7 })).unwrap()["mass"].as_f64().unwrap();
+ assert!((m - 125.0).abs() < 1e-3, "0.5 m cube of water: {m}");
+ b.call(&mut s, "body", &json!({ "id": 8, "position": [50, 0, 0] })).unwrap();
+ b.call(&mut s, "collider", &json!({ "id": 80, "body": 8, "shape": { "type": "sphere", "radius": 0.5 }, "mass": 3 })).unwrap();
+ assert_eq!(b.call(&mut s, "state", &json!({ "body": 8 })).unwrap()["mass"].as_f64(), Some(3.0));
+ b.call(&mut s, "remove", &json!({ "body": 8 })).unwrap();
+ b.call(&mut s, "force", &json!({ "body": 7, "force": [0, 600, 0] })).unwrap();
+ run(&mut b, &mut s, 1);
+ let up = b.call(&mut s, "state", &json!({ "body": 7 })).unwrap()["linvel"][1].as_f64().unwrap();
+ assert!((up - 600.0 / 125.0 / 60.0).abs() < 1e-4, "{up}");
+ run(&mut b, &mut s, 1);
+ let then = b.call(&mut s, "state", &json!({ "body": 7 })).unwrap()["linvel"][1].as_f64().unwrap();
+ assert!((then - up).abs() < 1e-6, "{then}");
+ // A frame without a tick (a frame rate above the tick rate) ends its force too: none is left for the next.
+ b.call(&mut s, "force", &json!({ "body": 7, "force": [0, 600, 0] })).unwrap();
+ assert_eq!(b.sync(&mut s), 0);
+ run(&mut b, &mut s, 1);
+ assert!((b.call(&mut s, "state", &json!({ "body": 7 })).unwrap()["linvel"][1].as_f64().unwrap() - up).abs() < 1e-6);
+ // Sent down, it lands: one contact started, between the ground's collider (1, of body 1) and its own. (Its
+ // other velocity is kept by a call that sets one.)
+ b.call(&mut s, "velocity", &json!({ "body": 7, "angvel": [0, 0, 0] })).unwrap();
+ assert_eq!(b.call(&mut s, "state", &json!({ "body": 7 })).unwrap()["linvel"][1].as_f64().unwrap(), then);
+ b.call(&mut s, "velocity", &json!({ "body": 7, "linvel": [0, -3, 0] })).unwrap();
+ run(&mut b, &mut s, 60);
+ assert_eq!(b.call(&mut s, "contacts", &Value::Null).unwrap(), json!([{ "a": 1, "b": 70, "bodyA": 1, "bodyB": 7, "started": true }]));
+ assert_eq!(b.call(&mut s, "contacts", &Value::Null).unwrap(), json!([]));
+ // An impulse at a corner turns it.
+ b.call(&mut s, "impulse", &json!({ "body": 7, "impulse": [0, 100, 0], "point": [0.25, 0.0, 0.25] })).unwrap();
+ run(&mut b, &mut s, 1);
+ let av = b.call(&mut s, "state", &json!({ "body": 7 })).unwrap()["angvel"].clone();
+ assert!(av[0].as_f64().unwrap().abs() > 1.0 && av[2].as_f64().unwrap().abs() > 1.0, "{av}");
+ }
+
+ /// Shapes from a geometry of the scene; what a call refuses and why; limits; removal; an object that is gone takes
+ /// its body with it.
+ #[test]
+ fn shapes_errors_and_removal() {
+ let (mut b, mut s) = (Bridge::default(), scene());
+ // A unit tetrahedron and a 2 m square of two triangles.
+ s.geometries.insert(1, (vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], vec![0, 1, 2, 0, 1, 3, 0, 2, 3, 1, 2, 3]));
+ s.geometries.insert(2, (vec![-1.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 1.0, -1.0, 0.0, 1.0], vec![0, 2, 1, 0, 3, 2]));
+ b.call(&mut s, "collider", &json!({ "id": 1, "shape": { "type": "trimesh", "geometry": 2, "scale": [5, 1, 5] } })).unwrap();
+ b.call(&mut s, "body", &json!({ "id": 2, "object": 2 })).unwrap();
+ b.call(&mut s, "collider", &json!({ "id": 2, "body": 2, "shape": { "type": "convexHull", "geometry": 1, "scale": [0.5, 0.5, 0.5] } })).unwrap();
+ run(&mut b, &mut s, 240);
+ let y = s.at[&2].0[1];
+ assert!(y > -0.01 && y < 0.3, "the hull rests on the scaled trimesh: {y}");
+ let h = b.call(&mut s, "ray", &json!({ "origin": [4.5, 3, 4.5], "direction": [0, -1, 0] })).unwrap();
+ assert!((h["distance"].as_f64().unwrap() - 3.0).abs() < 1e-4 && h["collider"] == 1 && h["body"].is_null() && h["object"].is_null(), "a static collider: {h}");
+ for (op, args, why) in [
+ ("body", json!({ "id": 2 }), "exists"),
+ ("body", json!({ "id": 3, "object": 99 }), "unknown object"),
+ ("body", json!({ "id": 3, "object": 2 }), "already has a body"),
+ ("body", json!({ "id": 3, "kind": "soft" }), "none of dynamic"),
+ ("body", json!({ "id": 3, "position": [0, "x", 0] }), "three finite numbers"),
+ ("body", json!({ "id": 3, "slot": 0 }), "without an object"),
+ ("collider", json!({ "id": 2, "shape": { "type": "sphere", "radius": 1 } }), "exists"),
+ ("collider", json!({ "id": 3, "body": 9, "shape": { "type": "sphere", "radius": 1 } }), "unknown body"),
+ ("collider", json!({ "id": 3, "shape": { "type": "sphere", "radius": -1 } }), "radius must be from 1e-3 to 1e4"),
+ ("collider", json!({ "id": 3, "shape": { "type": "cone" } }), "none of box"),
+ ("collider", json!({ "id": 3, "shape": { "type": "trimesh", "geometry": 9 } }), "unknown geometry"),
+ ("joint", json!({ "id": 1, "a": 2, "b": 9, "type": "fixed" }), "unknown body"),
+ ("joint", json!({ "id": 1, "a": 2, "b": 2, "type": "weld" }), "none of fixed"),
+ ("impulse", json!({ "body": 9 }), "unknown body"),
+ ("step", json!({}), "unknown call"),
+ ] {
+ let e = b.call(&mut s, op, &args).unwrap_err();
+ assert!(e.contains(why), "{op} {args}: {e}");
+ }
+ // Removing a body takes its collider; the ids are free again.
+ b.call(&mut s, "remove", &json!({ "body": 2 })).unwrap();
+ assert_eq!(b.bodies(), 0);
+ b.call(&mut s, "body", &json!({ "id": 2, "object": 2, "slot": 0 })).unwrap();
+ b.call(&mut s, "collider", &json!({ "id": 2, "body": 2, "shape": { "type": "sphere", "radius": 0.2 } })).unwrap();
+ // The object is removed from the scene while its body moves: the body goes at the next sync.
+ b.call(&mut s, "impulse", &json!({ "body": 2, "impulse": [0, 50, 0] })).unwrap();
+ s.at.remove(&2);
+ run(&mut b, &mut s, 2);
+ assert_eq!(b.bodies(), 0);
+ assert!(b.call(&mut s, "state", &json!({ "body": 2 })).is_err());
+ // The limit on bodies.
+ for k in 0..MAX_BODIES as u32 {
+ b.call(&mut s, "body", &json!({ "id": 100 + k, "kind": "fixed" })).unwrap();
+ }
+ assert!(b.call(&mut s, "body", &json!({ "id": 5 })).unwrap_err().contains("more than"));
+ }
+
+ /// Frames make whole ticks: 60 a second whatever the frame rate, at most `MAX_TICKS` a frame; an offline render
+ /// asks for a tick count once.
+ #[test]
+ fn ticks_due() {
+ let mut b = Bridge::default();
+ assert_eq!((0..60).map(|_| b.due(1.0 / 60.0)).sum::<u32>(), 60);
+ assert_eq!((0..120).map(|_| b.due(1.0 / 120.0)).sum::<u32>(), 60);
+ assert_eq!((0..30).map(|_| b.due(1.0 / 30.0)).sum::<u32>(), 60);
+ assert_eq!(b.due(10.0), MAX_TICKS);
+ assert_eq!((b.due(f64::NAN), b.due(0.0), b.due(-1.0)), (0, 0, 0), "a long frame leaves nothing behind");
+ assert_eq!(b.due_until(120), 120);
+ for _ in 0..50 {
+ b.tick();
+ }
+ assert_eq!((b.due_until(120), b.due_until(40), b.due_until(1_000_000)), (70, 0, 35_950));
+ }
+}
diff --git a/renderer/physics-core/src/check.rs b/renderer/physics-core/src/check.rs
new file mode 100644
index 0000000..49b5490
--- /dev/null
+++ b/renderer/physics-core/src/check.rs
@@ -0,0 +1,207 @@
+//! A fixed scene stepped for a fixed number of ticks, and the hash of where it ends (ROADMAP § 6 step 7's determinism
+//! check): a native binary and a wasm32 module (examples/determinism*.rs) both run it.
+
+use crate::world::*;
+
+/// The hash `script(600)` leaves with `enhanced-determinism` (recorded: a change of behaviour, or of Rapier, shows
+/// here). Natively and in wasm32 alike.
+pub const EXPECTED: u64 = 0x113d_50eb_06a4_7636;
+
+/// A tower of boxes hit by a ball, a hinged door pushed by another, a rope pendulum and a slider: contacts, friction,
+/// stacking and four kinds of joints, for `ticks` ticks. Returns the world's hash.
+pub fn script(ticks: u32) -> u64 {
+ let mut p = Physics::default();
+ p.add_collider(None, &ColliderDesc::new(Shape::Box([50.0, 0.5, 50.0]))).unwrap();
+ let dynamic = |position: [f32; 3]| BodyDesc { position, ..Default::default() };
+ // Ground at y = 0.5 (the box above is centred at 0): a 4 x 6 x 4 tower of half-metre boxes.
+ for y in 0..6 {
+ for x in 0..4 {
+ for z in 0..4 {
+ let b = p.add_body(&dynamic([x as f32 * 0.5 - 0.75 + 0.01 * y as f32, 0.75 + y as f32 * 0.5, z as f32 * 0.5 - 0.75])).unwrap();
+ p.add_collider(Some(b), &ColliderDesc::new(Shape::Box([0.25; 3]))).unwrap();
+ }
+ }
+ }
+ let ball = p.add_body(&BodyDesc { position: [-6.0, 1.5, 0.1], linvel: [14.0, 1.0, 0.0], ccd: true, ..Default::default() }).unwrap();
+ p.add_collider(Some(ball), &ColliderDesc { restitution: 0.4, ..ColliderDesc::new(Shape::Sphere(0.4)) }).unwrap();
+ // A door on a hinge at a fixed post, pushed by a capsule.
+ let post = p.add_body(&BodyDesc { kind: BodyKind::Fixed, position: [5.0, 1.5, 0.0], ..Default::default() }).unwrap();
+ let door = p.add_body(&dynamic([5.5, 1.5, 0.0])).unwrap();
+ p.add_collider(Some(door), &ColliderDesc::new(Shape::Box([0.5, 1.0, 0.05]))).unwrap();
+ p.add_joint(post, door, &JointDesc::Revolute { anchor1: [0.0; 3], anchor2: [-0.5, 0.0, 0.0], axis: [0.0, 1.0, 0.0], limits: Some(Limits { min: -1.5, max: 1.5 }), motor: None }).unwrap();
+ let pusher = p.add_body(&BodyDesc { position: [5.7, 1.5, 3.0], linvel: [0.0, 0.0, -6.0], ..Default::default() }).unwrap();
+ p.add_collider(Some(pusher), &ColliderDesc::new(Shape::Capsule { half_height: 0.3, radius: 0.2 })).unwrap();
+ // A weight on a rope, a hull on a ball joint, a slider with a motor.
+ let weight = p.add_body(&dynamic([-5.0, 3.0, 4.0])).unwrap();
+ p.add_collider(Some(weight), &ColliderDesc::new(Shape::Sphere(0.3))).unwrap();
+ p.add_joint(post, weight, &JointDesc::Rope { anchor1: [-8.0, 3.5, 4.0], anchor2: [0.0; 3], length: 2.5 }).unwrap();
+ let hull = p.add_body(&dynamic([8.0, 2.0, -3.0])).unwrap();
+ p.add_collider(Some(hull), &ColliderDesc::new(Shape::ConvexHull(vec![[0.0, 0.5, 0.0], [0.4, -0.3, 0.3], [-0.4, -0.3, 0.3], [0.0, -0.3, -0.5], [0.1, 0.1, 0.6]]))).unwrap();
+ p.add_joint(post, hull, &JointDesc::Spherical { anchor1: [3.0, 1.5, -3.0], anchor2: [0.0, 0.5, 0.0] }).unwrap();
+ let slider = p.add_body(&dynamic([0.0, 3.0, -6.0])).unwrap();
+ p.add_collider(Some(slider), &ColliderDesc::new(Shape::Box([0.3; 3]))).unwrap();
+ p.add_joint(post, slider, &JointDesc::Prismatic { anchor1: [-5.0, 1.5, -6.0], anchor2: [0.0; 3], axis: [1.0, 0.0, 0.0], limits: Some(Limits { min: -2.0, max: 2.0 }), motor: Some(Motor { velocity: 1.5, damping: 400.0, max_force: 500.0 }) }).unwrap();
+ let mut h = 0u64;
+ for t in 0..ticks {
+ p.step();
+ // A kick halfway, and the hash folded in every 30 ticks (so a divergence anywhere on the way shows).
+ if t == ticks / 2 {
+ p.apply_impulse(ball, [0.0, 80.0, 30.0], [0.0; 3]).unwrap();
+ }
+ if t % 30 == 29 {
+ h = (h ^ p.hash()).wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ }
+ h ^ p.hash()
+}
+
+/// `n` boxes dropped in a heap on the ground (a 10 x 10 column of them, slightly offset so they tumble), stepped
+/// `ticks` ticks: the solver's cost with many contacts. Returns the world's hash.
+pub fn pile(n: u32, ticks: u32) -> u64 {
+ let mut p = Physics::default();
+ p.add_collider(None, &ColliderDesc::new(Shape::Box([50.0, 0.5, 50.0]))).unwrap();
+ for k in 0..n {
+ let (x, z, y) = (k % 10, (k / 10) % 10, k / 100);
+ let jitter = ((k * 7919) % 13) as f32 * 0.01;
+ let b = p.add_body(&BodyDesc { position: [x as f32 * 0.55 - 2.5 + jitter, 0.8 + y as f32 * 0.55, z as f32 * 0.55 - 2.5 - jitter], ..Default::default() }).unwrap();
+ p.add_collider(Some(b), &ColliderDesc::new(Shape::Box([0.25; 3]))).unwrap();
+ }
+ for _ in 0..ticks {
+ p.step();
+ }
+ p.hash()
+}
+
+/// Random worlds for the determinism check, by kind: each is `case(kind, seed)`. The script above has one convex hull
+/// and no body of several colliders, and those are where the platforms' math first showed (the principal axes of an
+/// inertia tensor that is not diagonal: an eigen decomposition with an acos and two cos).
+pub const KINDS: [(&str, u32); 3] = [("convex hulls", 400), ("bodies of several colliders", 400), ("joints with limits and motors", 200)];
+
+/// The hash of all the cases (`cases()`) with `enhanced-determinism`, natively and in wasm32 alike.
+pub const EXPECTED_CASES: u64 = 0x9e16_a677_1fa8_f317;
+
+/// A generator of integers only: a float made from one is exact arithmetic, the same bits on every platform.
+struct Rng(u64);
+
+impl Rng {
+ fn next(&mut self) -> u64 {
+ self.0 ^= self.0 << 13;
+ self.0 ^= self.0 >> 7;
+ self.0 ^= self.0 << 17;
+ self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
+ }
+ /// In [-1, 1), 24 bits.
+ fn unit(&mut self) -> f32 {
+ (self.next() >> 40) as f32 / 8_388_608.0 - 1.0
+ }
+ fn v3(&mut self, scale: f32) -> [f32; 3] {
+ [self.unit() * scale, self.unit() * scale, self.unit() * scale]
+ }
+ /// In [lo, hi).
+ fn range(&mut self, lo: f32, hi: f32) -> f32 {
+ lo + (self.unit() * 0.5 + 0.5) * (hi - lo)
+ }
+ fn quat(&mut self) -> [f32; 4] {
+ [self.unit(), self.unit(), self.unit(), self.unit() + 1.5]
+ }
+}
+
+/// One random world of a kind (`KINDS`), stepped 90 ticks on a ground: its hash, folded every 10 ticks.
+pub fn case(kind: u32, seed: u32) -> u64 {
+ let mut r = Rng((seed as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ ((kind as u64 + 1) << 56) | 1);
+ for _ in 0..4 {
+ r.next();
+ }
+ let mut p = Physics::default();
+ p.add_collider(None, &ColliderDesc { position: [0.0, -0.5, 0.0], ..ColliderDesc::new(Shape::Box([50.0, 0.5, 50.0])) }).unwrap();
+ let body = |p: &mut Physics, r: &mut Rng, at: [f32; 3]| p.add_body(&BodyDesc { position: at, rotation: r.quat(), linvel: r.v3(2.0), angvel: r.v3(10.0), ..Default::default() }).unwrap();
+ let hull = |r: &mut Rng| Shape::ConvexHull((0..8).map(|_| r.v3(0.5)).collect());
+ match kind {
+ // Two tumbling hulls of 8 random points that meet over the ground.
+ 0 => {
+ for k in 0..2 {
+ let b = body(&mut p, &mut r, [k as f32 * 0.6, 1.5 + k as f32, 0.0]);
+ // (Points that hold no volume are refused: another draw.)
+ while p.add_collider(Some(b), &ColliderDesc::new(hull(&mut r))).is_err() {}
+ }
+ }
+ // A body of two boxes and one of a capsule and a sphere, each collider at its own place and turn.
+ 1 => {
+ let a = body(&mut p, &mut r, [0.0, 1.5, 0.0]);
+ for _ in 0..2 {
+ let shape = Shape::Box([r.range(0.1, 0.6), r.range(0.1, 0.6), r.range(0.1, 0.6)]);
+ p.add_collider(Some(a), &ColliderDesc { position: r.v3(0.7), rotation: r.quat(), ..ColliderDesc::new(shape) }).unwrap();
+ }
+ let b = body(&mut p, &mut r, [0.5, 3.5, 0.2]);
+ p.add_collider(Some(b), &ColliderDesc { position: r.v3(0.5), rotation: r.quat(), ..ColliderDesc::new(Shape::Capsule { half_height: r.range(0.1, 0.5), radius: r.range(0.1, 0.3) }) }).unwrap();
+ p.add_collider(Some(b), &ColliderDesc { position: r.v3(0.5), density: r.range(200.0, 3000.0), ..ColliderDesc::new(Shape::Sphere(r.range(0.1, 0.4))) }).unwrap();
+ }
+ // A box hinged to a post (limits, a motor) and a hull on a slider and a rope, all turned at random.
+ _ => {
+ let post = p.add_body(&BodyDesc { kind: BodyKind::Fixed, position: [0.0, 3.0, 0.0], rotation: r.quat(), ..Default::default() }).unwrap();
+ let a = body(&mut p, &mut r, [1.0, 3.0, 0.0]);
+ p.add_collider(Some(a), &ColliderDesc::new(Shape::Box([r.range(0.2, 0.6), r.range(0.1, 0.3), r.range(0.2, 0.6)]))).unwrap();
+ let (lo, hi) = (r.range(-2.0, -0.2), r.range(0.2, 2.0));
+ let motor = Motor { velocity: r.unit() * 5.0, damping: r.range(10.0, 500.0), max_force: r.range(10.0, 500.0) };
+ p.add_joint(post, a, &JointDesc::Revolute { anchor1: r.v3(0.3), anchor2: r.v3(0.5), axis: r.v3(1.0), limits: Some(Limits { min: lo, max: hi }), motor: Some(motor) }).unwrap();
+ let b = body(&mut p, &mut r, [-1.0, 3.0, 0.5]);
+ while p.add_collider(Some(b), &ColliderDesc::new(hull(&mut r))).is_err() {}
+ p.add_joint(post, b, &JointDesc::Prismatic { anchor1: r.v3(0.3), anchor2: r.v3(0.3), axis: r.v3(1.0), limits: Some(Limits { min: r.range(-1.5, -0.1), max: r.range(0.1, 1.5) }), motor: None }).unwrap();
+ p.add_joint(a, b, &JointDesc::Rope { anchor1: r.v3(0.3), anchor2: r.v3(0.3), length: r.range(1.0, 2.5) }).unwrap();
+ }
+ }
+ let mut h = 0u64;
+ for t in 0..90 {
+ p.step();
+ if t % 10 == 9 {
+ h = (h ^ p.hash()).wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ }
+ h
+}
+
+/// Every case's hash folded into one (`EXPECTED_CASES`).
+pub fn cases() -> u64 {
+ let mut h = 0xcbf2_9ce4_8422_2325u64;
+ for (kind, &(_, n)) in KINDS.iter().enumerate() {
+ for seed in 0..n {
+ h = (h ^ case(kind as u32, seed)).wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ }
+ h
+}
+
+#[cfg(test)]
+mod tests {
+ /// This build steps to the recorded bits (tools/physics-determinism.ts shows the wasm32 build does too): a
+ /// dependency or a feature that brings the platform's math functions back shows here.
+ #[test]
+ fn this_build_steps_to_the_recorded_bits() {
+ assert_eq!(format!("{:016x}", super::script(600)), format!("{:016x}", super::EXPECTED));
+ assert_eq!(format!("{:016x}", super::cases()), format!("{:016x}", super::EXPECTED_CASES));
+ }
+
+ /// Where Rapier 0.36 and parry 0.31 still take a math function from the platform (f32's own methods, whenever
+ /// `std` is in the crate graph: third_party/glamx/PATCH.md has how), on the paths a 3D world of ours runs, the
+ /// platform this test runs on gives what libm gives, so those calls change nothing:
+ /// - the broad phase's BVH optimizer (parry bvh_optimize.rs `optimization_config`) takes two `log2` of numbers
+ /// that depend on the collider count alone, and rounds what it makes of them to a count of subtrees: the same
+ /// count with either `log2`, for every collider count the world may hold (and twice as many);
+ /// - a convex hull's `support_feature_id_toward` takes the sine and cosine of one constant, a degree.
+ /// (The eigen decomposition is patched in glamx, and a hinge's limits reach Rapier centred: world.rs `add_joint`.)
+ #[test]
+ fn the_platforms_math_changes_nothing_where_rapier_still_calls_it() {
+ let subtrees = |leaves: u32, log2: fn(f32) -> f32| -> f32 {
+ let root = (leaves as f32).sqrt();
+ let (roots, subtree) = (root.ceil(), (root * 4.0).ceil());
+ let cost = roots * log2(roots) / (subtree * log2(subtree));
+ ((leaves * 5).div_ceil(100) as f32 / subtree - cost).round().max(0.0)
+ };
+ for leaves in 1..=2 * crate::bridge::MAX_COLLIDERS as u32 {
+ assert_eq!(subtrees(leaves, f32::log2), subtrees(leaves, libm::log2f), "{leaves} colliders");
+ }
+ let degree = (core::f64::consts::PI / 180.0) as f32;
+ let ((s, c), (ls, lc)) = (degree.sin_cos(), libm::sincosf(degree));
+ assert_eq!((s.to_bits(), c.to_bits()), (ls.to_bits(), lc.to_bits()));
+ }
+}
diff --git a/renderer/physics-core/src/lib.rs b/renderer/physics-core/src/lib.rs
new file mode 100644
index 0000000..bf36616
--- /dev/null
+++ b/renderer/physics-core/src/lib.rs
@@ -0,0 +1,17 @@
+//! ThreeRT's physics (ROADMAP § 6 step 7): rigid bodies, colliders, joints, contact events and scene queries, on Rapier.
+//! The world is the engine's: it is stepped at a fixed tick (`TICK`), and game scripts reach it only through the
+//! calls of `bridge::Bridge` (which also places the scene objects that bodies drive), never Rapier itself. Engine code
+//! may extend it with its own collider shapes (`CustomShape`: the voxel shape of step 8).
+//!
+//! Data in, data out: no GPU, no file system, no threads, so it builds for `wasm32-unknown-unknown` (players run the
+//! game in the browser).
+
+pub mod bridge;
+pub mod check;
+mod world;
+
+pub use world::{
+ limits, BodyDesc, BodyId, BodyKind, ColliderDesc, ColliderId, Contact, CustomShape, Fault, Hit, JointDesc, JointId, Limits, Motor, Physics, Shape, TICK,
+};
+/// Rapier itself, for engine code that implements `CustomShape` (not for game scripts).
+pub use rapier3d;
diff --git a/renderer/physics-core/src/robustness.rs b/renderer/physics-core/src/robustness.rs
new file mode 100644
index 0000000..93c2ec7
--- /dev/null
+++ b/renderer/physics-core/src/robustness.rs
@@ -0,0 +1,528 @@
+//! What a game script can do to the physics (it is untrusted, and calls `__engine.physics` directly, not only through
+//! the scene binding): each test is one finding of the review of ROADMAP § 6 step 7, through `Bridge::call` as a
+//! script's calls go, and fails (most by a panic in a tick) without its fix.
+
+use super::*;
+use crate::limits::*;
+
+/// Objects at a pose each (no parents), recording where they were placed.
+#[derive(Default)]
+struct Objects {
+ at: BTreeMap<u32, ([f32; 3], [f32; 4])>,
+ placed: Vec<(u32, [f32; 3], [f32; 4])>,
+}
+
+impl Scene for Objects {
+ fn world_pose(&self, o: u32) -> Option<([f32; 3], [f32; 4])> {
+ self.at.get(&o).copied()
+ }
+ fn place(&mut self, o: u32, p: [f32; 3], q: [f32; 4]) -> Option<([f32; 3], [f32; 4])> {
+ let e = self.at.get_mut(&o)?;
+ *e = (p, q);
+ self.placed.push((o, p, q));
+ Some((p, q))
+ }
+ fn drive(&mut self, _: u32) {}
+ fn geometry(&self, _: u32) -> Option<(&[f32], &[u32])> {
+ None
+ }
+}
+
+fn world() -> (Bridge, Objects) {
+ let mut s = Objects::default();
+ for o in 1..=64 {
+ s.at.insert(o, ([o as f32, 2.0, 0.0], [0.0, 0.0, 0.0, 1.0]));
+ }
+ (Bridge::default(), s)
+}
+
+fn ok(b: &mut Bridge, s: &mut Objects, op: &str, a: Value) -> Value {
+ b.call(s, op, &a).unwrap_or_else(|e| panic!("{op} {a}: {e}"))
+}
+
+fn run(b: &mut Bridge, s: &mut Objects, ticks: u32) {
+ for _ in 0..ticks {
+ b.tick();
+ b.sync(s);
+ }
+}
+
+fn sphere(r: f64) -> Value {
+ json!({ "type": "sphere", "radius": r })
+}
+
+/// A1, the entry: the inputs the review found getting a body disabled by Rapier's quarantine (and a joint on it then
+/// panicking a tick: interaction_groups.rs unreachable), and the rest of what has no bound, are refused with the
+/// reason; the world is as it was, and ticks on.
+#[test]
+fn numbers_out_of_bounds_are_refused() {
+ let (mut b, mut s) = world();
+ ok(&mut b, &mut s, "body", json!({ "id": 1, "position": [0, 2, 0] }));
+ ok(&mut b, &mut s, "collider", json!({ "id": 1, "body": 1, "shape": sphere(0.3) }));
+ ok(&mut b, &mut s, "body", json!({ "id": 2, "kind": "fixed", "position": [0, 4, 0] }));
+ let open = json!({ "type": "trimesh", "vertices": [1.4, 3.0, -2.2, -2.0, 0.8, 2.0, -0.4, 0.8, 1.5, 1.2, 0.07, -2.5], "indices": [0, 1, 2, 1, 2, 3] });
+ for (op, a, why) in [
+ ("collider", json!({ "id": 9, "body": 1, "shape": open }), "fixed bodies"),
+ ("velocity", json!({ "body": 1, "angvel": [1e20, 0, 0] }), "angular velocity"),
+ ("velocity", json!({ "body": 1, "angvel": [3e38, 3e38, 3e38] }), "angular velocity"),
+ ("velocity", json!({ "body": 1, "linvel": [1e5, 0, 0] }), "linear velocity"),
+ ("collider", json!({ "id": 9, "body": 1, "shape": sphere(0.3), "mass": 1e-38 }), "mass"),
+ ("collider", json!({ "id": 9, "body": 1, "shape": sphere(0.3), "density": 3e38 }), "density"),
+ ("collider", json!({ "id": 9, "body": 1, "shape": sphere(0.3), "position": [1e20, 0, 0] }), "position"),
+ ("collider", json!({ "id": 9, "body": 1, "shape": sphere(0.3), "friction": -1 }), "friction"),
+ ("collider", json!({ "id": 9, "body": 1, "shape": sphere(0.3), "restitution": 2 }), "restitution"),
+ ("body", json!({ "id": 3, "gravityScale": 3e38 }), "gravity scale"),
+ ("body", json!({ "id": 3, "position": [1e20, 0, 0] }), "position"),
+ ("body", json!({ "id": 3, "linearDamping": 1e30 }), "damping"),
+ ("body", json!({ "id": 3, "rotation": [0, 0, 0, 0] }), "non-zero quaternion"),
+ ("pose", json!({ "body": 1, "position": [3e38, 3e38, -3e38] }), "position"),
+ ("target", json!({ "body": 1, "position": [1e30, 0, 0] }), "target"),
+ ("impulse", json!({ "body": 1, "impulse": [3e38, 0, 0], "point": [0, 3e38, 0] }), "impulse"),
+ ("impulse", json!({ "body": 1, "torque": [1e30, 0, 0] }), "angular impulse"),
+ ("force", json!({ "body": 1, "force": [3e38, 0, 0], "torque": [3e38, 0, 0] }), "force"),
+ ("gravity", json!({ "gravity": [0, -1e30, 0] }), "gravity"),
+ ("joint", json!({ "id": 1, "a": 1, "b": 2, "type": "revolute", "limits": [-1e30, 1e30] }), "limits"),
+ ("joint", json!({ "id": 1, "a": 1, "b": 2, "type": "revolute", "axis": [0, 0, 0] }), "axis"),
+ ("joint", json!({ "id": 1, "a": 1, "b": 2, "type": "rope", "length": 1e30 }), "length"),
+ ("joint", json!({ "id": 1, "a": 1, "b": 2, "type": "spherical", "anchor1": [1e30, 0, 0] }), "anchor"),
+ ("joint", json!({ "id": 1, "a": 1, "b": 2, "type": "prismatic", "motor": { "velocity": 1e30 } }), "motor"),
+ ("ray", json!({ "origin": [1e30, 0, 0], "direction": [1, 0, 0] }), "origin"),
+ ("ray", json!({ "origin": [0, 0, 0], "direction": [0, 0, 0] }), "direction"),
+ ("overlap", json!({ "shape": sphere(1.0), "position": [1e30, 0, 0] }), "position"),
+ ] {
+ let e = b.call(&mut s, op, &a).expect_err(&format!("{op} {a} is refused"));
+ assert!(e.contains(why), "{op} {a}: {e}");
+ }
+ assert_eq!(b.bodies(), 2);
+ run(&mut b, &mut s, 60);
+ // An axis or a rotation of any finite size is a direction: [1e20, 1e20, 0, 0] is a half turn about (1, 1, 0) (the
+ // square of 1e20 overflows: it was a zero quaternion, and a body turned by it went non-finite).
+ ok(&mut b, &mut s, "pose", json!({ "body": 1, "position": [0, 2, 0], "rotation": [1e20, 1e20, 0, 0] }));
+ let q = ok(&mut b, &mut s, "state", json!({ "body": 1 }))["rotation"].clone();
+ let h = std::f64::consts::FRAC_1_SQRT_2;
+ assert!((0..4).all(|k| (q[k].as_f64().unwrap() - [h, h, 0.0, 0.0][k]).abs() < 1e-6), "{q}");
+ ok(&mut b, &mut s, "joint", json!({ "id": 1, "a": 1, "b": 2, "type": "revolute", "axis": [1e20, 0, 1e20] }));
+ run(&mut b, &mut s, 30);
+ assert_eq!(ok(&mut b, &mut s, "state", json!({ "body": 1 }))["sleeping"], false);
+}
+
+/// A1, the fallback: a body whose pose or velocity goes non-finite all the same (here behind the checks, as only
+/// Rapier could) is taken out after the tick with its colliders and joints instead of staying disabled and frozen
+/// with `sleeping: false`; "state" says why, "faults" reports it once, and a joint on it is refused instead of
+/// panicking the next tick. One past the world's edge goes the same way.
+#[test]
+fn a_body_gone_non_finite_is_taken_out() {
+ let (mut b, mut s) = world();
+ ok(&mut b, &mut s, "collider", json!({ "id": 1000, "position": [0, -0.5, 0], "shape": { "type": "box", "halfExtents": [50, 0.5, 50] } }));
+ ok(&mut b, &mut s, "body", json!({ "id": 1, "object": 1, "slot": 0 }));
+ ok(&mut b, &mut s, "collider", json!({ "id": 1, "body": 1, "shape": sphere(0.3) }));
+ ok(&mut b, &mut s, "body", json!({ "id": 2, "kind": "fixed", "position": [0, 4, 0] }));
+ ok(&mut b, &mut s, "body", json!({ "id": 3, "position": [3, 1, 0] }));
+ ok(&mut b, &mut s, "collider", json!({ "id": 3, "body": 3, "shape": sphere(0.3) }));
+ ok(&mut b, &mut s, "joint", json!({ "id": 1, "a": 1, "b": 3, "type": "rope", "length": 4 }));
+ run(&mut b, &mut s, 2);
+ let w = b.bodies[&1];
+ b.core.break_body(w);
+ run(&mut b, &mut s, 1);
+ assert_eq!(ok(&mut b, &mut s, "state", json!({ "body": 1 })), json!({ "removed": "its pose or velocity went non-finite" }));
+ assert_eq!(ok(&mut b, &mut s, "faults", json!({})), json!([{ "body": 1, "object": 1, "kind": "nonFinite", "reason": "its pose or velocity went non-finite" }]));
+ assert_eq!(ok(&mut b, &mut s, "faults", json!({})), json!([]), "reported once");
+ assert_eq!(b.bodies(), 2);
+ assert!(b.call(&mut s, "joint", &json!({ "id": 2, "a": 1, "b": 2, "type": "spherical" })).unwrap_err().contains("unknown body"));
+ // Its collider and joint went with it: their ids are free, its object and slot too.
+ ok(&mut b, &mut s, "collider", json!({ "id": 1, "body": 3, "position": [0, 0.5, 0], "shape": sphere(0.1) }));
+ ok(&mut b, &mut s, "joint", json!({ "id": 1, "a": 3, "b": 2, "type": "spherical" }));
+ ok(&mut b, &mut s, "body", json!({ "id": 1, "object": 1, "slot": 0 }));
+ assert!(b.call(&mut s, "state", &json!({ "body": 1 })).unwrap()["position"].is_array());
+ run(&mut b, &mut s, 30);
+ // Past the world's edge (put there behind the checks: 400 m/s, Rapier's cap, would take 40 minutes).
+ let w = b.bodies[&3];
+ b.core.put_body(w, [0.0, -2.0 * WORLD_EDGE, 0.0]);
+ run(&mut b, &mut s, 1);
+ assert_eq!(ok(&mut b, &mut s, "state", json!({ "body": 3 }))["removed"], "it left the world (past 1e6 m from the origin)");
+ // Reported as having left the world, not as an error: a body that falls off the level is an ordinary thing.
+ assert_eq!(ok(&mut b, &mut s, "faults", json!({})), json!([{ "body": 3, "object": null, "kind": "leftWorld", "reason": "it left the world (past 1e6 m from the origin)" }]));
+ run(&mut b, &mut s, 30);
+}
+
+/// A call that is refused changes nothing: an impulse at a point with a torque, whose point (or impulse) is out of
+/// bounds, used to apply the torque and wake the body before it was refused.
+#[test]
+fn a_refused_call_changes_nothing() {
+ let (mut b, mut s) = world();
+ ok(&mut b, &mut s, "body", json!({ "id": 1, "position": [0, 2, 0], "gravityScale": 0 }));
+ ok(&mut b, &mut s, "collider", json!({ "id": 1, "body": 1, "shape": sphere(0.3) }));
+ run(&mut b, &mut s, 200);
+ let before = ok(&mut b, &mut s, "state", json!({ "body": 1 }));
+ assert_eq!(before["sleeping"], true);
+ for a in [
+ json!({ "body": 1, "impulse": [0, 1, 0], "point": [0, 3e38, 0], "torque": [0, 5, 0] }),
+ json!({ "body": 1, "impulse": [3e38, 0, 0], "point": [0, 2, 0], "torque": [0, 5, 0] }),
+ json!({ "body": 1, "impulse": [3e38, 0, 0], "torque": [0, 5, 0] }),
+ json!({ "body": 1, "impulse": [0, 1, 0], "torque": [0, 3e38, 0] }),
+ json!({ "body": 1, "impulse": [0, 1, 0], "point": [0, 2, 0], "torque": [0, 3e38, 0] }),
+ ] {
+ assert!(b.call(&mut s, "impulse", &a).is_err(), "{a}");
+ assert!(b.call(&mut s, "force", &json!({ "body": 1, "force": [0, 1, 0], "torque": [3e38, 0, 0] })).is_err());
+ assert!(b.call(&mut s, "velocity", &json!({ "body": 1, "linvel": [0, 1, 0], "angvel": [3e38, 0, 0] })).is_err());
+ run(&mut b, &mut s, 1);
+ assert_eq!(ok(&mut b, &mut s, "state", json!({ "body": 1 })), before, "after {a}");
+ }
+ assert!(b.call(&mut s, "remove", &json!({ "body": 1, "collider": "x" })).is_err());
+ assert_eq!(ok(&mut b, &mut s, "state", json!({ "body": 1 })), before, "a remove that is refused removes nothing");
+ // Within bounds both act: the body turns and moves.
+ ok(&mut b, &mut s, "impulse", json!({ "body": 1, "impulse": [0, 1, 0], "point": [0, 2, 0], "torque": [0, 5, 0] }));
+ run(&mut b, &mut s, 1);
+ let after = ok(&mut b, &mut s, "state", json!({ "body": 1 }));
+ assert!(after["linvel"][1].as_f64().unwrap() > 0.0 && after["angvel"][1].as_f64().unwrap() > 0.0, "{after}");
+}
+
+/// A2: a joint from a body to itself (reachable from the binding: `new HingeJoint(a, a)`), then that body removed,
+/// panicked the next tick (impulse_joint_set.rs). It is refused; the review's sequence then ticks on.
+#[test]
+fn a_joint_from_a_body_to_itself_is_refused() {
+ let (mut b, mut s) = world();
+ for (k, kind) in ["fixed", "kinematic", "dynamic", "kinematic", "fixed"].iter().enumerate() {
+ let id = k as u32 + 1;
+ ok(&mut b, &mut s, "body", json!({ "id": id, "kind": kind, "position": [id, 2, 0] }));
+ ok(&mut b, &mut s, "collider", json!({ "id": id, "body": id, "shape": sphere(0.3) }));
+ }
+ ok(&mut b, &mut s, "joint", json!({ "id": 1, "a": 2, "b": 1, "type": "revolute" }));
+ ok(&mut b, &mut s, "joint", json!({ "id": 2, "a": 5, "b": 3, "type": "prismatic" }));
+ let e = b.call(&mut s, "joint", &json!({ "id": 3, "a": 4, "b": 4, "type": "prismatic" })).unwrap_err();
+ assert!(e.contains("two different bodies"), "{e}");
+ ok(&mut b, &mut s, "joint", json!({ "id": 4, "a": 1, "b": 4, "type": "rope", "length": 0.24 }));
+ for r in [2, 5, 4] {
+ ok(&mut b, &mut s, "remove", json!({ "body": r }));
+ }
+ run(&mut b, &mut s, 2);
+}
+
+/// A3: a capsule of half height 0 failed parry's assertion in a tick (point_segment.rs: `sqnab != 0`); under 1 mm it
+/// is its sphere now. The review's case (a big sensor capsule of no length on a body that a spinning body hits).
+#[test]
+fn a_capsule_of_no_length_is_its_sphere() {
+ for (radius, far) in [(2000.0, -1909.0), (5000.0, -1909.0), (5.0, 0.0)] {
+ let (mut b, mut s) = world();
+ ok(&mut b, &mut s, "body", json!({ "id": 7, "position": [-0.19, 0.0002, -1.18] }));
+ ok(&mut b, &mut s, "collider", json!({ "id": 1, "body": 7, "events": true, "shape": { "type": "capsule", "halfHeight": 0.82, "radius": 0.587 } }));
+ ok(&mut b, &mut s, "body", json!({ "id": 3, "ccd": true }));
+ ok(&mut b, &mut s, "collider", json!({ "id": 105, "body": 3, "events": true, "shape": { "type": "box", "halfExtents": [0.6, 1.61, 0.767] } }));
+ ok(&mut b, &mut s, "collider", json!({ "id": 3, "body": 3, "position": [0.143, -0.145, far], "shape": sphere(0.04) }));
+ ok(&mut b, &mut s, "velocity", json!({ "body": 3, "angvel": [19, -7.34, 15.58], "linvel": [-15.0, 4.95, -1.94] }));
+ run(&mut b, &mut s, 4);
+ ok(&mut b, &mut s, "collider", json!({ "id": 8, "body": 7, "sensor": true, "shape": { "type": "capsule", "halfHeight": 0, "radius": radius } }));
+ run(&mut b, &mut s, 30);
+ assert!(ok(&mut b, &mut s, "overlap", json!({ "shape": { "type": "capsule", "halfHeight": 0, "radius": 0.5 }, "position": [0, 0, 0] })).is_array());
+ }
+}
+
+/// A4: sizes of 1e19 and more panicked parry's EPA (epa3.rs: an index out of bounds) in a tick and in queries, and a
+/// hull reaching 1e7–1e9 m panicked in a tick (point_tetrahedron.rs). Sizes and hull points are held to 10 km; a
+/// trimesh's vertices to 100 km.
+#[test]
+fn huge_sizes_are_refused() {
+ let (mut b, mut s) = world();
+ ok(&mut b, &mut s, "body", json!({ "id": 2, "position": [0.3, 3.5, 0] }));
+ ok(&mut b, &mut s, "collider", json!({ "id": 2, "body": 2, "shape": { "type": "box", "halfExtents": [0.5, 0.2, 0.3] } }));
+ let huge = json!({ "type": "box", "halfExtents": [1e19, 1e19, 1e19] });
+ for (op, a, why) in [
+ ("collider", json!({ "id": 1, "shape": huge }), "half extents"),
+ ("collider", json!({ "id": 1, "shape": { "type": "box", "halfExtents": [1e5, 0.5, 0.5] } }), "half extents"),
+ ("collider", json!({ "id": 1, "shape": { "type": "capsule", "halfHeight": 1e9, "radius": 0.5 } }), "half height"),
+ ("collider", json!({ "id": 1, "shape": { "type": "convexHull", "points": [-1, 0, -1, 1, 0, -1, 0, 0, 1, 0, -1, 0, 1e7, 0, 0] } }), "points"),
+ ("collider", json!({ "id": 1, "shape": { "type": "trimesh", "vertices": [-1e30, 0, -1e30, 1e30, 0, -1e30, 1e30, 0, 1e30, -1e30, 0, 1e30], "indices": [0, 2, 1, 0, 3, 2] } }), "vertices"),
+ ("overlap", json!({ "shape": huge, "position": [0, 0, 0] }), "half extents"),
+ ("sweep", json!({ "shape": huge, "position": [0, 9, 0], "direction": [0, -1, 0] }), "half extents"),
+ ("sweep", json!({ "shape": { "type": "box", "halfExtents": [1e19, 0.5, 0.5] }, "position": [0, 0.2, 0], "rotation": [0.1, 0.2, 0.3, 0.9], "direction": [0, -1, 0] }), "half extents"),
+ ] {
+ let e = b.call(&mut s, op, &a).expect_err(&format!("{op} {a} is refused"));
+ assert!(e.contains(why), "{op} {a}: {e}");
+ }
+ // At the bounds it holds: a 10 km static box and a 9 km sliver of a hull, ordinary bodies dropped on both, swept.
+ ok(&mut b, &mut s, "collider", json!({ "id": 1, "position": [0, -MAX_SIZE, 0], "shape": { "type": "box", "halfExtents": [MAX_SIZE, MAX_SIZE, MAX_SIZE] } }));
+ ok(&mut b, &mut s, "collider", json!({ "id": 3, "position": [0, 0.5, 30], "shape": { "type": "convexHull", "points": [-1, 0, -1, 1, 0, -1, 0, 0, 1, 0, -1, 0, 9e3, 0, 0] } }));
+ for k in 0..6u32 {
+ let shape = [json!({ "type": "convexHull", "points": [0, 0, 0, 0.5, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 0.4, 0.4, 0.4] }), sphere(0.3), json!({ "type": "capsule", "halfHeight": 0.3, "radius": 0.2 })][k as usize % 3].clone();
+ ok(&mut b, &mut s, "body", json!({ "id": 10 + k, "position": [0.1 + k as f64 * 0.7, 1.7, 30.1 - 0.05 * k as f64], "rotation": [0.1 * k as f64, 0.2, 0.3, 0.9] }));
+ ok(&mut b, &mut s, "collider", json!({ "id": 10 + k, "body": 10 + k, "shape": shape }));
+ }
+ run(&mut b, &mut s, 240);
+ ok(&mut b, &mut s, "sweep", json!({ "shape": { "type": "box", "halfExtents": [MAX_SIZE, 0.5, 0.5] }, "position": [0, 5, 0], "rotation": [0.1, 0.2, 0.3, 0.9], "direction": [0, -1, 0] }));
+ ok(&mut b, &mut s, "sweep", json!({ "shape": { "type": "box", "halfExtents": [0.3, 0.3, 0.3] }, "position": [0.1, -0.2, 0.1], "rotation": [0.1, 0.2, 0.3, 0.9], "direction": [0, -1, 0] }));
+}
+
+/// A5: the object and the pose table had the call's numbers, not the body's: `rotation: [0, 0, 0, 2]` is the identity
+/// in the body and was [0, 0, 0, 2] in the scene. Placing uses the body's own pose now.
+#[test]
+fn objects_are_placed_where_their_bodies_are() {
+ let (mut b, mut s) = world();
+ ok(&mut b, &mut s, "body", json!({ "id": 1, "object": 3, "slot": 0, "rotation": [0, 0, 0, 2], "gravityScale": 0 }));
+ assert_eq!(s.at[&3].1, [0.0, 0.0, 0.0, 1.0]);
+ assert_eq!(b.poses()[3..7], [0.0, 0.0, 0.0, 1.0]);
+ ok(&mut b, &mut s, "pose", json!({ "body": 1, "position": [1, 2, 3], "rotation": [0, 0, 3, 0] }));
+ assert_eq!(s.at[&3], ([1.0, 2.0, 3.0], [0.0, 0.0, 1.0, 0.0]));
+ assert_eq!(b.poses()[..7], [1.0, 2.0, 3.0, 0.0, 0.0, 1.0, 0.0]);
+}
+
+/// A6: memory with no bound. Contacts nobody takes are held up to `MAX_CONTACTS` (the oldest go, counted); `moved`
+/// between syncs stays within a few times the bodies (an offline settle makes up to 36,000 ticks before its sync); a
+/// trimesh's triangles, the world's shape data and a query's shape are bounded; an index past 2^32 is not cut to 0.
+#[test]
+fn memory_is_bounded() {
+ let (mut b, mut s) = world();
+ for k in 0..200u32 {
+ ok(&mut b, &mut s, "collider", json!({ "id": 1000 + k, "sensor": true, "events": true, "shape": sphere(0.5) }));
+ }
+ ok(&mut b, &mut s, "body", json!({ "id": 1, "position": [0, 5, 0], "gravityScale": 0, "canSleep": false }));
+ for k in 0..20u32 {
+ ok(&mut b, &mut s, "collider", json!({ "id": k, "body": 1, "events": true, "shape": sphere(0.5) }));
+ }
+ // Moved in and out of the sensors every tick: 4,000 contacts begin or end a tick, nobody takes them.
+ for k in 0..60 {
+ ok(&mut b, &mut s, "pose", json!({ "body": 1, "position": [0, if k % 2 == 0 { 0 } else { 5 }, 0] }));
+ run(&mut b, &mut s, 1);
+ }
+ let dropped = ok(&mut b, &mut s, "hash", json!({}))["contactsDropped"].as_u64().unwrap();
+ assert_eq!(ok(&mut b, &mut s, "contacts", Value::Null).as_array().unwrap().len(), MAX_CONTACTS);
+ assert!(dropped > 100_000, "{dropped} dropped");
+ // `moved`, 1,000 awake bodies through 3,600 ticks without a sync.
+ let (mut b, mut s) = world();
+ for k in 0..1000u32 {
+ ok(&mut b, &mut s, "body", json!({ "id": k, "position": [k, 0, 0], "gravityScale": 0, "canSleep": false }));
+ }
+ for _ in 0..3600 {
+ b.tick();
+ assert!(b.moved.len() <= 5 * 1000 + 1024, "{}", b.moved.len());
+ }
+ assert_eq!(b.sync(&mut s), 1000);
+ // Triangles: 2 million on 4 vertices; then the world's total.
+ let tris = |n: usize| -> Vec<u32> { (0..n).flat_map(|k| [0u32, 1 + (k % 2) as u32, 3]).collect() };
+ let mesh = |n: usize| json!({ "type": "trimesh", "vertices": [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], "indices": tris(n) });
+ assert!(b.call(&mut s, "collider", &json!({ "id": 1, "shape": mesh(2_000_000) })).unwrap_err().contains("at most"));
+ let mut k = 0;
+ let e = loop {
+ match b.call(&mut s, "collider", &json!({ "id": 10 + k, "shape": mesh(MAX_MESH_TRIANGLES) })) {
+ Ok(_) => k += 1,
+ Err(e) => break e,
+ }
+ };
+ assert!(e.contains("points and triangles") && k == MAX_SHAPE_DATA as u32 / (MAX_MESH_TRIANGLES as u32 + 4), "{k}: {e}");
+ ok(&mut b, &mut s, "remove", json!({ "collider": 10 }));
+ ok(&mut b, &mut s, "collider", json!({ "id": 10, "shape": mesh(MAX_MESH_TRIANGLES) }));
+ assert!(b.call(&mut s, "overlap", &json!({ "shape": mesh(1), "position": [0.2, 0.2, 0.2] })).unwrap_err().contains("not a trimesh"));
+ let wrap = json!({ "type": "trimesh", "vertices": [0, 0, 0, 1, 0, 0, 0, 1, 0], "indices": [4294967296u64, 1, 2] });
+ assert!(b.call(&mut s, "collider", &json!({ "id": 2, "shape": wrap })).unwrap_err().contains("below 2^32"));
+}
+
+/// A7: a convex hull of points in a plane was accepted with no volume (mass 0: a dynamic body on it hung in the air);
+/// it is refused, as docs/RUNTIME.md says.
+#[test]
+fn a_flat_hull_is_refused() {
+ let (mut b, mut s) = world();
+ ok(&mut b, &mut s, "body", json!({ "id": 1, "position": [0, 2, 0] }));
+ let flat = json!({ "type": "convexHull", "points": [0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0.5, 0, 0.5] });
+ assert!(b.call(&mut s, "collider", &json!({ "id": 1, "body": 1, "shape": flat })).unwrap_err().contains("flat"));
+ let line = json!({ "type": "convexHull", "points": [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3] });
+ assert!(b.call(&mut s, "collider", &json!({ "id": 1, "body": 1, "shape": line })).is_err());
+ ok(&mut b, &mut s, "collider", json!({ "id": 1, "body": 1, "shape": { "type": "convexHull", "points": [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1] } }));
+}
+
+/// A8: a frame owing exactly `MAX_TICKS` ticks dropped its remainder: 12.5 fps made 562 ticks in 10 s, not 600. Only
+/// what a frame owes past `MAX_TICKS` is dropped.
+#[test]
+fn a_frame_of_five_ticks_keeps_its_remainder() {
+ for (fps, expected) in [(12.5, 600), (12.0, 600), (13.0, 600), (60.0, 600), (144.0, 600), (10.0, 500)] {
+ let mut b = Bridge::default();
+ let frames = (10.0 * fps) as u32;
+ let ticks: u32 = (0..frames).map(|_| b.due(1.0 / fps)).sum();
+ assert!(ticks.abs_diff(expected) <= 1, "{fps} fps: {ticks} ticks in 10 s");
+ }
+}
+
+/// A9: a body asleep when its object was removed stayed (only a body that moved found out its object was gone): a new
+/// object with the same id was refused a body, and an impulse on the old body moved the new object. The scene tells
+/// the bridge what it removed.
+#[test]
+fn a_sleeping_body_goes_with_its_object() {
+ let (mut b, mut s) = world();
+ ok(&mut b, &mut s, "collider", json!({ "id": 1000, "position": [0, -0.5, 0], "shape": { "type": "box", "halfExtents": [50, 0.5, 50] } }));
+ s.at.insert(7, ([0.0, 0.3, 0.0], [0.0, 0.0, 0.0, 1.0]));
+ ok(&mut b, &mut s, "body", json!({ "id": 1, "object": 7, "slot": 0 }));
+ ok(&mut b, &mut s, "collider", json!({ "id": 1, "body": 1, "shape": { "type": "box", "halfExtents": [0.3, 0.3, 0.3] } }));
+ run(&mut b, &mut s, 300);
+ assert_eq!(ok(&mut b, &mut s, "state", json!({ "body": 1 }))["sleeping"], true);
+ s.at.remove(&7);
+ b.objects_removed(&[7]);
+ assert!(b.call(&mut s, "state", &json!({ "body": 1 })).unwrap_err().contains("unknown body"));
+ s.at.insert(7, ([30.0, 9.0, 30.0], [0.0, 0.0, 0.0, 1.0]));
+ ok(&mut b, &mut s, "body", json!({ "id": 2, "object": 7, "slot": 0 }));
+ assert!(b.call(&mut s, "impulse", &json!({ "body": 1, "impulse": [0, 50, 0] })).is_err());
+ assert_eq!(s.at[&7].0, [30.0, 9.0, 30.0]);
+}
+
+/// B3: the hash takes one NaN for all (the platforms make NaNs of different bits: ffc00000 natively, 7fc00000 in
+/// wasm32).
+#[test]
+fn the_hash_takes_one_nan() {
+ use crate::world::hash_bits;
+ assert_eq!(hash_bits(f32::from_bits(0xffc0_0000)), hash_bits(f32::from_bits(0x7fc0_0000)));
+ assert_eq!(hash_bits(-0.0), (-0.0f32).to_bits(), "only NaNs are made one");
+}
+
+/// A small generator of integers (the fuzz below is the same on every machine).
+struct Rng(u64);
+
+impl Rng {
+ fn next(&mut self) -> u64 {
+ self.0 ^= self.0 << 13;
+ self.0 ^= self.0 >> 7;
+ self.0 ^= self.0 << 17;
+ self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
+ }
+ fn below(&mut self, n: u64) -> u64 {
+ self.next() % n
+ }
+ fn unit(&mut self) -> f64 {
+ (self.next() >> 11) as f64 / (1u64 << 53) as f64
+ }
+ fn chance(&mut self, p: f64) -> bool {
+ self.unit() < p
+ }
+ /// A number: ordinary (within ±scale) at level 0; at higher levels a quarter of them are 0 or of any size up to
+ /// 1e±4, 1e±9, 1e±20, 1e±40 (past f32: infinite once cast).
+ fn num(&mut self, level: u32, scale: f64) -> f64 {
+ if level == 0 || self.chance(0.75) {
+ return (self.unit() * 2.0 - 1.0) * scale;
+ }
+ if self.chance(0.1) {
+ return 0.0;
+ }
+ let e = [4, 9, 20, 40][level as usize - 1];
+ let x = 10f64.powi(self.below(2 * e + 1) as i32 - e as i32) * (1.0 + self.unit());
+ if self.chance(0.5) {
+ x
+ } else {
+ -x
+ }
+ }
+ fn v3(&mut self, level: u32, scale: f64) -> Value {
+ json!([self.num(level, scale), self.num(level, scale), self.num(level, scale)])
+ }
+ fn quat(&mut self, level: u32) -> Value {
+ json!([self.num(level, 1.0), self.num(level, 1.0), self.num(level, 1.0), self.num(level, 1.0)])
+ }
+ fn shape(&mut self, level: u32) -> Value {
+ let size = |r: &mut Rng| r.num(level, 1.0).abs() + if level == 0 { 0.05 } else { 0.0 };
+ match self.below(6) {
+ 0 | 1 => json!({ "type": "box", "halfExtents": [size(self), size(self), size(self)] }),
+ 2 => json!({ "type": "sphere", "radius": size(self) }),
+ 3 => json!({ "type": "capsule", "halfHeight": if self.chance(0.2) { 0.0 } else { size(self) }, "radius": size(self) }),
+ 4 => {
+ let flat = self.chance(0.15);
+ let points: Vec<f64> = (0..4 + self.below(12)).flat_map(|_| [self.num(level, 1.0), if flat { 0.0 } else { self.num(level, 1.0) }, self.num(level, 1.0)]).collect();
+ json!({ "type": "convexHull", "points": points })
+ }
+ _ => {
+ let n = 3 + self.below(8);
+ let vertices: Vec<f64> = (0..n * 3).map(|_| self.num(level, 3.0)).collect();
+ let indices: Vec<u64> = (0..(1 + self.below(8)) * 3).map(|_| self.below(n + 1)).collect();
+ json!({ "type": "trimesh", "vertices": vertices, "indices": indices })
+ }
+ }
+ }
+}
+
+/// Random calls with ordinary and with absurd numbers (a small version of the review's fuzz, whose 210,000 runs found
+/// the panics above: 611 of 120,000 at its two mildest levels before the fixes, none after): no call and no tick
+/// panics, the pose table stays finite, and the world's hash can always be taken.
+#[test]
+fn random_calls_never_panic() {
+ for level in 0..=4u32 {
+ for seed in 1..=300u64 {
+ let mut r = Rng((seed + level as u64 * 1_000_000).wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1);
+ let (mut b, mut s) = world();
+ if r.chance(0.8) {
+ ok(&mut b, &mut s, "collider", json!({ "id": 999, "position": [0, -0.5, 0], "shape": { "type": "box", "halfExtents": [50, 0.5, 50] }, "events": true }));
+ }
+ for _ in 0..100 {
+ let id = 1 + r.below(10);
+ let (op, a): (&str, Value) = match r.below(26) {
+ 0..=4 => {
+ let kind = ["dynamic", "dynamic", "dynamic", "fixed", "kinematic"][r.below(5) as usize];
+ let mut a = json!({ "id": id, "kind": kind, "ccd": r.chance(0.3), "canSleep": r.chance(0.7), "position": r.v3(level, 3.0) });
+ if r.chance(0.4) {
+ a["rotation"] = r.quat(level);
+ a["linvel"] = r.v3(level, 10.0);
+ a["angvel"] = r.v3(level, 10.0);
+ }
+ if r.chance(0.2) {
+ a["linearDamping"] = json!(r.num(level, 2.0));
+ a["gravityScale"] = json!(r.num(level, 2.0));
+ }
+ if r.chance(0.5) {
+ a["object"] = json!(1 + r.below(12));
+ a["slot"] = json!(r.below(14));
+ }
+ ("body", a)
+ }
+ 5..=9 => {
+ let mut a = json!({ "id": id + 100 * r.below(3), "shape": r.shape(level), "sensor": r.chance(0.15), "events": r.chance(0.5) });
+ if r.chance(0.85) {
+ a["body"] = json!(1 + r.below(10));
+ }
+ if r.chance(0.3) {
+ a["position"] = r.v3(level, 1.0);
+ a["rotation"] = r.quat(level);
+ a[if r.chance(0.5) { "mass" } else { "density" }] = json!(r.num(level, 100.0));
+ a["friction"] = json!(r.num(level, 2.0));
+ }
+ ("collider", a)
+ }
+ 10..=12 => {
+ let ty = ["fixed", "revolute", "prismatic", "spherical", "rope"][r.below(5) as usize];
+ let mut a = json!({ "id": id, "a": 1 + r.below(10), "b": 1 + r.below(10), "type": ty, "length": r.num(level, 2.0).abs(), "anchor1": r.v3(level, 1.0), "anchor2": r.v3(level, 1.0) });
+ if r.chance(0.5) {
+ a["axis"] = r.v3(level, 1.0);
+ a["limits"] = json!([r.num(level, 2.0), r.num(level, 2.0)]);
+ a["motor"] = json!({ "velocity": r.num(level, 5.0), "damping": r.num(level, 1e4), "maxForce": r.num(level, 1e5) });
+ }
+ ("joint", a)
+ }
+ 13 => ("remove", [json!({ "body": id }), json!({ "collider": id }), json!({ "joint": id })][r.below(3) as usize].clone()),
+ 14 => ("impulse", if r.chance(0.5) { json!({ "body": id, "impulse": r.v3(level, 500.0), "torque": r.v3(level, 50.0) }) } else { json!({ "body": id, "impulse": r.v3(level, 500.0), "point": r.v3(level, 3.0) }) }),
+ 15 => ("force", json!({ "body": id, "force": r.v3(level, 5000.0), "torque": r.v3(level, 500.0) })),
+ 16 => ("velocity", json!({ "body": id, "linvel": r.v3(level, 20.0), "angvel": r.v3(level, 20.0) })),
+ 17 => ("pose", json!({ "body": id, "position": r.v3(level, 3.0), "rotation": r.quat(level) })),
+ 18 => ("target", json!({ "body": id, "position": r.v3(level, 3.0), "rotation": r.quat(level) })),
+ 19 => {
+ // The scene moves or removes an object; its body follows.
+ let o = 1 + r.below(12) as u32;
+ if r.chance(0.2) {
+ s.at.remove(&o);
+ b.objects_removed(&[o]);
+ } else {
+ s.at.insert(o, ([r.num(level, 3.0) as f32, r.num(level, 3.0) as f32, r.num(level, 3.0) as f32], [0.0, 0.0, 0.0, 1.0]));
+ }
+ ("follow", json!({ "body": id }))
+ }
+ 20 => ("ray", json!({ "origin": r.v3(level, 5.0), "direction": r.v3(level, 1.0), "max": r.num(level, 100.0).abs(), "all": r.chance(0.5), "skip": id })),
+ 21 => ("overlap", json!({ "shape": r.shape(level), "position": r.v3(level, 3.0), "rotation": r.quat(level) })),
+ 22 => ("sweep", json!({ "shape": r.shape(level), "position": r.v3(level, 3.0), "rotation": r.quat(level), "direction": r.v3(level, 1.0), "max": r.num(level, 100.0).abs() })),
+ 23 => ("gravity", json!({ "gravity": r.v3(level, 20.0) })),
+ 24 => ([("contacts", Value::Null), ("faults", json!({})), ("hash", json!({}))][r.below(3) as usize]).clone(),
+ _ => {
+ for _ in 0..1 + r.below(5) {
+ b.tick();
+ }
+ b.sync(&mut s);
+ ("state", json!({ "body": id }))
+ }
+ };
+ // (A call may be refused, with its reason; it may not panic.)
+ let _ = b.call(&mut s, op, &a);
+ assert!(b.poses().iter().all(|x| x.is_finite()), "level {level}, seed {seed}: a pose is not finite after {op} {a}");
+ }
+ }
+ }
+}
diff --git a/renderer/physics-core/src/world.rs b/renderer/physics-core/src/world.rs
new file mode 100644
index 0000000..8bed8dc
--- /dev/null
+++ b/renderer/physics-core/src/world.rs
@@ -0,0 +1,1303 @@
+//! The physics world: plain descriptions in, handles and poses out.
+
+use rapier3d::parry::query::ShapeCastOptions;
+use rapier3d::prelude::*;
+use std::collections::BTreeMap;
+use std::sync::Mutex;
+
+/// The fixed step, s. The engine steps whole ticks only.
+pub const TICK: f32 = 1.0 / 60.0;
+
+/// The bounds every number of a description or a call is held to (docs/RUNTIME.md lists them). Game code is untrusted,
+/// and a number Rapier cannot take panics a tick natively and traps it in wasm32, so the world refuses what is outside
+/// them (with the reason), whoever calls it. What the simulation itself drives out of bounds is taken out of the world
+/// after the tick (`Physics::take_faults`).
+pub mod limits {
+ /// Positions of bodies and of static colliders, joint anchors, points of impulses, query origins, a trimesh's
+ /// vertices, joint limits and a rope's length: |x| ≤ 100 km.
+ pub const MAX_COORD: f32 = 1e5;
+ /// A body that gets further than this from the origin on any axis is taken out of the world (it left the level).
+ pub const WORLD_EDGE: f32 = 1e6;
+ /// Half extents, radii, a capsule's radius: from 1 mm to 10 km; a capsule's half height up to 10 km (under 1 mm it
+ /// is a sphere). A convex hull's points and a collider's offset on its body: |x| ≤ 10 km.
+ pub const MIN_SIZE: f32 = 1e-3;
+ pub const MAX_SIZE: f32 = 1e4;
+ /// A convex hull holds at least 1 mm³ (points in a plane or on a line have none, so no mass).
+ pub const MIN_VOLUME: f32 = 1e-9;
+ /// m/s and rad/s, as given (what the simulation reaches is not bounded by these).
+ pub const MAX_LINVEL: f32 = 1e4;
+ pub const MAX_ANGVEL: f32 = 1e3;
+ /// N s (and N m s for an angular one), N (and N m).
+ pub const MAX_IMPULSE: f32 = 1e6;
+ pub const MAX_FORCE: f32 = 1e8;
+ /// A collider's mass (kg) and density (kg/m³): 0 (it adds nothing to its body) or within these.
+ pub const MASS: [f32; 2] = [1e-3, 1e7];
+ pub const DENSITY: [f32; 2] = [1e-3, 1e5];
+ /// |gravity scale|; each component of the world's gravity, m/s².
+ pub const MAX_GRAVITY_SCALE: f32 = 100.0;
+ pub const MAX_GRAVITY: f32 = 1e3;
+ /// Damping (linear and angular, 1/s) and friction, from 0; restitution is from 0 to 1.
+ pub const MAX_DAMPING: f32 = 1e3;
+ pub const MAX_FRICTION: f32 = 1e3;
+ /// A joint motor: |velocity| (rad/s or m/s) and its damping; its force has no upper bound (Rapier's default).
+ pub const MAX_MOTOR_VELOCITY: f32 = 1e4;
+ pub const MAX_MOTOR_DAMPING: f32 = 1e9;
+ /// A query reaches at most this far, m (a longer `max` is cut to it).
+ pub const MAX_QUERY_DISTANCE: f32 = 1e6;
+ /// A trimesh's triangles, and the shape data the whole world holds (a hull's points, a trimesh's vertices and
+ /// triangles, summed over its colliders).
+ pub const MAX_MESH_TRIANGLES: usize = 1 << 20;
+ pub const MAX_SHAPE_DATA: usize = 1 << 22;
+ /// Contact events held until `take_contacts`: past this the oldest go (and are counted).
+ pub const MAX_CONTACTS: usize = 8192;
+}
+use limits::*;
+
+pub type BodyId = u32;
+pub type ColliderId = u32;
+pub type JointId = u32;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum BodyKind {
+ /// Moved by forces and contacts.
+ Dynamic,
+ /// Never moves.
+ Fixed,
+ /// Moved by the game (`set_kinematic_target`): it pushes dynamic bodies and is pushed by nothing.
+ Kinematic,
+}
+
+/// A rigid body: position (m), rotation (quaternion xyzw), velocities (m/s, rad/s).
+#[derive(Clone, Debug)]
+pub struct BodyDesc {
+ pub kind: BodyKind,
+ pub position: [f32; 3],
+ pub rotation: [f32; 4],
+ pub linvel: [f32; 3],
+ pub angvel: [f32; 3],
+ pub linear_damping: f32,
+ pub angular_damping: f32,
+ pub gravity_scale: f32,
+ pub can_sleep: bool,
+ /// Continuous collision detection (fast, small bodies).
+ pub ccd: bool,
+}
+
+impl Default for BodyDesc {
+ fn default() -> Self {
+ BodyDesc { kind: BodyKind::Dynamic, position: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], linvel: [0.0; 3], angvel: [0.0; 3], linear_damping: 0.0, angular_damping: 0.0, gravity_scale: 1.0, can_sleep: true, ccd: false }
+ }
+}
+
+/// A collider shape the engine defines (not one of `Shape`'s): it hands Rapier the shape (the voxel shape of step 8).
+pub trait CustomShape {
+ fn shared(&self) -> SharedShape;
+}
+
+pub enum Shape {
+ /// Half extents.
+ Box([f32; 3]),
+ Sphere(f32),
+ /// Along y: half the segment's length, and the radius.
+ Capsule { half_height: f32, radius: f32 },
+ /// The convex hull of the points.
+ ConvexHull(Vec<[f32; 3]>),
+ /// Triangles: for fixed bodies and the world's static colliders only. (Rapier gives an open trimesh a mass from its
+ /// triangles as if they bounded a volume: a few grams with the centre of mass far away, which a dynamic body
+ /// cannot take.)
+ Trimesh { vertices: Vec<[f32; 3]>, indices: Vec<[u32; 3]> },
+ Custom(Box<dyn CustomShape>),
+}
+
+/// A collider: its shape, its pose relative to its body (or in the world without one), and its material.
+pub struct ColliderDesc {
+ pub shape: Shape,
+ pub position: [f32; 3],
+ pub rotation: [f32; 4],
+ /// kg/m³ (the body's mass is its colliders').
+ pub density: f32,
+ /// Its mass in kg, whatever its volume, instead of a density.
+ pub mass: Option<f32>,
+ pub friction: f32,
+ pub restitution: f32,
+ /// A sensor reports what overlaps it and collides with nothing.
+ pub sensor: bool,
+ /// Report its contacts (`Physics::take_contacts`).
+ pub events: bool,
+}
+
+impl ColliderDesc {
+ pub fn new(shape: Shape) -> ColliderDesc {
+ ColliderDesc { shape, position: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], density: 1000.0, mass: None, friction: 0.5, restitution: 0.0, sensor: false, events: false }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Limits {
+ pub min: f32,
+ pub max: f32,
+}
+
+/// A velocity motor: the joint is driven toward `velocity` (rad/s or m/s) by a force of `damping` x the difference (N
+/// s/m, or N m s/rad), at most `max_force`.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Motor {
+ pub velocity: f32,
+ pub damping: f32,
+ pub max_force: f32,
+}
+
+/// A joint between two bodies; anchors and axes in each body's own space.
+#[derive(Clone, Debug)]
+pub enum JointDesc {
+ /// The two bodies keep their relative pose: `anchor1` on the first is held at `anchor2` on the second.
+ Fixed { anchor1: [f32; 3], anchor2: [f32; 3] },
+ /// A hinge about `axis` through the anchors.
+ Revolute { anchor1: [f32; 3], anchor2: [f32; 3], axis: [f32; 3], limits: Option<Limits>, motor: Option<Motor> },
+ /// A slider along `axis`.
+ Prismatic { anchor1: [f32; 3], anchor2: [f32; 3], axis: [f32; 3], limits: Option<Limits>, motor: Option<Motor> },
+ /// A ball joint.
+ Spherical { anchor1: [f32; 3], anchor2: [f32; 3] },
+ /// The anchors stay within `length` of each other (a rope).
+ Rope { anchor1: [f32; 3], anchor2: [f32; 3], length: f32 },
+}
+
+/// Two colliders began or stopped touching.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Contact {
+ pub a: ColliderId,
+ pub b: ColliderId,
+ pub started: bool,
+}
+
+/// A body (or a static collider) the world took out after a tick, with the colliders that went with it, and why.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Fault {
+ pub body: Option<BodyId>,
+ pub colliders: Vec<ColliderId>,
+ /// The body left the world (past `WORLD_EDGE`: it fell off the level, an ordinary thing in a game); otherwise its
+ /// state or a shape went non-finite (bad data or a blown-up simulation: an error the author should hear of).
+ pub left_world: bool,
+ pub reason: &'static str,
+}
+
+/// What a ray or a swept shape met: the collider and its body, the distance along the direction, the surface normal.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Hit {
+ pub collider: ColliderId,
+ pub body: Option<BodyId>,
+ pub distance: f32,
+ pub point: [f32; 3],
+ pub normal: [f32; 3],
+}
+
+#[derive(Default)]
+struct Events(Mutex<Vec<CollisionEvent>>);
+
+impl EventHandler for Events {
+ fn handle_collision_event(&self, _: &RigidBodySet, _: &ColliderSet, event: CollisionEvent, _: Option<&ContactPair>) {
+ self.0.lock().unwrap().push(event);
+ }
+ fn handle_contact_force_event(&self, _: Real, _: &RigidBodySet, _: &ColliderSet, _: &ContactPair, _: Real) {}
+ fn handle_soft_body_tear_event(&self, _: &SoftBodySet, _: &SoftBodyTearEvent) {}
+}
+
+fn v(a: [f32; 3]) -> Vector {
+ Vector::new(a[0], a[1], a[2])
+}
+
+/// The rotation of a quaternion of any finite size (scaled by its largest component first: squaring 1e20 overflows).
+/// Err for one that is not finite or is zero.
+fn rotation(q: [f32; 4]) -> Result<Rotation, String> {
+ let m = q.iter().fold(0.0f32, |m, x| m.max(x.abs()));
+ if !(m.is_finite() && m > 0.0) {
+ return Err("physics: a rotation must be a finite, non-zero quaternion (x, y, z, w)".into());
+ }
+ Ok(Rotation::from_xyzw(q[0] / m, q[1] / m, q[2] / m, q[3] / m).normalize())
+}
+
+fn pose(p: [f32; 3], q: [f32; 4]) -> Result<Pose, String> {
+ Ok(Pose::from_parts(v(p), rotation(q)?))
+}
+
+/// The unit vector along `a`, of any finite size; Err for one that is not finite or is zero.
+fn unit(a: [f32; 3], what: &str) -> Result<Vector, String> {
+ let m = a.iter().fold(0.0f32, |m, x| m.max(x.abs()));
+ if !(m.is_finite() && m > 0.0) {
+ return Err(format!("physics: {what} must be a finite, non-zero vector"));
+ }
+ Ok(Vector::new(a[0] / m, a[1] / m, a[2] / m).normalize())
+}
+
+/// Every number of `a` finite and within ±`max`.
+fn within(a: &[f32], max: f32, what: &str) -> Result<(), String> {
+ if a.iter().all(|x| x.is_finite() && x.abs() <= max) {
+ Ok(())
+ } else {
+ Err(format!("physics: {what} must be finite and within ±{max:e}"))
+ }
+}
+
+/// `x` finite and within [lo, hi].
+fn between(x: f32, lo: f32, hi: f32, what: &str) -> Result<(), String> {
+ if x.is_finite() && x >= lo && x <= hi {
+ Ok(())
+ } else {
+ Err(format!("physics: {what} must be from {lo:e} to {hi:e}"))
+ }
+}
+
+/// A mass or a density: 0, or within `range`.
+fn amount(x: f32, range: [f32; 2], what: &str) -> Result<(), String> {
+ if x == 0.0 {
+ Ok(())
+ } else {
+ between(x, range[0], range[1], what).map_err(|e| format!("{e} (or 0)"))
+ }
+}
+
+impl Shape {
+ /// The shape's data as the world counts it against `MAX_SHAPE_DATA`: a hull's points, a trimesh's vertices and
+ /// triangles (the others hold a few numbers; a custom shape is the engine's, not counted).
+ fn data(&self) -> usize {
+ match self {
+ Shape::ConvexHull(p) => p.len(),
+ Shape::Trimesh { vertices, indices } => vertices.len() + indices.len(),
+ _ => 0,
+ }
+ }
+
+ /// The Rapier shape, or why it cannot be built (a size out of bounds, no volume, bad numbers).
+ fn shared(&self) -> Result<SharedShape, String> {
+ let size = |x: f32, what: &str| between(x, MIN_SIZE, MAX_SIZE, what);
+ match self {
+ Shape::Box(h) => {
+ for &x in h {
+ size(x, "a box's half extents")?;
+ }
+ Ok(SharedShape::cuboid(h[0], h[1], h[2]))
+ }
+ Shape::Sphere(r) => size(*r, "a sphere's radius").map(|_| SharedShape::ball(*r)),
+ Shape::Capsule { half_height, radius } => {
+ size(*radius, "a capsule's radius")?;
+ between(*half_height, 0.0, MAX_SIZE, "a capsule's half height")?;
+ // (A segment of (nearly) no length fails parry's assertions in a tick: that capsule is its sphere.)
+ Ok(if *half_height < MIN_SIZE { SharedShape::ball(*radius) } else { SharedShape::capsule_y(*half_height, *radius) })
+ }
+ Shape::ConvexHull(points) => {
+ if points.len() < 4 {
+ return Err("physics: a convex hull needs 4 points".into());
+ }
+ for p in points {
+ within(p, MAX_SIZE, "a convex hull's points")?;
+ }
+ let pts: Vec<Vector> = points.iter().map(|&p| v(p)).collect();
+ let s = SharedShape::convex_hull(&pts).ok_or("physics: the convex hull of these points cannot be built")?;
+ // (Points in a plane give a flat hull: no volume, so no mass, and a dynamic body on it hangs in the air.)
+ let volume = s.mass_properties(1.0).mass();
+ if !(volume >= MIN_VOLUME) {
+ return Err(format!("physics: a convex hull must hold a volume (at least {MIN_VOLUME:e} m³): these points are flat"));
+ }
+ Ok(s)
+ }
+ Shape::Trimesh { vertices, indices } => {
+ if indices.is_empty() || indices.len() > MAX_MESH_TRIANGLES {
+ return Err(format!("physics: a trimesh needs from 1 to {MAX_MESH_TRIANGLES} triangles"));
+ }
+ for p in vertices {
+ within(p, MAX_COORD, "a trimesh's vertices")?;
+ }
+ let n = vertices.len();
+ if indices.iter().any(|t| t.iter().any(|&i| i as usize >= n)) {
+ return Err("physics: a trimesh's index is past its vertices".into());
+ }
+ SharedShape::trimesh(vertices.iter().map(|&p| v(p)).collect(), indices.clone()).map_err(|e| format!("physics: the trimesh cannot be built ({e})"))
+ }
+ Shape::Custom(c) => Ok(c.shared()),
+ }
+ }
+}
+
+/// A number's bits as the hash takes them: one NaN for all (the platforms make NaNs of different bits, ffc00000
+/// natively and 7fc00000 in wasm32).
+pub(crate) fn hash_bits(x: f32) -> u32 {
+ if x.is_nan() {
+ 0x7fc0_0000
+ } else {
+ x.to_bits()
+ }
+}
+
+/// The physics world. Ids are the world's own, never reused; removed things are simply gone.
+pub struct Physics {
+ world: PhysicsWorld,
+ events: Events,
+ bodies: BTreeMap<BodyId, RigidBodyHandle>,
+ /// Each collider with its shape's data (`Shape::data`), and their sum.
+ colliders: BTreeMap<ColliderId, (ColliderHandle, usize)>,
+ shape_data: usize,
+ joints: BTreeMap<JointId, ImpulseJointHandle>,
+ /// The kinematic bodies (`awake`: the islands hold dynamic ones only).
+ kinematic: std::collections::BTreeSet<BodyId>,
+ next: u32,
+ ticks: u64,
+ contacts: std::collections::VecDeque<Contact>,
+ contacts_dropped: u64,
+ /// What was taken out of the world after a tick, and why (`take_faults`).
+ faults: Vec<Fault>,
+}
+
+impl Default for Physics {
+ fn default() -> Self {
+ Physics::new([0.0, -9.81, 0.0])
+ }
+}
+
+impl Physics {
+ pub fn new(gravity: [f32; 3]) -> Physics {
+ let mut world = PhysicsWorld::new();
+ world.gravity = v(gravity);
+ world.integration_parameters.dt = TICK;
+ Physics {
+ world,
+ events: Events::default(),
+ bodies: BTreeMap::new(),
+ colliders: BTreeMap::new(),
+ shape_data: 0,
+ joints: BTreeMap::new(),
+ kinematic: Default::default(),
+ next: 0,
+ ticks: 0,
+ contacts: Default::default(),
+ contacts_dropped: 0,
+ faults: vec![],
+ }
+ }
+
+ fn id(&mut self) -> u32 {
+ self.next += 1;
+ self.next
+ }
+
+ pub fn set_gravity(&mut self, gravity: [f32; 3]) -> Result<(), String> {
+ within(&gravity, MAX_GRAVITY, "gravity")?;
+ self.world.gravity = v(gravity);
+ Ok(())
+ }
+
+ /// Ticks stepped so far.
+ pub fn ticks(&self) -> u64 {
+ self.ticks
+ }
+
+ pub fn bodies(&self) -> usize {
+ self.bodies.len()
+ }
+
+ /// Adds a body; Err (why) if a number is out of its bounds (`limits`).
+ pub fn add_body(&mut self, d: &BodyDesc) -> Result<BodyId, String> {
+ within(&d.position, MAX_COORD, "a body's position")?;
+ within(&d.linvel, MAX_LINVEL, "a body's linear velocity")?;
+ within(&d.angvel, MAX_ANGVEL, "a body's angular velocity")?;
+ between(d.linear_damping, 0.0, MAX_DAMPING, "linear damping")?;
+ between(d.angular_damping, 0.0, MAX_DAMPING, "angular damping")?;
+ within(&[d.gravity_scale], MAX_GRAVITY_SCALE, "the gravity scale")?;
+ let b = match d.kind {
+ BodyKind::Dynamic => RigidBodyBuilder::dynamic(),
+ BodyKind::Fixed => RigidBodyBuilder::fixed(),
+ BodyKind::Kinematic => RigidBodyBuilder::kinematic_position_based(),
+ }
+ .pose(pose(d.position, d.rotation)?)
+ .linvel(v(d.linvel))
+ .angvel(v(d.angvel))
+ .linear_damping(d.linear_damping)
+ .angular_damping(d.angular_damping)
+ .gravity_scale(d.gravity_scale)
+ .can_sleep(d.can_sleep)
+ .ccd_enabled(d.ccd);
+ // (Its id rides in Rapier's user data: from a handle back to the id.)
+ let id = self.id();
+ let h = self.world.insert_body(b.user_data(id as u128));
+ self.bodies.insert(id, h);
+ if d.kind == BodyKind::Kinematic {
+ self.kinematic.insert(id);
+ }
+ Ok(id)
+ }
+
+ /// Removes a body with its colliders and joints. Returns the colliders that went with it.
+ pub fn remove_body(&mut self, id: BodyId) -> Vec<ColliderId> {
+ let Some(h) = self.bodies.remove(&id) else { return vec![] };
+ self.kinematic.remove(&id);
+ // (Its own colliders and joints only: removing a body costs what it holds, not what the world holds.)
+ let gone: Vec<ColliderId> = self.world.bodies.get(h).map(|b| b.colliders().iter().filter_map(|&c| self.world.colliders.get(c).map(|c| c.user_data as u32)).collect()).unwrap_or_default();
+ let jointed = self.world.impulse_joints.attached_joints(h).next().is_some();
+ self.world.remove_body_with_colliders(h, true);
+ for c in &gone {
+ if let Some((_, data)) = self.colliders.remove(c) {
+ self.shape_data -= data;
+ }
+ }
+ if jointed {
+ let world = &self.world;
+ self.joints.retain(|_, j| world.impulse_joints.get(*j).is_some());
+ }
+ gone
+ }
+
+ /// Adds a collider to `body` (None: a static collider in the world). Err (why) if the body is unknown, the shape
+ /// cannot be built, a number is out of its bounds, or the world's shape data would pass `MAX_SHAPE_DATA`.
+ pub fn add_collider(&mut self, body: Option<BodyId>, d: &ColliderDesc) -> Result<ColliderId, String> {
+ let parent = match body {
+ Some(b) => Some(*self.bodies.get(&b).ok_or("physics: unknown body")?),
+ None => None,
+ };
+ // (On a body its offset moves the centre of mass: a size; in the world it is a place.)
+ within(&d.position, if parent.is_some() { MAX_SIZE } else { MAX_COORD }, "a collider's position")?;
+ amount(d.density, DENSITY, "a collider's density")?;
+ if let Some(m) = d.mass {
+ amount(m, MASS, "a collider's mass")?;
+ }
+ between(d.friction, 0.0, MAX_FRICTION, "friction")?;
+ between(d.restitution, 0.0, 1.0, "restitution")?;
+ if matches!(d.shape, Shape::Trimesh { .. }) && parent.is_some_and(|p| !self.world.bodies[p].is_fixed()) {
+ return Err("physics: a trimesh is for fixed bodies and static colliders only (it has no volume to give a moving body a mass)".into());
+ }
+ let data = d.shape.data();
+ if self.shape_data + data > MAX_SHAPE_DATA {
+ return Err(format!("physics: the world's colliders would hold more than {MAX_SHAPE_DATA} points and triangles"));
+ }
+ let shape = d.shape.shared()?;
+ let mut c = ColliderBuilder::new(shape).position(pose(d.position, d.rotation)?).density(d.density).friction(d.friction).restitution(d.restitution).sensor(d.sensor);
+ if let Some(m) = d.mass {
+ c = c.mass(m);
+ }
+ if d.events {
+ c = c.active_events(ActiveEvents::COLLISION_EVENTS);
+ }
+ let id = self.id();
+ let h = self.world.insert_collider(c.user_data(id as u128), parent);
+ self.colliders.insert(id, (h, data));
+ self.shape_data += data;
+ Ok(id)
+ }
+
+ pub fn remove_collider(&mut self, id: ColliderId) {
+ if let Some((h, data)) = self.colliders.remove(&id) {
+ self.world.remove_collider(h);
+ self.shape_data -= data;
+ }
+ }
+
+ /// Joins two bodies; None if one is unknown or the joint's numbers are bad. Anchors are in each body's space, an
+ /// axis in the first body's. The bodies are joined as they are turned now: a fixed joint keeps their turn against
+ /// each other, and a hinge's or a slider's angle or travel is 0 as they are (its limits count from there).
+ pub fn add_joint(&mut self, a: BodyId, b: BodyId, d: &JointDesc) -> Result<JointId, String> {
+ let (ha, hb) = (*self.bodies.get(&a).ok_or("physics: unknown body")?, *self.bodies.get(&b).ok_or("physics: unknown body")?);
+ // (Rapier's joint graph cannot take a joint from a body to itself: removing that body panics a later tick.)
+ if a == b {
+ return Err("physics: a joint joins two different bodies".into());
+ }
+ // (A disabled body's joint panics the next tick; the world never keeps one, this is the guard.)
+ if !(self.world.bodies[ha].is_enabled() && self.world.bodies[hb].is_enabled()) {
+ return Err("physics: a joint's body is disabled".into());
+ }
+ let (anchor1, anchor2) = match d {
+ JointDesc::Fixed { anchor1, anchor2 } | JointDesc::Revolute { anchor1, anchor2, .. } | JointDesc::Prismatic { anchor1, anchor2, .. } | JointDesc::Spherical { anchor1, anchor2 } | JointDesc::Rope { anchor1, anchor2, .. } => (*anchor1, *anchor2),
+ };
+ within(&anchor1, MAX_COORD, "a joint's anchor")?;
+ within(&anchor2, MAX_COORD, "a joint's anchor")?;
+ let limits = |l: &Option<Limits>| -> Result<Option<[f32; 2]>, String> {
+ match l {
+ None => Ok(None),
+ Some(l) => {
+ within(&[l.min, l.max], MAX_COORD, "a joint's limits")?;
+ if l.min > l.max {
+ return Err("physics: a joint's limits must be [min, max] with min <= max".into());
+ }
+ Ok(Some([l.min, l.max]))
+ }
+ }
+ };
+ let motor = |m: &Option<Motor>| -> Result<Option<Motor>, String> {
+ match m {
+ None => Ok(None),
+ Some(m) => {
+ within(&[m.velocity], MAX_MOTOR_VELOCITY, "a motor's velocity")?;
+ between(m.damping, 0.0, MAX_MOTOR_DAMPING, "a motor's damping")?;
+ between(m.max_force, 0.0, f32::MAX, "a motor's maximum force")?;
+ Ok(Some(*m))
+ }
+ }
+ };
+ let (a1, a2) = (v(anchor1), v(anchor2));
+ // The centre of a hinge's limits, rad (0: none, or limits about 0).
+ let mut centre = 0.0f32;
+ let mut joint: GenericJoint = match d {
+ JointDesc::Fixed { .. } => FixedJointBuilder::new().local_anchor1(a1).local_anchor2(a2).build().into(),
+ JointDesc::Revolute { axis, limits: l, motor: m, .. } => {
+ let mut j = RevoluteJointBuilder::new(unit(*axis, "a joint's axis")?).local_anchor1(a1).local_anchor2(a2);
+ // Limits go to Rapier centred, [-h, h], with their centre turned into the first body's joint frame
+ // below. Rapier takes the sine and cosine of a quarter of (min + max) with f32's own methods, the
+ // platform's libm wherever `std` is in the crate graph (0.024 % of angles then differ in the last bit
+ // between macOS and wasm32); of 0 they are exact everywhere, and the centre's are libm's here.
+ if let Some([min, max]) = limits(l)? {
+ let half = (max - min) * 0.5;
+ centre = (min + max) * 0.5;
+ j = j.limits([-half, half]);
+ }
+ if let Some(m) = motor(m)? {
+ j = j.motor_velocity(m.velocity, m.damping).motor_max_force(m.max_force);
+ }
+ j.build().into()
+ }
+ JointDesc::Prismatic { axis, limits: l, motor: m, .. } => {
+ let mut j = PrismaticJointBuilder::new(unit(*axis, "a joint's axis")?).local_anchor1(a1).local_anchor2(a2);
+ if let Some(l) = limits(l)? {
+ j = j.limits(l);
+ }
+ if let Some(m) = motor(m)? {
+ j = j.motor_velocity(m.velocity, m.damping).motor_max_force(m.max_force);
+ }
+ j.build().into()
+ }
+ JointDesc::Spherical { .. } => SphericalJointBuilder::new().local_anchor1(a1).local_anchor2(a2).build().into(),
+ JointDesc::Rope { length, .. } => {
+ between(*length, 0.0, MAX_COORD, "a rope's length")?;
+ RopeJointBuilder::new(*length).local_anchor1(a1).local_anchor2(a2).build().into()
+ }
+ };
+ // The joint's frame in the second body is where the first body's is now (the builders give both bodies the
+ // same frame, which is right only for bodies turned alike: others would be wrenched into line).
+ if matches!(d, JointDesc::Fixed { .. } | JointDesc::Revolute { .. } | JointDesc::Prismatic { .. }) {
+ let (ra, rb) = (self.world.bodies[ha].position().rotation, self.world.bodies[hb].position().rotation);
+ joint.local_frame2.rotation = (rb.inverse() * ra * joint.local_frame1.rotation).normalize();
+ }
+ // A hinge's limits centred: the first body's frame turned by the centre about the hinge (its x axis), so the
+ // angle Rapier reads is the hinge's less the centre, -centre as the bodies are now, and [-h, h] is [min, max].
+ if centre != 0.0 {
+ let (s, c) = libm::sincosf(centre * 0.5);
+ joint.local_frame1.rotation = (joint.local_frame1.rotation * Rotation::from_xyzw(s, 0.0, 0.0, c)).normalize();
+ }
+ let h = self.world.insert_impulse_joint(ha, hb, joint);
+ let id = self.id();
+ self.joints.insert(id, h);
+ Ok(id)
+ }
+
+ pub fn remove_joint(&mut self, id: JointId) {
+ if let Some(h) = self.joints.remove(&id) {
+ self.world.remove_impulse_joint(h);
+ }
+ }
+
+ pub fn has_collider(&self, id: ColliderId) -> bool {
+ self.colliders.contains_key(&id)
+ }
+
+ pub fn has_joint(&self, id: JointId) -> bool {
+ self.joints.contains_key(&id)
+ }
+
+ /// One tick of `TICK` seconds. Contacts that began or ended are kept for `take_contacts`. A body the tick left in
+ /// a state the world cannot keep is then taken out with its colliders and joints (`take_faults` says which and
+ /// why): one whose pose or velocity went non-finite (Rapier disables it and leaves it frozen, and a joint on it
+ /// would panic a later tick), one whose collider did, and one past `WORLD_EDGE`.
+ pub fn step(&mut self) {
+ self.world.step_with_events(&(), &self.events);
+ self.ticks += 1;
+ for e in self.events.0.lock().unwrap().drain(..) {
+ // (A removed collider's contact ends without it: its id is no longer known.)
+ let id = |h: ColliderHandle| self.world.colliders.get(h).map(|c| c.user_data as u32);
+ if let (Some(a), Some(b)) = (id(e.collider1()), id(e.collider2())) {
+ if self.contacts.len() == MAX_CONTACTS {
+ self.contacts.pop_front();
+ self.contacts_dropped += 1;
+ }
+ self.contacts.push_back(Contact { a: a.min(b), b: a.max(b), started: e.started() });
+ }
+ }
+ let q = self.world.quarantine();
+ let mut out: Vec<(RigidBodyHandle, bool, &'static str)> = q.bodies().iter().map(|&h| (h, false, "its pose or velocity went non-finite")).collect();
+ let mut statics = vec![];
+ for &c in q.colliders() {
+ match self.world.colliders.get(c).and_then(|c| c.parent()) {
+ Some(p) => out.push((p, false, "its collider's shape went non-finite")),
+ None => statics.push(c),
+ }
+ }
+ out.extend(self.world.active_bodies().filter(|(_, b)| b.is_dynamic() && !(b.translation().abs().max_element() <= WORLD_EDGE)).map(|(h, _)| (h, true, "it left the world (past 1e6 m from the origin)")));
+ for c in statics {
+ if let Some(id) = self.world.colliders.get(c).map(|c| c.user_data as u32) {
+ self.remove_collider(id);
+ self.faults.push(Fault { body: None, colliders: vec![id], left_world: false, reason: "its shape went non-finite" });
+ }
+ }
+ for (h, left_world, reason) in out {
+ let Some(id) = self.world.bodies.get(h).map(|b| b.user_data as u32) else { continue };
+ if self.bodies.contains_key(&id) {
+ let colliders = self.remove_body(id);
+ self.faults.push(Fault { body: Some(id), colliders, left_world, reason });
+ }
+ }
+ }
+
+ /// The contacts begun and ended since the last call (colliders with `events`), in the order they happened (the
+ /// newest `MAX_CONTACTS` of them).
+ pub fn take_contacts(&mut self) -> Vec<Contact> {
+ std::mem::take(&mut self.contacts).into()
+ }
+
+ /// Contacts dropped so far because nobody took them (`MAX_CONTACTS`).
+ pub fn contacts_dropped(&self) -> u64 {
+ self.contacts_dropped
+ }
+
+ /// What the ticks since the last call took out of the world, and why (`step`).
+ pub fn take_faults(&mut self) -> Vec<Fault> {
+ std::mem::take(&mut self.faults)
+ }
+
+ fn body(&self, id: BodyId) -> Option<&RigidBody> {
+ self.world.bodies.get(*self.bodies.get(&id)?)
+ }
+
+ fn body_mut(&mut self, id: BodyId) -> Option<&mut RigidBody> {
+ let h = *self.bodies.get(&id)?;
+ self.world.bodies.get_mut(h)
+ }
+
+ /// A body's position and rotation (quaternion xyzw).
+ pub fn pose(&self, id: BodyId) -> Option<([f32; 3], [f32; 4])> {
+ let p = self.body(id)?.position();
+ Some((p.translation.to_array(), p.rotation.to_array()))
+ }
+
+ /// A body's linear and angular velocity.
+ pub fn velocity(&self, id: BodyId) -> Option<([f32; 3], [f32; 3])> {
+ let b = self.body(id)?;
+ Some((b.linvel().to_array(), b.angvel().to_array()))
+ }
+
+ pub fn sleeping(&self, id: BodyId) -> bool {
+ self.body(id).is_some_and(|b| b.is_sleeping())
+ }
+
+ pub fn is_kinematic(&self, id: BodyId) -> bool {
+ self.kinematic.contains(&id)
+ }
+
+ pub fn mass(&self, id: BodyId) -> Option<f32> {
+ Some(self.body(id)?.mass())
+ }
+
+ /// Bodies that moved in the last step (awake dynamic bodies and kinematic ones), with their poses, in id order.
+ pub fn moved(&self) -> Vec<(BodyId, [f32; 3], [f32; 4])> {
+ self.bodies
+ .iter()
+ .filter_map(|(&id, &h)| {
+ let b = self.world.bodies.get(h)?;
+ (!b.is_fixed() && !b.is_sleeping()).then(|| (id, b.position().translation.to_array(), b.position().rotation.to_array()))
+ })
+ .collect()
+ }
+
+ /// The ids of the bodies that are awake (dynamic ones in an active island, kinematic ones that are not asleep),
+ /// added to `out` in no order: what the last step moved, at the cost of the awake bodies only.
+ pub fn awake(&self, out: &mut Vec<BodyId>) {
+ out.extend(self.world.active_bodies().filter(|(_, b)| b.is_dynamic()).map(|(_, b)| b.user_data as u32));
+ for &id in &self.kinematic {
+ if self.body(id).is_some_and(|b| !b.is_sleeping()) {
+ out.push(id);
+ }
+ }
+ }
+
+ /// Moves a body there at once (a teleport; its velocity kept).
+ pub fn set_pose(&mut self, id: BodyId, position: [f32; 3], rotation: [f32; 4]) -> Result<(), String> {
+ within(&position, MAX_COORD, "a body's position")?;
+ let p = pose(position, rotation)?;
+ if let Some(b) = self.body_mut(id) {
+ b.set_position(p, true);
+ }
+ Ok(())
+ }
+
+ /// Sets either velocity or both (None keeps that one: a body may have reached more than a call may set).
+ pub fn set_velocity(&mut self, id: BodyId, linvel: Option<[f32; 3]>, angvel: Option<[f32; 3]>) -> Result<(), String> {
+ if let Some(l) = linvel {
+ within(&l, MAX_LINVEL, "a linear velocity")?;
+ }
+ if let Some(a) = angvel {
+ within(&a, MAX_ANGVEL, "an angular velocity")?;
+ }
+ if let Some(b) = self.body_mut(id) {
+ if let Some(l) = linvel {
+ b.set_linvel(v(l), true);
+ }
+ if let Some(a) = angvel {
+ b.set_angvel(v(a), true);
+ }
+ }
+ Ok(())
+ }
+
+ /// An impulse (N s) at the body's centre of mass, and an angular one (N m s).
+ pub fn apply_impulse(&mut self, id: BodyId, impulse: [f32; 3], torque: [f32; 3]) -> Result<(), String> {
+ within(&impulse, MAX_IMPULSE, "an impulse")?;
+ within(&torque, MAX_IMPULSE, "an angular impulse")?;
+ if let Some(b) = self.body_mut(id) {
+ b.apply_impulse(v(impulse), true);
+ b.apply_torque_impulse(v(torque), true);
+ }
+ Ok(())
+ }
+
+ /// An impulse (N s) at a point of the world (it turns the body as well, unless the point is its centre of mass), and
+ /// an angular one (N m s). All of it is checked before any of it acts: a call that is refused changes nothing.
+ pub fn apply_impulse_at(&mut self, id: BodyId, impulse: [f32; 3], point: [f32; 3], torque: [f32; 3]) -> Result<(), String> {
+ within(&impulse, MAX_IMPULSE, "an impulse")?;
+ within(&point, MAX_COORD, "an impulse's point")?;
+ within(&torque, MAX_IMPULSE, "an angular impulse")?;
+ if let Some(b) = self.body_mut(id) {
+ b.apply_impulse_at_point(v(impulse), v(point), true);
+ b.apply_torque_impulse(v(torque), true);
+ }
+ Ok(())
+ }
+
+ /// A force (N) at the centre of mass and a torque (N m), added to those the body has: they act in every step until
+ /// `clear_forces`.
+ pub fn add_force(&mut self, id: BodyId, force: [f32; 3], torque: [f32; 3]) -> Result<(), String> {
+ within(&force, MAX_FORCE, "a force")?;
+ within(&torque, MAX_FORCE, "a torque")?;
+ if let Some(b) = self.body_mut(id) {
+ b.add_force(v(force), true);
+ b.add_torque(v(torque), true);
+ }
+ Ok(())
+ }
+
+ pub fn clear_forces(&mut self, id: BodyId) {
+ if let Some(b) = self.body_mut(id) {
+ b.reset_forces(false);
+ b.reset_torques(false);
+ }
+ }
+
+ /// Where a kinematic body is at the end of the next step (it moves there, pushing what is in the way).
+ pub fn set_kinematic_target(&mut self, id: BodyId, position: [f32; 3], rotation: [f32; 4]) -> Result<(), String> {
+ within(&position, MAX_COORD, "a kinematic body's target")?;
+ let p = pose(position, rotation)?;
+ if let Some(b) = self.body_mut(id).filter(|b| b.is_kinematic()) {
+ b.set_next_kinematic_position(p);
+ }
+ Ok(())
+ }
+
+ fn hit(&self, h: ColliderHandle, distance: f32, point: Vector, normal: Vector) -> Option<Hit> {
+ let c = self.world.colliders.get(h)?;
+ let collider = c.user_data as u32;
+ let body = c.parent().and_then(|p| self.world.bodies.get(p)).map(|b| b.user_data as u32);
+ Some(Hit { collider, body, distance, point: point.to_array(), normal: normal.to_array() })
+ }
+
+ /// The first collider a ray meets within `max` metres (the world as of the last step). `skip`: a body whose
+ /// colliders the ray passes through (the one that casts it).
+ pub fn cast_ray(&self, origin: [f32; 3], direction: [f32; 3], max: f32, skip: Option<BodyId>) -> Result<Option<Hit>, String> {
+ let Some((ray, max)) = Self::ray(origin, direction, max)? else { return Ok(None) };
+ let Some((h, i)) = self.world.cast_ray_and_get_normal(&ray, max, true, self.filter(skip)) else { return Ok(None) };
+ Ok(self.hit(h, i.time_of_impact, ray.point_at(i.time_of_impact), i.normal))
+ }
+
+ /// Every collider a ray passes through within `max` metres, nearest first, at most `limit` of them.
+ pub fn cast_ray_all(&self, origin: [f32; 3], direction: [f32; 3], max: f32, skip: Option<BodyId>, limit: usize) -> Result<Vec<Hit>, String> {
+ let Some((ray, max)) = Self::ray(origin, direction, max)? else { return Ok(vec![]) };
+ let mut hits: Vec<Hit> = self.world.intersect_ray(ray, max, true, self.filter(skip)).filter_map(|(h, _, i)| self.hit(h, i.time_of_impact, ray.point_at(i.time_of_impact), i.normal)).collect();
+ // (Equal distances in collider order: the same answer on every machine.)
+ hits.sort_by(|a, b| a.distance.total_cmp(&b.distance).then(a.collider.cmp(&b.collider)));
+ hits.truncate(limit);
+ Ok(hits)
+ }
+
+ /// A query's ray and reach (cut to `MAX_QUERY_DISTANCE`); None for a reach of 0 or less (it meets nothing).
+ fn ray(origin: [f32; 3], direction: [f32; 3], max: f32) -> Result<Option<(Ray, f32)>, String> {
+ within(&origin, MAX_COORD, "a query's origin")?;
+ let d = unit(direction, "a query's direction")?;
+ if max.is_nan() {
+ return Err("physics: a query's max must be a number".into());
+ }
+ Ok((max > 0.0).then(|| (Ray::new(v(origin), d), max.min(MAX_QUERY_DISTANCE))))
+ }
+
+ /// A query's shape: a box, a sphere, a capsule, a convex hull or the engine's own (a trimesh is built anew for
+ /// every call; queries do not take one).
+ fn query_shape(shape: &Shape) -> Result<SharedShape, String> {
+ if matches!(shape, Shape::Trimesh { .. }) {
+ return Err("physics: a query's shape is a box, a sphere, a capsule or a convex hull, not a trimesh".into());
+ }
+ shape.shared()
+ }
+
+ fn filter(&self, skip: Option<BodyId>) -> QueryFilter<'_> {
+ match skip.and_then(|b| self.bodies.get(&b)) {
+ Some(&h) => QueryFilter::default().exclude_rigid_body(h),
+ None => QueryFilter::default(),
+ }
+ }
+
+ /// The colliders a shape placed at a pose overlaps, in id order.
+ pub fn overlap(&self, shape: &Shape, position: [f32; 3], rotation: [f32; 4], skip: Option<BodyId>) -> Result<Vec<ColliderId>, String> {
+ let s = Self::query_shape(shape)?;
+ within(&position, MAX_COORD, "a query's position")?;
+ let mut out: Vec<ColliderId> = self.world.intersect_shape(pose(position, rotation)?, &*s.0, self.filter(skip)).map(|(_, c)| c.user_data as u32).collect();
+ out.sort_unstable();
+ Ok(out)
+ }
+
+ /// The first collider a shape meets when moved from a pose along `direction` by at most `max` metres.
+ pub fn sweep(&self, shape: &Shape, position: [f32; 3], rotation: [f32; 4], direction: [f32; 3], max: f32, skip: Option<BodyId>) -> Result<Option<Hit>, String> {
+ let s = Self::query_shape(shape)?;
+ let p = pose(position, rotation)?;
+ let Some((ray, max)) = Self::ray(position, direction, max)? else { return Ok(None) };
+ let options = ShapeCastOptions { max_time_of_impact: max, target_distance: 0.0, stop_at_penetration: true, compute_impact_geometry_on_penetration: true };
+ let Some((h, hit)) = self.world.cast_shape(&p, ray.dir, &*s.0, options, self.filter(skip)) else { return Ok(None) };
+ Ok(self.hit(h, hit.time_of_impact, hit.witness1, hit.normal1))
+ }
+
+ /// Tests only: the body's velocity made infinite behind the world's checks (as only Rapier itself could), so that
+ /// the next tick quarantines it.
+ #[cfg(test)]
+ pub(crate) fn break_body(&mut self, id: BodyId) {
+ let h = self.bodies[&id];
+ self.world.bodies[h].set_linvel(Vector::new(f32::INFINITY, 0.0, 0.0), true);
+ }
+
+ /// Tests only: the body moved to a place behind the world's checks.
+ #[cfg(test)]
+ pub(crate) fn put_body(&mut self, id: BodyId, at: [f32; 3]) {
+ let h = self.bodies[&id];
+ self.world.bodies[h].set_translation(v(at), true);
+ }
+
+ /// A hash of every body's pose and velocity, bit for bit, in id order (FNV-1a): equal worlds hash alike.
+ pub fn hash(&self) -> u64 {
+ let mut h = 0xcbf2_9ce4_8422_2325u64;
+ let mut feed = |x: u32| {
+ for b in x.to_le_bytes() {
+ h = (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ };
+ for (&id, &handle) in &self.bodies {
+ let Some(b) = self.world.bodies.get(handle) else { continue };
+ feed(id);
+ for x in b.position().translation.to_array().into_iter().chain(b.position().rotation.to_array()).chain(b.linvel().to_array()).chain(b.angvel().to_array()) {
+ feed(hash_bits(x));
+ }
+ }
+ h
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const G: f32 = 9.81;
+
+ /// A world with a ground whose top is the plane y = 0.
+ fn ground() -> (Physics, ColliderId) {
+ let mut p = Physics::default();
+ let g = p.add_collider(None, &ColliderDesc { position: [0.0, -0.5, 0.0], ..ColliderDesc::new(Shape::Box([50.0, 0.5, 50.0])) }).unwrap();
+ (p, g)
+ }
+
+ fn body(p: &mut Physics, position: [f32; 3], shape: Shape) -> BodyId {
+ let b = p.add_body(&BodyDesc { position, ..Default::default() }).unwrap();
+ p.add_collider(Some(b), &ColliderDesc::new(shape)).unwrap();
+ b
+ }
+
+ fn fixed(p: &mut Physics, position: [f32; 3]) -> BodyId {
+ p.add_body(&BodyDesc { kind: BodyKind::Fixed, position, ..Default::default() }).unwrap()
+ }
+
+ fn run(p: &mut Physics, ticks: u32) {
+ for _ in 0..ticks {
+ p.step();
+ }
+ }
+
+ fn dist(a: [f32; 3], b: [f32; 3]) -> f32 {
+ (0..3).map(|k| (a[k] - b[k]).powi(2)).sum::<f32>().sqrt()
+ }
+
+ /// Free fall follows the integrator's own law: Rapier integrates a tick in 4 substeps (velocity first, then
+ /// position), so after n ticks a body has dropped g dt² (n² / 2 + n / 8), within a millimetre of it; that is within
+ /// 0.5 % of g t² / 2 after a second.
+ #[test]
+ fn free_fall() {
+ let mut p = Physics::default();
+ let b = body(&mut p, [0.0, 100.0, 0.0], Shape::Sphere(0.5));
+ run(&mut p, 60);
+ let y = p.pose(b).unwrap().0[1];
+ let expect = 100.0 - G * TICK * TICK * (60.0 * 60.0 / 2.0 + 60.0 / 8.0);
+ assert!((y - expect).abs() < 1e-3, "{y} for {expect}");
+ assert!((100.0 - y - G / 2.0).abs() < 0.005 * G / 2.0);
+ let v = p.velocity(b).unwrap().0[1];
+ assert!((v + G).abs() < 1e-3, "{v}");
+ assert_eq!(p.ticks(), 60);
+ }
+
+ /// Five 1 m boxes stacked with a millimetre between them come to rest in a column: box k's centre at k + 0.5 m
+ /// within 2 mm for each contact under it (Rapier lets a contact sink about a millimetre), not drifted sideways,
+ /// upright, asleep.
+ #[test]
+ fn stacking() {
+ let (mut p, _) = ground();
+ let boxes: Vec<BodyId> = (0..5).map(|k| body(&mut p, [0.0, 0.5 + k as f32 * 1.001, 0.0], Shape::Box([0.5; 3]))).collect();
+ run(&mut p, 600);
+ for (k, &b) in boxes.iter().enumerate() {
+ let (pos, rot) = p.pose(b).unwrap();
+ assert!((pos[1] - (k as f32 + 0.5)).abs() < 2e-3 * (k as f32 + 1.0), "box {k} at {}", pos[1]);
+ assert!(pos[0].abs() < 5e-3 && pos[2].abs() < 5e-3, "box {k} drifted to {pos:?}");
+ assert!(rot[3].abs() > 0.9999, "box {k} turned: {rot:?}");
+ assert!(p.sleeping(b), "box {k} still awake");
+ }
+ assert!(p.moved().is_empty(), "asleep bodies are not reported as moved");
+ // Their masses: 1 m³ of 1000 kg/m³.
+ assert!((p.mass(boxes[0]).unwrap() - 1000.0).abs() < 1.0);
+ }
+
+ /// A box on a 20° slope (tan 20° = 0.364) stays with friction 0.6 and slides with friction 0.1, at g (sin - mu cos).
+ #[test]
+ fn friction_on_a_slope() {
+ let slide = |mu: f32| {
+ let mut p = Physics::default();
+ let a = 20f32.to_radians();
+ let q = [0.0, 0.0, (a / 2.0).sin(), (a / 2.0).cos()]; // about z: the slope rises along +x
+ p.add_collider(None, &ColliderDesc { rotation: q, friction: mu, ..ColliderDesc::new(Shape::Box([20.0, 0.5, 20.0])) }).unwrap();
+ // On the slope's surface (0.5 above its middle plane, plus half the box), turned with it.
+ let up = [-a.sin(), a.cos(), 0.0];
+ let b = p.add_body(&BodyDesc { position: [up[0] * 0.752, up[1] * 0.752, 0.0], rotation: q, can_sleep: false, ..Default::default() }).unwrap();
+ p.add_collider(Some(b), &ColliderDesc { friction: mu, ..ColliderDesc::new(Shape::Box([0.25; 3])) }).unwrap();
+ let start = p.pose(b).unwrap().0;
+ run(&mut p, 60);
+ (dist(p.pose(b).unwrap().0, start), a)
+ };
+ let (held, _) = slide(0.6);
+ assert!(held < 0.01, "slid {held} m with friction 0.6");
+ let (slid, a) = slide(0.1);
+ let expect = 0.5 * G * (a.sin() - 0.1 * a.cos());
+ assert!((slid - expect).abs() < 0.1 * expect, "slid {slid} m, expected {expect}");
+ }
+
+ /// A weight on a hinge 1 m from it, let go level: the hinge holds it at 1 m (within 5 mm), it stays in the plane
+ /// across the axis, and at the bottom it moves at sqrt(2 g L) = 4.43 m/s within 2 %.
+ #[test]
+ fn revolute_pendulum() {
+ let mut p = Physics::default();
+ let post = fixed(&mut p, [0.0, 5.0, 0.0]);
+ let w = p.add_body(&BodyDesc { position: [1.0, 5.0, 0.0], can_sleep: false, ..Default::default() }).unwrap();
+ p.add_collider(Some(w), &ColliderDesc::new(Shape::Sphere(0.05))).unwrap();
+ p.add_joint(post, w, &JointDesc::Revolute { anchor1: [0.0; 3], anchor2: [-1.0, 0.0, 0.0], axis: [0.0, 0.0, 1.0], limits: None, motor: None }).unwrap();
+ let (mut lowest, mut fastest) = (f32::MAX, 0.0f32);
+ for _ in 0..120 {
+ p.step();
+ let (pos, _) = p.pose(w).unwrap();
+ assert!((dist(pos, [0.0, 5.0, 0.0]) - 1.0).abs() < 5e-3, "{pos:?}");
+ assert!(pos[2].abs() < 1e-3);
+ let v = p.velocity(w).unwrap().0;
+ lowest = lowest.min(pos[1]);
+ fastest = fastest.max((v[0] * v[0] + v[1] * v[1]).sqrt());
+ }
+ assert!((lowest - 4.0).abs() < 0.01, "lowest {lowest}");
+ let expect = (2.0 * G).sqrt();
+ assert!((fastest - expect).abs() < 0.02 * expect, "fastest {fastest}, expected {expect}");
+ }
+
+ /// A door on a hinge limited to ±0.5 rad, pushed by its own weight about a level axis: it swings down to the limit
+ /// and stops there (0.5 rad within 0.03).
+ #[test]
+ fn revolute_limits() {
+ let mut p = Physics::default();
+ let post = fixed(&mut p, [0.0, 5.0, 0.0]);
+ let door = p.add_body(&BodyDesc { position: [0.5, 5.0, 0.0], can_sleep: false, ..Default::default() }).unwrap();
+ p.add_collider(Some(door), &ColliderDesc::new(Shape::Box([0.5, 0.05, 0.4]))).unwrap();
+ p.add_joint(post, door, &JointDesc::Revolute { anchor1: [0.0; 3], anchor2: [-0.5, 0.0, 0.0], axis: [0.0, 0.0, 1.0], limits: Some(Limits { min: -0.5, max: 0.5 }), motor: None }).unwrap();
+ let mut most = 0.0f32;
+ for _ in 0..300 {
+ p.step();
+ let pos = p.pose(door).unwrap().0;
+ most = most.max((-(pos[1] - 5.0)).atan2(pos[0]));
+ }
+ assert!(most < 0.53, "swung to {most} rad");
+ let pos = p.pose(door).unwrap().0;
+ assert!(((-(pos[1] - 5.0)).atan2(pos[0]) - 0.5).abs() < 0.03, "rests at {pos:?}");
+ }
+
+ /// Limits that are not about 0 (the world hands Rapier centred ones and turns the centre into the joint's frame):
+ /// the same door limited to [-0.9, -0.2] rad swings down to 0.9 rad and stops; limited to [0.2, 0.9] it is lifted
+ /// to its lower limit, 0.2 rad up, and its weight holds it there.
+ #[test]
+ fn revolute_limits_off_centre() {
+ for (min, max, rests) in [(-0.9, -0.2, 0.9), (0.2, 0.9, -0.2)] {
+ let mut p = Physics::default();
+ let post = fixed(&mut p, [0.0, 5.0, 0.0]);
+ let door = p.add_body(&BodyDesc { position: [0.5, 5.0, 0.0], can_sleep: false, ..Default::default() }).unwrap();
+ p.add_collider(Some(door), &ColliderDesc::new(Shape::Box([0.5, 0.05, 0.4]))).unwrap();
+ let j = p.add_joint(post, door, &JointDesc::Revolute { anchor1: [0.0; 3], anchor2: [-0.5, 0.0, 0.0], axis: [0.0, 0.0, 1.0], limits: Some(Limits { min, max }), motor: None }).unwrap();
+ // What Rapier has: limits about 0, so the sine and cosine it takes of their centre are exact everywhere.
+ let l = p.world.impulse_joints.get(p.joints[&j]).unwrap().data.limits(JointAxis::AngX).unwrap();
+ assert_eq!(l.min, -l.max);
+ assert!((l.max - 0.35).abs() < 1e-6, "{l:?}");
+ run(&mut p, 400);
+ let pos = p.pose(door).unwrap().0;
+ let down = (-(pos[1] - 5.0)).atan2(pos[0]);
+ assert!((down - rests).abs() < 0.03, "limits [{min}, {max}]: rests {down} rad down, expected {rests}");
+ }
+ }
+
+ /// A slider along x: gravity does not take it off its axis (within 2 mm); its motor brings it to 1.5 m/s; it stops at
+ /// the limit, 2 m along.
+ #[test]
+ fn prismatic_motor_and_limits() {
+ let mut p = Physics::default();
+ let rail = fixed(&mut p, [0.0, 3.0, 0.0]);
+ let s = p.add_body(&BodyDesc { position: [0.0, 3.0, 0.0], can_sleep: false, ..Default::default() }).unwrap();
+ p.add_collider(Some(s), &ColliderDesc::new(Shape::Box([0.2; 3]))).unwrap();
+ p.add_joint(rail, s, &JointDesc::Prismatic { anchor1: [0.0; 3], anchor2: [0.0; 3], axis: [1.0, 0.0, 0.0], limits: Some(Limits { min: -2.0, max: 2.0 }), motor: Some(Motor { velocity: 1.5, damping: 1e5, max_force: 1e5 }) }).unwrap();
+ run(&mut p, 30);
+ let (pos, vel) = (p.pose(s).unwrap().0, p.velocity(s).unwrap().0);
+ assert!((pos[1] - 3.0).abs() < 2e-3 && pos[2].abs() < 2e-3, "{pos:?}");
+ assert!((vel[0] - 1.5).abs() < 0.05, "{vel:?}");
+ run(&mut p, 300);
+ let pos = p.pose(s).unwrap().0;
+ assert!((pos[0] - 2.0).abs() < 0.02 && (pos[1] - 3.0).abs() < 2e-3, "{pos:?}");
+ }
+
+ /// A ball joint keeps its anchor (1 m, within 5 mm) while the body swings in any direction; a rope lets its weight
+ /// fall freely until it is taut and then holds it at its length (2 m within 2 cm); a fixed joint keeps two bodies'
+ /// offset (within 2 mm) as they fall and tumble together.
+ #[test]
+ fn spherical_rope_and_fixed() {
+ let mut p = Physics::default();
+ let post = fixed(&mut p, [0.0, 10.0, 0.0]);
+ let ball = p.add_body(&BodyDesc { position: [1.0, 10.0, 0.0], linvel: [0.0, 0.0, 2.0], can_sleep: false, ..Default::default() }).unwrap();
+ p.add_collider(Some(ball), &ColliderDesc::new(Shape::Sphere(0.1))).unwrap();
+ p.add_joint(post, ball, &JointDesc::Spherical { anchor1: [0.0; 3], anchor2: [-1.0, 0.0, 0.0] }).unwrap();
+ let weight = p.add_body(&BodyDesc { position: [5.0, 10.0, 0.0], can_sleep: false, ..Default::default() }).unwrap();
+ p.add_collider(Some(weight), &ColliderDesc::new(Shape::Sphere(0.1))).unwrap();
+ p.add_joint(post, weight, &JointDesc::Rope { anchor1: [5.0, 0.0, 0.0], anchor2: [0.0; 3], length: 2.0 }).unwrap();
+ let a = p.add_body(&BodyDesc { position: [-5.0, 10.0, 0.0], angvel: [1.0, 2.0, 0.5], can_sleep: false, ..Default::default() }).unwrap();
+ p.add_collider(Some(a), &ColliderDesc::new(Shape::Box([0.2; 3]))).unwrap();
+ let b = body(&mut p, [-4.0, 10.0, 0.0], Shape::Box([0.2; 3]));
+ p.add_joint(a, b, &JointDesc::Fixed { anchor1: [0.5, 0.0, 0.0], anchor2: [-0.5, 0.0, 0.0] }).unwrap();
+ let mut swung = 0.0f32;
+ for t in 0..240 {
+ p.step();
+ let pos = p.pose(ball).unwrap().0;
+ assert!((dist(pos, [0.0, 10.0, 0.0]) - 1.0).abs() < 5e-3, "ball joint at tick {t}: {pos:?}");
+ swung = swung.max(pos[2].abs());
+ let w = p.pose(weight).unwrap().0;
+ assert!(dist(w, [5.0, 10.0, 0.0]) < 2.02, "rope at tick {t}: {w:?}");
+ assert!((dist(p.pose(a).unwrap().0, p.pose(b).unwrap().0) - 1.0).abs() < 2e-3, "fixed joint at tick {t}");
+ }
+ assert!(swung > 0.3, "the ball joint lets it swing sideways ({swung})");
+ let w = p.pose(weight).unwrap().0;
+ assert!((dist(w, [5.0, 10.0, 0.0]) - 2.0).abs() < 0.02 && w[1] < 8.1, "hangs at {w:?}");
+ assert!(p.pose(a).unwrap().0[1] < 0.0, "the fixed pair fell");
+ }
+
+ /// Joints take the bodies as they are turned when joined. A bar turned a quarter about x, hinged to a post about the
+ /// post's y axis, is not wrenched into line: it stays as it is, and set turning it turns about that axis, its end on
+ /// the hinge. Two bodies turned 0.7 rad against each other and fixed together stay so.
+ #[test]
+ fn joints_join_bodies_as_they_are_turned() {
+ let quarter = [std::f32::consts::FRAC_1_SQRT_2, 0.0, 0.0, std::f32::consts::FRAC_1_SQRT_2];
+ let mut p = Physics::new([0.0; 3]);
+ let post = p.add_body(&BodyDesc { kind: BodyKind::Fixed, ..Default::default() }).unwrap();
+ let bar = p.add_body(&BodyDesc { position: [0.5, 0.0, 0.0], rotation: quarter, ..Default::default() }).unwrap();
+ p.add_collider(Some(bar), &ColliderDesc::new(Shape::Box([0.5, 0.1, 0.1]))).unwrap();
+ p.add_joint(post, bar, &JointDesc::Revolute { anchor1: [0.0; 3], anchor2: [-0.5, 0.0, 0.0], axis: [0.0, 1.0, 0.0], limits: None, motor: None }).unwrap();
+ let dot = |a: [f32; 4], b: [f32; 4]| (a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]).abs();
+ for _ in 0..30 {
+ p.step();
+ }
+ let (at, q) = p.pose(bar).unwrap();
+ assert!(dot(q, quarter) > 0.99999 && (at[0] - 0.5).abs() < 1e-3 && at[1].abs() < 1e-3 && at[2].abs() < 1e-3, "left as it was: {at:?} {q:?}");
+ // One radian a second about the post's y for a second: the bar's middle goes round the hinge.
+ p.set_velocity(bar, Some([0.0, 0.0, -0.5]), Some([0.0, 1.0, 0.0])).unwrap();
+ for _ in 0..60 {
+ p.step();
+ }
+ let (at, q) = p.pose(bar).unwrap();
+ assert!((at[0] - 0.5 * 1f32.cos()).abs() < 0.01 && at[1].abs() < 1e-3 && (at[2] + 0.5 * 1f32.sin()).abs() < 0.01, "{at:?}");
+ // (Its turn: a radian about y after the quarter about x.)
+ let (s, c) = (0.5f32.sin(), 0.5f32.cos());
+ let k = std::f32::consts::FRAC_1_SQRT_2;
+ assert!(dot(q, [c * k, s * k, -s * k, c * k]) > 0.9999, "{q:?}");
+ // Fixed: the turn of one against the other is kept.
+ let turned = [0.0, 0.0, 0.35f32.sin(), 0.35f32.cos()];
+ let a = p.add_body(&BodyDesc { position: [10.0, 0.0, 0.0], ..Default::default() }).unwrap();
+ let b = p.add_body(&BodyDesc { position: [11.0, 0.0, 0.0], rotation: turned, ..Default::default() }).unwrap();
+ for body in [a, b] {
+ p.add_collider(Some(body), &ColliderDesc::new(Shape::Sphere(0.2))).unwrap();
+ }
+ p.add_joint(a, b, &JointDesc::Fixed { anchor1: [1.0, 0.0, 0.0], anchor2: [0.0; 3] }).unwrap();
+ for _ in 0..30 {
+ p.step();
+ }
+ let ((pa, qa), (pb, qb)) = (p.pose(a).unwrap(), p.pose(b).unwrap());
+ assert!(dot(qa, [0.0, 0.0, 0.0, 1.0]) > 0.99999 && dot(qb, turned) > 0.99999, "{qa:?} {qb:?}");
+ assert!((pa[0] - 10.0).abs() < 1e-3 && (pb[0] - 11.0).abs() < 1e-3 && pb[1].abs() < 1e-3, "{pa:?} {pb:?}");
+ }
+
+ /// Contacts of colliders that ask for them: a ball landing reports one contact begun with the ground, and one ended
+ /// when it is thrown up again. A sensor reports what enters it and stops nothing.
+ #[test]
+ fn contact_events() {
+ let (mut p, g) = ground();
+ let b = p.add_body(&BodyDesc { position: [0.0, 1.0, 0.0], can_sleep: false, ..Default::default() }).unwrap();
+ let c = p.add_collider(Some(b), &ColliderDesc { events: true, ..ColliderDesc::new(Shape::Sphere(0.25)) }).unwrap();
+ let quiet = body(&mut p, [5.0, 1.0, 0.0], Shape::Sphere(0.25));
+ run(&mut p, 120);
+ assert_eq!(p.take_contacts(), vec![Contact { a: g, b: c, started: true }], "the ball without `events` reports nothing");
+ assert!(p.take_contacts().is_empty());
+ p.set_velocity(b, Some([0.0, 5.0, 0.0]), Some([0.0; 3])).unwrap();
+ run(&mut p, 10);
+ assert_eq!(p.take_contacts(), vec![Contact { a: g, b: c, started: false }]);
+ let _ = quiet;
+ // A sensor 3 m up: the ball thrown through it enters and leaves, and is not slowed more than gravity does.
+ let s = p.add_collider(None, &ColliderDesc { position: [0.0, 3.0, 0.0], sensor: true, events: true, ..ColliderDesc::new(Shape::Box([1.0, 0.2, 1.0])) }).unwrap();
+ p.set_pose(b, [0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]).unwrap();
+ p.set_velocity(b, Some([0.0, 12.0, 0.0]), Some([0.0; 3])).unwrap();
+ run(&mut p, 40);
+ let seen = p.take_contacts();
+ assert_eq!(seen, vec![Contact { a: c, b: s, started: true }, Contact { a: c, b: s, started: false }]);
+ assert!(p.pose(b).unwrap().0[1] > 3.5, "through the sensor");
+ }
+
+ /// Rays, overlaps and sweeps against a box standing on the ground.
+ #[test]
+ fn scene_queries() {
+ let (mut p, g) = ground();
+ let b = body(&mut p, [0.0, 0.5, 0.0], Shape::Box([0.5; 3]));
+ run(&mut p, 2);
+ let c = p.cast_ray([0.2, 10.0, 0.1], [0.0, -1.0, 0.0], 100.0, None).unwrap().unwrap();
+ assert_eq!(c.body, Some(b));
+ assert!((c.distance - 9.0).abs() < 1e-3 && (c.point[1] - 1.0).abs() < 1e-3, "{c:?}");
+ assert!(dist(c.normal, [0.0, 1.0, 0.0]) < 1e-4);
+ // Past the box: the ground (a collider without a body). Skipping the box's body: the ground under it.
+ let h = p.cast_ray([3.0, 10.0, 0.0], [0.0, -2.0, 0.0], 100.0, None).unwrap().unwrap();
+ assert_eq!((h.collider, h.body), (g, None));
+ assert!((h.distance - 10.0).abs() < 1e-3);
+ assert_eq!(p.cast_ray([0.2, 10.0, 0.1], [0.0, -1.0, 0.0], 100.0, Some(b)).unwrap().unwrap().collider, g);
+ // Too short, pointing away, bad numbers: nothing.
+ assert!(p.cast_ray([0.2, 10.0, 0.1], [0.0, -1.0, 0.0], 5.0, None).unwrap().is_none());
+ assert!(p.cast_ray([0.2, 10.0, 0.1], [0.0, 1.0, 0.0], 100.0, None).unwrap().is_none());
+ assert!(p.cast_ray([0.2, f32::NAN, 0.1], [0.0, -1.0, 0.0], 100.0, None).is_err());
+ assert!(p.cast_ray([0.2, 10.0, 0.1], [0.0; 3], 100.0, None).is_err());
+ // Overlap: a sphere at the box's corner touches the box and the ground; one high up nothing.
+ let hits = p.overlap(&Shape::Sphere(0.3), [0.6, 0.1, 0.6], [0.0, 0.0, 0.0, 1.0], None).unwrap();
+ assert_eq!(hits, vec![g, c.collider]);
+ assert_eq!(p.overlap(&Shape::Sphere(0.3), [0.6, 0.1, 0.6], [0.0, 0.0, 0.0, 1.0], Some(b)).unwrap(), vec![g]);
+ assert!(p.overlap(&Shape::Sphere(0.3), [0.0, 5.0, 0.0], [0.0, 0.0, 0.0, 1.0], None).unwrap().is_empty());
+ // Sweep: a sphere of 0.25 m lowered from 5 m meets the box's top (y = 1) after 3.75 m.
+ let s = p.sweep(&Shape::Sphere(0.25), [0.0, 5.0, 0.0], [0.0, 0.0, 0.0, 1.0], [0.0, -1.0, 0.0], 100.0, None).unwrap().unwrap();
+ assert_eq!(s.body, Some(b));
+ assert!((s.distance - 3.75).abs() < 1e-3, "{s:?}");
+ // Its point and normal are the box's (as a ray's are), in world space: on the top, facing up.
+ assert!(dist(s.point, [0.0, 1.0, 0.0]) < 1e-3 && dist(s.normal, [0.0, 1.0, 0.0]) < 1e-4, "{s:?}");
+ // Sideways: it meets the box's side x = -0.5 after 4.25 m, at the side's point facing it, -x.
+ let s = p.sweep(&Shape::Sphere(0.25), [-5.0, 0.5, 0.2], [0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0], 100.0, None).unwrap().unwrap();
+ assert!((s.distance - 4.25).abs() < 1e-3, "{s:?}");
+ assert!(dist(s.point, [-0.5, 0.5, 0.2]) < 1e-3 && dist(s.normal, [-1.0, 0.0, 0.0]) < 1e-4, "{s:?}");
+ assert!(p.sweep(&Shape::Sphere(0.25), [0.0, 5.0, 0.0], [0.0, 0.0, 0.0, 1.0], [0.0, -1.0, 0.0], 2.0, None).unwrap().is_none());
+ }
+
+ /// A kinematic body goes where it is told and pushes a dynamic one; nothing pushes it.
+ #[test]
+ fn kinematic_bodies_push() {
+ let (mut p, _) = ground();
+ let k = p.add_body(&BodyDesc { kind: BodyKind::Kinematic, position: [-2.0, 0.5, 0.0], ..Default::default() }).unwrap();
+ p.add_collider(Some(k), &ColliderDesc::new(Shape::Box([0.5; 3]))).unwrap();
+ let d = body(&mut p, [0.0, 0.5, 0.0], Shape::Box([0.5; 3]));
+ for t in 1..=120 {
+ p.set_kinematic_target(k, [-2.0 + t as f32 * 0.02, 0.5, 0.0], [0.0, 0.0, 0.0, 1.0]).unwrap();
+ p.step();
+ }
+ let (kp, dp) = (p.pose(k).unwrap().0, p.pose(d).unwrap().0);
+ assert!((kp[0] - 0.4).abs() < 1e-3 && (kp[1] - 0.5).abs() < 1e-6, "{kp:?}");
+ assert!(dp[0] > kp[0] + 0.99, "pushed ahead of it: {dp:?}");
+ // (A target for a dynamic body is ignored.)
+ p.set_kinematic_target(d, [9.0, 9.0, 9.0], [0.0, 0.0, 0.0, 1.0]).unwrap();
+ p.step();
+ assert!(p.pose(d).unwrap().0[1] < 1.0);
+ }
+
+ /// Shapes: a capsule, a convex hull and an engine-defined shape (`CustomShape`) rest on a trimesh floor at the
+ /// heights their shapes give; a hull has mass.
+ #[test]
+ fn shapes() {
+ struct Ball(f32);
+ impl CustomShape for Ball {
+ fn shared(&self) -> SharedShape {
+ SharedShape::ball(self.0)
+ }
+ }
+ let mut p = Physics::default();
+ // A floor of two triangles at y = 0.
+ p.add_collider(None, &ColliderDesc::new(Shape::Trimesh { vertices: vec![[-20.0, 0.0, -20.0], [20.0, 0.0, -20.0], [20.0, 0.0, 20.0], [-20.0, 0.0, 20.0]], indices: vec![[0, 2, 1], [0, 3, 2]] })).unwrap();
+ let capsule = body(&mut p, [0.0, 1.0, 0.0], Shape::Capsule { half_height: 0.3, radius: 0.2 });
+ let hull = body(&mut p, [3.0, 1.0, 0.0], Shape::ConvexHull(vec![[-0.3, -0.2, -0.3], [0.3, -0.2, -0.3], [0.3, -0.2, 0.3], [-0.3, -0.2, 0.3], [-0.3, 0.2, -0.3], [0.3, 0.2, -0.3], [0.3, 0.2, 0.3], [-0.3, 0.2, 0.3]]));
+ let custom = body(&mut p, [-3.0, 1.0, 0.0], Shape::Custom(Box::new(Ball(0.35))));
+ run(&mut p, 300);
+ assert!((p.pose(capsule).unwrap().0[1] - 0.5).abs() < 5e-3, "{:?}", p.pose(capsule));
+ assert!((p.pose(hull).unwrap().0[1] - 0.2).abs() < 5e-3, "{:?}", p.pose(hull));
+ assert!((p.pose(custom).unwrap().0[1] - 0.35).abs() < 5e-3, "{:?}", p.pose(custom));
+ assert!((p.mass(hull).unwrap() - 0.6 * 0.4 * 0.6 * 1000.0).abs() < 1.0);
+ }
+
+ /// Bad input adds nothing; removing a body takes its colliders and joints with it.
+ #[test]
+ fn bad_input_and_removal() {
+ let (mut p, g) = ground();
+ assert!(p.add_body(&BodyDesc { position: [f32::NAN, 0.0, 0.0], ..Default::default() }).is_err());
+ let b = body(&mut p, [0.0, 2.0, 0.0], Shape::Box([0.5; 3]));
+ assert!(p.add_collider(Some(999), &ColliderDesc::new(Shape::Sphere(1.0))).is_err());
+ assert!(p.add_collider(Some(b), &ColliderDesc::new(Shape::Sphere(-1.0))).is_err());
+ assert!(p.add_collider(Some(b), &ColliderDesc::new(Shape::Box([1.0, 0.0, 1.0]))).is_err());
+ assert!(p.add_collider(Some(b), &ColliderDesc::new(Shape::ConvexHull(vec![[0.0; 3], [1.0, 0.0, 0.0]]))).is_err());
+ assert!(p.add_collider(Some(b), &ColliderDesc::new(Shape::Trimesh { vertices: vec![[0.0; 3]], indices: vec![[0, 1, 2]] })).is_err());
+ let c = body(&mut p, [2.0, 2.0, 0.0], Shape::Box([0.5; 3]));
+ assert!(p.add_joint(b, 999, &JointDesc::Spherical { anchor1: [0.0; 3], anchor2: [0.0; 3] }).is_err());
+ assert!(p.add_joint(b, c, &JointDesc::Revolute { anchor1: [0.0; 3], anchor2: [0.0; 3], axis: [0.0; 3], limits: None, motor: None }).is_err());
+ assert!(p.add_joint(b, c, &JointDesc::Rope { anchor1: [0.0; 3], anchor2: [0.0; 3], length: f32::NAN }).is_err());
+ let j = p.add_joint(b, c, &JointDesc::Fixed { anchor1: [1.0, 0.0, 0.0], anchor2: [-1.0, 0.0, 0.0] }).unwrap();
+ run(&mut p, 2);
+ assert_eq!((p.bodies(), p.colliders.len(), p.joints.len()), (2, 3, 1));
+ p.remove_body(b);
+ assert_eq!((p.bodies(), p.colliders.len(), p.joints.len()), (1, 2, 0));
+ assert!(p.pose(b).is_none() && p.pose(c).is_some());
+ p.remove_joint(j);
+ run(&mut p, 120);
+ // The other falls on the ground alone; rays find the ground where the removed box was.
+ assert!((p.pose(c).unwrap().0[1] - 0.5).abs() < 5e-3);
+ assert_eq!(p.cast_ray([0.0, 10.0, 0.0], [0.0, -1.0, 0.0], 100.0, None).unwrap().unwrap().collider, g);
+ p.remove_collider(g);
+ run(&mut p, 60);
+ assert!(p.pose(c).unwrap().0[1] < 0.0, "with the ground gone it falls on");
+ }
+
+ /// The same scene stepped twice ends in the same bits, and (with `enhanced-determinism`) in the recorded ones, which
+ /// the wasm32 build gives too (tools/physics-determinism.ts).
+ #[test]
+ fn steps_repeat() {
+ let (a, b) = (crate::check::script(600), crate::check::script(600));
+ assert_eq!(a, b);
+ assert_ne!(a, crate::check::script(599));
+ #[cfg(feature = "enhanced-determinism")]
+ assert_eq!(a, crate::check::EXPECTED, "the script's end changed: if meant, record {a:#x}");
+ }
+}
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 92ece3f..c7df2b5 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -17,6 +17,7 @@ pub mod sky;
pub mod tables;
pub mod texpack;
pub mod view;
+pub mod physics;
pub mod voxel;
pub mod world;
diff --git a/renderer/src/live.rs b/renderer/src/live.rs
index 05563f4..6fc5590 100644
--- a/renderer/src/live.rs
+++ b/renderer/src/live.rs
@@ -1401,8 +1401,23 @@ impl LiveCore {
if !changes.any() {
return Ok(false);
}
- // Objects added in place are not in the move tables (their records follow the scene's): a move rebuilds.
- if !changes.structural && changes.moved.iter().any(|id| self.sc.edit.placed.contains_key(id)) {
+ // New materials without textures: entries after the scene's, before the edits that place objects drawn with
+ // them (and the GPU's table with them, grown if it is full).
+ if !changes.new_materials.is_empty() && !changes.structural {
+ if self.sc.tables.add_materials(world, &changes.new_materials) {
+ self.upload_materials();
+ // (A clear coat, an unlit material: the kernel variant with it, compiled once.)
+ let (e, (tex, func, groups)) = (&self.sc.tables, self.sc.fixed_features);
+ self.sc.up.kernel.features = gpu::features_of(&e.materials, e.fog.as_ref(), tex, func, groups, self.sc.instance_features) | if e.aerial[0] > 0.0 { gpu::F_AERIAL } else { 0 };
+ } else {
+ self.fallback = Some("a new material that cannot be added in place (it emits, is glass or a cutout)".into());
+ self.fallbacks += 1;
+ changes.structural = true;
+ }
+ }
+ // Objects added in place are not in the move tables (their records follow the scene's): a move rebuilds. Not a
+ // mesh a body drives: it is an instance, and its record moves as the build's do (`placed_movable`).
+ if !changes.structural && changes.moved.iter().any(|id| self.sc.edit.placed.contains_key(id) && self.placed_movable(world, *id).is_none()) {
self.fallback = Some("an object added in place moved".into());
self.fallbacks += 1;
changes.structural = true;
@@ -1466,8 +1481,8 @@ impl LiveCore {
// Movable models placed as instances move their transform (with a shared pose too); the rest
// re-transform triangles.
let r = &self.sc.tables.retained;
- match r.instance_of.get(&k) {
- Some(&i) if !changes.poses.contains(&k) || r.pose_member.contains_key(&k) => placed.push((k, i)),
+ match r.instance_of.get(&k).copied().or_else(|| self.placed_movable(world, k)) {
+ Some(i) if !changes.poses.contains(&k) || r.pose_member.contains_key(&k) => placed.push((k, i)),
_ => {
dynamic.insert(k);
}
@@ -1581,10 +1596,10 @@ impl LiveCore {
}
return Ok(true);
};
- let (q, up, e) = (&self.g.queue, &self.sc.up, &mut self.sc.tables);
if d.materials {
- q.write_buffer(&up.materials, 0, bytemuck::cast_slice(&e.materials));
+ self.upload_materials();
}
+ let (q, up, e) = (&self.g.queue, &self.sc.up, &mut self.sc.tables);
if d.lights && !e.lights.is_empty() {
q.write_buffer(&up.lights, 0, bytemuck::cast_slice(&crate::lights_with_groups(&e.lights)));
}
@@ -1704,16 +1719,29 @@ impl LiveCore {
let Some(accel) = self.sc.up.accel.as_mut() else { return false };
let size = std::mem::size_of::<scene::GpuInstance>() as u64;
let q = &self.g.queue;
+ // (Many records, a rigid body world's thousands a frame, are written as the one range that holds them: the
+ // records between are as the GPU has them.)
+ let merged = placed.len() > 32;
+ let (mut lo, mut hi) = (usize::MAX, 0usize);
// (Instances the last update moved and this one does not catch up in `commit`.)
for &(node, i) in placed {
let w = world.world_matrix(node);
- let inst = &mut self.sc.instances[i as usize];
+ // (A mesh an edit added in place keeps its instance with the edit's, `placed_movable`; its record and TLAS
+ // instance are where the build's are.)
+ let inst = match self.sc.edit.added.get_mut(&node) {
+ Some(Picked::Mesh(inst)) => inst,
+ _ => &mut self.sc.instances[i as usize],
+ };
let old = self.sc.gpu_instances[i as usize];
inst.world = w;
let mut r = inst.gpu(old.info[0], old.info[3]);
r.p = old.m;
self.sc.gpu_instances[i as usize] = r;
- q.write_buffer(&self.sc.up.instances, i as u64 * size, bytemuck::bytes_of(&r));
+ if merged {
+ (lo, hi) = (lo.min(i as usize), hi.max(i as usize));
+ } else {
+ q.write_buffer(&self.sc.up.instances, i as u64 * size, bytemuck::bytes_of(&r));
+ }
let pivot = w.transform_point3(glam::Vec3::ZERO);
let st = self.sc.tables.stride;
let o = &mut self.sc.tables.objects[inst.object as usize * st];
@@ -1728,6 +1756,9 @@ impl LiveCore {
}
self.inst_moving.push(i);
}
+ if merged {
+ q.write_buffer(&self.sc.up.instances, lo as u64 * size, bytemuck::cast_slice(&self.sc.gpu_instances[lo..=hi]));
+ }
q.write_buffer(&self.sc.up.objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
if build_tlas {
let mut e = self.g.device.create_command_encoder(&Default::default());
@@ -1738,6 +1769,26 @@ impl LiveCore {
true
}
+ /// The material table to the GPU: written in place, or, with more materials than its buffer holds (materials added
+ /// while the game runs), into a buffer twice the size, the scene's bind group made over it.
+ fn upload_materials(&mut self) {
+ let bytes: &[u8] = bytemuck::cast_slice(&self.sc.tables.materials);
+ if bytes.len() as u64 > self.sc.up.materials.size() {
+ let usage = self.sc.up.materials.usage();
+ self.sc.up.materials = self.g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("materials"), size: (bytes.len() as u64 * 2).next_multiple_of(16), usage, mapped_at_creation: false });
+ self.g.rebind_scene(&mut self.sc.up);
+ }
+ self.g.queue.write_buffer(&self.sc.up.materials, 0, bytes);
+ }
+
+ /// The record of a mesh an edit added in place that moves as an instance does (`move_instances`): one a rigid body
+ /// drives, placed by its node's transform (an emitter mesh's triangles are in world space: it cannot).
+ fn placed_movable(&self, world: &World, id: u32) -> Option<u32> {
+ let &(_, record) = self.sc.edit.placed.get(&id)?;
+ let mesh = matches!(self.sc.edit.added.get(&id), Some(Picked::Mesh(_)));
+ (mesh && world.objects.get(&id).is_some_and(|o| o.driven) && !self.sc.tables.retained.emitter_mesh.contains_key(&id)).then_some(record as u32)
+ }
+
/// `update_instanced` with its fallback (the reason in the frame log, the scene rebuilt) and its CPU time; whether it
/// changed anything.
fn instanced_in_place(&mut self, world: &World, ids: &[u32], build_tlas: bool, changes: &mut crate::world::Changes) -> bool {
@@ -2496,6 +2547,7 @@ impl LiveCore {
drop_mesh_user(k, edit, tables, meshes);
}
tables.retained.own_instance.remove(id);
+ tables.retained.instance_of.remove(id);
if let Some(k) = tables.retained.objects.remove(id).filter(|&k| k as usize >= edit.base.2) {
edit.objects.give(k as usize, 1);
}
@@ -2654,6 +2706,10 @@ impl LiveCore {
if class == 2 || (emits && capacity.is_some()) {
return Err("a glass or function material (an instanced mesh: emitting too)".into());
}
+ // (An emitter mesh's triangles are in world space: one a body moves is flattened by the build.)
+ if emits && o.driven {
+ return Err("an emitting mesh a rigid body drives (the build flattens it)".into());
+ }
if class == 1 && features & gpu::F_MASKED == 0 {
return Err("the scene's first cutout (kernel feature)".into());
}
@@ -3807,6 +3863,7 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {
e.copy_buffer_to_buffer(out, 0, &staging, 0, (w * h * 4) as u64);
}
});
+ game.click_shown();
let (hist, fno) = (core.history_len as u32, core.frame);
syncs.retain(|(id, from)| {
if fno > *from {
@@ -3850,7 +3907,7 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {
use std::io::Write;
let line = serde_json::json!({
"t": start.elapsed().as_secs_f64() * 1e3, "interval": last_frame.elapsed().as_secs_f64() * 1e3, "start": t_frame.duration_since(prev_start).as_secs_f64() * 1e3,
- "cpu": t_frame.elapsed().as_secs_f64() * 1e3, "script": game.frame_ms, "js": game.js_ms, "skin": core.cpu_skin_ms, "upload": core.cpu_upload_ms, "blas": core.gpu_blas_ms, "wait": core.cpu_wait_ms, "gpu": core.gpu_ms, "trace": core.gpu_trace_ms, "edit": core.edit_ms, "instanced": core.instanced_ms, "edit_split": [core.edit_split.tris, core.edit_split.upload, core.edit_split.blas, core.edit_split.added, core.edit_split.deformed, core.edit_split.objects], "rebuild": core.rebuild_ms, "fallback": core.fallback, "fallbacks": core.fallbacks, "room": core.room_stats(), "voxel": std::mem::take(&mut game.host.voxels.borrow_mut().ticks), "scale": core.render_scale, "history": core.history_len,
+ "cpu": t_frame.elapsed().as_secs_f64() * 1e3, "script": game.frame_ms, "js": game.js_ms, "commit": game.commit_ms, "skin": core.cpu_skin_ms, "upload": core.cpu_upload_ms, "blas": core.gpu_blas_ms, "wait": core.cpu_wait_ms, "gpu": core.gpu_ms, "trace": core.gpu_trace_ms, "edit": core.edit_ms, "instanced": core.instanced_ms, "edit_split": [core.edit_split.tris, core.edit_split.upload, core.edit_split.blas, core.edit_split.added, core.edit_split.deformed, core.edit_split.objects], "rebuild": core.rebuild_ms, "fallback": core.fallback, "fallbacks": core.fallbacks, "room": core.room_stats(), "voxel": std::mem::take(&mut game.host.voxels.borrow_mut().ticks), "physics": game.host.physics.borrow_mut().as_mut().map(|p| { let s = p.take_stats(); serde_json::json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved }) }), "scale": core.render_scale, "history": core.history_len,
});
writeln!(l, "{line}")?;
}
@@ -4022,6 +4079,61 @@ mod instanced_tests {
assert_eq!(picked(&core), None, "a rebuild agrees");
}
+ /// A mesh a rigid body drives, added while the game runs with a material the scene did not have (ROADMAP § 6 step
+ /// 7): placed in place, and its body's moves are its instance's transform, with no rebuild; a rebuild places it the
+ /// same and it goes on moving in place. (Skipped without a GPU with hardware RT.)
+ #[test]
+ fn driven_meshes_added_in_place_move_as_instances() {
+ let g = match gpu::Gpu::new() {
+ Ok(g) if g.hwrt => g,
+ other => return eprintln!("skipped: {}", other.map_or_else(|e| e.to_string(), |_| "no hardware RT".into())),
+ };
+ let mut w = World::default();
+ let mat = |r: f32| serde_json::from_value(serde_json::json!({ "name": "m", "color": [r, r, r], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true })).unwrap();
+ w.set_material(1, mat(0.5));
+ let quad = |s: f32| Geometry { positions: vec![-s, -s, 0.0, s, -s, 0.0, s, s, 0.0, -s, s, 0.0], normals: vec![0.0, 0.0, 1.0].repeat(4), uvs: vec![0.0; 8], indices: vec![0, 1, 2, 0, 2, 3], groups: vec![], colors: vec![] };
+ w.set_geometry(2, quad(1.0)).unwrap();
+ w.set_geometry(3, quad(0.5)).unwrap();
+ let mesh = |geometry, material| Kind::Mesh { geometry, material, own_blas: true, materials: vec![] };
+ w.set_object(10, "a".into(), None, mesh(2, 1), true, false).unwrap();
+ let cam = serde_json::from_value(serde_json::json!({ "fov": 50, "near": 0.1, "far": 100, "exposure": { "mode": "manual", "ev100": 0 } })).unwrap();
+ w.set_object(4, "camera".into(), None, Kind::Camera(cam), true, false).unwrap();
+ w.set_transform(4, Vec3::new(0.0, 0.0, 5.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ w.set_settings(crate::world::Settings { camera: Some(4), ..Default::default() });
+ let mut core = LiveCore::new(g, &w, Path::new("."), &crate::default_presets_dir(), 64, 36).unwrap();
+ w.take_changes();
+ let picked = |core: &LiveCore, u: f32| core.pick(u, 0.5).map(|p| p.0);
+ // The box and its material arrive together, as scene code adds them; its body is told of it right after.
+ let materials = core.sc.tables.materials.len();
+ w.set_material(5, mat(0.9));
+ w.set_object(11, "b".into(), None, mesh(3, 5), true, false).unwrap();
+ w.set_driven(11).unwrap();
+ w.set_transform(11, Vec3::new(0.0, 0.0, 1.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ assert!(!core.commit(&mut w).unwrap(), "added in place, its material too");
+ assert_eq!(core.sc.tables.materials.len(), materials + 1);
+ assert_eq!(picked(&core, 0.5).as_deref(), Some("b"));
+ // Its body moves it 3 m to the side (u 0.95 of the image, 4 m from the camera): no rebuild, its record moved
+ // with the rows it had the frame before.
+ let record = core.sc.edit.placed[&11].1;
+ assert!(w.place_driven(11, Vec3::new(3.0, 0.0, 1.0), glam::Quat::IDENTITY));
+ assert!(!core.commit(&mut w).unwrap(), "moved as an instance");
+ assert_eq!(core.fallbacks, 0);
+ assert_eq!((picked(&core, 0.5).as_deref(), picked(&core, 0.95).as_deref()), (Some("a"), Some("b")));
+ let r = core.sc.gpu_instances[record];
+ assert_eq!((r.m[0][3], r.p[0][3]), (3.0, 0.0), "moved: last frame's rows kept");
+ // A rebuild places it as an instance too, and it moves on in place.
+ core.rebuild(&w).unwrap();
+ assert!(core.sc.tables.retained.instance_of.contains_key(&11) && core.sc.edit.placed.is_empty());
+ assert_eq!((picked(&core, 0.5).as_deref(), picked(&core, 0.95).as_deref()), (Some("a"), Some("b")));
+ assert!(w.place_driven(11, Vec3::new(0.0, 0.0, 1.0), glam::Quat::IDENTITY));
+ assert!(!core.commit(&mut w).unwrap(), "moved as an instance");
+ assert_eq!((picked(&core, 0.5).as_deref(), picked(&core, 0.95)), (Some("b"), None));
+ // Removed in place.
+ w.remove(11);
+ assert!(!core.commit(&mut w).unwrap(), "removed in place");
+ assert_eq!(picked(&core, 0.5).as_deref(), Some("a"));
+ }
+
/// An instanced mesh's moved instances keep their previous-frame rows (motion vectors) through the commit that moves
/// them, and catch up at the next commit that does not move them. (Skipped without a GPU with hardware RT.)
#[test]
diff --git a/renderer/src/main.rs b/renderer/src/main.rs
index 9f8f68e..e219743 100644
--- a/renderer/src/main.rs
+++ b/renderer/src/main.rs
@@ -366,6 +366,8 @@ fn render_live(slot: &mut Option<gpu::Gpu>, job: &Job, presets: &Path, frames: u
if host.has_frame() {
host.seek(start)?;
}
+ // The physics world as it is where the frames start (as `render` has it at its scene time); the frames step it on.
+ host.settle_physics((start.max(0.0) * 60.0).round() as u32);
let mut w = host.world.borrow_mut();
w.take_changes();
let missing: Vec<String> = w.files().into_iter().filter(|f| !job.game.assets.join(f).is_file()).collect();
@@ -393,7 +395,8 @@ fn render_live(slot: &mut Option<gpu::Gpu>, job: &Job, presets: &Path, frames: u
if host.has_frame() {
host.frame(1.0 / 60.0)?;
}
- if host.has_frame() || swayed {
+ let physics = host.advance_physics(1.0 / 60.0);
+ if host.has_frame() || swayed || physics {
core.commit(&mut host.world.borrow_mut())?;
}
core.render(1, |_, _| {});
@@ -429,6 +432,8 @@ fn render(g: &gpu::Gpu, job: &Job, presets: &Path, init_ms: f64, hosts: &mut Hos
if host.has_frame() {
host.seek(job.time.unwrap_or(0.0))?;
}
+ // The physics world as it is after the job's scene time (60 ticks a second from the setup's world).
+ host.settle_physics((job.time.unwrap_or(0.0).max(0.0) * 60.0).round() as u32);
timings.push(("script_ms".into(), script_ms));
let mut sc = {
let mut w = host.world.borrow_mut();
diff --git a/renderer/src/physics.rs b/renderer/src/physics.rs
new file mode 100644
index 0000000..0ee1d8a
--- /dev/null
+++ b/renderer/src/physics.rs
@@ -0,0 +1,209 @@
+//! Physics in the renderer (ROADMAP § 6 step 7): the game session's physics world, owned and stepped by the engine at
+//! a fixed tick. Everything about it is `physics_core::bridge::Bridge` (the world on Rapier, scene code's calls, the
+//! objects that bodies drive; it has no GPU in it and builds for wasm32); here is the scene it drives, the renderer's
+//! `World`, and the frame's timing. Scene code reaches it through `__engine.physics(op, args)` and reads the driven
+//! objects' poses through `__engine.physicsPoses()`; it never steps it. After a frame's ticks the bodies that moved
+//! place their objects: a driven mesh or model is an instance, so a move is its TLAS transform, no triangle (live.rs
+//! `move_instances`), and nothing of it passes through the script. A session that never makes a physics call has no
+//! world and pays nothing.
+
+use crate::world::World;
+use anyhow::{anyhow, Result};
+use glam::{Mat4, Quat, Vec3};
+use physics_core::bridge::{Bridge, Scene};
+use serde_json::Value;
+use std::time::Instant;
+
+/// A frame's physics, for the frame log: the ticks stepped and their time, the time to place the driven objects, the
+/// bodies and how many of them moved.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct Stats {
+ pub ticks: u32,
+ pub step_ms: f64,
+ pub sync_ms: f64,
+ pub bodies: usize,
+ pub moved: usize,
+}
+
+impl Scene for World {
+ fn world_pose(&self, object: u32) -> Option<([f32; 3], [f32; 4])> {
+ self.objects.contains_key(&object).then(|| {
+ let (_, r, t) = self.world_matrix(object).to_scale_rotation_translation();
+ (t.to_array(), r.to_array())
+ })
+ }
+
+ /// Under a parent, in the parent's space.
+ fn place(&mut self, object: u32, position: [f32; 3], rotation: [f32; 4]) -> Option<([f32; 3], [f32; 4])> {
+ let parent = self.objects.get(&object)?.parent;
+ let (mut t, mut r) = (Vec3::from(position), Quat::from_array(rotation));
+ if let Some(p) = parent {
+ let local = self.world_matrix(p).inverse() * Mat4::from_rotation_translation(r, t);
+ let (_, lr, lt) = local.to_scale_rotation_translation();
+ (t, r) = (lt, lr);
+ }
+ // (A parent scaled to nothing has no inverse: the object stays where it is.)
+ if !(t.is_finite() && r.is_finite()) {
+ let o = &self.objects[&object];
+ return Some((o.position.to_array(), o.rotation.to_array()));
+ }
+ self.place_driven(object, t, r);
+ Some((t.to_array(), r.to_array()))
+ }
+
+ fn drive(&mut self, object: u32) {
+ let _ = self.set_driven(object);
+ }
+
+ fn geometry(&self, id: u32) -> Option<(&[f32], &[u32])> {
+ self.geometries.get(&id).map(|g| (g.positions.as_slice(), g.indices.as_slice()))
+ }
+}
+
+#[derive(Default)]
+pub struct PhysicsWorld {
+ bridge: Bridge,
+ stats: Stats,
+ /// Time in scene code's calls since `take_call_ms` (a click's chain, THREERT_CLICK_LOG).
+ call_ms: f64,
+}
+
+impl PhysicsWorld {
+ /// One engine call from scene code (`Bridge::call`). Returns its answer as JSON.
+ pub fn call(&mut self, w: &mut World, op: &str, a: &Value) -> Result<Value> {
+ let t = Instant::now();
+ let r = self.bridge.call(w, op, a).map_err(|e| anyhow!(e));
+ self.call_ms += t.elapsed().as_secs_f64() * 1e3;
+ r
+ }
+
+ /// The scene removed these objects: their bodies go (`Bridge::objects_removed`).
+ pub fn objects_removed(&mut self, objects: &[u32]) {
+ self.bridge.objects_removed(objects);
+ }
+
+ pub fn take_call_ms(&mut self) -> f64 {
+ std::mem::take(&mut self.call_ms)
+ }
+
+ /// The driven objects' poses by slot (`Bridge::poses`).
+ pub fn poses(&self) -> &[f32] {
+ self.bridge.poses()
+ }
+
+ /// `ticks` ticks, then the moved bodies' objects placed.
+ fn step(&mut self, w: &mut World, ticks: u32) {
+ let t0 = Instant::now();
+ for _ in 0..ticks {
+ self.bridge.tick();
+ }
+ let t1 = Instant::now();
+ let moved = self.bridge.sync(w);
+ self.stats.ticks += ticks;
+ self.stats.step_ms += (t1 - t0).as_secs_f64() * 1e3;
+ self.stats.sync_ms += t1.elapsed().as_secs_f64() * 1e3;
+ self.stats.bodies = self.bridge.bodies();
+ self.stats.moved += moved;
+ }
+
+ /// A frame of `dt` seconds: the whole ticks that fit (`Bridge::due`).
+ pub fn advance(&mut self, w: &mut World, dt: f64) {
+ let ticks = self.bridge.due(dt);
+ self.step(w, ticks);
+ }
+
+ /// Steps until the world has made `ticks` ticks in all (an offline render at a scene time; `Bridge::due_until`).
+ /// Settling is not a frame: with no tick due it does nothing, so the forces scene code applied (in setup, before a
+ /// live run's first frame) still act in the first frame's ticks instead of ending in an empty sync.
+ pub fn settle(&mut self, w: &mut World, ticks: u32) {
+ let ticks = self.bridge.due_until(ticks);
+ if ticks > 0 {
+ self.step(w, ticks);
+ }
+ }
+
+ /// The frame's figures, and a fresh count for the next.
+ pub fn take_stats(&mut self) -> Stats {
+ std::mem::take(&mut self.stats)
+ }
+
+ /// The world's hash (`Physics::hash`).
+ pub fn hash(&self) -> u64 {
+ self.bridge.hash()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::world::Kind;
+ use serde_json::json;
+
+ fn world() -> World {
+ let mut w = World::default();
+ w.set_geometry(1, crate::world::Geometry { positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], normals: vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0], uvs: vec![0.0; 6], indices: vec![0, 1, 2], ..Default::default() }).unwrap();
+ w
+ }
+
+ /// The renderer's world as the bridge's scene: a body drives an object under a turned, scaled parent to where the
+ /// body is in the world, the object's own scale kept; the object is movable and driven from then on; a session's
+ /// frames make whole ticks and the frame's figures count them.
+ #[test]
+ fn bodies_drive_the_worlds_objects() {
+ let mut w = world();
+ let group = Kind::Group;
+ w.set_object(1, "group".into(), None, group, true, false).unwrap();
+ w.set_transform(1, Vec3::new(4.0, 0.0, 0.0), Quat::from_rotation_y(std::f32::consts::FRAC_PI_2), Vec3::splat(2.0)).unwrap();
+ w.set_object(2, "box".into(), Some(1), Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(2, Vec3::new(0.0, 1.0, 0.5), Quat::IDENTITY, Vec3::splat(0.5)).unwrap();
+ let at = w.world_matrix(2).transform_point3(Vec3::ZERO);
+ assert!((at - Vec3::new(5.0, 2.0, 0.0)).length() < 1e-5, "{at}");
+ let mut p = PhysicsWorld::default();
+ p.call(&mut w, "body", &json!({ "id": 1, "object": 2, "slot": 0, "gravityScale": 0, "linvel": [0, 0, 6] })).unwrap();
+ p.call(&mut w, "collider", &json!({ "id": 1, "body": 1, "shape": { "type": "sphere", "radius": 0.5 } })).unwrap();
+ assert!(w.objects[&2].driven && w.objects[&2].movable);
+ p.advance(&mut w, 0.5);
+ let s = p.take_stats();
+ assert_eq!((s.ticks, s.bodies, s.moved), (5, 1, 1), "at most five ticks a frame");
+ let now = w.world_matrix(2).transform_point3(Vec3::ZERO);
+ assert!((now - Vec3::new(5.0, 2.0, 0.5)).length() < 1e-4, "5 ticks at 6 m/s: {now}");
+ assert_eq!(w.objects[&2].scale, Vec3::splat(0.5));
+ // What scene code reads: the object's own position, in the group's space.
+ let local = w.objects[&2].position;
+ assert_eq!(p.poses()[..3], local.to_array());
+ assert!((local - Vec3::new(-0.25, 1.0, 0.5)).length() < 1e-4, "{local}");
+ p.settle(&mut w, 65);
+ assert_eq!(p.take_stats().ticks, 60);
+ // The object removed from the world: its body goes when it would next be placed.
+ w.remove(2);
+ p.advance(&mut w, 1.0 / 60.0);
+ assert_eq!(p.take_stats().bodies, 0);
+ }
+
+ /// The renderer's build of the physics steps to the recorded bits, as physics-core's own build and its wasm32
+ /// build do (tools/physics-determinism.ts): features that the renderer's other dependencies turn on in the shared
+ /// crates (num-traits' and glam's `std`) do not bring the platform's math functions into it.
+ #[test]
+ fn the_renderers_physics_steps_to_the_recorded_bits() {
+ use physics_core::check;
+ assert_eq!(format!("{:016x}", check::script(600)), format!("{:016x}", check::EXPECTED));
+ assert_eq!(format!("{:016x}", check::cases()), format!("{:016x}", check::EXPECTED_CASES));
+ }
+
+ /// A force applied before a live run (in setup) acts in its first frame's tick: settling at time 0 makes no tick
+ /// and does not end it (a frame without a tick does).
+ #[test]
+ fn settling_with_no_tick_keeps_the_forces() {
+ let mut w = world();
+ w.set_object(1, "box".into(), None, Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();
+ let mut p = PhysicsWorld::default();
+ p.call(&mut w, "body", &json!({ "id": 1, "object": 1, "slot": 0, "gravityScale": 0 })).unwrap();
+ p.call(&mut w, "collider", &json!({ "id": 1, "body": 1, "shape": { "type": "sphere", "radius": 0.5 }, "mass": 2 })).unwrap();
+ p.call(&mut w, "force", &json!({ "body": 1, "force": [0, 120, 0] })).unwrap();
+ p.settle(&mut w, 0);
+ assert_eq!(p.take_stats().ticks, 0);
+ p.advance(&mut w, 1.0 / 60.0);
+ let v = p.call(&mut w, "state", &json!({ "body": 1 })).unwrap()["linvel"][1].as_f64().unwrap();
+ assert!((v - 120.0 / 2.0 / 60.0).abs() < 1e-4, "120 N on 2 kg through one tick: {v}");
+ }
+}
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 77fd72f..c9f68a5 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -1060,8 +1060,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let shown = w.shown(*id);
let flags = if n.cast_shadow { 0 } else { TRI_NO_SHADOW };
match &n.kind {
- Kind::Mesh { geometry, material, own_blas: true, materials: mesh_mats } if shown && instancing && mesh_mats.len() <= 1 && !w.movable(*id) && m.determinant() > 0.0 => {
- // Its own BLAS (scene code's `dynamicGeometry`): placed like a model instance, its geometry's triangles
+ Kind::Mesh { geometry, material, own_blas, materials: mesh_mats } if shown && instancing && mesh_mats.len() <= 1 && m.determinant() > 0.0 && (n.driven || (*own_blas && !w.movable(*id))) => {
+ // Its own BLAS (scene code's `dynamicGeometry`, or a mesh a rigid body drives: its moves are the
+ // instance's transform, `retained.instance_of`): placed like a model instance, its geometry's triangles
// in model space in the pool, shared by the objects of the same geometry and material. Glass, emissive
// and function materials are flattened (as a model's would be), so they are never instanced.
let g = w.geometries.get(geometry).ok_or_else(|| anyhow!("object {}: unknown geometry {geometry}", n.name))?;
@@ -1092,11 +1093,15 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
retained.objects.insert(*id, oi);
retained.own_instance.insert(*id, instances.len() as u32);
+ if n.driven {
+ retained.instance_of.insert(*id, instances.len() as u32);
+ }
instances.push(Instance { mesh, world: m, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false });
}
continue;
}
- if emits_only(&materials[mat as usize]) {
+ // (A driven emitter's triangles cannot stay in world space: it is flattened, dynamic, below.)
+ if emits_only(&materials[mat as usize]) && !n.driven {
// An emitting material: its own BLAS too, but its triangles in world space (placed at identity,
// never shared), so they are light-sampled as flattened triangles are and can be edited in place
// (live.rs `edit_geometry`; ROADMAP § 6 step 3).
@@ -1120,7 +1125,12 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
continue;
}
put_colors(&mut vcolors, tris.len(), vc.then(|| tri_colors(g, false, None)));
- append_arrays(g, m, mat, flags, None, &mut tris, &mut tri_flags, &mut attrs);
+ // (A driven mesh that cannot be an instance (glass, emissive, a material function): dynamic triangles,
+ // re-transformed in place as any movable mesh's.)
+ append_arrays(g, m, mat, if n.driven { flags | TRI_DYNAMIC } else { flags }, None, &mut tris, &mut tri_flags, &mut attrs);
+ if n.driven {
+ retained.dynamic.insert(*id, DynamicModel { first, mats: attrs[first as usize..].iter().map(|a| a.uv[3].to_bits()).collect(), ..Default::default() });
+ }
}
Kind::Instanced { geometry, procedural, materials: mats, capacity } if shown => {
// Copies of one geometry: one shared mesh (one BLAS), an instance and an object entry per copy, the
diff --git a/renderer/src/script.rs b/renderer/src/script.rs
index e5516e7..41efd95 100644
--- a/renderer/src/script.rs
+++ b/renderer/src/script.rs
@@ -80,6 +80,8 @@ pub struct ScriptHost {
pub world: Rc<RefCell<World>>,
/// The voxel engine's objects (`__engine.voxelLevel` / `voxelExplode`; renderer/src/voxel.rs).
pub voxels: Rc<RefCell<crate::voxel::VoxelWorld>>,
+ /// The physics world (`__engine.physics`; renderer/src/physics.rs): None until scene code makes a physics call.
+ pub physics: Rc<RefCell<Option<crate::physics::PhysicsWorld>>>,
}
pub struct EventOut {
@@ -129,8 +131,20 @@ fn fail(ctx: &Ctx, e: anyhow::Error) -> rquickjs::Error {
}
/// The engine API (`globalThis.__engine`), see packages/scene/src/engine.ts.
-fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<RefCell<crate::voxel::VoxelWorld>>) -> rquickjs::Result<()> {
+fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<RefCell<crate::voxel::VoxelWorld>>, physics: &Rc<RefCell<Option<crate::physics::PhysicsWorld>>>) -> rquickjs::Result<()> {
let e = Object::new(ctx.clone())?;
+ // Physics (renderer/src/physics.rs): one call, `physics(op, args)`, answering in JSON. The world is made by the
+ // first call; the engine steps it, scene code cannot.
+ let (p, w) = (physics.clone(), world.clone());
+ e.set("physics", Function::new(ctx.clone(), move |ctx: Ctx<'js>, op: String, args: Value<'js>| -> rquickjs::Result<String> {
+ let a: serde_json::Value = if args.is_undefined() || args.is_null() { serde_json::Value::Null } else { parse(&ctx, "physics", &args)? };
+ let out = p.borrow_mut().get_or_insert_with(Default::default).call(&mut w.borrow_mut(), &op, &a).map_err(|e| fail(&ctx, e))?;
+ Ok(out.to_string())
+ })?)?;
+ // The poses of the objects that bodies drive, by the slot the binding gave each body (7 floats: position, rotation
+ // xyzw, as scene code reads an object's): one copy for all a frame reads. Empty without a world.
+ let p = physics.clone();
+ e.set("physicsPoses", Function::new(ctx.clone(), move |ctx: Ctx<'js>| -> rquickjs::Result<TypedArray<'js, f32>> { TypedArray::new(ctx, p.borrow().as_ref().map_or(vec![], |p| p.poses().to_vec())) })?)?;
// The voxel engine's level and explosions (renderer/src/voxel.rs): the level is loaded natively once the session
// knows the asset root; an explosion returns what it did as JSON.
let v = voxels.clone();
@@ -241,13 +255,14 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<R
e.set("object", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> {
let j = to_json(&d)?;
let num = |k: &str| j[k].as_u64().map(|x| x as u32);
+ // `body`: a rigid body will drive it (physics.rs). A mesh is then an instance of its own BLAS, so one added while
+ // the game runs is placed in place and its moves are its instance's transform.
+ let body = j["body"].as_bool().unwrap_or(false);
let kind = match j["kind"].as_str().unwrap_or("group") {
- "mesh" => Kind::Mesh {
- geometry: num("geometry").unwrap_or(0),
- material: num("material").unwrap_or(0),
- own_blas: j["dynamicGeometry"].as_bool().unwrap_or(false),
- materials: j["materials"].as_array().map_or(vec![], |a| a.iter().filter_map(|v| v.as_u64().map(|x| x as u32)).collect()),
- },
+ "mesh" => {
+ let materials: Vec<u32> = j["materials"].as_array().map_or(vec![], |a| a.iter().filter_map(|v| v.as_u64().map(|x| x as u32)).collect());
+ Kind::Mesh { geometry: num("geometry").unwrap_or(0), material: num("material").unwrap_or(0), own_blas: j["dynamicGeometry"].as_bool().unwrap_or(false) || (body && materials.len() <= 1), materials }
+ }
"model" => Kind::Model { uri: j["uri"].as_str().unwrap_or_default().to_string(), nodes: serde_json::from_value(j["nodes"].clone()).ok(), animation: serde_json::from_value(j["animation"].clone()).ok() },
"light" => Kind::Light(serde_json::from_value(j["light"].clone()).map_err(|e| Exception::throw_type(&ctx, &format!("engine.object light: {e}")))?),
"camera" => Kind::Camera(serde_json::from_value(j["camera"].clone()).map_err(|e| Exception::throw_type(&ctx, &format!("engine.object camera: {e}")))?),
@@ -293,7 +308,12 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<R
},
_ => Kind::Group,
};
- w.borrow_mut().set_object(id, j["name"].as_str().unwrap_or_default().to_string(), num("parent"), kind, j["castShadow"].as_bool().unwrap_or(true), j["movable"].as_bool().unwrap_or(false)).map_err(|e| fail(&ctx, e))
+ let mut w = w.borrow_mut();
+ w.set_object(id, j["name"].as_str().unwrap_or_default().to_string(), num("parent"), kind, j["castShadow"].as_bool().unwrap_or(true), j["movable"].as_bool().unwrap_or(false)).map_err(|e| fail(&ctx, e))?;
+ if body {
+ w.set_driven(id).map_err(|e| fail(&ctx, e))?;
+ }
+ Ok(())
})?)?;
let w = world.clone();
e.set("transform", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, t: TypedArray<f32>| -> rquickjs::Result<()> {
@@ -344,7 +364,14 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<R
w.borrow_mut().set_animation(id, a).map_err(|e| fail(&ctx, e))
})?)?;
let w = world.clone();
- e.set("remove", Function::new(ctx.clone(), move |id: u32| w.borrow_mut().remove(id))?)?;
+ let p = physics.clone();
+ e.set("remove", Function::new(ctx.clone(), move |id: u32| {
+ let gone = w.borrow_mut().remove(id);
+ // (A body asleep would never find out its object went; the object's id may come again.)
+ if let Some(p) = p.borrow_mut().as_mut() {
+ p.objects_removed(&gone);
+ }
+ })?)?;
let w = world.clone();
e.set("environment", Function::new(ctx.clone(), move |ctx: Ctx, d: Value| -> rquickjs::Result<()> {
let env: desc::Environment = parse(&ctx, "environment", &d)?;
@@ -406,13 +433,13 @@ impl ScriptHost {
let ctx = Context::full(&rt)?;
let world = Rc::new(RefCell::new(World::default()));
let voxels = Rc::new(RefCell::new(crate::voxel::VoxelWorld::default()));
- let mut h = ScriptHost { _rt: rt, ctx, deadline, epoch, info: serde_json::Value::Null, world, voxels };
- let (w, v) = (h.world.clone(), h.voxels.clone());
+ let mut h = ScriptHost { _rt: rt, ctx, deadline, epoch, info: serde_json::Value::Null, world, voxels, physics: Default::default() };
+ let (w, v, ph) = (h.world.clone(), h.voxels.clone(), h.physics.clone());
let info: String = h.call(SETUP_MS, |ctx| {
let g = ctx.globals();
g.set("__host_log", Function::new(ctx.clone(), |level: String, msg: String| eprintln!("[game{}] {msg}", if level == "info" { String::new() } else { format!(" {level}") }))?)?;
g.set("__host_now", Function::new(ctx.clone(), move || epoch.elapsed().as_secs_f64() * 1000.0)?)?;
- install_engine(ctx, &w, &v)?;
+ install_engine(ctx, &w, &v, &ph)?;
ctx.eval::<(), _>(PRELUDE)?;
code(ctx)?;
host(ctx)?.get::<_, Function>("describe")?.call(())
@@ -490,6 +517,25 @@ impl ScriptHost {
})
}
+ /// A frame of the physics world, if scene code made one: its ticks, and the objects its bodies drive placed
+ /// (renderer/src/physics.rs). True if there is a world (the caller commits what moved).
+ pub fn advance_physics(&self, dt: f32) -> bool {
+ match self.physics.borrow_mut().as_mut() {
+ Some(p) => {
+ p.advance(&mut self.world.borrow_mut(), dt as f64);
+ true
+ }
+ None => false,
+ }
+ }
+
+ /// The physics world `ticks` ticks on (an offline render at a scene time).
+ pub fn settle_physics(&self, ticks: u32) {
+ if let Some(p) = self.physics.borrow_mut().as_mut() {
+ p.settle(&mut self.world.borrow_mut(), ticks);
+ }
+ }
+
/// Runs the frame script for one rendered frame.
pub fn frame(&self, dt: f32) -> Result<()> {
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_millis() as f64);
@@ -521,12 +567,25 @@ pub struct GameSession {
pub setup_ms: f64,
/// Frame script + commit cost of the last frame, ms.
pub frame_ms: f32,
- /// Of `frame_ms`, the frame script's own JavaScript (the rest: applying what it changed, `LiveCore::commit`).
+ /// Of `frame_ms`, the frame script's own JavaScript (the rest: the physics' ticks, and applying what both changed,
+ /// `LiveCore::commit`: `commit_ms`).
pub js_ms: f32,
+ pub commit_ms: f32,
/// Last handler log line (window title).
pub status: String,
/// The frame script's clock (`f.time`).
clock: GameClock,
+ /// When the last click arrived, until its first frame is drawn (`click_shown`; THREERT_CLICK_LOG=1).
+ clicked: Option<Instant>,
+ /// Whether the last event's commit rebuilt the scene.
+ rebuilt: bool,
+}
+
+/// THREERT_CLICK_LOG=1: a click's chain timed on stderr (`click: ...`): the pick, the script (handler, frame script,
+/// binding; of which the physics world's calls), the commit, and the first frame after it.
+fn click_log() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("THREERT_CLICK_LOG").is_ok_and(|v| v == "1"))
}
/// The frame script's clock: the gameplay FrameRunner adds each frame's dt clamped to [0, 0.1] s, in f64. While a
@@ -549,7 +608,7 @@ impl GameSession {
let setup_ms = host.setup(room, None)?;
host.world.borrow_mut().take_changes();
eprintln!("game: setup {setup_ms:.0} ms in the node runtime, {} objects, handlers {}, frame script {}", host.world.borrow().objects.len(), host.info["handlers"], host.has_frame());
- Ok(GameSession { host, seq: 0, setup_ms, frame_ms: 0.0, js_ms: 0.0, status: String::new(), clock: GameClock::default() })
+ Ok(GameSession { host, seq: 0, setup_ms, frame_ms: 0.0, js_ms: 0.0, commit_ms: 0.0, status: String::new(), clock: GameClock::default(), clicked: None, rebuilt: false })
}
/// Loads the bundle, builds the scene in the runtime and opens a live view of it. Models and file textures resolve
@@ -597,6 +656,7 @@ impl GameSession {
let e = self.host.event(kind, &payload)?;
let t = Instant::now();
let rebuilt = self.commit(core)?;
+ self.rebuilt = rebuilt;
self.seq = e.seq;
core.seq = e.seq;
for l in &e.log {
@@ -614,20 +674,46 @@ impl GameSession {
if !self.host.has_handler("click") {
return Ok(None);
}
+ let t0 = Instant::now();
let Some((target, p, sub)) = core.pick(u, v) else { return Ok(None) };
+ let pick_ms = t0.elapsed().as_secs_f64() * 1e3;
let r = |x: f32| (x * 1e4).round() / 1e4;
- let mut payload = serde_json::json!({ "target": target, "point": [r(p.x), r(p.y), r(p.z)], "player": "you" });
+ // (`ray`: the view ray through the click, for a `Raycaster` in scene code: `raycaster.set(origin, direction)`.)
+ let (o, d) = core.ray(u, v);
+ let mut payload = serde_json::json!({ "target": target, "point": [r(p.x), r(p.y), r(p.z)], "player": "you", "ray": { "origin": o.to_array(), "direction": d.to_array() } });
if let Some(i) = sub {
payload["instanceId"] = i.into();
}
- self.event(core, "click", payload).map(Some)
+ if !click_log() {
+ return self.event(core, "click", payload).map(Some);
+ }
+ if let Some(p) = self.host.physics.borrow_mut().as_mut() {
+ p.take_call_ms();
+ }
+ let t1 = Instant::now();
+ let e = self.event(core, "click", payload)?;
+ let all = t1.elapsed().as_secs_f64() * 1e3;
+ let physics = self.host.physics.borrow_mut().as_mut().map_or(0.0, |p| p.take_call_ms());
+ eprintln!("click: pick {pick_ms:.3} ms, script {:.3} ms (the physics world's calls {physics:.3} ms), commit {:.3} ms ({})", e.ms, all - e.ms, if self.rebuilt { "rebuild" } else { "in place" });
+ self.clicked = Some(t0);
+ Ok(Some(e))
+ }
+
+ /// A frame was drawn: the first one after a click is timed (THREERT_CLICK_LOG=1).
+ pub fn click_shown(&mut self) {
+ if let Some(t) = self.clicked.take() {
+ eprintln!("click: first frame submitted {:.3} ms after the click", t.elapsed().as_secs_f64() * 1e3);
+ }
}
- /// Runs the frame script and applies what it changed; true if that rebuilt the scene.
+ /// Runs the frame script and applies what it changed; true if that rebuilt the scene. A frame script (or its
+ /// sync) that throws does not stop the world: the frame's physics ticks are made and what changed is committed all
+ /// the same, then the error is returned (the window and `live` print it and go on).
pub fn frame(&mut self, core: &mut crate::live::LiveCore, dt: f32) -> Result<bool> {
if !self.host.has_frame() {
- // Wind sway follows the scene time with or without a frame script.
- if self.host.world.borrow_mut().apply_sway(core.scene_time()) {
+ // Wind sway and the physics follow the scene time with or without a frame script.
+ let swayed = self.host.world.borrow_mut().apply_sway(core.scene_time());
+ if self.host.advance_physics(dt) || swayed {
return self.commit(core);
}
return Ok(false);
@@ -635,10 +721,15 @@ impl GameSession {
let t = Instant::now();
core.set_time(self.clock.tick(dt));
self.host.world.borrow_mut().apply_sway(core.scene_time());
- self.host.frame(dt)?;
+ let scripted = self.host.frame(dt);
self.js_ms = t.elapsed().as_secs_f32() * 1000.0;
+ // The physics' ticks after the frame script (its impulses and targets act in this frame's ticks).
+ self.host.advance_physics(dt);
+ let tc = Instant::now();
let rebuilt = self.commit(core)?;
+ self.commit_ms = tc.elapsed().as_secs_f32() * 1000.0;
self.frame_ms = t.elapsed().as_secs_f32() * 1000.0;
+ scripted?;
Ok(rebuilt)
}
}
@@ -729,6 +820,40 @@ mod tests {
assert!(ScriptHost::from_modules("import x from './nope.js';", runtime).is_err());
}
+ /// A frame whose script throws (as the binding's sync does once when the engine took out a body whose state went
+ /// non-finite, or a `physics` cannot be made a body): the error is returned, and the frame's physics tick and
+ /// commit are made all the same. (Skipped without a GPU.)
+ #[test]
+ fn a_frame_script_that_throws_does_not_stop_the_world() {
+ let g = match crate::gpu::Gpu::new() {
+ Ok(g) => g,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ // The game above with a weightless body that drives the sign at 6 m/s, and a frame script that throws in its
+ // second frame.
+ let game = GAME.replace("return \"{}\";", "__engine.physics('body', { id: 1, object: 4, gravityScale: 0, linvel: [0, 0, 6] }); __engine.physics('collider', { id: 1, body: 1, shape: { type: 'sphere', radius: 0.5 } }); return \"{}\";").replace("frame: (dt) => { frames++; },", "frame: (dt) => { frames++; if (frames === 2) throw new Error('the sync threw'); },").replace(", map: 2 }", " }");
+ // (Without the sign's texture: its bytes are not an image.)
+ assert!(game.contains("__engine.physics") && game.contains("the sync threw") && !game.contains("map: 2"));
+ let bundle = std::env::temp_dir().join(format!("threert-frame-throws-{}.js", std::process::id()));
+ std::fs::write(&bundle, game).unwrap();
+ let started = GameSession::start(&bundle, "room", std::path::Path::new("."), g, &crate::default_presets_dir(), 64, 36);
+ std::fs::remove_file(&bundle).ok();
+ let (mut s, mut core) = started.unwrap();
+ let z = |s: &GameSession| s.host.world.borrow().objects[&4].position.z;
+ let ticks = |s: &GameSession| s.host.physics.borrow_mut().as_mut().unwrap().take_stats().ticks;
+ s.frame(&mut core, 1.0 / 60.0).unwrap();
+ assert_eq!(ticks(&s), 1);
+ assert!((z(&s) - 0.1).abs() < 1e-4, "{}", z(&s));
+ let e = s.frame(&mut core, 1.0 / 60.0).unwrap_err();
+ assert!(format!("{e:#}").contains("the sync threw"), "{e:#}");
+ assert_eq!(ticks(&s), 1, "the tick of the frame that threw");
+ assert!((z(&s) - 0.2).abs() < 1e-4, "{}", z(&s));
+ let c = s.host.world.borrow_mut().take_changes();
+ assert!(c.moved.is_empty() && !c.structural, "and its commit");
+ s.frame(&mut core, 1.0 / 60.0).unwrap();
+ assert!((z(&s) - 0.3).abs() < 1e-4, "{}", z(&s));
+ }
+
#[test]
fn budgets_and_errors() {
let h = ScriptHost::new(GAME).unwrap();
diff --git a/renderer/src/tables.rs b/renderer/src/tables.rs
index 7b44763..6184a86 100644
--- a/renderer/src/tables.rs
+++ b/renderer/src/tables.rs
@@ -90,6 +90,13 @@ impl Tables {
return Ok(None);
}
let mut d = Dirty::default();
+ // (The live view has added them before its geometry edits; here for the callers without one.)
+ if !c.new_materials.is_empty() {
+ if !self.add_materials(w, &c.new_materials) {
+ return Ok(None);
+ }
+ d.materials = true;
+ }
for id in &c.powers {
let o = w.objects.get(id).ok_or_else(|| anyhow!("unknown object {id}"))?;
if let Some(&oi) = self.retained.objects.get(id) {
@@ -163,6 +170,32 @@ impl Tables {
/// Whether a material may emit without a rebuild: it already has emitter entries, or (`emit_in_place`) its
/// triangles can get them in place, queued in `started_emitting` (ROADMAP § 6 step 3).
+ /// Materials created since the build (`Changes::new_materials`: no texture, no function), as entries after the
+ /// scene's. False, and nothing added, if one of them cannot be: it emits, is glass or layered, or a cutout (the
+ /// build sorts triangles by those; the caller rebuilds).
+ pub fn add_materials(&mut self, w: &World, ids: &std::collections::BTreeSet<u32>) -> bool {
+ let mut fresh = vec![];
+ for id in ids {
+ if self.retained.materials.contains_key(id) {
+ continue;
+ }
+ let Some(m) = w.materials.get(id) else { return false };
+ let Ok(gm) = scene::build_material(*id, m, &w.textures, &self.retained.shaders, &mut |_, _| Err(anyhow!("a texture"))) else { return false };
+ if scene::material_class(&gm) != 0 {
+ return false;
+ }
+ fresh.push((*id, gm));
+ }
+ for (id, gm) in fresh {
+ let mi = self.materials.len() as u32;
+ self.retained.materials.insert(id, mi);
+ self.materials.push(gm);
+ // (What is drawn with it are instances' triangles: it cannot start emitting in place, `can_emit`.)
+ self.fixed_mats.insert(mi);
+ }
+ true
+ }
+
fn can_emit(&mut self, mi: u32, m: &GpuMaterial) -> bool {
let lum = 0.2126 * m.emissive[0] + 0.7152 * m.emissive[1] + 0.0722 * m.emissive[2];
if lum <= 0.0 || self.emissive.contains(&mi) {
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index a9b21e1..7f9980a 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -195,6 +195,9 @@ pub struct Object {
/// UE Mobility "Movable": scripts move it (and everything under it) without rebuilding the scene; its triangles
/// are kept apart (dynamic BLASes) and re-transformed in place. Set by scene code, or by the first move.
pub movable: bool,
+ /// A rigid body drives it (renderer/src/physics.rs): movable, and a mesh among them is placed as an instance of its
+ /// own BLAS, so a move is its TLAS transform and no triangle.
+ pub driven: bool,
/// Wind sway (`windSway` in packages/scene): the renderer leans the object about its origin with scene time.
pub sway: Option<Sway>,
/// The sway's current rotation (identity without one), applied after the object's own rotation.
@@ -305,11 +308,15 @@ pub struct Changes {
pub instanced: HashSet<u32>,
/// Density grids created in this batch (their volume objects may not exist yet: `World::set_grid` keeps them).
pub grids_new: BTreeSet<u32>,
+ /// Materials created in this batch that bring no texture and no material function: the live view adds them in
+ /// place (live.rs `add_materials`; a rebuild for one it cannot take), so an object added while the game runs may
+ /// come with a material of its own.
+ pub new_materials: BTreeSet<u32>,
}
impl Changes {
pub fn any(&self) -> bool {
- self.structural || !self.materials.is_empty() || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.exposure || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()
+ self.structural || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.exposure || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()
}
/// Geometry edits are pending (`geometries`, `added`, `removed`).
pub fn edits(&self) -> bool {
@@ -490,6 +497,10 @@ impl World {
Some(old) if same_texture_refs(old, &m) && old.transparent == m.transparent && old.vertex_colors == m.vertex_colors => {
self.changes.materials.insert(id);
}
+ // A new one of plain parameters (no texture, no function, not a particle's): in place.
+ None if [m.map, m.normal_map, m.roughness_map, m.metalness_map, m.ao_map, m.emissive_map, m.transmission_map].iter().all(Option::is_none) && m.shader.is_none() && !m.transparent && !m.vertex_colors => {
+ self.changes.new_materials.insert(id);
+ }
_ => self.changes.structural = true,
}
self.materials.insert(id, m);
@@ -537,7 +548,7 @@ impl World {
}
let o = match self.objects.remove(&id) {
Some(o) => Object { name, parent, kind, cast_shadow, movable: movable || o.movable, ..o },
- None => Object { name, parent, kind, position: Vec3::ZERO, rotation: Quat::IDENTITY, scale: Vec3::ONE, visible: true, cast_shadow, power: 1.0, custom: [0.0; 4], movable, sway: None, sway_rot: Quat::IDENTITY },
+ None => Object { name, parent, kind, position: Vec3::ZERO, rotation: Quat::IDENTITY, scale: Vec3::ONE, visible: true, cast_shadow, power: 1.0, custom: [0.0; 4], movable, driven: false, sway: None, sway_rot: Quat::IDENTITY },
};
self.objects.insert(id, o);
if fresh {
@@ -559,6 +570,41 @@ impl World {
Ok(())
}
+ /// A rigid body drives object `id` from now on: it is movable, built as an instance where it can be (a rebuild,
+ /// once; none for an object this batch adds in place, which is placed as one: live.rs `edit_geometry`).
+ pub fn set_driven(&mut self, id: u32) -> Result<()> {
+ let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
+ if !o.driven {
+ o.driven = true;
+ o.movable = true;
+ if !self.changes.added.contains(&id) {
+ self.changes.structural = true;
+ }
+ }
+ Ok(())
+ }
+
+ /// A rigid body's object at its new position and rotation (in its parent's space): `set_transform` with the scale
+ /// kept, and for a driven mesh without the questions a move of any object asks (a world of bodies moves thousands a
+ /// frame). False if there is no such object.
+ pub fn place_driven(&mut self, id: u32, position: Vec3, rotation: Quat) -> bool {
+ let Some(o) = self.objects.get_mut(&id) else { return false };
+ if o.position == position && o.rotation == rotation {
+ return true;
+ }
+ (o.position, o.rotation) = (position, rotation);
+ // (A driven mesh is movable and is not the camera: its move is a move. One added in this batch is placed where
+ // it is then, as `note_move` has it.)
+ if o.driven && matches!(o.kind, Kind::Mesh { .. }) {
+ if !self.changes.added.contains(&id) {
+ self.changes.moved.insert(id);
+ }
+ } else {
+ self.note_move(id);
+ }
+ true
+ }
+
/// Wind sway for an object (None: none, the object back at rest).
pub fn set_sway(&mut self, id: u32, sway: Option<Sway>) -> Result<()> {
let o = self.objects.get_mut(&id).ok_or_else(|| anyhow!("unknown object {id}"))?;
@@ -819,8 +865,8 @@ impl World {
Ok(())
}
- /// Removes an object and its descendants.
- pub fn remove(&mut self, id: u32) {
+ /// Removes an object and its descendants. Returns their ids (those it had: the bodies that drove them go too).
+ pub fn remove(&mut self, id: u32) -> Vec<u32> {
let mut doomed = vec![id];
let mut k = 0;
while k < doomed.len() {
@@ -837,15 +883,16 @@ impl World {
if !self.changes.added.remove(&only) {
self.changes.removed.insert(only);
}
- return;
+ return doomed;
}
}
- for d in doomed {
+ for &d in &doomed {
self.instanced.remove(&d);
if self.objects.remove(&d).is_some() {
self.changes.structural = true;
}
}
+ doomed
}
pub fn set_environment(&mut self, e: desc::Environment) {
@@ -1159,6 +1206,43 @@ mod tests {
serde_json::from_value(serde_json::json!({ "name": "m", "color": [1, 1, 1], "opacity": 1, "metalness": 0, "roughness": 0.5, "emissive": [0, 0, 0], "emissiveIntensity": 1, "doubleSided": false })).unwrap()
}
+ /// What a game adds while it runs (ROADMAP § 6 step 7): a material without textures is added in place; a mesh a
+ /// rigid body will drive is placed in place and is movable from the start; its body's moves are moves in place.
+ #[test]
+ fn driven_objects_and_new_materials_in_place() {
+ let tri = || Geometry { positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], normals: vec![0.0; 9], uvs: vec![0.0; 6], indices: vec![0, 1, 2], groups: vec![], colors: vec![] };
+ let mesh = |material, own_blas| Kind::Mesh { geometry: 1, material, own_blas, materials: vec![] };
+ let mut w = World::default();
+ w.set_material(1, mat());
+ w.set_geometry(1, tri()).unwrap();
+ w.set_object(1, "still".into(), None, mesh(1, false), true, false).unwrap();
+ assert!(w.take_changes().structural, "the first commit builds the scene");
+ w.set_material(2, mat());
+ let c = w.take_changes();
+ assert!(!c.structural && c.any() && c.new_materials.contains(&2), "a new material of plain parameters: in place");
+ let mut textured = mat();
+ textured.map = Some(9);
+ w.set_material(3, textured);
+ assert!(w.take_changes().structural, "one with a texture: a rebuild");
+ // (The engine's `object` call gives a mesh a body will drive its own BLAS.)
+ w.set_object(2, "box".into(), None, mesh(2, true), true, false).unwrap();
+ w.set_driven(2).unwrap();
+ w.set_transform(2, Vec3::Y, Quat::IDENTITY, Vec3::ONE).unwrap();
+ let c = w.take_changes();
+ assert!(!c.structural && c.added.contains(&2) && c.moved.is_empty(), "added in place, where it is");
+ assert!(w.objects[&2].driven && w.movable(2));
+ assert!(w.place_driven(2, Vec3::new(0.0, 2.0, 0.0), Quat::IDENTITY));
+ let c = w.take_changes();
+ assert!(!c.structural && c.moved.contains(&2) && w.objects[&2].position.y == 2.0, "its body's move: in place");
+ assert!(w.place_driven(2, Vec3::new(0.0, 2.0, 0.0), Quat::IDENTITY) && !w.take_changes().any(), "where it is already: nothing");
+ assert!(!w.place_driven(99, Vec3::ZERO, Quat::IDENTITY));
+ // An object the scene was built with becomes one a body drives: a rebuild, once.
+ w.set_driven(1).unwrap();
+ assert!(w.take_changes().structural && w.movable(1));
+ w.set_driven(1).unwrap();
+ assert!(!w.take_changes().any());
+ }
+
#[test]
fn geometry_edits_in_place() {
let tri = || Geometry { positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], normals: vec![0.0; 9], uvs: vec![0.0; 6], indices: vec![0, 1, 2], groups: vec![], colors: vec![] };
diff --git a/renderer/third_party/glamx/CHANGELOG.md b/renderer/third_party/glamx/CHANGELOG.md
new file mode 100644
index 0000000..781ed58
--- /dev/null
+++ b/renderer/third_party/glamx/CHANGELOG.md
@@ -0,0 +1,26 @@
+# v0.3.1
+
+- Add `From` conversions between `Pose2`/`Pose3` and their `(translation, rotation)` tuples.
+ ([#3](https://github.com/dimforge/glamx/pull/3))
+- Fix `Rot2::slerp` (and therefore `Pose2::lerp`) taking the long way around whenever the arc
+ crosses the `-pi`/`pi` cut of `Rot2::angle`. It now interpolates along the shortest arc.
+
+# v0.3.0
+
+- Update to `glam 0.33`, `simba 0.10`, and `nalgebra 0.35`. ([#5](https://github.com/dimforge/glamx/pull/5))
+- Mirror glam 0.33's type-gating features: `all-types` (default), `float-types`, `integer-types`, `size-types`, and individual `f64`/`i8`/`u8`/`i16`/`u16`/`i32`/`u32`/`i64`/`u64`/`isize`/`usize` passthroughs. Disabling `f64` now also removes the corresponding glamx `D*` types (`DRot2`, `DPose3`, `DSymmetricEigen3`, ...). ([#5](https://github.com/dimforge/glamx/pull/5))
+- Bump MSRV to 1.89. ([#5](https://github.com/dimforge/glamx/pull/5))
+
+# v0.2.0
+
+- Add `padding` field to `Pose3` for better compatibility with `bytemuck` and `spirv`.
+- Fix various internal implementation details that are incompatible with `spirv`/`naga`.
+- Update to `glam 0.32`.
+
+# v0.1.3
+
+- Add `From`/`Into` conversions between f32 and f64 type variants.
+
+# v0.1.2
+
+- Add optional `rkyv 0.8` support.
\ No newline at end of file
diff --git a/renderer/third_party/glamx/Cargo.toml b/renderer/third_party/glamx/Cargo.toml
new file mode 100644
index 0000000..d7eb316
--- /dev/null
+++ b/renderer/third_party/glamx/Cargo.toml
@@ -0,0 +1,174 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+name = "glamx"
+version = "0.3.1"
+authors = ["Sébastien Crozet <[email protected]>"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "Extensions for glam: Pose2, Pose3, Rot2, and matrix utilities."
+homepage = "https://dimforge.com"
+documentation = "https://docs.rs/glamx"
+readme = "README.md"
+keywords = [
+ "math",
+ "geometry",
+ "rotation",
+ "pose",
+ "glam",
+]
+categories = [
+ "mathematics",
+ "game-development",
+ "no-std",
+]
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/dimforge/glamx"
+
+[features]
+all-types = [
+ "float-types",
+ "integer-types",
+ "size-types",
+ "glam/all-types",
+]
+approx = [
+ "dep:approx",
+ "glam/approx",
+]
+bytemuck = [
+ "dep:bytemuck",
+ "glam/bytemuck",
+]
+cuda = ["glam/cuda"]
+debug-glam-assert = ["glam/debug-glam-assert"]
+default = [
+ "std",
+ "all-types",
+]
+encase = ["glam/encase"]
+f64 = ["glam/f64"]
+fast-math = ["glam/fast-math"]
+float-types = [
+ "f64",
+ "glam/float-types",
+]
+glam-assert = ["glam/glam-assert"]
+glamx-serde = []
+i16 = ["glam/i16"]
+i32 = ["glam/i32"]
+i64 = ["glam/i64"]
+i8 = ["glam/i8"]
+integer-types = [
+ "i8",
+ "u8",
+ "i16",
+ "u16",
+ "i32",
+ "u32",
+ "i64",
+ "u64",
+ "glam/integer-types",
+]
+isize = ["glam/isize"]
+libm = [
+ "glam/libm",
+ "simba/libm_force",
+ "num-traits/libm",
+]
+mint = ["glam/mint"]
+nalgebra = ["dep:nalgebra"]
+nostd-libm = [
+ "simba/libm",
+ "glam/nostd-libm",
+]
+rand = ["glam/rand"]
+rkyv = [
+ "dep:rkyv",
+ "glam/rkyv",
+]
+scalar-math = ["glam/scalar-math"]
+serde = [
+ "dep:serde",
+ "glam/serde",
+ "glamx-serde",
+]
+size-types = [
+ "isize",
+ "usize",
+ "glam/size-types",
+]
+std = [
+ "glam/std",
+ "simba/std",
+ "approx?/std",
+]
+u16 = ["glam/u16"]
+u32 = ["glam/u32"]
+u64 = ["glam/u64"]
+u8 = ["glam/u8"]
+usize = ["glam/usize"]
+
+[lib]
+name = "glamx"
+path = "src/lib.rs"
+
+[dependencies.approx]
+version = "0.5"
+optional = true
+default-features = false
+
+[dependencies.bytemuck]
+version = "1"
+features = ["derive"]
+optional = true
+
+[dependencies.glam]
+version = "0.33.7"
+default-features = false
+
+[dependencies.nalgebra]
+version = "0.35"
+features = ["convert-glam033"]
+optional = true
+default-features = false
+
+[dependencies.num-traits]
+version = "0.2"
+features = ["libm"]
+default-features = false
+
+[dependencies.rkyv]
+version = "0.8"
+optional = true
+default-features = false
+
+[dependencies.serde]
+version = "1.0"
+features = ["derive"]
+optional = true
+
+[dependencies.simba]
+version = "0.10"
+default-features = false
+
+[dev-dependencies.approx]
+version = "0.5"
+
+[dev-dependencies.glam]
+version = "0.33"
+features = ["approx"]
diff --git a/renderer/third_party/glamx/LICENSE-APACHE b/renderer/third_party/glamx/LICENSE-APACHE
new file mode 100644
index 0000000..301f1f0
--- /dev/null
+++ b/renderer/third_party/glamx/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright 2020 Cameron Hart
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/renderer/third_party/glamx/LICENSE-MIT b/renderer/third_party/glamx/LICENSE-MIT
new file mode 100644
index 0000000..31aa793
--- /dev/null
+++ b/renderer/third_party/glamx/LICENSE-MIT
@@ -0,0 +1,23 @@
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/renderer/third_party/glamx/PATCH.md b/renderer/third_party/glamx/PATCH.md
new file mode 100644
index 0000000..00cd553
--- /dev/null
+++ b/renderer/third_party/glamx/PATCH.md
@@ -0,0 +1,55 @@
+# glamx 0.3.1, patched for ThreeRT
+
+This is glamx 0.3.1 from crates.io (MIT OR Apache-2.0, the licenses beside this file) with one change, in
+`src/eigen3.rs` (`SymmetricEigen3::eigenvalues`), and a lint allowed. `renderer/Cargo.toml` and `renderer/physics-core/Cargo.toml` use it
+through `[patch.crates-io]`.
+
+## Why
+
+Rapier's physics must end in the same bits natively and in wasm32 (ROADMAP § 6 step 7: players run the game in the
+browser, and step 9 replays commands). The principal axes of a body's inertia come from this eigen decomposition
+whenever the inertia tensor is not diagonal (a convex hull, a body of several colliders), and it calls `r.acos()` and
+`phi.cos()` with method syntax. On an `f32` that is the type's own method (the platform's libm) in every crate graph
+that has `std` in it: glamx depends on num-traits, and any crate that turns on `num-traits/std` makes those methods
+visible here, whatever glamx's own features are. Rapier's `enhanced-determinism` and building without `std` do not
+reach it. Natively (macOS) and in wasm32 the eigenvalues then differ in the last bit: 48 of 1,000 random worlds ended
+in other bits (`physics_core::check::cases`).
+
+## What
+
+- `acos` and the two `cos` are called through `simba::scalar::ComplexField` by name: libm's under simba's
+ `libm_force` (which `enhanced-determinism` turns on), on every platform and in every crate graph.
+- The five `powi(2)` are written as products (`powi` resolves to a multiplication with `std` and to `powf(x, 2.0)`
+ without).
+
+- `src/lib.rs` allows unused imports (as a path dependency the crate's warnings show).
+
+## Every crate that is built must name the patch
+
+`[patch.crates-io]` only takes effect in the manifest of the crate (or workspace root) that cargo is building: a
+dependency's own `[patch]` is ignored. Today that is `renderer/Cargo.toml` and `renderer/physics-core/Cargo.toml`.
+**Any new crate that depends on physics-core (the web build's wasm crate, a tool, a bench) must repeat it in its own
+manifest**:
+
+```toml
+[patch.crates-io]
+glamx = { path = "<path to>/renderer/third_party/glamx" }
+```
+
+Left out, nothing fails to build: the crate silently gets crates.io's glamx and, with `std` anywhere in its graph,
+the platform's math functions again. What shows it is a test in that crate that steps physics-core's recorded script
+and cases and compares the hashes, as the renderer's does (`renderer/src/physics.rs`,
+`the_renderers_physics_steps_to_the_recorded_bits`):
+
+```rust
+use physics_core::check;
+assert_eq!(check::script(600), check::EXPECTED);
+assert_eq!(check::cases(), check::EXPECTED_CASES);
+```
+
+Every such crate needs that test (for a wasm crate: run in wasm32, as `tools/physics-determinism.ts` runs
+physics-core's). Without the patch the renderer's fails: `f66d349c1eae947a` against the recorded case hash.
+
+Nothing else differs from the published crate (`.github`, `.gitignore` and cargo's packaging files are left out).
+To update: copy the new version here, apply the same change, run `node tools/physics-determinism.ts` and
+`cargo test --release` in `renderer/physics-core` and `renderer`.
diff --git a/renderer/third_party/glamx/README.md b/renderer/third_party/glamx/README.md
new file mode 100644
index 0000000..a02d79a
--- /dev/null
+++ b/renderer/third_party/glamx/README.md
@@ -0,0 +1,56 @@
+# glamx - Glam eXtensions
+
+Extensions for [glam](https://github.com/bitshifter/glam-rs): Pose2, Pose3, Rot2, SVD, eigendecomposition, and matrix utilities.
+
+[![Crates.io](https://img.shields.io/crates/v/glamx.svg)](https://crates.io/crates/glamx)
+[![Documentation](https://docs.rs/glamx/badge.svg)](https://docs.rs/glamx)
+[![License](https://img.shields.io/crates/l/glamx.svg)](https://github.com/dimforge/glamx#license)
+
+## Overview
+
+`glamx` provides additional types commonly needed in game development, robotics, and computer graphics that aren't included in glam:
+
+- **`Rot2` / `DRot2`**: 2D rotations represented as unit complex numbers
+- **`Rot3` / `DRot3`**: 3D rotations (re-exports of glam's quaternions)
+- **`Pose2` / `DPose2`**: 2D rigid body transformations (rotation + translation)
+- **`Pose3` / `DPose3`**: 3D rigid body transformations (rotation + translation)
+- **`MatExt`**: Extension trait for glam matrix types
+- **`SymmetricEigen2` / `SymmetricEigen3`**: Eigendecomposition for symmetric matrices
+- **`Svd2` / `Svd3`**: Singular Value Decomposition for 2x2 and 3x3 matrices
+
+This crate re-exports all of glam's types, so you can use it as a drop-in replacement.
+
+## Feature Flags
+
+| Feature | Description |
+|-----------------|----------------------------------------|
+| `std` (default) | Enables standard library support |
+| `f64` (default via `all-types`) | Enables `f64` glam types and the corresponding glamx `D*` types (`DRot2`, `DPose2`, `DSymmetricEigen2`, ...) |
+| `serde` | Enables serialization via serde |
+| `bytemuck` | Enables bytemuck derives for `Rot2`/`DRot2` |
+| `nalgebra` | Enables conversions to/from nalgebra types |
+| `libm` | Uses libm for `no_std` math operations |
+| `approx` | Enables approximate comparison traits |
+| `rand` | Enables random generation support |
+| `mint` | Enables mint type conversions |
+| `encase` | Enables encase encoding |
+
+All of glam's other type-gating features (`all-types`, `float-types`, `integer-types`, `size-types`, `i8`/`u8`/`i16`/`u16`/`i32`/`u32`/`i64`/`u64`/`isize`/`usize`) are also exposed as passthroughs to glam.
+
+## `no_std` Support
+
+`glamx` is `no_std` compatible. Disable default features and enable `libm` for math operations:
+
+```toml
+[dependencies]
+glamx = { version = "0.1", default-features = false, features = ["libm"] }
+```
+
+## License
+
+Licensed under either of
+
+- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
+- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
+
+at your option.
diff --git a/renderer/third_party/glamx/src/eigen2.rs b/renderer/third_party/glamx/src/eigen2.rs
new file mode 100644
index 0000000..33db170
--- /dev/null
+++ b/renderer/third_party/glamx/src/eigen2.rs
@@ -0,0 +1,141 @@
+//! Eigendecomposition for symmetric 2x2 matrices.
+//!
+//! Adapted from <https://github.com/Jondolf/barry/tree/main/src/math/eigen>
+
+use glam::Vec2Swizzles;
+
+#[cfg(not(feature = "std"))]
+use simba::scalar::ComplexField;
+
+/// Macro to generate SymmetricEigen2 for a specific scalar type.
+macro_rules! impl_symmetric_eigen2 {
+ ($SymmetricEigen2:ident, $Mat2:ty, $Vec2:ty, $Real:ty $(, #[$attr:meta])*) => {
+ #[doc = concat!("The eigen decomposition of a symmetric 2x2 matrix (", stringify!($Real), " precision).")]
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+ $(#[$attr])*
+ pub struct $SymmetricEigen2 {
+ /// The eigenvalues of the symmetric 2x2 matrix.
+ pub eigenvalues: $Vec2,
+ /// The two eigenvectors of the symmetric 2x2 matrix (as columns).
+ pub eigenvectors: $Mat2,
+ }
+
+ impl $SymmetricEigen2 {
+ /// Computes the eigen decomposition of the given symmetric 2x2 matrix.
+ ///
+ /// The eigenvalues are returned in descending order `eigen1 > eigen2`.
+ /// This can be reversed with the [`reverse`](Self::reverse) method.
+ pub fn new(mat: $Mat2) -> Self {
+ let eigenvalues = Self::eigenvalues(mat);
+ let eigenvector1 = Self::eigenvector(mat, eigenvalues.x);
+ let eigenvector2 = Self::eigenvector(mat, eigenvalues.y);
+
+ Self {
+ eigenvalues,
+ eigenvectors: <$Mat2>::from_cols(eigenvector1, eigenvector2),
+ }
+ }
+
+ /// Reverses the order of the eigenvalues and their corresponding eigenvectors.
+ pub fn reverse(&self) -> Self {
+ Self {
+ eigenvalues: self.eigenvalues.yx(),
+ eigenvectors: <$Mat2>::from_cols(self.eigenvectors.y_axis, self.eigenvectors.x_axis),
+ }
+ }
+
+ /// Computes the eigenvalues of a symmetric 2x2 matrix.
+ ///
+ /// Reference: <https://croninprojects.org/Vince/Geodesy/FindingEigenvectors.pdf>
+ pub fn eigenvalues(mat: $Mat2) -> $Vec2 {
+ let [a, b, c] = [
+ 1.0,
+ -(mat.x_axis.x + mat.y_axis.y),
+ mat.x_axis.x * mat.y_axis.y - mat.x_axis.y * mat.y_axis.x,
+ ];
+ // The eigenvalues are the roots of the quadratic equation:
+ // ax^2 + bx + c = 0
+ // x = (-b +/- sqrt(b^2 - 4ac)) / 2a
+ let sqrt_part = (b.powi(2) - 4.0 * a * c).sqrt();
+ let eigen1 = (-b + sqrt_part) / (2.0 * a);
+ let eigen2 = (-b - sqrt_part) / (2.0 * a);
+ <$Vec2>::new(eigen1, eigen2)
+ }
+
+ /// Computes the unit-length eigenvector corresponding to the given `eigenvalue`
+ /// of the symmetric 2x2 `mat`.
+ ///
+ /// Reference: <https://croninprojects.org/Vince/Geodesy/FindingEigenvectors.pdf>
+ pub fn eigenvector(mat: $Mat2, eigenvalue: $Real) -> $Vec2 {
+ <$Vec2>::new(1.0, (eigenvalue - mat.x_axis.x) / mat.y_axis.x).normalize()
+ }
+ }
+ };
+}
+
+impl_symmetric_eigen2!(SymmetricEigen2, glam::Mat2, glam::Vec2, f32);
+#[cfg(feature = "f64")]
+impl_symmetric_eigen2!(DSymmetricEigen2, glam::DMat2, glam::DVec2, f64);
+
+// f32 <-> f64 conversions
+#[cfg(feature = "f64")]
+impl From<SymmetricEigen2> for DSymmetricEigen2 {
+ #[inline]
+ fn from(e: SymmetricEigen2) -> Self {
+ Self {
+ eigenvalues: e.eigenvalues.as_dvec2(),
+ eigenvectors: e.eigenvectors.as_dmat2(),
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<DSymmetricEigen2> for SymmetricEigen2 {
+ #[inline]
+ fn from(e: DSymmetricEigen2) -> Self {
+ Self {
+ eigenvalues: e.eigenvalues.as_vec2(),
+ eigenvectors: e.eigenvectors.as_mat2(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use approx::assert_relative_eq;
+
+ #[test]
+ fn eigen_2x2() {
+ let mat = glam::Mat2::from_cols_array_2d(&[[6.0, 3.0], [3.0, 4.0]]);
+ let eigen = SymmetricEigen2::new(mat);
+
+ assert_relative_eq!(
+ eigen.eigenvalues,
+ glam::Vec2::new(8.16228, 1.83772),
+ epsilon = 0.001
+ );
+ assert_relative_eq!(
+ glam::Mat2::from_cols(eigen.eigenvectors.x_axis, eigen.eigenvectors.y_axis,),
+ glam::Mat2::from_cols(
+ glam::Vec2::new(0.811242, 0.58471),
+ glam::Vec2::new(0.58471, -0.811242),
+ ),
+ epsilon = 0.001
+ );
+ }
+
+ #[cfg(feature = "f64")]
+ #[test]
+ fn eigen_2x2_f64() {
+ let mat = glam::DMat2::from_cols_array_2d(&[[6.0, 3.0], [3.0, 4.0]]);
+ let eigen = DSymmetricEigen2::new(mat);
+
+ assert_relative_eq!(
+ eigen.eigenvalues,
+ glam::DVec2::new(8.16227766016838, 1.8377223398316202),
+ epsilon = 1e-10
+ );
+ }
+}
diff --git a/renderer/third_party/glamx/src/eigen3.rs b/renderer/third_party/glamx/src/eigen3.rs
new file mode 100644
index 0000000..ad2b4a5
--- /dev/null
+++ b/renderer/third_party/glamx/src/eigen3.rs
@@ -0,0 +1,414 @@
+//! Eigendecomposition for symmetric 3x3 matrices.
+//!
+//! The eigensolver is a Rust adaptation, with modifications, of the pseudocode and approach described in
+//! "A Robust Eigensolver for 3 x 3 Symmetric Matrices" by David Eberly, Geometric Tools, Redmond WA 98052.
+//! <https://www.geometrictools.com/Documentation/RobustEigenSymmetric3x3.pdf>
+//!
+//! Adapted from <https://github.com/Jondolf/barry/tree/main/src/math/eigen>
+
+#![allow(clippy::manual_swap)] // Needed for spirv compatibility.
+
+use glam::Vec3Swizzles;
+use num_traits::float::FloatConst;
+
+#[cfg(not(feature = "std"))]
+use simba::scalar::ComplexField;
+
+/// Macro to generate SymmetricEigen3 for a specific scalar type.
+macro_rules! impl_symmetric_eigen3 {
+ ($SymmetricEigen3:ident, $Mat3:ty, $Vec3:ty, $Real:ty $(, #[$attr:meta])*) => {
+ #[doc = concat!("The eigen decomposition of a symmetric 3x3 matrix (", stringify!($Real), " precision).")]
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+ $(#[$attr])*
+ pub struct $SymmetricEigen3 {
+ /// The eigenvalues of the symmetric 3x3 matrix.
+ pub eigenvalues: $Vec3,
+ /// The three eigenvectors of the symmetric 3x3 matrix (as columns).
+ pub eigenvectors: $Mat3,
+ }
+
+ impl $SymmetricEigen3 {
+ /// Computes the eigen decomposition of the given symmetric 3x3 matrix.
+ ///
+ /// The eigenvalues are returned in ascending order `eigen1 < eigen2 < eigen3`.
+ /// This can be reversed with the [`reverse`](Self::reverse) method.
+ pub fn new(mat: $Mat3) -> Self {
+ let eigenvalues = Self::eigenvalues(mat);
+ let eigenvector1 = Self::eigenvector1(mat, eigenvalues.x);
+ let eigenvector2 = Self::eigenvector2(mat, eigenvector1, eigenvalues.y);
+ let eigenvector3 = Self::eigenvector3(eigenvector1, eigenvector2);
+
+ Self {
+ eigenvalues,
+ eigenvectors: <$Mat3>::from_cols(eigenvector1, eigenvector2, eigenvector3),
+ }
+ }
+
+ /// Reverses the order of the eigenvalues and their corresponding eigenvectors.
+ pub fn reverse(&self) -> Self {
+ Self {
+ eigenvalues: self.eigenvalues.zyx(),
+ eigenvectors: <$Mat3>::from_cols(
+ self.eigenvectors.z_axis,
+ self.eigenvectors.y_axis,
+ self.eigenvectors.x_axis,
+ ),
+ }
+ }
+
+ /// Computes the eigenvalues of a symmetric 3x3 matrix.
+ ///
+ /// Reference: <https://en.wikipedia.org/wiki/Eigenvalue_algorithm#3%C3%973_matrices>
+ pub fn eigenvalues(mat: $Mat3) -> $Vec3 {
+ // (ThreeRT patch, PATCH.md: squares written out, the same bits whatever `powi` resolves to.)
+ let sq = |x: $Real| x * x;
+ let p1 = sq(mat.y_axis.x) + sq(mat.z_axis.x) + sq(mat.z_axis.y);
+ if p1 == 0.0 {
+ // The matrix is diagonal.
+ let mut eigenvalues = [mat.x_axis.x, mat.y_axis.y, mat.z_axis.z];
+ // Simple 3-element sorting network (no alloc needed).
+ // NOTE: manual swaps instead of .swap() to avoid ptr::swap which
+ // generates memcpy unsupported in SPIR-V.
+ if eigenvalues[0] > eigenvalues[1] { let t = eigenvalues[0]; eigenvalues[0] = eigenvalues[1]; eigenvalues[1] = t; }
+ if eigenvalues[1] > eigenvalues[2] { let t = eigenvalues[1]; eigenvalues[1] = eigenvalues[2]; eigenvalues[2] = t; }
+ if eigenvalues[0] > eigenvalues[1] { let t = eigenvalues[0]; eigenvalues[0] = eigenvalues[1]; eigenvalues[1] = t; }
+ <$Vec3>::from_array(eigenvalues)
+ } else {
+ let q = (mat.x_axis.x + mat.y_axis.y + mat.z_axis.z) / 3.0;
+ let p2 = sq(mat.x_axis.x - q)
+ + sq(mat.y_axis.y - q)
+ + sq(mat.z_axis.z - q)
+ + 2.0 * p1;
+
+ let p = (p2 / 6.0).sqrt();
+
+ // NOTE: `p` shouldn’t be zero, but in some platforms (nvidia gpus apparently),
+ // denormals can be flushed resulting in a zero.
+ let r = if p != 0.0 {
+ let mat_b = 1.0 / p * (mat - q * <$Mat3>::IDENTITY);
+ mat_b.determinant() / 2.0
+ } else {
+ 1.0 // Will result in phy == 0.0
+ };
+
+ // r should be in the [-1, 1] range for a symmetric matrix,
+ // but computation error can leave it slightly outside this range.
+ let pi: $Real = <$Real as FloatConst>::PI();
+ let phi = if r <= -1.0 {
+ pi / 3.0
+ } else if r >= 1.0 {
+ 0.0
+ } else {
+ // (ThreeRT patch, PATCH.md: through simba by name. `r.acos()` is f32's own method, the
+ // platform's libm, in every crate graph that has `std` in it, whatever this crate's
+ // features are; simba's is libm's under `libm_force`, the same bits on every platform.)
+ <$Real as simba::scalar::ComplexField>::acos(r) / 3.0
+ };
+
+ // The eigenvalues satisfy eigen3 <= eigen2 <= eigen1
+ let eigen1 = q + 2.0 * p * <$Real as simba::scalar::ComplexField>::cos(phi);
+ let eigen3 = q + 2.0 * p * <$Real as simba::scalar::ComplexField>::cos(phi + 2.0 * pi / 3.0);
+ let eigen2 = 3.0 * q - eigen1 - eigen3; // trace(mat) = eigen1 + eigen2 + eigen3
+ <$Vec3>::new(eigen3, eigen2, eigen1)
+ }
+ }
+
+ /// Computes the unit-length eigenvector corresponding to the `eigenvalue1` of `mat` that was
+ /// computed from the root of a cubic polynomial with a multiplicity of 1.
+ ///
+ /// If the other two eigenvalues are well separated, this method can be used for computing
+ /// all three eigenvectors. However, to avoid numerical issues when eigenvalues are close to
+ /// each other, it's recommended to use the `eigenvector2` method for the second eigenvector.
+ ///
+ /// The third eigenvector can be computed as the cross product of the first two.
+ pub fn eigenvector1(mat: $Mat3, eigenvalue1: $Real) -> $Vec3 {
+ let cols = mat - <$Mat3>::from_diagonal(<$Vec3>::splat(eigenvalue1).into());
+ let c0xc1 = cols.x_axis.cross(cols.y_axis);
+ let c0xc2 = cols.x_axis.cross(cols.z_axis);
+ let c1xc2 = cols.y_axis.cross(cols.z_axis);
+ let d0 = c0xc1.length_squared();
+ let d1 = c0xc2.length_squared();
+ let d2 = c1xc2.length_squared();
+
+ let mut d_max = d0;
+ let mut i_max = 0;
+
+ if d1 > d_max {
+ d_max = d1;
+ i_max = 1;
+ }
+ if d2 > d_max {
+ d_max = d2;
+ i_max = 2;
+ }
+
+ // When all eigenvalues are equal (multiplicity 3), mat - eigenvalue * I is the
+ // zero matrix, so all cross products are zero. Any unit vector is a valid
+ // eigenvector in this case.
+ if d_max < 1e-20 {
+ return <$Vec3>::X;
+ }
+
+ if i_max == 0 {
+ c0xc1 / d0.sqrt()
+ } else if i_max == 1 {
+ c0xc2 / d1.sqrt()
+ } else {
+ c1xc2 / d2.sqrt()
+ }
+ }
+
+ /// Computes the unit-length eigenvector corresponding to the `eigenvalue2` of `mat` that was
+ /// computed from the root of a cubic polynomial with a potential multiplicity of 2.
+ ///
+ /// The third eigenvector can be computed as the cross product of the first two.
+ pub fn eigenvector2(mat: $Mat3, eigenvector1: $Vec3, eigenvalue2: $Real) -> $Vec3 {
+ // Compute right-handed orthonormal set { U, V, W }, where W is eigenvector1.
+ let (u, v) = Self::any_orthonormal_pair(eigenvector1);
+
+ // The unit-length eigenvector is E = x0 * U + x1 * V. We need to compute x0 and x1.
+ //
+ // Define the symmetric 2x2 matrix M = J^T * (mat - eigenvalue2 * I), where J = [U V]
+ // and I is a 3x3 identity matrix. This means that E = J * X, where X is a column vector
+ // with rows x0 and x1. The 3x3 linear system (mat - eigenvalue2 * I) * E = 0 reduces to
+ // the 2x2 linear system M * X = 0.
+ //
+ // When eigenvalue2 != eigenvalue3, M has rank 1 and is not the zero matrix.
+ // Otherwise, it has rank 0, and it is the zero matrix.
+
+ let au = mat * u;
+ let av = mat * v;
+
+ let mut m00 = u.dot(au) - eigenvalue2;
+ let mut m01 = u.dot(av);
+ let mut m11 = v.dot(av) - eigenvalue2;
+ let (abs_m00, abs_m01, abs_m11) = (m00.abs(), m01.abs(), m11.abs());
+
+ if abs_m00 >= abs_m11 {
+ let max_abs_component = abs_m00.max(abs_m01);
+ if max_abs_component > 0.0 {
+ if abs_m00 >= abs_m01 {
+ // m00 is the largest component of the row.
+ // Factor it out for normalization and discard to avoid underflow or overflow.
+ m01 /= m00;
+ m00 = 1.0 / (1.0 + m01 * m01).sqrt();
+ m01 *= m00;
+ } else {
+ // m01 is the largest component of the row.
+ // Factor it out for normalization and discard to avoid underflow or overflow.
+ m00 /= m01;
+ m01 = 1.0 / (1.0 + m00 * m00).sqrt();
+ m00 *= m01;
+ }
+ return m01 * u - m00 * v;
+ }
+ } else {
+ let max_abs_component = abs_m11.max(abs_m01);
+ if max_abs_component > 0.0 {
+ if abs_m11 >= abs_m01 {
+ // m11 is the largest component of the row.
+ // Factor it out for normalization and discard to avoid underflow or overflow.
+ m01 /= m11;
+ m11 = 1.0 / (1.0 + m01 * m01).sqrt();
+ m01 *= m11;
+ } else {
+ // m01 is the largest component of the row.
+ // Factor it out for normalization and discard to avoid underflow or overflow.
+ m11 /= m01;
+ m01 = 1.0 / (1.0 + m11 * m11).sqrt();
+ m11 *= m01;
+ }
+ return m11 * u - m01 * v;
+ }
+ }
+
+ // M is the zero matrix, any unit-length solution suffices.
+ u
+ }
+
+ /// Computes the third eigenvector as the cross product of the first two.
+ /// If the given eigenvectors are valid, the returned vector should be unit length.
+ pub fn eigenvector3(eigenvector1: $Vec3, eigenvector2: $Vec3) -> $Vec3 {
+ eigenvector1.cross(eigenvector2)
+ }
+
+ /// Compute any orthonormal pair of vectors perpendicular to `v`.
+ fn any_orthonormal_pair(v: $Vec3) -> ($Vec3, $Vec3) {
+ let sign = if v.z >= 0.0 { 1.0 } else { -1.0 };
+ let a = -1.0 / (sign + v.z);
+ let b = v.x * v.y * a;
+ let u = <$Vec3>::new(1.0 + sign * v.x * v.x * a, sign * b, -sign * v.x);
+ let w = <$Vec3>::new(b, sign + v.y * v.y * a, -v.y);
+ (u, w)
+ }
+ }
+ };
+}
+
+impl_symmetric_eigen3!(SymmetricEigen3, glam::Mat3, glam::Vec3, f32);
+impl_symmetric_eigen3!(SymmetricEigen3A, glam::Mat3A, glam::Vec3A, f32);
+#[cfg(feature = "f64")]
+impl_symmetric_eigen3!(DSymmetricEigen3, glam::DMat3, glam::DVec3, f64);
+
+// f32 <-> f64 conversions
+#[cfg(feature = "f64")]
+impl From<SymmetricEigen3> for DSymmetricEigen3 {
+ #[inline]
+ fn from(e: SymmetricEigen3) -> Self {
+ Self {
+ eigenvalues: e.eigenvalues.as_dvec3(),
+ eigenvectors: e.eigenvectors.as_dmat3(),
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<DSymmetricEigen3> for SymmetricEigen3 {
+ #[inline]
+ fn from(e: DSymmetricEigen3) -> Self {
+ Self {
+ eigenvalues: e.eigenvalues.as_vec3(),
+ eigenvectors: e.eigenvectors.as_mat3(),
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<SymmetricEigen3A> for DSymmetricEigen3 {
+ #[inline]
+ fn from(e: SymmetricEigen3A) -> Self {
+ Self {
+ eigenvalues: e.eigenvalues.as_dvec3(),
+ eigenvectors: e.eigenvectors.as_dmat3(),
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<DSymmetricEigen3> for SymmetricEigen3A {
+ #[inline]
+ fn from(e: DSymmetricEigen3) -> Self {
+ Self {
+ eigenvalues: e.eigenvalues.as_vec3a(),
+ eigenvectors: e.eigenvectors.as_mat3().into(),
+ }
+ }
+}
+
+// SymmetricEigen3 <-> SymmetricEigen3A conversions
+impl From<SymmetricEigen3> for SymmetricEigen3A {
+ #[inline]
+ fn from(e: SymmetricEigen3) -> Self {
+ Self {
+ eigenvalues: e.eigenvalues.into(),
+ eigenvectors: glam::Mat3A::from(e.eigenvectors),
+ }
+ }
+}
+
+impl From<SymmetricEigen3A> for SymmetricEigen3 {
+ #[inline]
+ fn from(e: SymmetricEigen3A) -> Self {
+ Self {
+ eigenvalues: e.eigenvalues.into(),
+ eigenvectors: glam::Mat3::from(e.eigenvectors),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use approx::assert_relative_eq;
+
+ #[test]
+ fn eigen_3x3() {
+ let mat =
+ glam::Mat3::from_cols_array_2d(&[[2.0, 7.0, 8.0], [7.0, 6.0, 3.0], [8.0, 3.0, 0.0]]);
+ let eigen = SymmetricEigen3::new(mat);
+
+ assert_relative_eq!(
+ eigen.eigenvalues,
+ glam::Vec3::new(-7.6051016780, 0.5774961930, 15.0276054850),
+ epsilon = 1.0e-6
+ );
+ assert_relative_eq!(
+ glam::Mat3::from_cols(
+ eigen.eigenvectors.x_axis,
+ eigen.eigenvectors.y_axis,
+ eigen.eigenvectors.z_axis
+ ),
+ glam::Mat3::from_cols(
+ glam::Vec3::new(1.0754474819, -0.3328260589, -1.0).normalize(),
+ glam::Vec3::new(-0.5420669703, 1.2530131898, -1.0).normalize(),
+ glam::Vec3::new(1.3587443369, 1.3858835966, 1.0).normalize()
+ ),
+ epsilon = 1.0e-6
+ );
+ }
+
+ #[test]
+ fn eigen_3x3_diagonal() {
+ let mat =
+ glam::Mat3::from_cols_array_2d(&[[2.0, 0.0, 0.0], [0.0, 5.0, 0.0], [0.0, 0.0, 3.0]]);
+ let eigen = SymmetricEigen3::new(mat);
+
+ assert_eq!(eigen.eigenvalues, glam::Vec3::new(2.0, 3.0, 5.0));
+ assert_eq!(
+ glam::Mat3::from_cols(
+ eigen.eigenvectors.x_axis.normalize().abs(),
+ eigen.eigenvectors.y_axis.normalize().abs(),
+ eigen.eigenvectors.z_axis.normalize().abs()
+ ),
+ glam::Mat3::from_cols_array_2d(&[[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]])
+ );
+ }
+
+ #[cfg(feature = "f64")]
+ #[test]
+ fn eigen_3x3_f64() {
+ let mat =
+ glam::DMat3::from_cols_array_2d(&[[2.0, 7.0, 8.0], [7.0, 6.0, 3.0], [8.0, 3.0, 0.0]]);
+ let eigen = DSymmetricEigen3::new(mat);
+
+ assert_relative_eq!(
+ eigen.eigenvalues,
+ glam::DVec3::new(-7.6051016780, 0.5774961930, 15.0276054850),
+ epsilon = 1.0e-8
+ );
+ }
+
+ #[test]
+ fn eigen_3x3_identity() {
+ // Identity matrix has all eigenvalues equal to 1 (multiplicity 3)
+ // Any orthonormal basis is a valid set of eigenvectors
+ let mat = glam::Mat3::IDENTITY;
+ let eigen = SymmetricEigen3::new(mat);
+
+ assert_eq!(eigen.eigenvalues, glam::Vec3::ONE);
+
+ // Verify eigenvectors are orthonormal (any orthonormal basis is valid)
+ assert_relative_eq!(
+ eigen.eigenvectors * eigen.eigenvectors.transpose(),
+ glam::Mat3::IDENTITY,
+ epsilon = 1e-6
+ );
+ }
+
+ #[test]
+ fn eigen_3x3_uniform_scaling() {
+ // Uniform scaling matrix: 5*I has all eigenvalues equal to 5
+ let mat = glam::Mat3::from_diagonal(glam::Vec3::splat(5.0));
+ let eigen = SymmetricEigen3::new(mat);
+
+ assert_eq!(eigen.eigenvalues, glam::Vec3::splat(5.0));
+
+ // Verify eigenvectors are orthonormal
+ assert_relative_eq!(
+ eigen.eigenvectors * eigen.eigenvectors.transpose(),
+ glam::Mat3::IDENTITY,
+ epsilon = 1e-6
+ );
+ }
+}
diff --git a/renderer/third_party/glamx/src/lib.rs b/renderer/third_party/glamx/src/lib.rs
new file mode 100644
index 0000000..7758bdf
--- /dev/null
+++ b/renderer/third_party/glamx/src/lib.rs
@@ -0,0 +1,128 @@
+//! # glamx - Extensions for glam
+//!
+//! This crate provides additional types and utilities for the `glam` math library:
+//!
+//! - [`Rot2`] / [`DRot2`]: 2D rotations represented as unit complex numbers
+//! - [`Rot3`] / [`DRot3`]: 3D rotations (re-exports of glam's quaternions)
+//! - [`Pose2`] / [`DPose2`]: 2D rigid body transformations (rotation + translation)
+//! - [`Pose3`] / [`DPose3`]: 3D rigid body transformations (rotation + translation)
+//! - [`MatExt`]: Extension traits for glam matrix types
+//! - [`SymmetricEigen2`] / [`SymmetricEigen3`]: Eigendecomposition for symmetric matrices
+//! - [`Svd2`] / [`Svd3`]: Singular Value Decomposition for 2x2 and 3x3 matrices
+//!
+//! ## Naming Convention
+//!
+//! Types without a prefix use `f32` precision, while types with a `D` prefix use `f64` precision:
+//! - `Rot2` (f32) / `DRot2` (f64)
+//! - `Pose2` (f32) / `DPose2` (f64)
+//! - `SymmetricEigen2` (f32) / `DSymmetricEigen2` (f64)
+//!
+//! ## Feature Flags
+//!
+//! - `std` (default): Enables standard library support
+//! - `serde`: Enables serialization support via serde
+//! - `bytemuck`: Enables bytemuck derive for Rot2/DRot2
+//! - `nalgebra`: Enables conversions to/from nalgebra types
+//! - `libm`: Uses libm for no_std math operations
+//!
+//! ### Type-gating features (mirror glam 0.33)
+//!
+//! These transitively enable the matching feature on `glam`. They control which
+//! type aliases the underlying `glam` re-export exposes; glamx adds extension
+//! types only for the floating-point variants, so disabling `f64` also removes
+//! all `D*` types (DRot2, DPose2, DSymmetricEigen2, ...).
+//!
+//! - `all-types` (default): enables `float-types`, `integer-types`, `size-types`.
+//! - `float-types`: enables `f64`.
+//! - `integer-types`: enables `i8`, `u8`, `i16`, `u16`, `i32`, `u32`, `i64`, `u64`.
+//! - `size-types`: enables `isize`, `usize`.
+//! - Individual features: `f64`, `i8`, `u8`, `i16`, `u16`, `i32`, `u32`, `i64`,
+//! `u64`, `isize`, `usize`.
+//!
+//! ## glam Re-exports
+//!
+//! This crate re-exports all of glam's types so you can use it as a drop-in replacement without
+//! an explicit dependency to `glam`.
+//! Alternatively, depending on your coding style preferences, you can use the `glam` re-export.
+
+#![no_std]
+// (ThreeRT patch, PATCH.md: built as a path dependency its warnings show. These imports are unused in a crate graph
+// with `std` in it, where the method calls they are for resolve to f32's own methods.)
+#![allow(unused_imports)]
+
+#[cfg(feature = "std")]
+extern crate std;
+
+// Re-export approx for convenience
+#[cfg(feature = "approx")]
+pub use approx;
+/// Re-export of the glam crate.
+pub use glam;
+
+mod eigen2;
+mod eigen3;
+mod matrix_ext;
+mod pose2;
+mod pose3;
+mod rot2;
+mod rot3;
+mod svd2;
+mod svd3;
+
+#[cfg(feature = "f64")]
+pub use eigen2::DSymmetricEigen2;
+pub use eigen2::SymmetricEigen2;
+#[cfg(feature = "f64")]
+pub use eigen3::DSymmetricEigen3;
+pub use eigen3::{SymmetricEigen3, SymmetricEigen3A};
+pub use glam::*;
+pub use matrix_ext::MatExt;
+#[cfg(feature = "f64")]
+pub use pose2::DPose2;
+pub use pose2::Pose2;
+#[cfg(feature = "f64")]
+pub use pose3::DPose3;
+pub use pose3::{Pose3, Pose3A};
+#[cfg(feature = "f64")]
+pub use rot2::DRot2;
+pub use rot2::Rot2;
+#[cfg(feature = "f64")]
+pub use rot3::DRot3;
+pub use rot3::Rot3;
+#[cfg(feature = "f64")]
+pub use svd2::DSvd2;
+pub use svd2::Svd2;
+#[cfg(feature = "f64")]
+pub use svd3::DSvd3;
+pub use svd3::{Svd3, Svd3A};
+
+/// Prelude module for convenient imports.
+///
+/// This module re-exports all public types and traits.
+pub mod prelude {
+ #[cfg(feature = "f64")]
+ pub use crate::eigen2::DSymmetricEigen2;
+ pub use crate::eigen2::SymmetricEigen2;
+ #[cfg(feature = "f64")]
+ pub use crate::eigen3::DSymmetricEigen3;
+ pub use crate::eigen3::{SymmetricEigen3, SymmetricEigen3A};
+ pub use crate::matrix_ext::MatExt;
+ #[cfg(feature = "f64")]
+ pub use crate::pose2::DPose2;
+ pub use crate::pose2::Pose2;
+ #[cfg(feature = "f64")]
+ pub use crate::pose3::DPose3;
+ pub use crate::pose3::Pose3;
+ #[cfg(feature = "f64")]
+ pub use crate::rot2::DRot2;
+ pub use crate::rot2::Rot2;
+ #[cfg(feature = "f64")]
+ pub use crate::rot3::DRot3;
+ pub use crate::rot3::Rot3;
+ #[cfg(feature = "f64")]
+ pub use crate::svd2::DSvd2;
+ pub use crate::svd2::Svd2;
+ #[cfg(feature = "f64")]
+ pub use crate::svd3::DSvd3;
+ pub use crate::svd3::{Svd3, Svd3A};
+}
diff --git a/renderer/third_party/glamx/src/matrix_ext.rs b/renderer/third_party/glamx/src/matrix_ext.rs
new file mode 100644
index 0000000..8a87299
--- /dev/null
+++ b/renderer/third_party/glamx/src/matrix_ext.rs
@@ -0,0 +1,255 @@
+//! Matrix extension traits for glam types.
+
+#[cfg(feature = "f64")]
+use crate::eigen2::DSymmetricEigen2;
+use crate::eigen2::SymmetricEigen2;
+#[cfg(feature = "f64")]
+use crate::eigen3::DSymmetricEigen3;
+use crate::eigen3::{SymmetricEigen3, SymmetricEigen3A};
+#[cfg(feature = "f64")]
+use crate::svd2::DSvd2;
+use crate::svd2::Svd2;
+#[cfg(feature = "f64")]
+use crate::svd3::DSvd3;
+use crate::svd3::{Svd3, Svd3A};
+
+/// Extension trait for square matrix types.
+///
+/// Provides additional functionality not available in glam:
+/// - `abs()` - element-wise absolute value
+/// - `try_inverse()` - inverse with singularity check
+/// - `swap_cols()` / `swap_rows()` - column/row swapping
+/// - `symmetric_eigen()` - eigendecomposition for symmetric matrices
+pub trait MatExt: Sized + Copy {
+ /// The scalar type.
+ type Scalar;
+ /// The vector type.
+ type Vector;
+ /// The symmetric eigen decomposition type.
+ type SymmetricEigen;
+ /// The Singular Values Decomposition type.
+ type Svd;
+
+ /// Returns a matrix with all components set to their absolute values.
+ fn abs(&self) -> Self;
+
+ /// Tries to invert the matrix, returning None if not invertible.
+ fn try_inverse(&self) -> Option<Self>;
+
+ /// Swaps two columns of this matrix.
+ fn swap_cols(&mut self, a: usize, b: usize);
+
+ /// Swaps two rows of this matrix.
+ fn swap_rows(&mut self, a: usize, b: usize);
+
+ /// Computes the symmetric eigendecomposition.
+ ///
+ /// If `self` isn’t symmetric, expect incorrect results.
+ fn symmetric_eigen(&self) -> Self::SymmetricEigen;
+
+ /// Computes the eigenvalues of a symmetric matrix.
+ ///
+ /// If `self` isn’t symmetric, expect incorrect results.
+ fn symmetric_eigenvalues(&self) -> Self::Vector;
+
+ /// Computes the SVD of this matrix.
+ fn svd(&self) -> Self::Svd;
+}
+
+/// Macro to implement MatExt for a specific matrix type.
+macro_rules! impl_mat2_ext {
+ ($Mat2:ty, $Vec2:ty, $Real:ty, $SymmetricEigen2:ty, $Svd2:ty) => {
+ impl MatExt for $Mat2 {
+ type Scalar = $Real;
+ type Vector = $Vec2;
+ type SymmetricEigen = $SymmetricEigen2;
+ type Svd = $Svd2;
+
+ #[inline]
+ fn abs(&self) -> Self {
+ Self::from_cols(self.x_axis.abs(), self.y_axis.abs())
+ }
+
+ #[inline]
+ fn try_inverse(&self) -> Option<Self> {
+ let det = self.determinant();
+ if det.abs() < <$Real>::EPSILON {
+ None
+ } else {
+ Some(self.inverse())
+ }
+ }
+
+ #[inline]
+ fn swap_cols(&mut self, a: usize, b: usize) {
+ assert!(a < 2, "column index {a} is out of bounds");
+ assert!(b < 2, "column index {b} is out of bounds");
+
+ let ca = self.col(a);
+ let cb = self.col(b);
+ *self.col_mut(a) = cb;
+ *self.col_mut(b) = ca;
+ }
+
+ #[inline]
+ fn swap_rows(&mut self, a: usize, b: usize) {
+ assert!(a < 2, "row index {a} is out of bounds");
+ assert!(b < 2, "row index {b} is out of bounds");
+ self.x_axis.as_mut().swap(a, b);
+ self.y_axis.as_mut().swap(a, b);
+ }
+
+ #[inline]
+ fn symmetric_eigen(&self) -> Self::SymmetricEigen {
+ <$SymmetricEigen2>::new(*self)
+ }
+
+ #[inline]
+ fn symmetric_eigenvalues(&self) -> Self::Vector {
+ <$SymmetricEigen2>::eigenvalues(*self)
+ }
+
+ #[inline]
+ fn svd(&self) -> Self::Svd {
+ <$Svd2>::from_matrix(*self)
+ }
+ }
+ };
+}
+
+/// Macro to implement MatExt for a specific matrix type.
+macro_rules! impl_mat3_ext {
+ ($Mat3:ty, $Vec3:ty, $Real:ty, $SymmetricEigen3:ty, $Svd3:ty) => {
+ impl MatExt for $Mat3 {
+ type Scalar = $Real;
+ type Vector = $Vec3;
+ type SymmetricEigen = $SymmetricEigen3;
+ type Svd = $Svd3;
+
+ #[inline]
+ fn abs(&self) -> Self {
+ Self::from_cols(self.x_axis.abs(), self.y_axis.abs(), self.z_axis.abs())
+ }
+
+ #[inline]
+ fn try_inverse(&self) -> Option<Self> {
+ let det = self.determinant();
+ if det.abs() < <$Real>::EPSILON {
+ None
+ } else {
+ Some(self.inverse())
+ }
+ }
+
+ fn swap_cols(&mut self, a: usize, b: usize) {
+ assert!(a < 3, "column index {a} is out of bounds");
+ assert!(b < 3, "column index {b} is out of bounds");
+
+ let ca = self.col(a);
+ let cb = self.col(b);
+ *self.col_mut(a) = cb;
+ *self.col_mut(b) = ca;
+ }
+
+ fn swap_rows(&mut self, a: usize, b: usize) {
+ assert!(a < 3, "row index {a} is out of bounds");
+ assert!(b < 3, "row index {b} is out of bounds");
+ self.x_axis.as_mut().swap(a, b);
+ self.y_axis.as_mut().swap(a, b);
+ self.z_axis.as_mut().swap(a, b);
+ }
+
+ fn symmetric_eigen(&self) -> Self::SymmetricEigen {
+ <$SymmetricEigen3>::new(*self)
+ }
+
+ fn symmetric_eigenvalues(&self) -> Self::Vector {
+ <$SymmetricEigen3>::eigenvalues(*self)
+ }
+
+ #[inline]
+ fn svd(&self) -> Self::Svd {
+ <$Svd3>::from_matrix(*self)
+ }
+ }
+ };
+}
+
+impl_mat2_ext!(glam::Mat2, glam::Vec2, f32, SymmetricEigen2, Svd2);
+#[cfg(feature = "f64")]
+impl_mat2_ext!(glam::DMat2, glam::DVec2, f64, DSymmetricEigen2, DSvd2);
+impl_mat3_ext!(glam::Mat3, glam::Vec3, f32, SymmetricEigen3, Svd3);
+impl_mat3_ext!(glam::Mat3A, glam::Vec3A, f32, SymmetricEigen3A, Svd3A);
+#[cfg(feature = "f64")]
+impl_mat3_ext!(glam::DMat3, glam::DVec3, f64, DSymmetricEigen3, DSvd3);
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_mat2_abs() {
+ let m = glam::Mat2::from_cols(glam::Vec2::new(-1.0, 2.0), glam::Vec2::new(3.0, -4.0));
+ let abs_m = m.abs();
+ assert_eq!(abs_m.x_axis, glam::Vec2::new(1.0, 2.0));
+ assert_eq!(abs_m.y_axis, glam::Vec2::new(3.0, 4.0));
+ }
+
+ #[test]
+ fn test_mat2_try_inverse() {
+ let m = glam::Mat2::from_cols(glam::Vec2::new(1.0, 2.0), glam::Vec2::new(3.0, 4.0));
+ let inv = m.try_inverse();
+ assert!(inv.is_some());
+
+ // Singular matrix
+ let singular = glam::Mat2::from_cols(glam::Vec2::new(1.0, 2.0), glam::Vec2::new(2.0, 4.0));
+ let no_inv = singular.try_inverse();
+ assert!(no_inv.is_none());
+ }
+
+ #[test]
+ fn test_mat3_abs() {
+ let m = glam::Mat3::from_cols(
+ glam::Vec3::new(-1.0, 2.0, -3.0),
+ glam::Vec3::new(4.0, -5.0, 6.0),
+ glam::Vec3::new(-7.0, 8.0, -9.0),
+ );
+ let abs_m = m.abs();
+ assert_eq!(abs_m.x_axis, glam::Vec3::new(1.0, 2.0, 3.0));
+ assert_eq!(abs_m.y_axis, glam::Vec3::new(4.0, 5.0, 6.0));
+ assert_eq!(abs_m.z_axis, glam::Vec3::new(7.0, 8.0, 9.0));
+ }
+
+ #[test]
+ fn test_mat3_swap_cols() {
+ let mut m = glam::Mat3::from_cols(
+ glam::Vec3::new(1.0, 2.0, 3.0),
+ glam::Vec3::new(4.0, 5.0, 6.0),
+ glam::Vec3::new(7.0, 8.0, 9.0),
+ );
+ m.swap_cols(0, 2);
+ assert_eq!(m.x_axis, glam::Vec3::new(7.0, 8.0, 9.0));
+ assert_eq!(m.z_axis, glam::Vec3::new(1.0, 2.0, 3.0));
+ }
+
+ #[cfg(feature = "f64")]
+ #[test]
+ fn test_dmat2_abs() {
+ let m = glam::DMat2::from_cols(glam::DVec2::new(-1.0, 2.0), glam::DVec2::new(3.0, -4.0));
+ let abs_m = m.abs();
+ assert_eq!(abs_m.x_axis, glam::DVec2::new(1.0, 2.0));
+ assert_eq!(abs_m.y_axis, glam::DVec2::new(3.0, 4.0));
+ }
+
+ #[test]
+ fn test_mat3_symmetric_eigen() {
+ use approx::assert_relative_eq;
+ let m =
+ glam::Mat3::from_cols_array_2d(&[[2.0, 0.0, 0.0], [0.0, 3.0, 0.0], [0.0, 0.0, 5.0]]);
+ let eigenvalues = m.symmetric_eigenvalues();
+ // Eigenvalues of a diagonal matrix are its diagonal entries, sorted ascending
+ assert_relative_eq!(eigenvalues.x, 2.0, epsilon = 0.001);
+ assert_relative_eq!(eigenvalues.y, 3.0, epsilon = 0.001);
+ assert_relative_eq!(eigenvalues.z, 5.0, epsilon = 0.001);
+ }
+}
diff --git a/renderer/third_party/glamx/src/pose2.rs b/renderer/third_party/glamx/src/pose2.rs
new file mode 100644
index 0000000..63cae35
--- /dev/null
+++ b/renderer/third_party/glamx/src/pose2.rs
@@ -0,0 +1,559 @@
+//! 2D pose types for rigid body transformations.
+
+#[cfg(feature = "f64")]
+use crate::rot2::DRot2;
+use crate::rot2::Rot2;
+use core::ops::{Mul, MulAssign};
+
+/// Macro to generate a 2D pose type for a specific scalar type.
+macro_rules! impl_pose2 {
+ ($Pose2:ident, $Rot2:ident, $Real:ty, $Vec2:ty, $Vec3:ty, $Mat2:ty, $Mat3:ty $(, #[$attr:meta])*) => {
+ #[doc = concat!("A 2D pose (rotation + translation), representing a rigid body transformation (", stringify!($Real), " precision).")]
+ #[derive(Copy, Clone, Debug, PartialEq)]
+ #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+ #[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
+ #[repr(C)]
+ $(#[$attr])*
+ pub struct $Pose2 {
+ /// The rotational part of the pose.
+ pub rotation: $Rot2,
+ /// The translational part of the pose.
+ pub translation: $Vec2,
+ }
+
+ impl $Pose2 {
+ /// The identity pose (no rotation, no translation).
+ pub const IDENTITY: Self = Self {
+ rotation: $Rot2::IDENTITY,
+ translation: <$Vec2>::ZERO,
+ };
+
+ /// Creates the identity pose.
+ #[inline]
+ pub fn identity() -> Self {
+ Self::IDENTITY
+ }
+
+ /// Creates a pose from a translation vector.
+ #[inline]
+ pub fn from_translation(translation: $Vec2) -> Self {
+ Self {
+ rotation: $Rot2::IDENTITY,
+ translation,
+ }
+ }
+
+ /// Creates a pose from translation components.
+ #[inline]
+ pub fn translation(x: $Real, y: $Real) -> Self {
+ Self::from_translation(<$Vec2>::new(x, y))
+ }
+
+ /// Creates a pose from a rotation.
+ #[inline]
+ pub fn from_rotation(rotation: $Rot2) -> Self {
+ Self {
+ rotation,
+ translation: <$Vec2>::ZERO,
+ }
+ }
+
+ /// Creates a pose that is a pure rotation with the given angle (in radians).
+ #[inline]
+ pub fn rotation(angle: $Real) -> Self {
+ Self::from_rotation(<$Rot2>::new(angle))
+ }
+
+ /// Creates a pose from translation and rotation parts.
+ #[inline]
+ pub fn from_parts(translation: $Vec2, rotation: $Rot2) -> Self {
+ Self {
+ rotation,
+ translation,
+ }
+ }
+
+ /// Creates a pose from translation and angle.
+ #[inline]
+ pub fn new(translation: $Vec2, angle: $Real) -> Self {
+ Self {
+ rotation: $Rot2::new(angle),
+ translation,
+ }
+ }
+
+ /// Prepends a translation to this pose (applies translation in local frame).
+ #[inline]
+ pub fn prepend_translation(self, translation: $Vec2) -> Self {
+ Self {
+ rotation: self.rotation,
+ translation: self.translation + self.rotation * translation,
+ }
+ }
+
+ /// Appends a translation to this pose (applies translation in world frame).
+ #[inline]
+ pub fn append_translation(self, translation: $Vec2) -> Self {
+ Self {
+ rotation: self.rotation,
+ translation: self.translation + translation,
+ }
+ }
+
+ /// Returns the inverse of this pose.
+ #[inline]
+ pub fn inverse(&self) -> Self {
+ let inv_rot = self.rotation.inverse();
+ Self {
+ rotation: inv_rot,
+ translation: inv_rot.transform_vector(-self.translation),
+ }
+ }
+
+ /// Computes `self.inverse() * rhs`.
+ #[inline]
+ pub fn inv_mul(&self, rhs: &Self) -> Self {
+ self.inverse() * *rhs
+ }
+
+ /// Transforms a 2D point by this pose.
+ ///
+ /// This applies both the rotation and translation.
+ #[inline]
+ pub fn transform_point(&self, p: $Vec2) -> $Vec2 {
+ self.rotation.transform_vector(p) + self.translation
+ }
+
+ /// Transforms a 2D vector by this pose.
+ ///
+ /// This applies only the rotation (ignores translation).
+ #[inline]
+ pub fn transform_vector(&self, v: $Vec2) -> $Vec2 {
+ self.rotation.transform_vector(v)
+ }
+
+ /// Transforms a point by the inverse of this pose.
+ #[inline]
+ pub fn inverse_transform_point(&self, p: $Vec2) -> $Vec2 {
+ self.rotation.inverse_transform_vector(p - self.translation)
+ }
+
+ /// Transforms a vector by the inverse of this pose.
+ #[inline]
+ pub fn inverse_transform_vector(&self, v: $Vec2) -> $Vec2 {
+ self.rotation.inverse_transform_vector(v)
+ }
+
+ /// Linearly interpolates between two poses.
+ ///
+ /// Uses spherical linear interpolation for the rotation part.
+ #[inline]
+ pub fn lerp(&self, other: &Self, t: $Real) -> Self {
+ Self {
+ rotation: self.rotation.slerp(&other.rotation, t),
+ translation: self.translation.lerp(other.translation, t),
+ }
+ }
+
+ /// Returns `true` if, and only if, all elements are finite.
+ #[inline]
+ pub fn is_finite(&self) -> bool {
+ self.rotation.is_finite() && self.translation.is_finite()
+ }
+
+ /// Returns `true` if any element is `NaN`.
+ #[inline]
+ pub fn is_nan(&self) -> bool {
+ self.rotation.is_nan() || self.translation.is_nan()
+ }
+
+ /// Converts this pose to a homogeneous 3x3 matrix.
+ #[inline]
+ pub fn to_mat3(&self) -> $Mat3 {
+ let (sin, cos) = (self.rotation.sin(), self.rotation.cos());
+ <$Mat3>::from_cols(
+ <$Vec3>::new(cos, sin, 0.0),
+ <$Vec3>::new(-sin, cos, 0.0),
+ <$Vec3>::new(self.translation.x, self.translation.y, 1.0),
+ )
+ }
+
+ /// Creates a pose from a homogeneous 3x3 matrix.
+ ///
+ /// The matrix is assumed to represent a rigid body transformation
+ /// (rotation + translation only, no scaling or shearing).
+ #[inline]
+ pub fn from_mat3(mat: $Mat3) -> Self {
+ let rotation = $Rot2::from_mat(<$Mat2>::from_cols(
+ mat.x_axis.truncate(),
+ mat.y_axis.truncate(),
+ ));
+ let translation = mat.z_axis.truncate();
+ Self { rotation, translation }
+ }
+ }
+
+ // Pose2 * Pose2
+ impl Mul<$Pose2> for $Pose2 {
+ type Output = Self;
+
+ #[inline]
+ fn mul(self, rhs: Self) -> Self::Output {
+ Self {
+ rotation: self.rotation * rhs.rotation,
+ translation: self.translation + self.rotation.transform_vector(rhs.translation),
+ }
+ }
+ }
+
+ impl MulAssign<$Pose2> for $Pose2 {
+ #[inline]
+ fn mul_assign(&mut self, rhs: Self) {
+ *self = *self * rhs;
+ }
+ }
+
+ // Pose2 * Vec2 (transform point - applies rotation and translation)
+ impl Mul<$Vec2> for $Pose2 {
+ type Output = $Vec2;
+
+ #[inline]
+ fn mul(self, rhs: $Vec2) -> Self::Output {
+ self.transform_point(rhs)
+ }
+ }
+
+ impl Mul<$Vec2> for &$Pose2 {
+ type Output = $Vec2;
+
+ #[inline]
+ fn mul(self, rhs: $Vec2) -> Self::Output {
+ self.transform_point(rhs)
+ }
+ }
+
+ impl Mul<&$Vec2> for $Pose2 {
+ type Output = $Vec2;
+
+ #[inline]
+ fn mul(self, rhs: &$Vec2) -> Self::Output {
+ self.transform_point(*rhs)
+ }
+ }
+
+ impl Default for $Pose2 {
+ fn default() -> Self {
+ Self::IDENTITY
+ }
+ }
+
+ // &Pose2 * &Pose2
+ impl Mul<&$Pose2> for &$Pose2 {
+ type Output = $Pose2;
+
+ #[inline]
+ fn mul(self, rhs: &$Pose2) -> Self::Output {
+ *self * *rhs
+ }
+ }
+
+ // Pose2 * &Pose2
+ impl Mul<&$Pose2> for $Pose2 {
+ type Output = $Pose2;
+
+ #[inline]
+ fn mul(self, rhs: &$Pose2) -> Self::Output {
+ self * *rhs
+ }
+ }
+
+ // &Pose2 * Pose2
+ impl Mul<$Pose2> for &$Pose2 {
+ type Output = $Pose2;
+
+ #[inline]
+ fn mul(self, rhs: $Pose2) -> Self::Output {
+ *self * rhs
+ }
+ }
+
+ impl Mul<$Pose2> for $Rot2 {
+ type Output = $Pose2;
+
+ #[inline]
+ fn mul(self, rhs: $Pose2) -> Self::Output {
+ $Pose2 {
+ translation: self * rhs.translation,
+ rotation: self * rhs.rotation,
+ }
+ }
+ }
+
+ impl Mul<$Rot2> for $Pose2 {
+ type Output = $Pose2;
+
+ #[inline]
+ fn mul(self, rhs: $Rot2) -> Self::Output {
+ $Pose2 {
+ translation: self.translation,
+ rotation: self.rotation * rhs,
+ }
+ }
+ }
+
+ impl MulAssign<$Rot2> for $Pose2 {
+ #[inline]
+ fn mul_assign(&mut self, rhs: $Rot2) {
+ *self = *self * rhs;
+ }
+ }
+
+ impl From<$Rot2> for $Pose2 {
+ #[inline]
+ fn from(rotation: $Rot2) -> Self {
+ Self::from_rotation(rotation)
+ }
+ }
+
+ impl From<($Vec2, $Real)> for $Pose2 {
+ #[inline]
+ fn from((translation, rotation): ($Vec2, $Real)) -> Self {
+ Self {
+ translation,
+ rotation: $Rot2::new(rotation),
+ }
+ }
+ }
+
+ impl From<$Pose2> for ($Vec2, $Real) {
+ #[inline]
+ fn from(pose: $Pose2) -> ($Vec2, $Real) {
+ (pose.translation, pose.rotation.angle())
+ }
+ }
+
+ #[cfg(feature = "approx")]
+ impl approx::AbsDiffEq for $Pose2 {
+ type Epsilon = $Real;
+
+ fn default_epsilon() -> Self::Epsilon {
+ <$Real>::EPSILON
+ }
+
+ fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
+ self.rotation.abs_diff_eq(&other.rotation, epsilon)
+ && self.translation.abs_diff_eq(other.translation, epsilon)
+ }
+ }
+
+ #[cfg(feature = "approx")]
+ impl approx::RelativeEq for $Pose2 {
+ fn default_max_relative() -> Self::Epsilon {
+ <$Real>::EPSILON
+ }
+
+ fn relative_eq(
+ &self,
+ other: &Self,
+ epsilon: Self::Epsilon,
+ max_relative: Self::Epsilon,
+ ) -> bool {
+ self.rotation.relative_eq(&other.rotation, epsilon, max_relative)
+ && self.translation.abs_diff_eq(other.translation, epsilon.max(max_relative))
+ }
+ }
+ };
+}
+
+impl_pose2!(
+ Pose2,
+ Rot2,
+ f32,
+ glam::Vec2,
+ glam::Vec3,
+ glam::Mat2,
+ glam::Mat3,
+ #[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
+);
+#[cfg(feature = "f64")]
+impl_pose2!(
+ DPose2,
+ DRot2,
+ f64,
+ glam::DVec2,
+ glam::DVec3,
+ glam::DMat2,
+ glam::DMat3
+);
+
+// f32 <-> f64 conversions
+#[cfg(feature = "f64")]
+impl From<Pose2> for DPose2 {
+ #[inline]
+ fn from(p: Pose2) -> Self {
+ Self {
+ rotation: p.rotation.into(),
+ translation: p.translation.into(),
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<DPose2> for Pose2 {
+ #[inline]
+ fn from(p: DPose2) -> Self {
+ Self {
+ rotation: p.rotation.into(),
+ translation: p.translation.as_vec2(),
+ }
+ }
+}
+
+// Nalgebra conversions
+#[cfg(feature = "nalgebra")]
+mod nalgebra_conv {
+ use super::*;
+
+ impl From<Pose2> for nalgebra::Isometry2<f32> {
+ fn from(p: Pose2) -> Self {
+ nalgebra::Isometry2 {
+ translation: p.translation.into(),
+ rotation: p.rotation.into(),
+ }
+ }
+ }
+
+ impl From<nalgebra::Isometry2<f32>> for Pose2 {
+ fn from(iso: nalgebra::Isometry2<f32>) -> Self {
+ Self {
+ rotation: Rot2::from_cos_sin_unchecked(iso.rotation.re, iso.rotation.im),
+ translation: glam::Vec2::new(iso.translation.x, iso.translation.y),
+ }
+ }
+ }
+
+ #[cfg(feature = "f64")]
+ impl From<DPose2> for nalgebra::Isometry2<f64> {
+ fn from(p: DPose2) -> Self {
+ nalgebra::Isometry2 {
+ translation: p.translation.into(),
+ rotation: p.rotation.into(),
+ }
+ }
+ }
+
+ #[cfg(feature = "f64")]
+ impl From<nalgebra::Isometry2<f64>> for DPose2 {
+ fn from(iso: nalgebra::Isometry2<f64>) -> Self {
+ Self {
+ rotation: DRot2::from_cos_sin_unchecked(iso.rotation.re, iso.rotation.im),
+ translation: glam::DVec2::new(iso.translation.x, iso.translation.y),
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use approx::assert_relative_eq;
+ use core::f32::consts::PI;
+
+ #[test]
+ fn test_pose2_identity() {
+ let p = Pose2::IDENTITY;
+ assert_eq!(p.rotation, Rot2::IDENTITY);
+ assert_eq!(p.translation, glam::Vec2::ZERO);
+ assert!(p.is_finite());
+ }
+
+ #[test]
+ fn test_pose2_from_translation() {
+ let t = glam::Vec2::new(1.0, 2.0);
+ let p = Pose2::from_translation(t);
+ assert_eq!(p.translation, t);
+ assert_eq!(p.rotation, Rot2::IDENTITY);
+ }
+
+ #[test]
+ fn test_pose2_from_rotation_translation() {
+ let t = glam::Vec2::new(1.0, 2.0);
+ let r = Rot2::new(PI / 4.0);
+ let p = Pose2::from_parts(t, r);
+ assert_eq!(p.translation, t);
+ assert_eq!(p.rotation, r);
+ }
+
+ #[test]
+ fn test_pose2_transform_point() {
+ let p = Pose2::new(glam::Vec2::new(1.0, 0.0), PI / 2.0);
+ let point = glam::Vec2::new(1.0, 0.0);
+ let result = p.transform_point(point);
+ assert_relative_eq!(result.x, 1.0, epsilon = 1e-6);
+ assert_relative_eq!(result.y, 1.0, epsilon = 1e-6);
+ // Operator should also work
+ let result2 = p * point;
+ assert_relative_eq!(result2.x, 1.0, epsilon = 1e-6);
+ assert_relative_eq!(result2.y, 1.0, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_pose2_transform_vector() {
+ let p = Pose2::new(glam::Vec2::new(100.0, 200.0), PI / 2.0);
+ let vector = glam::Vec2::new(1.0, 0.0);
+ // Vector transformation ignores translation
+ let result = p.transform_vector(vector);
+ assert_relative_eq!(result.x, 0.0, epsilon = 1e-6);
+ assert_relative_eq!(result.y, 1.0, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_pose2_inverse() {
+ let p = Pose2::new(glam::Vec2::new(1.0, 2.0), 0.5);
+ let inv = p.inverse();
+ let identity = p * inv;
+ assert_relative_eq!(identity.rotation.re, 1.0, epsilon = 1e-6);
+ assert_relative_eq!(identity.rotation.im, 0.0, epsilon = 1e-6);
+ assert_relative_eq!(identity.translation.x, 0.0, epsilon = 1e-6);
+ assert_relative_eq!(identity.translation.y, 0.0, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_pose2_to_from_mat3() {
+ let p = Pose2::new(glam::Vec2::new(1.0, 2.0), PI / 4.0);
+ let m = p.to_mat3();
+ let p2 = Pose2::from_mat3(m);
+ assert_relative_eq!(p.rotation.re, p2.rotation.re, epsilon = 1e-6);
+ assert_relative_eq!(p.rotation.im, p2.rotation.im, epsilon = 1e-6);
+ assert_relative_eq!(p.translation.x, p2.translation.x, epsilon = 1e-6);
+ assert_relative_eq!(p.translation.y, p2.translation.y, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_pose2_lerp_across_branch_cut() {
+ let p1 = Pose2::new(glam::Vec2::new(0.0, 0.0), 3.13);
+ let p2 = Pose2::new(glam::Vec2::new(2.0, 4.0), 3.15);
+ let mid = p1.lerp(&p2, 0.5);
+ assert_relative_eq!(mid.rotation.angle(), 3.14, epsilon = 1e-6);
+ assert_relative_eq!(mid.translation.x, 1.0, epsilon = 1e-6);
+ assert_relative_eq!(mid.translation.y, 2.0, epsilon = 1e-6);
+ }
+
+ #[cfg(feature = "f64")]
+ #[test]
+ fn test_dpose2_new() {
+ let p = DPose2::new(glam::DVec2::new(1.0, 2.0), core::f64::consts::PI / 4.0);
+ assert_relative_eq!(p.translation.x, 1.0, epsilon = 1e-10);
+ assert_relative_eq!(p.translation.y, 2.0, epsilon = 1e-10);
+ }
+
+ #[test]
+ fn test_convert_back_to_equal_pose2() {
+ let (t1, r1) = (glam::Vec2::new(1.0, 2.0), PI / 4.0);
+ let p: Pose2 = (t1, r1).into();
+ let (t2, r2) = p.into();
+
+ assert_relative_eq!(t1, t2, epsilon = 1e-6);
+ assert_relative_eq!(r1, r2, epsilon = 1e-6);
+ }
+}
diff --git a/renderer/third_party/glamx/src/pose3.rs b/renderer/third_party/glamx/src/pose3.rs
new file mode 100644
index 0000000..ce91c9c
--- /dev/null
+++ b/renderer/third_party/glamx/src/pose3.rs
@@ -0,0 +1,675 @@
+//! 3D pose types for rigid body transformations.
+
+#[cfg(feature = "f64")]
+use crate::rot3::DRot3;
+use crate::rot3::Rot3;
+use core::ops::{Mul, MulAssign};
+
+/// Macro to generate a 3D pose type for a specific scalar type.
+macro_rules! impl_pose3 {
+ ($Pose3:ident, $Rot3:ident, $Real:ty, $Vec3:ty, $Mat4: ty, $camera: ident $(, $Padding: ty, $bytemuck: ident)?) => {
+ #[doc = concat!("A 3D pose (rotation + translation), representing a rigid body transformation (", stringify!($Real), " precision).")]
+ #[derive(Copy, Clone, Debug, PartialEq)]
+ #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+ #[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
+ $(#[cfg_attr(feature = "bytemuck", derive($bytemuck::Pod, $bytemuck::Zeroable))])*
+ #[repr(C)]
+ pub struct $Pose3 {
+ /// The rotational part of the pose.
+ pub rotation: $Rot3,
+ /// The translational part of the pose.
+ pub translation: $Vec3,
+ $(
+ /// Explicit padding for compatibility with bytemuck and targets like spirv.
+ ///
+ /// Can have any value as it is never read from or written to.
+ pub padding: $Padding,
+ )*
+ }
+
+ impl $Pose3 {
+ /// The identity pose (no rotation, no translation).
+ pub const IDENTITY: Self = Self {
+ rotation: $Rot3::IDENTITY,
+ translation: <$Vec3>::ZERO,
+ $(padding: 0 as $Padding,)*
+ };
+
+ /// Creates the identity pose.
+ #[inline]
+ pub fn identity() -> Self {
+ Self::IDENTITY
+ }
+
+ /// Creates a pose from a translation vector.
+ #[inline]
+ pub fn from_translation(translation: $Vec3) -> Self {
+ Self {
+ rotation: $Rot3::IDENTITY,
+ translation,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+
+ /// Creates a pose from translation components.
+ #[inline]
+ pub fn translation(x: $Real, y: $Real, z: $Real) -> Self {
+ Self::from_translation(<$Vec3>::new(x, y, z))
+ }
+
+ /// Creates a pose from a rotation.
+ #[inline]
+ pub fn from_rotation(rotation: $Rot3) -> Self {
+ Self {
+ rotation,
+ translation: <$Vec3>::ZERO,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+
+ /// Creates a pose from translation and rotation parts.
+ #[inline]
+ pub fn from_parts(translation: $Vec3, rotation: $Rot3) -> Self {
+ Self {
+ rotation,
+ translation,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+
+ /// Creates a pose from translation and axis-angle rotation.
+ #[inline]
+ pub fn new(translation: $Vec3, axisangle: $Vec3) -> Self {
+ let rotation = $Rot3::from_scaled_axis(axisangle.into());
+ Self {
+ rotation,
+ translation,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+
+ /// Creates a pose from axis-angle rotation only (no translation).
+ #[inline]
+ pub fn rotation(axisangle: $Vec3) -> Self {
+ Self {
+ rotation: $Rot3::from_scaled_axis(axisangle.into()),
+ translation: <$Vec3>::ZERO,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+
+ /// Prepends a translation to this pose (applies translation in local frame).
+ #[inline]
+ pub fn prepend_translation(self, translation: $Vec3) -> Self {
+ Self {
+ rotation: self.rotation,
+ translation: self.translation + self.rotation * translation,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+
+ /// Appends a translation to this pose (applies translation in world frame).
+ #[inline]
+ pub fn append_translation(self, translation: $Vec3) -> Self {
+ Self {
+ rotation: self.rotation,
+ translation: self.translation + translation,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+
+ /// Returns the inverse of this pose.
+ #[inline]
+ pub fn inverse(&self) -> Self {
+ let inv_rot = self.rotation.inverse();
+ Self {
+ rotation: inv_rot,
+ translation: inv_rot * (-self.translation),
+ $(padding: 0 as $Padding,)*
+ }
+ }
+
+ /// Computes `self.inverse() * rhs`.
+ #[inline]
+ pub fn inv_mul(&self, rhs: &Self) -> Self {
+ let inv_rot1 = self.rotation.inverse();
+ let tr_12 = rhs.translation - self.translation;
+ $Pose3 {
+ translation: inv_rot1 * tr_12,
+ rotation: inv_rot1 * rhs.rotation,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+
+ /// Transforms a 3D point by this pose.
+ ///
+ /// This applies both the rotation and translation.
+ #[inline]
+ pub fn transform_point(&self, p: $Vec3) -> $Vec3 {
+ self.rotation * p + self.translation
+ }
+
+ /// Transforms a 3D vector by this pose.
+ ///
+ /// This applies only the rotation (ignores translation).
+ #[inline]
+ pub fn transform_vector(&self, v: $Vec3) -> $Vec3 {
+ self.rotation * v
+ }
+
+ /// Transforms a point by the inverse of this pose.
+ #[inline]
+ pub fn inverse_transform_point(&self, p: $Vec3) -> $Vec3 {
+ self.rotation.inverse() * (p - self.translation)
+ }
+
+ /// Transforms a vector by the inverse of this pose.
+ #[inline]
+ pub fn inverse_transform_vector(&self, v: $Vec3) -> $Vec3 {
+ self.rotation.inverse() * v
+ }
+
+ /// Linearly interpolates between two poses.
+ ///
+ /// Uses spherical linear interpolation for the rotation part.
+ #[inline]
+ pub fn lerp(&self, other: &Self, t: $Real) -> Self {
+ Self {
+ rotation: self.rotation.slerp(other.rotation, t),
+ translation: self.translation.lerp(other.translation, t),
+ $(padding: 0 as $Padding,)*
+ }
+ }
+
+ /// Returns `true` if, and only if, all elements are finite.
+ #[inline]
+ pub fn is_finite(&self) -> bool {
+ self.rotation.is_finite() && self.translation.is_finite()
+ }
+
+ /// Returns `true` if any element is `NaN`.
+ #[inline]
+ pub fn is_nan(&self) -> bool {
+ self.rotation.is_nan() || self.translation.is_nan()
+ }
+
+ /// Converts this pose to a homogeneous 4x4 matrix.
+ #[inline]
+ pub fn to_mat4(&self) -> $Mat4 {
+ <$Mat4>::from_rotation_translation(self.rotation, self.translation.into())
+ }
+
+ /// Creates a pose from a homogeneous 4x4 matrix.
+ ///
+ /// The matrix is assumed to represent a rigid body transformation
+ /// (rotation + translation only, no scaling or shearing).
+ #[inline]
+ pub fn from_mat4(mat: $Mat4) -> Self {
+ let (_, rotation, translation) = mat.to_scale_rotation_translation();
+ Self {
+ rotation,
+ translation: translation.into(),
+ $(padding: 0 as $Padding,)*
+ }
+ }
+
+ /// Builds a right-handed look-at view matrix.
+ ///
+ /// It maps the view direction target - eye to the negative z axis to and the eye to the
+ /// origin. This conforms to the common notion of right-handed camera look-at view matrix from the computer graphics community, i.e. the camera is assumed to look toward its local -z axis.
+ ///
+ /// # Arguments
+ /// - `eye`: The eye position.
+ /// - `target`: The target position.
+ /// - `up`: A vector approximately aligned with required the vertical axis. The only
+ /// requirement of this parameter is to not be collinear to target - eye.
+ #[inline]
+ pub fn look_at_rh(eye: $Vec3, target: $Vec3, up: $Vec3) -> $Pose3 {
+ let rotation = glam::$camera::rh::view::look_at_quat(eye.into(), target.into(), up.into());
+ let translation = rotation * (-eye);
+
+ $Pose3 {
+ rotation,
+ translation,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+
+ /// Creates a pose that corresponds to the local frame of an observer standing at the
+ /// point eye and looking toward target.
+ ///
+ /// It maps the `z` axis to the view direction target - eye and the origin to the eye.
+ ///
+ /// # Arguments
+ /// - `eye`: The observer position.
+ /// - `target`: The target position.
+ /// - `up`: Vertical direction. The only requirement of this parameter is to not be
+ /// collinear to eye - at. Non-collinearity is not checked.
+ #[inline]
+ pub fn face_towards(eye: $Vec3, target: $Vec3, up: $Vec3) -> $Pose3 {
+ $Pose3 {
+ rotation: glam::$camera::lh::view::look_at_quat(eye.into(), target.into(), up.into())
+ .inverse(),
+ translation: eye,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+ }
+
+ // Pose3 * Pose3
+ impl Mul<$Pose3> for $Pose3 {
+ type Output = Self;
+
+ #[inline]
+ fn mul(self, rhs: Self) -> Self::Output {
+ Self {
+ rotation: self.rotation * rhs.rotation,
+ translation: self.translation + self.rotation * rhs.translation,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+ }
+
+ impl MulAssign<$Pose3> for $Pose3 {
+ #[inline]
+ fn mul_assign(&mut self, rhs: Self) {
+ *self = *self * rhs;
+ }
+ }
+
+ // Pose3 * Vec3 (transform point - applies rotation and translation)
+ impl Mul<$Vec3> for $Pose3 {
+ type Output = $Vec3;
+
+ #[inline]
+ fn mul(self, rhs: $Vec3) -> Self::Output {
+ self.transform_point(rhs)
+ }
+ }
+
+ impl Mul<$Vec3> for &$Pose3 {
+ type Output = $Vec3;
+
+ #[inline]
+ fn mul(self, rhs: $Vec3) -> Self::Output {
+ self.transform_point(rhs)
+ }
+ }
+
+ impl Mul<&$Vec3> for $Pose3 {
+ type Output = $Vec3;
+
+ #[inline]
+ fn mul(self, rhs: &$Vec3) -> Self::Output {
+ self.transform_point(*rhs)
+ }
+ }
+
+ // &Pose3 * &Pose3
+ impl Mul<&$Pose3> for &$Pose3 {
+ type Output = $Pose3;
+
+ #[inline]
+ fn mul(self, rhs: &$Pose3) -> Self::Output {
+ *self * *rhs
+ }
+ }
+
+ // Pose3 * &Pose3
+ impl Mul<&$Pose3> for $Pose3 {
+ type Output = $Pose3;
+
+ #[inline]
+ fn mul(self, rhs: &$Pose3) -> Self::Output {
+ self * *rhs
+ }
+ }
+
+ // &Pose3 * Pose3
+ impl Mul<$Pose3> for &$Pose3 {
+ type Output = $Pose3;
+
+ #[inline]
+ fn mul(self, rhs: $Pose3) -> Self::Output {
+ *self * rhs
+ }
+ }
+
+ impl Default for $Pose3 {
+ fn default() -> Self {
+ Self::IDENTITY
+ }
+ }
+
+ impl Mul<$Pose3> for $Rot3 {
+ type Output = $Pose3;
+
+ #[inline]
+ fn mul(self, rhs: $Pose3) -> Self::Output {
+ $Pose3 {
+ translation: self * rhs.translation,
+ rotation: self * rhs.rotation,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+ }
+
+ impl Mul<$Rot3> for $Pose3 {
+ type Output = $Pose3;
+
+ #[inline]
+ fn mul(self, rhs: $Rot3) -> Self::Output {
+ $Pose3 {
+ translation: self.translation,
+ rotation: self.rotation * rhs,
+ $(padding: 0 as $Padding,)*
+ }
+ }
+ }
+
+ impl MulAssign<$Rot3> for $Pose3 {
+ #[inline]
+ fn mul_assign(&mut self, rhs: $Rot3) {
+ *self = *self * rhs;
+ }
+ }
+
+ impl From<$Rot3> for $Pose3 {
+ #[inline]
+ fn from(rotation: $Rot3) -> Self {
+ Self::from_rotation(rotation)
+ }
+ }
+
+ impl From<($Vec3, $Rot3)> for $Pose3 {
+ #[inline]
+ fn from((translation, rotation): ($Vec3, $Rot3)) -> Self {
+ Self::from_parts(translation, rotation)
+ }
+ }
+
+ impl From<$Pose3> for ($Vec3, $Rot3) {
+ #[inline]
+ fn from(pose: $Pose3) -> ($Vec3, $Rot3) {
+ (pose.translation, pose.rotation)
+ }
+ }
+
+ #[cfg(feature = "approx")]
+ impl approx::AbsDiffEq for $Pose3 {
+ type Epsilon = $Real;
+
+ fn default_epsilon() -> Self::Epsilon {
+ <$Real>::EPSILON
+ }
+
+ fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
+ self.rotation.abs_diff_eq(other.rotation, epsilon)
+ && self.translation.abs_diff_eq(other.translation, epsilon)
+ }
+ }
+
+ #[cfg(feature = "approx")]
+ impl approx::RelativeEq for $Pose3 {
+ fn default_max_relative() -> Self::Epsilon {
+ <$Real>::EPSILON
+ }
+
+ fn relative_eq(
+ &self,
+ other: &Self,
+ epsilon: Self::Epsilon,
+ max_relative: Self::Epsilon,
+ ) -> bool {
+ self.rotation.abs_diff_eq(other.rotation, epsilon.max(max_relative))
+ && self.translation.abs_diff_eq(other.translation, epsilon.max(max_relative))
+ }
+ }
+ };
+}
+
+impl_pose3!(
+ Pose3,
+ Rot3,
+ f32,
+ glam::Vec3,
+ glam::Mat4,
+ camera,
+ u32,
+ bytemuck
+);
+impl_pose3!(Pose3A, Rot3, f32, glam::Vec3A, glam::Mat4, camera);
+#[cfg(feature = "f64")]
+impl_pose3!(DPose3, DRot3, f64, glam::DVec3, glam::DMat4, dcamera);
+
+// f32 <-> f64 conversions
+#[cfg(feature = "f64")]
+impl From<Pose3> for DPose3 {
+ #[inline]
+ fn from(p: Pose3) -> Self {
+ Self {
+ rotation: p.rotation.as_dquat(),
+ translation: p.translation.as_dvec3(),
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<DPose3> for Pose3 {
+ #[inline]
+ fn from(p: DPose3) -> Self {
+ Self {
+ rotation: p.rotation.as_quat(),
+ translation: p.translation.as_vec3(),
+ padding: 0,
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<Pose3A> for DPose3 {
+ #[inline]
+ fn from(p: Pose3A) -> Self {
+ Self {
+ rotation: p.rotation.as_dquat(),
+ translation: p.translation.as_dvec3(),
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<DPose3> for Pose3A {
+ #[inline]
+ fn from(p: DPose3) -> Self {
+ Self {
+ rotation: p.rotation.as_quat(),
+ translation: p.translation.as_vec3a(),
+ }
+ }
+}
+
+// Pose3 <-> Pose3A conversions
+impl From<Pose3> for Pose3A {
+ #[inline]
+ fn from(p: Pose3) -> Self {
+ Self {
+ rotation: p.rotation,
+ translation: p.translation.into(),
+ }
+ }
+}
+
+impl From<Pose3A> for Pose3 {
+ #[inline]
+ fn from(p: Pose3A) -> Self {
+ Self {
+ rotation: p.rotation,
+ translation: p.translation.into(),
+ padding: 0,
+ }
+ }
+}
+
+// Nalgebra conversions
+#[cfg(feature = "nalgebra")]
+mod nalgebra_conv {
+ use super::*;
+
+ impl From<Pose3> for nalgebra::Isometry3<f32> {
+ fn from(p: Pose3) -> Self {
+ nalgebra::Isometry3 {
+ translation: p.translation.into(),
+ rotation: p.rotation.into(),
+ }
+ }
+ }
+
+ impl From<nalgebra::Isometry3<f32>> for Pose3 {
+ fn from(iso: nalgebra::Isometry3<f32>) -> Self {
+ Self {
+ rotation: glam::Quat::from_xyzw(
+ iso.rotation.i,
+ iso.rotation.j,
+ iso.rotation.k,
+ iso.rotation.w,
+ ),
+ translation: glam::Vec3::new(
+ iso.translation.x,
+ iso.translation.y,
+ iso.translation.z,
+ ),
+ padding: 0,
+ }
+ }
+ }
+
+ #[cfg(feature = "f64")]
+ impl From<DPose3> for nalgebra::Isometry3<f64> {
+ fn from(p: DPose3) -> Self {
+ nalgebra::Isometry3 {
+ translation: p.translation.into(),
+ rotation: p.rotation.into(),
+ }
+ }
+ }
+
+ #[cfg(feature = "f64")]
+ impl From<nalgebra::Isometry3<f64>> for DPose3 {
+ fn from(iso: nalgebra::Isometry3<f64>) -> Self {
+ Self {
+ rotation: iso.rotation.into(),
+ translation: iso.translation.into(),
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use approx::assert_relative_eq;
+ use core::f32::consts::PI;
+
+ #[test]
+ fn test_pose3_identity() {
+ let p = Pose3::IDENTITY;
+ assert_eq!(p.rotation, Rot3::IDENTITY);
+ assert_eq!(p.translation, glam::Vec3::ZERO);
+ assert!(p.is_finite());
+ }
+
+ #[test]
+ fn test_pose3_from_translation() {
+ let t = glam::Vec3::new(1.0, 2.0, 3.0);
+ let p = Pose3::from_translation(t);
+ assert_eq!(p.translation, t);
+ assert_eq!(p.rotation, Rot3::IDENTITY);
+ }
+
+ #[test]
+ fn test_pose3_from_rotation_translation() {
+ let t = glam::Vec3::new(1.0, 2.0, 3.0);
+ let r = Rot3::from_rotation_z(PI / 4.0);
+ let p = Pose3::from_parts(t, r);
+ assert_eq!(p.translation, t);
+ assert_eq!(p.rotation, r);
+ }
+
+ #[test]
+ fn test_pose3_transform_point() {
+ let axisangle = glam::Vec3::new(0.0, 0.0, PI / 2.0);
+ let p = Pose3::new(glam::Vec3::new(1.0, 0.0, 0.0), axisangle);
+ let point = glam::Vec3::new(1.0, 0.0, 0.0);
+ let result = p.transform_point(point);
+ assert_relative_eq!(result.x, 1.0, epsilon = 1e-6);
+ assert_relative_eq!(result.y, 1.0, epsilon = 1e-6);
+ assert_relative_eq!(result.z, 0.0, epsilon = 1e-6);
+ // Operator should also work
+ let result2 = p * point;
+ assert_relative_eq!(result2.x, 1.0, epsilon = 1e-6);
+ assert_relative_eq!(result2.y, 1.0, epsilon = 1e-6);
+ assert_relative_eq!(result2.z, 0.0, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_pose3_transform_vector() {
+ let axisangle = glam::Vec3::new(0.0, 0.0, PI / 2.0);
+ let p = Pose3::new(glam::Vec3::new(100.0, 200.0, 300.0), axisangle);
+ let vector = glam::Vec3::new(1.0, 0.0, 0.0);
+ // Vector transformation ignores translation
+ let result = p.transform_vector(vector);
+ assert_relative_eq!(result.x, 0.0, epsilon = 1e-6);
+ assert_relative_eq!(result.y, 1.0, epsilon = 1e-6);
+ assert_relative_eq!(result.z, 0.0, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_pose3_inverse() {
+ let axisangle = glam::Vec3::new(0.1, 0.2, 0.3);
+ let p = Pose3::new(axisangle, glam::Vec3::new(1.0, 2.0, 3.0));
+ let inv = p.inverse();
+ let identity = p * inv;
+ assert_relative_eq!(identity.rotation, Rot3::IDENTITY, epsilon = 1e-6);
+ assert_relative_eq!(identity.translation.x, 0.0, epsilon = 1e-6);
+ assert_relative_eq!(identity.translation.y, 0.0, epsilon = 1e-6);
+ assert_relative_eq!(identity.translation.z, 0.0, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_pose3_to_from_mat4() {
+ let axisangle = glam::Vec3::new(0.1, 0.2, 0.3);
+ let p = Pose3::new(axisangle, glam::Vec3::new(1.0, 2.0, 3.0));
+ let m = p.to_mat4();
+ let p2 = Pose3::from_mat4(m);
+ assert_relative_eq!(p.rotation.x, p2.rotation.x, epsilon = 1e-5);
+ assert_relative_eq!(p.rotation.y, p2.rotation.y, epsilon = 1e-5);
+ assert_relative_eq!(p.rotation.z, p2.rotation.z, epsilon = 1e-5);
+ assert_relative_eq!(p.rotation.w, p2.rotation.w, epsilon = 1e-5);
+ assert_relative_eq!(p.translation.x, p2.translation.x, epsilon = 1e-6);
+ assert_relative_eq!(p.translation.y, p2.translation.y, epsilon = 1e-6);
+ assert_relative_eq!(p.translation.z, p2.translation.z, epsilon = 1e-6);
+ }
+
+ #[cfg(feature = "f64")]
+ #[test]
+ fn test_dpose3_new() {
+ let axisangle = glam::DVec3::new(0.1, 0.2, 0.3);
+ let p = DPose3::new(glam::DVec3::new(1.0, 2.0, 3.0), axisangle);
+ assert_relative_eq!(p.translation.x, 1.0, epsilon = 1e-10);
+ assert_relative_eq!(p.translation.y, 2.0, epsilon = 1e-10);
+ assert_relative_eq!(p.translation.z, 3.0, epsilon = 1e-10);
+ }
+
+ #[test]
+ fn test_convert_back_to_equal_pose3() {
+ let (t1, r1) = (
+ glam::Vec3::new(1.0, 2.0, 3.0),
+ glam::Quat::from_rotation_x(PI / 4.0),
+ );
+ let p: Pose3 = (t1, r1).into();
+ let (t2, r2) = p.into();
+
+ assert_relative_eq!(t1, t2, epsilon = 1e-6);
+ assert!(r1.dot(r2).abs() > 1.0 - 1e-5);
+ }
+}
diff --git a/renderer/third_party/glamx/src/rot2.rs b/renderer/third_party/glamx/src/rot2.rs
new file mode 100644
index 0000000..5fdc807
--- /dev/null
+++ b/renderer/third_party/glamx/src/rot2.rs
@@ -0,0 +1,546 @@
+//! 2D rotation types represented as unit complex numbers.
+
+use core::ops::{Mul, MulAssign};
+use simba::scalar::{ComplexField, RealField};
+
+/// Macro to generate a 2D rotation type for a specific scalar type.
+macro_rules! impl_rot2 {
+ ($Rot2:ident, $Real:ty, $Vec2:ty, $Mat2:ty $(, #[$attr:meta])*) => {
+ #[doc = concat!("A 2D rotation represented as a unit complex number (", stringify!($Real), " precision).")]
+ ///
+ /// The rotation is stored as `re + im * i` where `re = cos(angle)` and `im = sin(angle)`.
+ #[derive(Copy, Clone, Debug, PartialEq)]
+ #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+ #[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
+ #[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
+ #[repr(C)]
+ $(#[$attr])*
+ pub struct $Rot2 {
+ /// Real part (cosine of the angle).
+ pub re: $Real,
+ /// Imaginary part (sine of the angle).
+ pub im: $Real,
+ }
+
+ impl $Rot2 {
+ /// The identity rotation (no rotation).
+ pub const IDENTITY: Self = Self { re: 1.0, im: 0.0 };
+
+ /// Creates a new unit complex from cosine and sine values.
+ ///
+ /// The caller must ensure that `re*re + im*im = 1`.
+ #[inline]
+ pub const fn from_cos_sin_unchecked(re: $Real, im: $Real) -> Self {
+ Self { re, im }
+ }
+
+ /// Creates a rotation from a rotation matrix (without normalization).
+ #[inline]
+ pub fn from_matrix_unchecked(mat: $Mat2) -> Self {
+ Self {
+ re: mat.x_axis.x,
+ im: mat.x_axis.y,
+ }
+ }
+
+ /// Creates the identity rotation.
+ #[inline]
+ pub fn identity() -> Self {
+ Self::IDENTITY
+ }
+
+ /// Creates a rotation from an angle in radians.
+ #[inline]
+ pub fn new(angle: $Real) -> Self {
+ let (im, re) = <$Real as ComplexField>::sin_cos(angle);
+ Self { re, im }
+ }
+
+ /// Creates a rotation from an angle in radians.
+ #[inline]
+ pub fn from_angle(angle: $Real) -> Self {
+ Self::new(angle)
+ }
+
+ /// Returns the rotation angle in radians.
+ #[inline]
+ pub fn angle(&self) -> $Real {
+ RealField::atan2(self.im, self.re)
+ }
+
+ /// Returns the cosine of the rotation angle (the real part).
+ #[inline]
+ pub fn cos(&self) -> $Real {
+ self.re
+ }
+
+ /// Returns the sine of the rotation angle (the imaginary part).
+ #[inline]
+ pub fn sin(&self) -> $Real {
+ self.im
+ }
+
+ /// Returns the inverse rotation.
+ #[inline]
+ pub fn inverse(self) -> Self {
+ Self {
+ re: self.re,
+ im: -self.im,
+ }
+ }
+
+ /// Computes the length (magnitude) of `self`.
+ ///
+ /// For a valid unit rotation, this should always be `1.0`.
+ #[inline]
+ pub fn length(&self) -> $Real {
+ <$Real as ComplexField>::sqrt(self.re * self.re + self.im * self.im)
+ }
+
+ /// Computes the squared length of `self`.
+ ///
+ /// This is faster than `length()` as it avoids a square root.
+ /// For a valid unit rotation, this should always be `1.0`.
+ #[inline]
+ pub fn length_squared(&self) -> $Real {
+ self.re * self.re + self.im * self.im
+ }
+
+ /// Computes `1.0 / length()`.
+ #[inline]
+ pub fn length_recip(&self) -> $Real {
+ 1.0 / self.length()
+ }
+
+ /// Returns `self` normalized to length `1.0`.
+ ///
+ /// For valid unit rotations this should be a no-op.
+ #[inline]
+ pub fn normalize(&self) -> Self {
+ let len = self.length();
+ if len > <$Real>::EPSILON {
+ Self {
+ re: self.re / len,
+ im: self.im / len,
+ }
+ } else {
+ Self::IDENTITY
+ }
+ }
+
+ /// Returns `true` if, and only if, all elements are finite.
+ #[inline]
+ pub fn is_finite(&self) -> bool {
+ self.re.is_finite() && self.im.is_finite()
+ }
+
+ /// Returns `true` if any element is `NaN`.
+ #[inline]
+ pub fn is_nan(&self) -> bool {
+ self.re.is_nan() || self.im.is_nan()
+ }
+
+ /// Returns whether `self` is of length `1.0` or not.
+ ///
+ /// Uses a precision threshold of approximately `1e-4`.
+ #[inline]
+ pub fn is_normalized(&self) -> bool {
+ (self.length_squared() - 1.0).abs() < 2e-4
+ }
+
+ /// Rotates a 2D vector by this rotation.
+ #[inline]
+ pub fn transform_vector(&self, v: $Vec2) -> $Vec2 {
+ <$Vec2>::new(self.re * v.x - self.im * v.y, self.im * v.x + self.re * v.y)
+ }
+
+ /// Transforms a 2D vector by the inverse of this rotation.
+ #[inline]
+ pub fn inverse_transform_vector(&self, v: $Vec2) -> $Vec2 {
+ <$Vec2>::new(
+ self.re * v.x + self.im * v.y,
+ -self.im * v.x + self.re * v.y,
+ )
+ }
+
+ /// Returns the rotation matrix equivalent to this rotation.
+ #[inline]
+ pub fn to_mat(&self) -> $Mat2 {
+ <$Mat2>::from_cols(
+ <$Vec2>::new(self.re, self.im),
+ <$Vec2>::new(-self.im, self.re),
+ )
+ }
+
+ /// Creates a rotation from a 2x2 rotation matrix.
+ ///
+ /// The matrix should be a valid rotation matrix (orthogonal with determinant 1).
+ #[inline]
+ pub fn from_mat(mat: $Mat2) -> Self {
+ Self::from_mat_unchecked(mat).normalize()
+ }
+
+ /// Creates a rotation from a 2x2 matrix without normalization.
+ ///
+ /// Alias for `from_matrix_unchecked`.
+ #[inline]
+ pub fn from_mat_unchecked(mat: $Mat2) -> Self {
+ Self::from_matrix_unchecked(mat)
+ }
+
+ /// Gets the minimal rotation for transforming `from` to `to`.
+ ///
+ /// Both vectors must be normalized. The rotation is in the plane
+ /// spanned by the two vectors.
+ #[inline]
+ pub fn from_rotation_arc(from: $Vec2, to: $Vec2) -> Self {
+ // For unit vectors, the rotation from a to b has:
+ // re = a . b = cos(angle)
+ // im = a x b = sin(angle) (2D cross product is scalar)
+ let re = from.dot(to);
+ let im = from.x * to.y - from.y * to.x;
+ Self { re, im }
+ }
+
+ /// Spherical linear interpolation between two rotations.
+ ///
+ /// Interpolates along the shortest arc: the result is `self` at `t == 0` and `other`
+ /// at `t == 1`, whichever branch of `angle` the two rotations fall on. Interpolating
+ /// their angles instead would take the long way around whenever the arc crosses the
+ /// `-pi`/`pi` cut.
+ #[inline]
+ pub fn slerp(&self, other: &Self, t: $Real) -> Self {
+ *self * Self::new(self.angle_between(other) * t)
+ }
+
+ /// Raises this rotation to a power.
+ ///
+ /// For example, `powf(2.0)` will return a rotation with double the angle.
+ #[inline]
+ pub fn powf(&self, n: $Real) -> Self {
+ Self::new(self.angle() * n)
+ }
+
+ /// Rotates `self` towards `rhs` up to `max_angle` (in radians).
+ ///
+ /// When `max_angle` is `0.0`, the result will be equal to `self`. When `max_angle` is
+ /// equal to `self.angle_between(rhs)`, the result will be equal to `rhs`. If
+ /// `max_angle` is negative, rotates towards the exact opposite of `rhs`.
+ /// Will not go past the target.
+ #[inline]
+ pub fn rotate_towards(&self, rhs: &Self, max_angle: $Real) -> Self {
+ let angle_between = self.angle_between(rhs);
+ if angle_between.abs() <= max_angle.abs() {
+ *rhs
+ } else {
+ self.slerp(rhs, max_angle / angle_between)
+ }
+ }
+
+ /// Returns the angle (in radians) between `self` and `rhs`.
+ #[inline]
+ pub fn angle_between(&self, rhs: &Self) -> $Real {
+ let diff = self.inverse() * *rhs;
+ diff.angle()
+ }
+
+ /// Computes the dot product of `self` and `rhs`.
+ ///
+ /// The dot product is equal to the cosine of the angle between two rotations.
+ #[inline]
+ pub fn dot(&self, rhs: Self) -> $Real {
+ self.re * rhs.re + self.im * rhs.im
+ }
+
+ /// Performs a linear interpolation between `self` and `rhs` based on
+ /// the value `s`.
+ ///
+ /// When `s` is `0.0`, the result will be equal to `self`. When `s` is
+ /// `1.0`, the result will be equal to `rhs`. For rotations, `slerp` is
+ /// usually preferred over `lerp`.
+ #[inline]
+ pub fn lerp(&self, rhs: Self, s: $Real) -> Self {
+ Self {
+ re: self.re + (rhs.re - self.re) * s,
+ im: self.im + (rhs.im - self.im) * s,
+ }
+ }
+
+ /// Normalizes `self` in place.
+ ///
+ /// Does nothing if `self` is already normalized or zero length.
+ #[inline]
+ pub fn normalize_mut(&mut self) {
+ *self = self.normalize();
+ }
+ }
+
+ // Rot2 * Rot2
+ impl Mul<$Rot2> for $Rot2 {
+ type Output = Self;
+
+ #[inline]
+ fn mul(self, rhs: Self) -> Self::Output {
+ // Complex multiplication: (a + bi)(c + di) = (ac - bd) + (ad + bc)i
+ Self {
+ re: self.re * rhs.re - self.im * rhs.im,
+ im: self.re * rhs.im + self.im * rhs.re,
+ }
+ }
+ }
+
+ // &Rot2 * Rot2
+ impl Mul<$Rot2> for &$Rot2 {
+ type Output = $Rot2;
+
+ #[inline]
+ fn mul(self, rhs: $Rot2) -> Self::Output {
+ *self * rhs
+ }
+ }
+
+ impl MulAssign<$Rot2> for $Rot2 {
+ #[inline]
+ fn mul_assign(&mut self, rhs: Self) {
+ *self = *self * rhs;
+ }
+ }
+
+ // Rot2 * Vec2
+ impl Mul<$Vec2> for $Rot2 {
+ type Output = $Vec2;
+
+ #[inline]
+ fn mul(self, rhs: $Vec2) -> Self::Output {
+ self.transform_vector(rhs)
+ }
+ }
+
+ impl Default for $Rot2 {
+ fn default() -> Self {
+ Self::identity()
+ }
+ }
+
+ #[cfg(feature = "approx")]
+ impl approx::AbsDiffEq for $Rot2 {
+ type Epsilon = $Real;
+
+ fn default_epsilon() -> Self::Epsilon {
+ <$Real>::EPSILON
+ }
+
+ fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
+ (self.re - other.re).abs() <= epsilon && (self.im - other.im).abs() <= epsilon
+ }
+ }
+
+ #[cfg(feature = "approx")]
+ impl approx::RelativeEq for $Rot2 {
+ fn default_max_relative() -> Self::Epsilon {
+ <$Real>::EPSILON
+ }
+
+ fn relative_eq(
+ &self,
+ other: &Self,
+ epsilon: Self::Epsilon,
+ max_relative: Self::Epsilon,
+ ) -> bool {
+ approx::AbsDiffEq::abs_diff_eq(self, other, epsilon.max(max_relative))
+ }
+ }
+
+ #[cfg(feature = "approx")]
+ impl approx::UlpsEq for $Rot2 {
+ fn default_max_ulps() -> u32 {
+ 4
+ }
+
+ fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
+ approx::AbsDiffEq::abs_diff_eq(self, other, epsilon)
+ || (self.re.to_bits().abs_diff(other.re.to_bits()) <= max_ulps as _
+ && self.im.to_bits().abs_diff(other.im.to_bits()) <= max_ulps as _)
+ }
+ }
+ };
+}
+
+impl_rot2!(Rot2, f32, glam::Vec2, glam::Mat2);
+#[cfg(feature = "f64")]
+impl_rot2!(DRot2, f64, glam::DVec2, glam::DMat2);
+
+// f32 <-> f64 conversions
+#[cfg(feature = "f64")]
+impl From<Rot2> for DRot2 {
+ #[inline]
+ fn from(r: Rot2) -> Self {
+ Self {
+ re: r.re as f64,
+ im: r.im as f64,
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<DRot2> for Rot2 {
+ #[inline]
+ fn from(r: DRot2) -> Self {
+ Self {
+ re: r.re as f32,
+ im: r.im as f32,
+ }
+ }
+}
+
+// Nalgebra conversions
+#[cfg(feature = "nalgebra")]
+mod nalgebra_conv {
+ use super::*;
+
+ impl From<Rot2> for nalgebra::UnitComplex<f32> {
+ fn from(r: Rot2) -> Self {
+ nalgebra::UnitComplex::from_cos_sin_unchecked(r.re, r.im)
+ }
+ }
+
+ impl From<nalgebra::UnitComplex<f32>> for Rot2 {
+ fn from(r: nalgebra::UnitComplex<f32>) -> Self {
+ Self { re: r.re, im: r.im }
+ }
+ }
+
+ #[cfg(feature = "f64")]
+ impl From<DRot2> for nalgebra::UnitComplex<f64> {
+ fn from(r: DRot2) -> Self {
+ nalgebra::UnitComplex::from_cos_sin_unchecked(r.re, r.im)
+ }
+ }
+
+ #[cfg(feature = "f64")]
+ impl From<nalgebra::UnitComplex<f64>> for DRot2 {
+ fn from(r: nalgebra::UnitComplex<f64>) -> Self {
+ Self { re: r.re, im: r.im }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use approx::assert_relative_eq;
+ use core::f32::consts::PI;
+
+ #[test]
+ fn test_rot2_identity() {
+ let r = Rot2::IDENTITY;
+ assert_eq!(r.re, 1.0);
+ assert_eq!(r.im, 0.0);
+ assert!(r.is_normalized());
+ }
+
+ #[test]
+ fn test_rot2_new() {
+ let r = Rot2::new(PI / 2.0);
+ assert_relative_eq!(r.re, 0.0, epsilon = 1e-6);
+ assert_relative_eq!(r.im, 1.0, epsilon = 1e-6);
+ assert!(r.is_normalized());
+ }
+
+ #[test]
+ fn test_rot2_angle() {
+ let angle = 0.5;
+ let r = Rot2::new(angle);
+ assert_relative_eq!(r.angle(), angle, epsilon = 1e-6);
+ assert_relative_eq!(r.angle(), angle, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_rot2_inverse() {
+ let r = Rot2::new(0.5);
+ let inv = r.inverse();
+ let identity = r * inv;
+ assert_relative_eq!(identity.re, 1.0, epsilon = 1e-6);
+ assert_relative_eq!(identity.im, 0.0, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_rot2_transform_vector() {
+ let r = Rot2::new(PI / 2.0);
+ let v = glam::Vec2::new(1.0, 0.0);
+ let result = r.transform_vector(v);
+ assert_relative_eq!(result.x, 0.0, epsilon = 1e-6);
+ assert_relative_eq!(result.y, 1.0, epsilon = 1e-6);
+ // Operator should also work
+ let result2 = r * v;
+ assert_relative_eq!(result2.x, 0.0, epsilon = 1e-6);
+ assert_relative_eq!(result2.y, 1.0, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_rot2_length() {
+ let r = Rot2::new(0.5);
+ assert_relative_eq!(r.length(), 1.0, epsilon = 1e-6);
+ assert_relative_eq!(r.length_squared(), 1.0, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_rot2_from_rotation_arc() {
+ let from = glam::Vec2::new(1.0, 0.0);
+ let to = glam::Vec2::new(0.0, 1.0);
+ let r = Rot2::from_rotation_arc(from, to);
+ assert_relative_eq!(r.angle(), PI / 2.0, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_rot2_to_mat2() {
+ let r = Rot2::new(PI / 4.0);
+ let m = r.to_mat();
+ let from_mat = Rot2::from_mat(m);
+ assert_relative_eq!(r.re, from_mat.re, epsilon = 1e-6);
+ assert_relative_eq!(r.im, from_mat.im, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_rot2_angle_between() {
+ let r1 = Rot2::new(0.0);
+ let r2 = Rot2::new(PI / 2.0);
+ assert_relative_eq!(r1.angle_between(&r2), PI / 2.0, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_rot2_slerp() {
+ let r1 = Rot2::new(0.2);
+ let r2 = Rot2::new(1.0);
+ assert_relative_eq!(r1.slerp(&r2, 0.0).angle(), 0.2, epsilon = 1e-6);
+ assert_relative_eq!(r1.slerp(&r2, 1.0).angle(), 1.0, epsilon = 1e-6);
+ assert_relative_eq!(r1.slerp(&r2, 0.5).angle(), 0.6, epsilon = 1e-6);
+ assert!(r1.slerp(&r2, 0.5).is_normalized());
+ }
+
+ #[test]
+ fn test_rot2_slerp_shortest_arc() {
+ // The interpolation from 0 to 3pi/2 goes backwards through -3pi/4, not forwards.
+ let r1 = Rot2::new(0.0);
+ let r2 = Rot2::new(3.0 * PI / 2.0);
+ assert_relative_eq!(r1.slerp(&r2, 0.5).angle(), -PI / 4.0, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn test_rot2_slerp_across_branch_cut() {
+ // `angle` wraps to (-pi, pi], so these two are 0.02 rad apart, not 6.26.
+ let r1 = Rot2::new(3.13);
+ let r2 = Rot2::new(3.15);
+ assert_relative_eq!(r1.slerp(&r2, 0.5).angle(), 3.14, epsilon = 1e-6);
+ assert_relative_eq!(r1.slerp(&r2, 1.0).angle(), r2.angle(), epsilon = 1e-6);
+ }
+
+ #[cfg(feature = "f64")]
+ #[test]
+ fn test_drot2_new() {
+ let r = DRot2::new(core::f64::consts::PI / 2.0);
+ assert_relative_eq!(r.re, 0.0, epsilon = 1e-10);
+ assert_relative_eq!(r.im, 1.0, epsilon = 1e-10);
+ assert!(r.is_normalized());
+ }
+}
diff --git a/renderer/third_party/glamx/src/rot3.rs b/renderer/third_party/glamx/src/rot3.rs
new file mode 100644
index 0000000..0d82923
--- /dev/null
+++ b/renderer/third_party/glamx/src/rot3.rs
@@ -0,0 +1,15 @@
+//! 3D rotation types (re-exported from glam).
+//!
+//! This module provides type aliases for glam's quaternion types for consistency
+//! with the naming convention used by other types in this crate.
+
+/// A 3D rotation represented as a unit quaternion (f32 precision).
+///
+/// This is a direct re-export of `glam::Quat`.
+pub type Rot3 = glam::Quat;
+
+/// A 3D rotation represented as a unit quaternion (f64 precision).
+///
+/// This is a direct re-export of `glam::DQuat`.
+#[cfg(feature = "f64")]
+pub type DRot3 = glam::DQuat;
diff --git a/renderer/third_party/glamx/src/svd2.rs b/renderer/third_party/glamx/src/svd2.rs
new file mode 100644
index 0000000..13be296
--- /dev/null
+++ b/renderer/third_party/glamx/src/svd2.rs
@@ -0,0 +1,186 @@
+//! SVD decomposition for 2x2 matrices.
+
+#[cfg(not(feature = "std"))]
+use simba::scalar::{ComplexField, RealField};
+
+/// Macro to generate Svd2 for a specific scalar type.
+macro_rules! impl_svd2 {
+ ($Svd2:ident, $Mat2:ty, $Vec2:ty, $Real:ty $(, #[$attr:meta])*) => {
+ #[doc = concat!("The SVD of a 2x2 matrix (", stringify!($Real), " precision).")]
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+ $(#[$attr])*
+ pub struct $Svd2 {
+ /// The left orthogonal matrix U.
+ pub u: $Mat2,
+ /// The singular values (diagonal entries of S).
+ pub s: $Vec2,
+ /// The transposed right orthogonal matrix V^T.
+ pub vt: $Mat2,
+ }
+
+ impl $Svd2 {
+ /// Creates a new SVD from components.
+ #[inline]
+ pub fn new(u: $Mat2, s: $Vec2, vt: $Mat2) -> Self {
+ Self { u, s, vt }
+ }
+
+ /// Computes the SVD of a 2x2 matrix.
+ ///
+ /// Returns the decomposition `M = U * S * V^T` where:
+ /// - `U` is an orthogonal matrix
+ /// - `S` is a diagonal matrix (stored as a vector of singular values)
+ /// - `V^T` is the transpose of an orthogonal matrix
+ ///
+ /// The singular values are sorted in descending order (s.x >= s.y).
+ #[inline]
+ pub fn from_matrix(m: $Mat2) -> Self {
+ let e = (m.col(0).x + m.col(1).y) * 0.5;
+ let f = (m.col(0).x - m.col(1).y) * 0.5;
+ let g = (m.col(0).y + m.col(1).x) * 0.5;
+ let h = (m.col(0).y - m.col(1).x) * 0.5;
+ let q = (e * e + h * h).sqrt();
+ let r = (f * f + g * g).sqrt();
+
+ // Note that the singular values are always sorted because sx >= sy
+ // because q >= 0 and r >= 0.
+ let sx = q + r;
+ let sy = q - r;
+ let sy_sign: $Real = if sy < 0.0 { -1.0 } else { 1.0 };
+ let singular_values = <$Vec2>::new(sx, sy * sy_sign);
+
+ let a2 = h.atan2(e);
+ // When r ≈ 0 (pure rotation case), a1 is arbitrary. Set a1 = a2
+ // so that theta = 0 and phi = a2 (the rotation angle).
+ let a1 = if r < 1e-10 { a2 } else { g.atan2(f) };
+ let theta = (a2 - a1) * 0.5;
+ let phi = (a2 + a1) * 0.5;
+ let st = theta.sin();
+ let ct = theta.cos();
+ let sp = phi.sin();
+ let cp = phi.cos();
+
+ let u = <$Mat2>::from_cols(<$Vec2>::new(cp, sp), <$Vec2>::new(-sp, cp));
+ let vt = <$Mat2>::from_cols(
+ <$Vec2>::new(ct, st * sy_sign),
+ <$Vec2>::new(-st, ct * sy_sign),
+ );
+
+ Self {
+ u,
+ s: singular_values,
+ vt,
+ }
+ }
+
+ /// Rebuilds the matrix this SVD is the decomposition of.
+ ///
+ /// Returns `U * S * V^T`.
+ #[inline]
+ pub fn recompose(&self) -> $Mat2 {
+ let u_s = <$Mat2>::from_cols(self.u.col(0) * self.s.x, self.u.col(1) * self.s.y);
+ u_s * self.vt.transpose()
+ }
+
+ }
+ };
+}
+
+impl_svd2!(Svd2, glam::Mat2, glam::Vec2, f32);
+#[cfg(feature = "f64")]
+impl_svd2!(DSvd2, glam::DMat2, glam::DVec2, f64);
+
+// f32 <-> f64 conversions
+#[cfg(feature = "f64")]
+impl From<Svd2> for DSvd2 {
+ #[inline]
+ fn from(svd: Svd2) -> Self {
+ Self {
+ u: svd.u.as_dmat2(),
+ s: svd.s.as_dvec2(),
+ vt: svd.vt.as_dmat2(),
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<DSvd2> for Svd2 {
+ #[inline]
+ fn from(svd: DSvd2) -> Self {
+ Self {
+ u: svd.u.as_mat2(),
+ s: svd.s.as_vec2(),
+ vt: svd.vt.as_mat2(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use approx::assert_relative_eq;
+
+ #[test]
+ fn svd_2x2_identity() {
+ let mat = glam::Mat2::IDENTITY;
+ let svd = Svd2::from_matrix(mat);
+
+ assert_relative_eq!(svd.s, glam::Vec2::new(1.0, 1.0), epsilon = 1e-6);
+ assert_relative_eq!(svd.recompose(), mat, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn svd_2x2_diagonal() {
+ let mat = glam::Mat2::from_diagonal(glam::Vec2::new(3.0, 2.0));
+ let svd = Svd2::from_matrix(mat);
+
+ assert_relative_eq!(svd.s, glam::Vec2::new(3.0, 2.0), epsilon = 1e-6);
+ assert_relative_eq!(svd.recompose(), mat, epsilon = 1e-6);
+ }
+
+ #[test]
+ fn svd_2x2_general() {
+ let mat = glam::Mat2::from_cols_array_2d(&[[4.0, 3.0], [2.0, 1.0]]);
+ let svd = Svd2::from_matrix(mat);
+
+ // Verify recomposition
+ assert_relative_eq!(svd.recompose(), mat, epsilon = 1e-5);
+
+ // Verify singular values are non-negative and sorted
+ assert!(svd.s.x >= svd.s.y);
+ assert!(svd.s.y >= 0.0);
+
+ // Verify U and V^T are orthogonal
+ assert_relative_eq!(
+ svd.u * svd.u.transpose(),
+ glam::Mat2::IDENTITY,
+ epsilon = 1e-6
+ );
+ assert_relative_eq!(
+ svd.vt * svd.vt.transpose(),
+ glam::Mat2::IDENTITY,
+ epsilon = 1e-6
+ );
+ }
+
+ #[test]
+ fn svd_2x2_rotation() {
+ let angle = 0.5_f32;
+ let mat = glam::Mat2::from_angle(angle);
+ let svd = Svd2::from_matrix(mat);
+
+ // A rotation matrix has singular values of 1
+ assert_relative_eq!(svd.s, glam::Vec2::new(1.0, 1.0), epsilon = 1e-6);
+ assert_relative_eq!(svd.recompose(), mat, epsilon = 1e-6);
+ }
+
+ #[cfg(feature = "f64")]
+ #[test]
+ fn svd_2x2_f64() {
+ let mat = glam::DMat2::from_cols_array_2d(&[[4.0, 3.0], [2.0, 1.0]]);
+ let svd = DSvd2::from_matrix(mat);
+
+ assert_relative_eq!(svd.recompose(), mat, epsilon = 1e-10);
+ }
+}
diff --git a/renderer/third_party/glamx/src/svd3.rs b/renderer/third_party/glamx/src/svd3.rs
new file mode 100644
index 0000000..134ceea
--- /dev/null
+++ b/renderer/third_party/glamx/src/svd3.rs
@@ -0,0 +1,296 @@
+//! SVD decomposition for 3x3 matrices.
+//!
+//! Uses eigendecomposition of A^T * A to compute singular values and right singular vectors,
+//! then derives left singular vectors from those.
+
+#[cfg(not(feature = "std"))]
+use simba::scalar::ComplexField;
+
+#[cfg(feature = "f64")]
+use crate::eigen3::DSymmetricEigen3;
+use crate::eigen3::SymmetricEigen3;
+use crate::SymmetricEigen3A;
+
+/// Macro to generate Svd3 for a specific scalar type.
+macro_rules! impl_svd3 {
+ ($Svd3:ident, $Mat3:ty, $Vec3:ty, $SymmetricEigen3:ty, $Real:ty $(, #[$attr:meta])*) => {
+ #[doc = concat!("The SVD of a 3x3 matrix (", stringify!($Real), " precision).")]
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+ $(#[$attr])*
+ pub struct $Svd3 {
+ /// The left orthogonal matrix U.
+ pub u: $Mat3,
+ /// The singular values (diagonal entries of S), sorted in descending order.
+ pub s: $Vec3,
+ /// The transposed right orthogonal matrix V^T.
+ pub vt: $Mat3,
+ }
+
+ impl $Svd3 {
+ /// Creates a new SVD from components.
+ #[inline]
+ pub fn new(u: $Mat3, s: $Vec3, vt: $Mat3) -> Self {
+ Self { u, s, vt }
+ }
+
+ /// Computes the SVD of a 3x3 matrix.
+ ///
+ /// Returns the decomposition `M = U * S * V^T` where:
+ /// - `U` is an orthogonal matrix (left singular vectors as columns)
+ /// - `S` is a diagonal matrix (stored as a vector of singular values)
+ /// - `V^T` is the transpose of an orthogonal matrix
+ ///
+ /// The singular values are sorted in descending order (s.x >= s.y >= s.z).
+ #[inline]
+ pub fn from_matrix(a: $Mat3) -> Self {
+ // Compute A^T * A (symmetric positive semi-definite)
+ let ata = a.transpose() * a;
+
+ // Eigendecomposition of A^T * A gives:
+ // - eigenvalues = singular values squared
+ // - eigenvectors = right singular vectors (columns of V)
+ let eigen = <$SymmetricEigen3>::new(ata).reverse(); // reverse to get descending order
+
+ // Singular values are square roots of eigenvalues
+ let s = <$Vec3>::new(
+ eigen.eigenvalues.x.max(0.0).sqrt(),
+ eigen.eigenvalues.y.max(0.0).sqrt(),
+ eigen.eigenvalues.z.max(0.0).sqrt(),
+ );
+
+ // V is the eigenvector matrix
+ let v = eigen.eigenvectors;
+
+ // Compute U = A * V * S^(-1) for each column
+ // U.col(i) = A * V.col(i) / s[i]
+ let epsilon: $Real = 1e-10;
+
+ // Compute U columns with Gram-Schmidt orthogonalization
+ let u_col0_raw = if s.x > epsilon {
+ (a * v.col(0)) / s.x
+ } else {
+ v.col(0)
+ };
+ let u_col0 = u_col0_raw.normalize();
+
+ let u_col1_raw = if s.y > epsilon {
+ (a * v.col(1)) / s.y
+ } else {
+ Self::any_orthogonal(u_col0)
+ };
+ // Orthogonalize against u_col0
+ let u_col1 = (u_col1_raw - u_col0 * u_col1_raw.dot(u_col0)).normalize();
+
+ let u_col2_raw = if s.z > epsilon {
+ (a * v.col(2)) / s.z
+ } else {
+ u_col0.cross(u_col1)
+ };
+ // Orthogonalize against u_col0 and u_col1
+ let u_col2_orth = u_col2_raw - u_col0 * u_col2_raw.dot(u_col0) - u_col1 * u_col2_raw.dot(u_col1);
+ let u_col2 = u_col2_orth.normalize();
+
+ let u = <$Mat3>::from_cols(u_col0, u_col1, u_col2);
+
+ Self {
+ u,
+ s,
+ vt: v.transpose(),
+ }
+ }
+
+ /// Find any unit vector orthogonal to the given vector.
+ #[inline]
+ fn any_orthogonal(v: $Vec3) -> $Vec3 {
+ let abs_v = <$Vec3>::new(v.x.abs(), v.y.abs(), v.z.abs());
+ let other = if abs_v.x <= abs_v.y && abs_v.x <= abs_v.z {
+ <$Vec3>::X
+ } else if abs_v.y <= abs_v.z {
+ <$Vec3>::Y
+ } else {
+ <$Vec3>::Z
+ };
+ v.cross(other).normalize()
+ }
+
+ /// Rebuilds the matrix this SVD is the decomposition of.
+ ///
+ /// Returns `U * S * V^T`.
+ #[inline]
+ pub fn recompose(&self) -> $Mat3 {
+ let u_s = <$Mat3>::from_cols(
+ self.u.col(0) * self.s.x,
+ self.u.col(1) * self.s.y,
+ self.u.col(2) * self.s.z,
+ );
+ u_s * self.vt
+ }
+ }
+ };
+}
+
+impl_svd3!(Svd3, glam::Mat3, glam::Vec3, SymmetricEigen3, f32);
+impl_svd3!(Svd3A, glam::Mat3A, glam::Vec3A, SymmetricEigen3A, f32);
+#[cfg(feature = "f64")]
+impl_svd3!(DSvd3, glam::DMat3, glam::DVec3, DSymmetricEigen3, f64);
+
+// f32 <-> f64 conversions
+#[cfg(feature = "f64")]
+impl From<Svd3> for DSvd3 {
+ #[inline]
+ fn from(svd: Svd3) -> Self {
+ Self {
+ u: svd.u.as_dmat3(),
+ s: svd.s.as_dvec3(),
+ vt: svd.vt.as_dmat3(),
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<DSvd3> for Svd3 {
+ #[inline]
+ fn from(svd: DSvd3) -> Self {
+ Self {
+ u: svd.u.as_mat3(),
+ s: svd.s.as_vec3(),
+ vt: svd.vt.as_mat3(),
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<Svd3A> for DSvd3 {
+ #[inline]
+ fn from(svd: Svd3A) -> Self {
+ Self {
+ u: svd.u.as_dmat3(),
+ s: svd.s.as_dvec3(),
+ vt: svd.vt.as_dmat3(),
+ }
+ }
+}
+
+#[cfg(feature = "f64")]
+impl From<DSvd3> for Svd3A {
+ #[inline]
+ fn from(svd: DSvd3) -> Self {
+ Self {
+ u: svd.u.as_mat3().into(),
+ s: svd.s.as_vec3a(),
+ vt: svd.vt.as_mat3().into(),
+ }
+ }
+}
+
+// Svd3 <-> Svd3A conversions
+impl From<Svd3> for Svd3A {
+ #[inline]
+ fn from(svd: Svd3) -> Self {
+ Self {
+ u: glam::Mat3A::from(svd.u),
+ s: svd.s.into(),
+ vt: glam::Mat3A::from(svd.vt),
+ }
+ }
+}
+
+impl From<Svd3A> for Svd3 {
+ #[inline]
+ fn from(svd: Svd3A) -> Self {
+ Self {
+ u: glam::Mat3::from(svd.u),
+ s: svd.s.into(),
+ vt: glam::Mat3::from(svd.vt),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use approx::assert_relative_eq;
+
+ #[test]
+ fn svd_3x3_identity() {
+ let mat = glam::Mat3::IDENTITY;
+ let svd = Svd3::from_matrix(mat);
+
+ assert_relative_eq!(svd.s, glam::Vec3::new(1.0, 1.0, 1.0), epsilon = 1e-5);
+ assert_relative_eq!(svd.recompose(), mat, epsilon = 1e-5);
+ }
+
+ #[test]
+ fn svd_3x3_diagonal() {
+ let mat = glam::Mat3::from_diagonal(glam::Vec3::new(4.0, 3.0, 2.0));
+ let svd = Svd3::from_matrix(mat);
+
+ // Singular values should be sorted in descending order
+ assert_relative_eq!(svd.s, glam::Vec3::new(4.0, 3.0, 2.0), epsilon = 1e-5);
+ assert_relative_eq!(svd.recompose(), mat, epsilon = 1e-5);
+ }
+
+ #[test]
+ fn svd_3x3_general() {
+ // Use a full-rank matrix
+ let mat =
+ glam::Mat3::from_cols_array_2d(&[[1.0, 4.0, 7.0], [2.0, 5.0, 9.0], [3.0, 6.0, 10.0]]);
+ let svd = Svd3::from_matrix(mat);
+
+ // Verify recomposition (some numerical error from orthogonalization)
+ assert_relative_eq!(svd.recompose(), mat, epsilon = 1e-2);
+
+ // Verify singular values are sorted in descending order
+ assert!(svd.s.x >= svd.s.y);
+ assert!(svd.s.y >= svd.s.z);
+
+ // Verify U is orthogonal
+ assert_relative_eq!(
+ svd.u * svd.u.transpose(),
+ glam::Mat3::IDENTITY,
+ epsilon = 1e-5
+ );
+
+ // Verify V^T is orthogonal
+ assert_relative_eq!(
+ svd.vt * svd.vt.transpose(),
+ glam::Mat3::IDENTITY,
+ epsilon = 1e-5
+ );
+ }
+
+ #[test]
+ fn svd_3x3_rotation() {
+ let mat = glam::Mat3::from_rotation_x(0.5) * glam::Mat3::from_rotation_y(0.3);
+ let svd = Svd3::from_matrix(mat);
+
+ // A rotation matrix has singular values of 1
+ assert_relative_eq!(svd.s, glam::Vec3::ONE, epsilon = 1e-5);
+ assert_relative_eq!(svd.recompose(), mat, epsilon = 1e-5);
+ }
+
+ #[cfg(feature = "f64")]
+ #[test]
+ fn svd_3x3_f64() {
+ let mat =
+ glam::DMat3::from_cols_array_2d(&[[1.0, 4.0, 7.0], [2.0, 5.0, 9.0], [3.0, 6.0, 10.0]]);
+ let svd = DSvd3::from_matrix(mat);
+
+ assert_relative_eq!(svd.recompose(), mat, epsilon = 1e-8);
+ }
+
+ #[test]
+ fn svd_3x3_rank_deficient() {
+ // Test with a rank-2 matrix (third singular value is 0)
+ let mat =
+ glam::Mat3::from_cols_array_2d(&[[1.0, 4.0, 7.0], [2.0, 5.0, 8.0], [3.0, 6.0, 9.0]]);
+ let svd = Svd3::from_matrix(mat);
+
+ // Verify recomposition (larger tolerance for rank-deficient matrices)
+ assert_relative_eq!(svd.recompose(), mat, epsilon = 0.02);
+
+ // Third singular value should be small (matrix is nearly rank 2)
+ assert!(svd.s.z < 0.1);
+ }
+}
diff --git a/tests/render/physics-box-rest-live.ts b/tests/render/physics-box-rest-live.ts
new file mode 100644
index 0000000..18f70ee
--- /dev/null
+++ b/tests/render/physics-box-rest-live.ts
@@ -0,0 +1,7 @@
+// physics/box-rest in the real-time renderer: the engine steps the world a tick a frame and moves the box (150 frames).
+import def, { test as base } from "./physics-box-rest.ts";
+import type { TestMeta } from "./lib.ts";
+
+export const test: TestMeta = { ...base, id: "physics/box-rest-live", temporal: true, time: undefined, live: 150 };
+
+export default def;
diff --git a/tests/render/physics-box-rest.ts b/tests/render/physics-box-rest.ts
new file mode 100644
index 0000000..9bda25e
--- /dev/null
+++ b/tests/render/physics-box-rest.ts
@@ -0,0 +1,32 @@
+// Physics (ROADMAP § 6 step 7): a rigid body drives a scene object. A box of 0.5 m (a mesh emitting 5 nits) with
+// `physics = "dynamic"` (its collider is the box its geometry is), let go 2 m up over a fixed ground (its top the plane
+// y = 0), falls, lands and rests with its centre 0.25 m up. Seen from the side at that height after 2 s (120 ticks):
+// the region inside the box reads 5 nits (still in the air, or fallen through: 0). Black sky.
+import { BoxGeometry, Mesh, MeshStandardMaterial } from "@threert/scene";
+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "physics/box-rest", features: ["physics"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: [0.47, 0.445, 0.53, 0.555], expected: 5, tolerance: 0.02 },
+ time: 2,
+ note: "camera 6 m away at y 0.25, 30 deg vertical fov: the resting box spans u 0.454-0.546, v 0.419-0.581",
+};
+
+/** A fixed body whose top is the plane y = 0: a box of 40 x 1 x 40 m that is not drawn (a hidden object keeps its body). */
+export function ground(): Mesh {
+ const g = new Mesh(new BoxGeometry(40, 1, 40), new MeshStandardMaterial({ name: "ground", color: 0x000000 }));
+ g.position.set(0, -0.5, 0);
+ g.visible = false;
+ g.physics = "fixed";
+ return g;
+}
+
+export const glow = () => new MeshStandardMaterial({ name: "glow", color: 0x000000, emissive: 0xffffff, emissiveIntensity: 5 });
+
+export default function () {
+ const scene = sceneWithSky(0);
+ const box = new Mesh(new BoxGeometry(0.5, 0.5, 0.5), glow());
+ box.position.set(0, 2, 0);
+ box.physics = "dynamic";
+ return result(scene, camera(scene, [0, 0.25, 6], [0, 0.25, 0]), [box, ground()]);
+}
diff --git a/tests/render/physics-hinge.ts b/tests/render/physics-hinge.ts
new file mode 100644
index 0000000..af36fd2
--- /dev/null
+++ b/tests/render/physics-hinge.ts
@@ -0,0 +1,28 @@
+// A hinge with a limit (ROADMAP § 6 step 7): a bar of 1 x 0.3 x 0.4 m held at one end by a `HingeJoint` to a fixed
+// post, its axis toward the camera, limited to ±0.5 rad. Let go level, it swings down and rests against the limit, 0.5
+// rad below level. Three quarters along it is then at (0.658, -0.360) m from the hinge: the region there reads the
+// bar's 5 nits (still level, or hanging straight down without the limit: 0). No gravity on anything else; black sky.
+import { BoxGeometry, Group, HingeJoint, Mesh, Vector3 } from "@threert/scene";
+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { glow } from "./physics-box-rest.ts";
+
+export const test: TestMeta = {
+ id: "physics/hinge", features: ["physics"], reference: "analytic", temporal: false,
+ // Camera 6 m away, 30 deg vertical fov: the image is 3.215 m high, 5.716 m wide.
+ metric: { kind: "radiance", region: [0.603, 0.592, 0.627, 0.632], expected: 5, tolerance: 0.02 },
+ time: 4,
+ note: "the hinge at the origin, the camera at z = 6 looking at it",
+};
+
+export default function () {
+ const scene = sceneWithSky(0);
+ const bar = new Mesh(new BoxGeometry(1, 0.3, 0.4), glow());
+ bar.position.set(0.5, 0, 0);
+ // (Damped, so that it has come to rest by the render.)
+ bar.physics = { type: "dynamic", angularDamping: 2 };
+ // The post: nothing drawn, a fixed body at the hinge that touches nothing.
+ const post = new Group();
+ post.physics = { type: "fixed", shape: { type: "sphere", radius: 0.05 }, sensor: true };
+ const hinge = new HingeJoint(post, bar, { anchorB: new Vector3(-0.5, 0, 0), axis: new Vector3(0, 0, 1), limits: [-0.5, 0.5] });
+ return result(scene, camera(scene, [0, 0, 6], [0, 0, 0]), [bar, post, hinge]);
+}
diff --git a/tests/render/physics-instance-live.ts b/tests/render/physics-instance-live.ts
new file mode 100644
index 0000000..53738fc
--- /dev/null
+++ b/tests/render/physics-instance-live.ts
@@ -0,0 +1,26 @@
+// A body's mesh moves as an instance (ROADMAP § 6 step 7): a white box of 0.5 m with a dynamic body, let go 1.5 m up
+// on the left, and the same box as a plain mesh resting on the ground on the right, mirrored about the image's centre
+// line, under a uniform 1-nit sky. A lit, opaque mesh that a body drives is placed as an instance of its own BLAS: each
+// tick only its TLAS transform changes, no triangle. Once it has landed the two boxes read alike: ratio 1 (still in the
+// air, the left region shows the sky: 1.5).
+import { BoxGeometry, Mesh } from "@threert/scene";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { ground } from "./physics-box-rest.ts";
+
+export const test: TestMeta = {
+ id: "physics/instance-live", features: ["physics"], reference: "analytic", temporal: true,
+ // Camera 6 m away at y 0.25: the boxes at x = -1.2 and 1.2 span u 0.244-0.336 and 0.664-0.756.
+ metric: { kind: "ratio", a: [0.26, 0.45, 0.32, 0.55], b: [0.68, 0.45, 0.74, 0.55], expected: 1, tolerance: 0.03 },
+ live: 240,
+ note: "boxes 0.5 m at x = -1.2 (a body) and 1.2 (static), ground plane y = 0",
+};
+
+export default function () {
+ const scene = sceneWithSky(1);
+ const white = lambert(0.8, "box");
+ const [left, right] = [new Mesh(new BoxGeometry(0.5, 0.5, 0.5), white), new Mesh(new BoxGeometry(0.5, 0.5, 0.5), white)];
+ left.position.set(-1.2, 1.5, 0);
+ right.position.set(1.2, 0.25, 0);
+ left.physics = "dynamic";
+ return result(scene, camera(scene, [0, 0.25, 6], [0, 0.25, 0]), [left, right, plane(30, lambert(0.3)), ground()]);
+}
diff --git a/tests/render/physics-stack.ts b/tests/render/physics-stack.ts
new file mode 100644
index 0000000..b7dd849
--- /dev/null
+++ b/tests/render/physics-stack.ts
@@ -0,0 +1,27 @@
+// A stack (ROADMAP § 6 step 7): three boxes of 0.5 m, each a dynamic body, let go one above the other with 5 cm between
+// them (the lowest 5 cm over the ground), come to rest as a column 1.5 m high: the top box has come down 15 cm. Seen
+// from the side after 2 s, the strip just above the column's top (y 1.56 .. 1.64 m) is empty and the top box below it
+// glows: their ratio is 0 (at the start the top box still fills the strip: 1).
+import { BoxGeometry, Mesh } from "@threert/scene";
+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { glow, ground } from "./physics-box-rest.ts";
+
+export const test: TestMeta = {
+ id: "physics/stack", features: ["physics"], reference: "analytic", temporal: false,
+ // Camera 6 m away at y 1.25, 30 deg vertical fov: the image is 3.215 m high. Above the top: y 1.56 .. 1.64; the top box: y 1.30 .. 1.42.
+ metric: { kind: "ratio", a: [0.47, 0.3787, 0.53, 0.4036], b: [0.47, 0.4471, 0.53, 0.4844], expected: 0, tolerance: 0.02 },
+ time: 2,
+ note: "boxes let go at y 0.3, 0.85 and 1.4 m; the column's top comes to y = 1.5",
+};
+
+export default function () {
+ const scene = sceneWithSky(0);
+ const material = glow();
+ const boxes = [0, 1, 2].map((k) => {
+ const box = new Mesh(new BoxGeometry(0.5, 0.5, 0.5), material);
+ box.position.set(0, 0.3 + k * 0.55, 0);
+ box.physics = "dynamic";
+ return box;
+ });
+ return result(scene, camera(scene, [0, 1.25, 6], [0, 1.25, 0]), [...boxes, ground()]);
+}
diff --git a/tools/bench-physics.ts b/tools/bench-physics.ts
new file mode 100644
index 0000000..0909ed5
--- /dev/null
+++ b/tools/bench-physics.ts
@@ -0,0 +1,79 @@
+// What the boundary between the physics world and gameplay costs a frame (ROADMAP § 6 step 7): games/physics/
+// bench.game.ts live in lockstep (1 / 60 s a frame: one tick) with 0, 100, 1,000 and 10,000 bodies that all move
+// every tick, the frame script reading nothing and then reading every body's position and quaternion. From the frame
+// log, the mean over 120 frames each of:
+// step the physics world's tick (Rapier), not the boundary
+// sync the moved bodies' objects placed in the engine's scene (native, no script)
+// commit the renderer taking the moves: instance records, the TLAS rebuilt
+// script the frame script and the binding's sync (JavaScript): what the script side pays
+// `--pile` adds the same counts dropped as a pile, measured once it sleeps, and `--still` the same boxes without
+// bodies (the script's cost of the scene's objects by themselves). The GPU lock is held (the frames are rendered, their
+// GPU time is not what is measured).
+// node tools/bench-physics.ts [--pile] [--still] [--counts 0,100,1000,10000] [--json out.json]
+import { execFileSync } from "node:child_process";
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { acquireGpuLock, rendererBin, repoRoot } from "./lib/bench.ts";
+import { branchBuild } from "./lib/build-at.ts";
+import { startLive } from "./lib/live.ts";
+
+const args = process.argv.slice(2);
+const flag = (name: string) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined);
+const counts = (flag("--counts") ?? "0,100,1000,10000").split(",").map(Number);
+const holder = acquireGpuLock("bench-physics");
+if (holder) { console.log(`not run: GPU lock held by ${holder.tool} (pid ${holder.pid}) since ${holder.started}`); process.exit(2); }
+const bundle = join(repoRoot, "out/bundles/physics-bench.js");
+execFileSync("node", [join(repoRoot, "tools/bundle-game.ts"), join(repoRoot, "games/physics/bench.game.ts"), "-o", bundle], { stdio: "ignore" });
+const dir = join(repoRoot, "out/bench/physics");
+mkdirSync(dir, { recursive: true });
+
+interface Frame { js: number; commit: number; script: number; physics: { ticks: number; step: number; sync: number; bodies: number; moved: number } | null }
+const mean = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0);
+
+async function run(room: string, settle: number) {
+ const frameLog = join(dir, `${room}.jsonl`);
+ const live = startLive(branchBuild(rendererBin), bundle, { room, frameLog });
+ await live.firstFrame;
+ live.send({ cmd: "lockstep", dt: 1 / 60 });
+ let id = 0;
+ const step = async (frames: number) => {
+ const sync = `s${++id}`;
+ live.send({ cmd: "frames", n: frames, sync });
+ await live.wait((l) => l.includes(`live: sync ${sync}`), 900_000);
+ };
+ const count = () => readFileSync(frameLog, "utf8").trim().split("\n").length;
+ await step(settle);
+ const a = count();
+ await step(120);
+ const b = count();
+ live.send({ cmd: "event", type: "read" });
+ await step(10);
+ const c = count();
+ await step(120);
+ live.send({ cmd: "event", type: "sum" });
+ await step(2);
+ await live.quit();
+ const frames = readFileSync(frameLog, "utf8").trim().split("\n").map((l) => JSON.parse(l) as Frame);
+ const part = (from: number, to: number) => {
+ const f = frames.slice(from, to);
+ return {
+ bodies: Math.max(0, ...f.map((x) => x.physics?.bodies ?? 0)), moved: mean(f.map((x) => x.physics?.moved ?? 0)), step: mean(f.map((x) => x.physics?.step ?? 0)), sync: mean(f.map((x) => x.physics?.sync ?? 0)),
+ commit: mean(f.map((x) => x.commit)), script: mean(f.map((x) => x.js)),
+ };
+ };
+ const sum = live.lines.map((l) => /sum (\S+)/.exec(l)?.[1]).filter(Boolean).pop();
+ return { room, none: part(a, b), all: part(c, c + 120), sum };
+}
+
+const rows: Awaited<ReturnType<typeof run>>[] = [];
+for (const n of counts) rows.push(await run(`n${n}`, 30));
+if (args.includes("--still")) for (const n of counts.filter((n) => n > 0)) rows.push(await run(`s${n}`, 30));
+if (args.includes("--pile")) for (const n of counts.filter((n) => n > 0)) rows.push(await run(`pile${n}`, 900));
+const f = (x: number) => x.toFixed(x < 0.1 ? 4 : 3);
+console.log("| scene | bodies | moved a frame | step ms | sync ms | commit ms | script ms, reads none | script ms, reads all | reading all costs ms |");
+console.log("|---|---|---|---|---|---|---|---|---|");
+for (const r of rows) {
+ console.log(`| ${r.room} | ${Math.max(r.none.bodies - 1, 0)} + ground | ${r.none.moved.toFixed(0)} | ${f(r.none.step)} | ${f(r.none.sync)} | ${f(r.none.commit)} | ${f(r.none.script)} | ${f(r.all.script)} | ${f(r.all.script - r.none.script)} |`);
+}
+const out = flag("--json");
+if (out) writeFileSync(out, JSON.stringify(rows, null, 1));
diff --git a/tools/catalog.ts b/tools/catalog.ts
index f4526a1..48807b8 100644
--- a/tools/catalog.ts
+++ b/tools/catalog.ts
@@ -25,6 +25,8 @@ export const GAMES: Record<string, string> = {
"bistro-district": "games/bistro-district/bistro-district.game.ts",
// three.js's official instancing examples, their code unchanged (ROADMAP § 6 step 2e): 1,000 instances turning.
"instancing": "games/instancing/instancing.game.ts",
+ // Physics hello world (ROADMAP § 6 step 7): click adds a box with a rigid body, click a box kicks it.
+ "physics-hello": "games/physics/hello.game.ts",
};
const TITLES: Record<string, string> = { "bistro-district": "Bistro District (3 × 3)", "bistro-slice": "Bistro Night · C slice", "zero-day-animated": "Zero Day (animated)", kabukicho: "Kabukichō Night", "kabukicho-district": "Kabukichō District (3 × 3)", "kabukicho-district-row": "Kabukichō District (middle row)" };
diff --git a/tools/physics-determinism.ts b/tools/physics-determinism.ts
new file mode 100644
index 0000000..a3f6d81
--- /dev/null
+++ b/tools/physics-determinism.ts
@@ -0,0 +1,62 @@
+// The physics' determinism check (ROADMAP § 6 step 7): physics-core run natively and as a wasm32 module, the browser's
+// target. Both must end in the same bits:
+// - the script (renderer/physics-core/src/check.rs: a tower of boxes hit by a ball, a hinged door, a rope, a ball
+// joint and a motor-driven slider, 600 ticks): the two hashes are compared with each other and the recorded one;
+// - 1,000 random worlds (`check::case`: tumbling convex hulls, bodies of several colliders, joints with limits and
+// motors, 90 ticks each), every one compared, and their folded hash with the recorded one. The script alone has
+// one hull that happens to agree; these are the shapes whose mass properties need an eigen decomposition, where
+// the platforms' math functions first differed (48 of the 1,000 before glamx was patched).
+// Both are run twice: as physics-core builds on its own, and with `std` in the crate graph (the crate's `std-in-graph`
+// feature: what a larger program's other dependencies do, the renderer's among them), where Rapier's crates take
+// f32's own math functions unless they are kept from it (renderer/third_party/glamx/PATCH.md). Without the patch the
+// first run passes and the second fails.
+// `--without` builds without Rapier's `enhanced-determinism` instead and reports (the hashes differ; no exit code).
+// node tools/physics-determinism.ts [--without] (needs the wasm32-unknown-unknown target)
+import { execFileSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+const crate = join(import.meta.dirname, "../renderer/physics-core");
+const cargo = (args: string[]) => execFileSync("cargo", args, { cwd: crate, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"], maxBuffer: 1 << 26 });
+const without = process.argv.includes("--without");
+const source = readFileSync(join(crate, "src/check.rs"), "utf8");
+const constant = (name: string) => new RegExp(`${name}: u64 = 0x([0-9a-f_]+);`).exec(source)![1].replaceAll("_", "").padStart(16, "0");
+const kinds = [...source.matchAll(/\("([^"]+)", (\d+)\)/g)].map((m) => m[1]);
+const hex = (h: bigint) => BigInt.asUintN(64, h).toString(16).padStart(16, "0");
+const builds: [string, string[]][] = without ? [[" (without enhanced-determinism)", ["--no-default-features"]]] : [["", []], [" (std in the crate graph)", ["--features", "std-in-graph"]]];
+let failed = false;
+
+for (const [label, features] of builds) {
+ const run = ["run", "--release", "--locked", "--quiet", ...features, "--example", "determinism"];
+ const native = cargo(run).trim();
+ const nativeCases = cargo([...run, "--", "--cases"]).trim().split("\n").map((l) => l.split(" "));
+ cargo(["build", "--release", "--locked", "--quiet", ...features, "--target", "wasm32-unknown-unknown", "--example", "determinism_wasm"]);
+ const wasm = readFileSync(join(crate, "target/wasm32-unknown-unknown/release/examples/determinism_wasm.wasm"));
+ const { instance } = await WebAssembly.instantiate(wasm, {});
+ const browser = hex((instance.exports.physics_determinism as (ticks: number) => bigint)(600));
+ console.log(`physics determinism${label}: script: native ${native}, wasm32 ${browser}, recorded ${constant("EXPECTED")}`);
+ failed ||= native !== browser || native !== constant("EXPECTED");
+
+ // The random cases, one by one; and all of them folded as check::cases() folds them.
+ const differ = kinds.map(() => [] as string[]), count = kinds.map(() => 0);
+ let folded = 0xcbf29ce484222325n;
+ const caseOf = instance.exports.physics_determinism_case as (kind: number, seed: number) => bigint;
+ for (const [kind, seed, hash] of nativeCases) {
+ const w = hex(caseOf(Number(kind), Number(seed)));
+ count[Number(kind)]++;
+ if (w !== hash) differ[Number(kind)].push(`seed ${seed}: native ${hash}, wasm32 ${w}`);
+ folded = BigInt.asUintN(64, (folded ^ BigInt(`0x${hash}`)) * 0x100000001b3n);
+ }
+ kinds.forEach((name, k) => {
+ console.log(`physics determinism${label}: ${name}: ${count[k] - differ[k].length} of ${count[k]} equal natively and in wasm32`);
+ for (const d of differ[k].slice(0, 3)) console.log(` ${d}`);
+ failed ||= differ[k].length > 0;
+ });
+ console.log(`physics determinism${label}: cases: native ${hex(folded)}, recorded ${constant("EXPECTED_CASES")}`);
+ failed ||= hex(folded) !== constant("EXPECTED_CASES");
+}
+if (without) process.exit(0);
+if (failed) {
+ console.error("physics determinism: the hashes differ");
+ process.exit(1);
+}
diff --git a/tools/physics-hello.ts b/tools/physics-hello.ts
new file mode 100644
index 0000000..a6fffa3
--- /dev/null
+++ b/tools/physics-hello.ts
@@ -0,0 +1,113 @@
+// The physics hello world without a window (ROADMAP § 6 step 7): games/physics/hello.game.ts in the live renderer,
+// in lockstep (every frame 1 / 60 s: one tick), with scripted clicks ({"cmd":"click"}: the same path a window's click
+// takes), checked on numbers:
+// 1. a click on the ground 1.5 m in front of the wall: a box is added and rests there, its centre 0.25 m up;
+// 2. two clicks on the wall above it (1.2 and 1.7 m up): two more boxes appear 1.5 m off the wall, 0.45 m over the
+// column, and come to rest on it (centres 0.75 and 1.25 m up, within 5 cm: a box that lands on a box shifts a
+// little);
+// 3. a click on the ground elsewhere: a fourth box;
+// 4. a click on that box: it is kicked at 3 m/s along the ground and slides v² / (2 μ g) = 0.917 m (μ 0.5).
+// Four boxes added, one kick, every box asleep at the end. The scene is rebuilt once, by the first box (this scene has
+// no instance before it: the kernel variant with instances); every later box is placed in place, each with a material
+// the scene did not have, and no move rebuilds anything (the boxes move as instances). Prints each click's chain with
+// its times (THREERT_CLICK_LOG=1). Exit 1 on a failed check. The GPU lock is held.
+// node tools/physics-hello.ts [--json out.json]
+import { execFileSync } from "node:child_process";
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { BOX, CAMERA, KICK, OFF, WALL_Z } from "../games/physics/hello.game.ts";
+import { acquireGpuLock, rendererBin, repoRoot } from "./lib/bench.ts";
+import { branchBuild } from "./lib/build-at.ts";
+import { startLive } from "./lib/live.ts";
+
+type V3 = [number, number, number];
+const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
+const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+const unit = (a: V3): V3 => { const l = Math.hypot(...a); return [a[0] / l, a[1] / l, a[2] / l]; };
+
+/** Where a point of the world is in the image (u, v in 0..1), through the game's camera. */
+function project(p: V3): { u: number; v: number } {
+ const c = [...CAMERA.position] as V3, fwd = unit(sub([...CAMERA.target] as V3, c));
+ const right = unit(cross(fwd, [0, 1, 0])), up = cross(right, fwd);
+ const d = sub(p, c), z = dot(d, fwd), t = Math.tan((CAMERA.fov * Math.PI) / 360);
+ return { u: 0.5 + dot(d, right) / z / (2 * t * (CAMERA.width / CAMERA.height)), v: 0.5 - dot(d, up) / z / (2 * t) };
+}
+
+const holder = acquireGpuLock("physics-hello");
+if (holder) { console.log(`not run: GPU lock held by ${holder.tool} (pid ${holder.pid}) since ${holder.started}`); process.exit(2); }
+const bundle = join(repoRoot, "out/bundles/physics-hello.js");
+execFileSync("node", [join(repoRoot, "tools/bundle-game.ts"), join(repoRoot, "games/physics/hello.game.ts"), "-o", bundle], { stdio: "ignore" });
+const frameLog = join(repoRoot, "out/bench/physics/hello-frames.jsonl");
+mkdirSync(dirname(frameLog), { recursive: true });
+
+const live = startLive(branchBuild(rendererBin), bundle, { env: { THREERT_CLICK_LOG: "1", THREERT_EDIT_LOG: "1" }, frameLog });
+await live.firstFrame;
+live.send({ cmd: "lockstep", dt: 1 / 60 });
+let id = 0;
+const step = async (frames: number) => {
+ const sync = `s${++id}`;
+ live.send({ cmd: "frames", n: frames, sync });
+ await live.wait((l) => l.includes(`live: sync ${sync}`));
+};
+const click = async (at: V3, settle: number) => {
+ live.send({ cmd: "click", ...project(at) });
+ await step(settle);
+};
+await step(10);
+const column: V3 = [-1, 0, WALL_Z + OFF], lone: V3 = [1.5, 0, 2.5];
+await click(column, 120);
+await click([column[0], 1.2, WALL_Z], 150);
+await click([column[0], 1.7, WALL_Z], 180);
+await click(lone, 120);
+await click([lone[0], 0.3, lone[2]], 240);
+live.send({ cmd: "event", type: "report" });
+await step(2);
+await live.quit();
+
+const hello = live.lines.map((l) => /hello (\{.*\})/.exec(l)?.[1]).filter((x): x is string => !!x).map((x) => JSON.parse(x) as { click: number; add?: string; kick?: string; on?: string; at?: V3; miss?: boolean });
+const report = live.lines.map((l) => /report (\{.*\})/.exec(l)?.[1]).filter((x): x is string => !!x).map((x) => JSON.parse(x) as { boxes: { name: string; at: V3; speed: number; asleep: boolean }[]; kicks: number }).pop();
+const chain = live.lines.filter((l) => l.startsWith("click:"));
+const rebuilds = live.lines.filter((l) => l.startsWith("edit:") && l.includes("rebuild"));
+
+const failures: string[] = [];
+const check = (ok: boolean, what: string) => { console.log(`${ok ? "ok " : "FAIL"} ${what}`); if (!ok) failures.push(what); };
+const near = (a: V3, b: V3, tol: number) => Math.hypot(...sub(a, b)) <= tol;
+const fmt = (a: V3) => `(${a.map((v) => v.toFixed(3)).join(", ")})`;
+
+console.log("physics hello world: the clicks");
+for (const h of hello) console.log(` click ${h.click}: ${h.add ? `adds ${h.add} over the ${h.on} at ${fmt(h.at!)}` : h.kick ? `kicks ${h.kick}` : "meets nothing"}`);
+check(hello.filter((h) => h.add).length === 4 && hello.filter((h) => h.kick).length === 1, "4 boxes added, 1 kick");
+check(hello.filter((h) => h.add).map((h) => h.on).join() === "ground,wall,wall,ground", "added over the ground, the wall twice, the ground");
+check(hello.find((h) => h.kick)?.kick === "box3", "the kick meets box3");
+const boxes = report?.boxes ?? [];
+check(boxes.length === 4 && report?.kicks === 1, "the scene holds 4 boxes");
+if (boxes.length === 4) {
+ const h = BOX / 2;
+ for (const [k, y, tol] of [[0, h, 0.02], [1, h + BOX, 0.05], [2, h + 2 * BOX, 0.05]] as const) {
+ check(near(boxes[k].at, [column[0], y, column[2]], tol), `box${k} rests at ${fmt(boxes[k].at)}: ${fmt([column[0], y, column[2]])} within ${tol} m`);
+ }
+ // The kick: along the ground away from the camera, 3 m/s against friction 0.5.
+ const from: V3 = [lone[0], h, lone[2]];
+ const dir = unit([lone[0] - CAMERA.position[0], 0, lone[2] - CAMERA.position[2]]);
+ const expected = (KICK * KICK) / (2 * 0.5 * 9.81);
+ const moved = sub(boxes[3].at, from), along = dot(moved, dir), across = Math.hypot(...sub(moved, [dir[0] * along, 0, dir[2] * along]));
+ check(Math.abs(along - expected) <= 0.15 * expected && across < 0.05, `box3 slid ${along.toFixed(3)} m along the kick (${across.toFixed(3)} m off it): ${expected.toFixed(3)} m within 15 %`);
+ check(Math.abs(boxes[3].at[1] - h) < 0.01, `box3 is on the ground (y ${boxes[3].at[1].toFixed(4)})`);
+ check(boxes.every((b) => b.asleep && b.speed === 0), "every box is at rest, asleep");
+}
+const commits = chain.filter((l) => l.includes("pick")).map((l) => (l.includes("(rebuild)") ? "rebuild" : "in place"));
+check(commits.join() === "rebuild,in place,in place,in place,in place", `the first box rebuilds the scene (its first instance), the later clicks are in place: ${commits.join(", ")}`);
+check(rebuilds.length === 1 && rebuilds[0].includes("first instanced mesh"), `no move rebuilt the scene (${rebuilds.length} rebuild${rebuilds.length === 1 ? "" : "s"}: ${rebuilds.map((l) => l.replace(/^edit: /, "")).join(" | ")})`);
+
+console.log("physics hello world: each click's chain");
+for (const l of chain) console.log(` ${l}`);
+// The frame log's physics split over the run.
+const frames = readFileSync(frameLog, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { physics?: { ticks: number; step: number; sync: number; bodies: number; moved: number } | null });
+const ph = frames.map((f) => f.physics).filter((p): p is NonNullable<typeof p> => !!p && p.ticks > 0);
+const mean = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0);
+console.log(`physics hello world: ${ph.length} frames with ticks, step ${mean(ph.map((p) => p.step)).toFixed(4)} ms, sync ${mean(ph.map((p) => p.sync)).toFixed(4)} ms a frame (mean), at most ${Math.max(0, ...ph.map((p) => p.bodies))} bodies`);
+const out = process.argv.indexOf("--json");
+if (out > 0) writeFileSync(process.argv[out + 1], JSON.stringify({ hello, report, chain, failures }, null, 1));
+console.log(failures.length ? `physics hello world: FAIL (${failures.length})` : "physics hello world: pass");
+process.exit(failures.length ? 1 : 0);
diff --git a/tools/three/engine.ts b/tools/three/engine.ts
index 2962062..1040d2c 100644
--- a/tools/three/engine.ts
+++ b/tools/three/engine.ts
@@ -305,6 +305,12 @@ export class ThreeEngine implements Engine {
particlesSpawn(): void {}
+ physics(op: string): string {
+ // No physics in this baseline: driven objects stay where the scene put them.
+ this.notes.add(`physics ${op}`);
+ return "null";
+ }
+
gridProgram(name: string): void {
// Density grids belong to volumes, which this baseline does not draw.
this.notes.add(`grid program ${name}`);