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.

Voxel bodies (ROADMAP § 6 step 8): the level collides, loose parts are rigid bodies (#24)

Yujia683f3722f9a1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 75810e1..46139d2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -58,8 +58,10 @@ jobs:
# voxel-core and its determinism check.
job voxel '^(renderer/voxel-core/|tools/voxel-determinism\.ts$)'
# physics-core, the patched crates it builds with, its determinism check, and what that check builds of the
- # renderer for wasm32 (examples/physics_bits.rs, in the renderer's crate graph: its manifest and lock file).
- job physics '^(renderer/(physics-core/|third_party/|Cargo\.toml$|Cargo\.lock$|examples/physics_bits\.rs$)|tools/physics-determinism\.ts$)'
+ # renderer for wasm32 (examples/physics_bits.rs, in the renderer's crate graph: its manifest and lock file;
+ # the voxel bodies' script it runs there: voxel-core, the renderer's voxel and physics adapters, and the api
+ # and world they go through).
+ job physics '^(renderer/(physics-core/|voxel-core/|third_party/|Cargo\.toml$|Cargo\.lock$|examples/physics_bits\.rs$|src/(voxel|physics|api|world)\.rs$)|tools/physics-determinism\.ts$)'
# The engine's library for wasm32: the same as the renderer's.
job wasm '^(renderer/|presets/)' '^renderer/web/'
# The browser module (renderer/web, on the engine's library) and tools/web-engine.ts: the module in Node with
@@ -92,6 +94,14 @@ jobs:
with:
workspaces: renderer
- run: cd renderer && cargo build --release --locked
+ # The voxel bodies and the physics on the CPU, through the engine's own path (ROADMAP § 6 step 8), on the
+ # physics' own threads as the renderer steps (src/physics.rs `in_pool`; tools/physics-determinism.ts steps from
+ # outside any pool, which is not that path): the recorded hashes at 2 and 4 threads (native parallel = native
+ # sequential = wasm32 = recorded), then 10 runs of a fuzz of edits and calls with its checks and a small world
+ # stepped back to back a million times, which is where the step hung. A step that does not return in 30 s fails
+ # the job (the example's watchdog), it is not waited for.
+ - run: cd renderer && THREERT_PHYSICS_THREADS=2 cargo run --release --locked --example physics_fuzz -- --bits --runs 0 --stress 0
+ - run: cd renderer && THREERT_PHYSICS_THREADS=4 cargo run --release --locked --example physics_fuzz -- --bits --runs 10 --stress 1000000
voxel:
name: "voxel: wasm32, tests, determinism"
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index c809e29..430905a 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -4048,9 +4048,180 @@ benchmark level. The order follows the dependencies; a step that meets a further
- Bodies at rest on one another have no GPU number (no game makes a pile yet): step 8's first measurement.
- Under software traversal a rigid group's pose still rebuilds the scene every frame (`zero-day-animated`:
2.6 s a frame), as before step 7b.
-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.
+8. **[engine] Voxel bodies.** The level collides, and what an edit leaves hanging on nothing is a rigid body (it
+ replaces step 6's fall through the lattice). Native first: the acceptance is under hardware traversal; software
+ traversal has to work (bodies are units, no rebuild) and gets one set of figures; a browser is not part of this
+ step. Design: docs/VOXEL.md "Voxel bodies"; docs/RUNTIME.md "Physics" (the voxel shape, the engine's own bodies).
+ - Scope:
+ - **The collision shape**, on step 7's `Shape`: parry's `Voxels`, for the level's objects (fixed) and for the
+ loose parts (moving), chosen against a compound of boxes, a triangle mesh and a convex hull by measurement.
+ - **The level collides by default**: every object a fixed collider of its voxels, edited by the cells an edit
+ cleared; rays and shape casts of the physics world meet it. `physics: false` on the level is step 6 as it
+ was; `collide: false` on an object leaves it out. Ordinary meshes still declare `physics`.
+ - **Loose parts are rigid bodies**: mass from their voxels and each palette entry's density; they tumble, land
+ on the level and on one another, and sleep; they move as instances (no vertex is written again).
+ - **Debris**: parts under 8 voxels stay the game's particles; at most 300 voxel bodies (`maxBodies`). At the
+ cap a new part takes the place of the body that matters least (asleep before awake, then the fewest voxels,
+ then the oldest; never one the same edit carved or made: a body being cut keeps its larger part), if that
+ body is no larger than the part; else the part is debris. What goes is debris.
+ - **A body stays a body** when it has settled (asleep it costs no tick; turned, it does not fit the lattice,
+ and writing it back would lose voxels). The cap bounds them.
+ - **Edits reach bodies**: a carve cuts a body where it is, as it is turned; what is cut off is a body of its own.
+ - **Determinism and robustness** as in step 7: wasm32 builds in CI; a class of voxel worlds in `check::cases`
+ and the adapter's own script, native against wasm32; a fuzz of calls on voxel shapes.
+ - Acceptance (hardware traversal): a 4 m explosion's frame ≤ 50 ms and 60 fps after it; a building cut loose
+ falls, lands and sleeps within 16.7 ms a frame; about a hundred bodies with room to spare, and the number at
+ which 60 fps is lost; the CPU split (physics step, placing, meshes, colliders) recorded; scenes without voxel
+ bodies unchanged (the catalog's bytes, `renderer/shaders`, step 7's physics tests and hello world).
+ - **Status: done (branch `voxel-bodies`, 2026-11-11), measured natively under hardware traversal on this Mac
+ (M5 Pro; the benchmark level at 1280 x 720 at 0.5; tables in docs/VOXEL.md "Voxel bodies").**
+ - Acceptance, as measured:
+ - **A 4 m explosion's frame: 18.4 ms of CPU** (walls and ground), **21.9 ms** for a 4 m crater of 140,785
+ voxels (target 50 ms); the frames after: CPU p50 5.2 ms, GPU 5.2 ms.
+ - **A building cut loose** (the cut of 30 x 30 m: 20 parts, the largest 32,680 voxels): while they fall and
+ land a frame's CPU is p50 5.3–5.5 ms, p95 8.1 ms, none over 16.7 ms; the physics step 0.28 ms, at worst
+ 0.52 (step 6: 26–28 ms a frame for as long as it fell); 17 of 20 asleep after 9.5 s.
+ - **About a hundred bodies: yes, with room to spare.** Natively the world is stepped by Rapier's parallel
+ solver on 4 threads (decided 2026-11-11 on these figures). The number of bodies moving at once at which
+ 60 fps is lost (large ones: slabs and columns of buildings in one heap): **about 450–500 on 4 threads,
+ about a hundred on one** (`THREERT_PHYSICS_THREADS=1`: at 100–149 moving the step is 10–14 ms and a
+ frame's CPU 14–18 ms; from 150 every frame is over). What takes the frame is Rapier's step; placing the
+ parts is under 0.2 ms, the GPU's frame does not change. The bodies are the same in every frame either way.
+ - **The cap is 300 bodies, measured**: a scenario that makes more than 500 holds the count at the cap, and
+ with every one of 300 in the air a frame's CPU is 10.7–10.9 ms at the median, 12.8–13.2 at p95, and no
+ frame of 1,094 is over 16.7 ms on account of the physics (two runs; one stray frame each with a step under
+ 1 ms). At 400 the frame holds in two runs of four and goes over in the others on 2 and 3 frames of 1,094
+ (17.0–19.3 ms, with 320–400 moving); at 512 a frame is 16.3 ms at the median with all moving, 5 of 22 such
+ frames over. With the parallel solver off the cap to set is 128 (about at the frame: 7 frames of 1,095
+ over, the worst 22.0 ms).
+ - The CPU split of an edit (the 4 m crater: carve 2.4, colliders 6.5, meshes 7.5, commit 3.9 ms; the cut:
+ carve 21.6, colliders 15.3, meshes 5.3, parts and bodies 27.8, commit 37.7, the first physics step 5.6).
+ - Scenes without voxel bodies: the catalog's 25 bundles are byte-identical to main's under software
+ traversal; `renderer/shaders` has no diff; `test-render` 173 of 173 (the 170 of main and three new
+ `voxel/cut-body*`, a fourth since); step 7's physics tests and hello world give the numbers they gave.
+ The perf smoke was not measured (it refused: the GPU was 20 % busy with other applications).
+ - Software traversal (works, not optimised): bodies are units added and moved in place, no rebuild, guard
+ count 0; the 4 m explosion's frame 18.6 ms, the cut's 194 ms (the parts' trees are built on the CPU),
+ after it a frame's CPU p50 8.1 ms, none over 16.7 ms.
+ - Determinism: 300 voxel worlds and the adapter's script end in the same bits natively and in wasm32 (the
+ physics job in CI); step 7's worlds end in the bits they did; the level run twice through explosions, the
+ cut and a crater gives the same level and physics hashes.
+ - Done: `Shape::Voxels`, `Physics::edit_voxels` and the world's own ray at voxel shapes (physics-core); the
+ bridge's engine bodies and colliders (ids from 2^30 up: scene code names them and cannot make or remove
+ them); `voxel_core::Edit::cleared` and `Level::take`; in renderer/src/voxel.rs the level's colliders, the
+ bodies, their sync, the carve of bodies, the cap; `voxelBodies()` and `voxelImpulse` in `packages/voxel`;
+ physics hits on the engine's colliders carry their ids. The time the engine spends inside a voxel call is
+ not counted against the frame script's 50 ms (a cut through a hundred bodies takes that long, and the
+ script was ended after it).
+ - **From scene code** (`voxel/cut-body-push`, a live test): a ray of `Raycaster.intersectPhysics` meets the
+ level (`hit.object` is `engineColliders`, whose `physics` is null; no `body`) and a voxel body (`body`), and
+ `voxelImpulse(hit.body, ...)` throws it. Writing that test found two faults the Rust tests had stepped
+ past: the scene package asked the engine's world only once a scene object with `physics` existed (a voxel
+ level makes none: `voxelLevel` now binds the queries), and an id read out of an answer came back from the
+ script engine as a double and was refused (the bridge reads a whole number as the id it is).
+ - Three faults of Rapier 0.36 / parry 0.31 with voxel shapes, each with a test and a way round in physics-core
+ (none patches the crates): the solver panics on a ball against voxels (parry's function for that pair keeps
+ no workspace; the pair now goes through its general voxel function); parry's ray misses voxels along a
+ lattice plane (the world walks the cells itself); a shape edited where it sits keeps stale contacts (the
+ collider is taken out and put back).
+ - **A fourth, in the parallel step: it can hang for good** (found by the review's fuzz on this PR's head,
+ 2026-11-12: one run of fifty; a world of six bodies stepped back to back hangs after 30,000 to 500,000
+ steps). Rapier hands the broad phase's tree optimisation to `rayon::spawn` and later waits for it with a
+ channel's blocking `recv`. Stepped on a pool's worker, the job is on that worker's own deque and the wait
+ is outside rayon, so only another worker can run it, and rayon does not promise one comes: waking for a
+ job in a worker's deque is best effort (no store-to-load barrier between the push and the pusher's read
+ of the sleep counters; shown by adding one fence to a scratch rayon-core: 15 million steps without a hang
+ against a hang in five runs of five). When every other worker is just falling asleep they all miss it.
+ Rapier's own `configure_thread_pool` has the same hole. **Way round, in `renderer/src/physics.rs`
+ `in_pool`, nothing patched**: the thread that waits for the step injects an empty job into the pool every
+ 0.5 ms until the step returns; an injected job always wakes a worker, and a woken worker looks through
+ every deque. A hung step costs 0.5 ms once. Why nothing met it before: the determinism check steps from a
+ thread outside the pool (the job is then injected, the path that always wakes), and the level's frames are
+ milliseconds apart (the workers are long asleep and are woken outright); it takes steps microseconds
+ apart. **Checks, on the CPU**: `renderer/examples/physics_fuzz.rs` (the fuzz, and the six-body world
+ stepped back to back, with a watchdog: a step that does not return in 30 s is a failure): 500 fuzz runs in a row and 20 of its
+ many-bodies variant with every check held, and 26 million back-to-back steps, none hung; with
+ the kick off (`THREERT_PHYSICS_KICK=off`) the stress hangs in three runs of three. CI's renderer job runs it
+ on the physics' threads as the renderer steps: the recorded hashes at 2 and 4 threads (the determinism
+ check steps from outside any pool, which is not the renderer's path), 10 fuzz runs and a million steps.
+ - **What the same review found besides, fixed here** (`out/review-24/review.md`):
+ - The time budget of a script: each voxel call moved the deadline by a millisecond at least, so a frame
+ script looping on cheap calls (or on ones that throw) never ended. The engine's time is now lent as
+ measured and at most 250 ms an entry (the 30 m cut, the largest single edit measured, is 115 ms); a voxel
+ call made after the deadline throws at once (the script engine checks its deadline only every so many
+ operations, and a loop of calls of some milliseconds makes few). Edits and frames asked for before the
+ level is loaded are at most 4,096 (they are outside the script engine's memory limit).
+ - A hole in the level's collider where a crater crosses a terrain tile's border: a neighbour that lost cells
+ of its own had its shell made whole only around those, not over the crater the other tile bared. Each
+ object is now made whole over its own box and every carved neighbour's (checked against brute force, with
+ the review's rays).
+ - At the cap, a cut retired the remainder of the body it was cutting and kept the chip (no body was
+ asleep, so the oldest was the one being cut): every id gone after a cut through 400 bodies. Now nothing the
+ edit carved or made is retired while it runs; the body that goes is the one that matters least (asleep,
+ then fewest voxels, then oldest), and only for a part at least as large; else the part is debris.
+ - A carve took bodies with another shape than the level: the radius now clamped to 128 voxels and to 0
+ below as the level's, a box whole for every class it reaches (it was shrunk by the class's share).
+ - Smaller: the physics' threads not made is a sequential step, said once (it was a panic every step); an
+ unknown `THREERT_PHYSICS_THREADS` is said; a level collider the physics took out on an error is
+ forgotten; no `powi` in a body's density; CI's physics job runs on changes to `api.rs` and `world.rs`.
+ - Open:
+ - **The parallel solver's independence of the thread count is checked as far as this, and no further**:
+ on this machine at 1, 2, 4, 8 and 15 threads (the determinism check's script and 1,500 random worlds of five
+ kinds, each small; heaps of up to 1,000 voxel pieces; 20,000 voxel worlds without a panic: these on the
+ process's pool, stepped from outside it), on the physics' own threads as the renderer steps (the script and
+ the 1,500 worlds again, and the voxel adapter's script, at 1, 2, 4 and 8 threads; the benchmark level's
+ hashes through explosions, the cut and a crater, equal to the sequential build's), and in CI on Linux at 2 and 4 threads on every change to the physics (native parallel
+ = native sequential = wasm32 = recorded; 7–11 s of the physics job with a warm cache). Not checked: other
+ machines and CPU families beyond CI's, worlds with joints and thousands of bodies at once, long runs of
+ large heaps. wasm32 stays sequential (no threads here), and the bits agree. Step 9's checkpoints are what
+ would find a difference in the field.
+ - **The cap of 300 is this machine's** (an M5 Pro's four threads): a slower machine holds fewer at 60 fps, and
+ nothing adapts it. A level can set `maxBodies`. Asleep, bodies cost nothing, and a game's bodies seldom all
+ move at once.
+ - **A large cut's own frame is over 50 ms**: 117 ms for the cut of 30 x 30 m (the scene's commit of the new
+ parts' meshes 38 ms, the parts' meshes and bodies 28, the carve 22, the colliders 15); a cut through a heap
+ of a hundred bodies 19–21 ms (p95 32–36). Explosions are within the target, which is what the acceptance
+ names (as in step 6). Not split over frames; not in this step.
+ - **A voxel part that glows rebuilds the scene once when it comes loose** (a driven mesh that emits is not
+ placed as an instance: the build flattens it; seen in `voxel/cut-body-live`, whose posts glow). The
+ daylight level has none; a level with lamps at night does.
+ - **The level's colliders cost 5.4 s of load and 303 MiB** on the benchmark level (the first frame comes
+ after 10.7 s with them, 5.5 s without). **An offline still pays the 5.4 s too** (16.5–19.6 s for a still of
+ the level against 11.1–12.2 s before), though nothing in it collides: not changed in this step. natively this is a fixed cost of
+ every level of that size. They are a shell of the cells within 4 of the open (every solid cell was 26 s and
+ 1.3 GiB), and objects of one file share one shape until one is edited (before that: 6.9 s and 455 MiB).
+ What is left is the terrain's 1,600 tiles, a shape each. Decided against (2026-11-11): a shell of 2 cells
+ (a body would get through it at 12 m/s), and building them after the first frame (a level whose first
+ seconds have no collision behaves by its load time).
+ - The script surface is `voxelBodies()`, `voxelImpulse` and the ids physics hits report; the rest is step 10's
+ (voxel bodies as objects with `.physics`, paint and added voxels on bodies, mass by cell).
+ - A tick's time is still not bounded: the first tick after an edit that frees many parts steps them all (400
+ jagged pieces in one heap: 7 ms a tick, at worst 19; 1,000: 23 ms, at worst 52).
+ - **A large loose part's collider holds every cell** (the level's are shells): a solid block of 200³ cut
+ loose is an edit of 2.8 s and 619 MB, and past 2²⁴ cells the part is refused and becomes debris (a large
+ building cut loose whole would vanish, not fall). Measured by the review; a shell for bodies (they are hit
+ from every side, so 4 cells all round), or a split into pieces, is for when a level has such parts.
+ - Scene code can put colliders of its own on the engine's voxel bodies (a design question: step 10's voxel
+ bodies as objects); scene code's and the engine's bodies and colliders share one count of the physics
+ world's limits (a level with `maxBodies: 20000` leaves scripts none); every part cut off a body leaves an
+ empty slot in the level's object list for good.
+ - Tree crowns cost more than buildings: five crowns of 10,616–18,894 voxels moving step in 1.6–2.2 ms (leaves
+ make many contacts), a building part of 32,680 in under 0.5 ms. They sleep 5–10 s after the cut.
+ - Software traversal is not optimised (the cut's frame 194 ms). A browser: a small voxel scene with bodies in
+ Chrome is not run in this step.
+ - The faults above that are parry's and Rapier's own are to be reported upstream (the step's hang: a draft
+ with a reproduction of 60 lines on Rapier alone, not sent). **The kick is a way round, not a cure**: it
+ rests on two things rayon does today (an injected job wakes a sleeping worker; a worker looks through
+ every deque before it sleeps). To be dropped when Rapier joins that pass without blocking a worker; the
+ stress with `THREERT_PHYSICS_KICK=off` says when.
+ - Then the decision: keep Rapier or write our own. What this step measured for it: Rapier does what the step
+ needs on both ends (the same bits natively and in wasm32, and on several threads; voxel against voxel
+ resting, stacking and sleeping on a level of 61.6 M collider cells; edits of a shape by its cells in 0.1 ms),
+ with the four faults above found and worked round without patching it (the fourth, the hang of the parallel
+ step, by a review's fuzz after this step's own checks had passed). Its cost is the step: about 0.1 ms a large body
+ that moves, on one thread, so a hundred moving bodies are the frame; its parallel solver, now the native
+ default, is worth a factor of 3 on 4 threads at the same bits (about 450–500 moving bodies in a frame). What an engine of our own would have to beat is that step, and it would have
+ to bring the determinism, the sleeping and the voxel-voxel contacts with it.
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.
@@ -4058,6 +4229,10 @@ benchmark level. The order follows the dependencies; a step that meets a further
period the hash of the world data and of the physics world (`Physics::hash`) is logged, and a node replaying
compares. The ends are not assumed to agree bit for bit: a difference is found at the first checkpoint after it
and placed between two checkpoints.
+ - **The voxel world now depends on the physics' determinism** (step 8): where a loose part comes to rest, and so
+ which voxels a later edit carves from it, is the physics world's doing. A replay needs the physics' bits to
+ agree wherever the voxels' must; the checkpoints above cover both hashes, and step 8's checks hold native
+ against wasm32 for voxel shapes.
- **World handlers' changes are commands.** What `on` handlers do to the scene (step 7) is not in the game state;
it all leaves the script through the scene binding's sync, and that is where it is logged and replayed from. No
other way out of a world handler may be added.
@@ -4099,6 +4274,11 @@ benchmark level. The order follows the dependencies; a step that meets a further
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.
+ - **Voxel bodies as objects** (left by step 8, decided 2026-11-11): a loose part is today a body id
+ (`voxelBodies()`, a physics hit's `body`, `voxelImpulse`), drawn by objects scene code did not make. How it
+ appears to a game in three's style (an object with `.physics`: `applyImpulse`, `getLinearVelocity`, contact
+ events, joints between voxel objects) is designed here. With it: paint and added voxels reaching bodies, and
+ a body's mass spread by its cells' own densities (it is their mean today).
- Fire and smoke on the existing volume and particle paths.
- Vehicles and ropes on step 7's joints.
- Acceptance: the benchmark level played through as a game, every line of `docs/VOXEL.md`'s benchmark measured.
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 883f554..36a6720 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -47,7 +47,7 @@ runtime, and drives the engine directly, the way a UE game drives its actors:
| Scene binding | `packages/scene/src/engine.ts` `SceneBinding` | Keeps the engine in step with a DSL scene. Objects report their own changes (core.ts change tracking: transforms, visibility, power, shadow flag, mesh geometry / material, add / remove), so a sync visits only what changed. Lights, cameras and materials are compared against what was last sent. |
| World | `renderer/src/world.rs` | The engine's objects, resources, environment and settings, and what changed since the last commit: parameter changes (power, light / material parameters, environment, camera) or structural ones. Asset paths must stay inside the asset root (game code is untrusted on nodes). |
| Live commit | `renderer/src/live.rs` `LiveCore::commit`, `tables.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF, wetness / rain / fog, camera). Anything structural rebuilds the GPU scene from the world, in memory; history survives, validated per pixel. |
-| 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`. |
+| 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. The time the engine spends inside a voxel call (`voxelExplode`, `voxelEdit`, `voxelFrame`) is the engine's, not the script's: the deadline moves by it as measured, up to 250 ms an entry; past that it counts against the script, and a voxel call made after the deadline throws "interrupted" at once. 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)`. |
| World handlers | `packages/gameplay/src/world.ts` | `on[type](world, ev)`: an event handled on this node, changing the scene at once. `WorldContext`: `scene`, `camera`, read-only `state`, `object(id)`, `time`, `now`, `random()`, `emit(type, payload)`. |
| Frame scripts | `packages/gameplay/src/frame.ts` | `FrameContext`: `time`, `dt`, `snap`, `now`, read-only `state`, `scene`, `camera`, `object(id)`, `random()`. |
@@ -211,6 +211,45 @@ crate.position.set(0, 5, 0); // a write moves the body there
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()`.
+- **Voxels** (ROADMAP § 6 step 8; docs/VOXEL.md "Voxel bodies"): a voxel level collides without a `physics` on
+ anything. Its objects are fixed colliders of their voxels and what an edit cuts loose is a dynamic body, both of
+ the engine's own shape (`physics_core::Shape::Voxels`: parry's voxel shape; a collider's cells are changed where
+ it is by `Physics::edit_voxels`, at a cost by the cells that change). Rays, shape casts and contacts report them
+ like any collider. They are **the engine's bodies**: their ids are from 2^30 up, scene code cannot make or remove
+ one (`body`, `collider` and `remove` refuse those ids), and can name one in every other call; `voxelBodies()`
+ (`packages/voxel`) lists the bodies with their ids, and `voxelImpulse(body, impulse, point?)` pushes one. A hit of
+ `Raycaster.intersectPhysics` or of a `Shapecaster` on one of them has `engineColliders` for its `object` (they
+ are no scene object's) and carries `collider` and, on a body, `body`: the id those calls take. **On the voxel
+ level `hit.object.physics` is null and there is no `body`; on a voxel body there is a `body`.** So hello world's
+ test for something fixed, `hit.object.physics?.type === "fixed"`, does not find the level: it is
+ `hit.object === engineColliders && hit.body === undefined`. A level that collides is in the physics world, and
+ the queries ask it, whether or not any scene object has `physics` (`tests/render/voxel-cut-body-push.ts`: a
+ ray's hit on a body, its `body` into `voxelImpulse`, the part thrown). (A voxel body as an object with `.physics`
+ is ROADMAP § 6 step 10's.) A voxel shape's limits: cells of 1 cm to 100 m, at most 2^24
+ cells, each within 2^20 cells and 100 km of the shape's origin.
+ - Two things the world does itself for voxel shapes, because Rapier 0.36 and parry 0.31 do them wrongly
+ (`physics-core/src/world.rs` has the tests): rays are walked cell by cell (parry's ray misses every cell when it
+ lies on a plane of the lattice and runs along it), and a ball against voxels goes through parry's general voxel
+ contacts (its own function for that pair makes Rapier's solver panic when a contact goes). Neither touches a
+ world without voxel shapes: step 7's worlds end in the bits they did.
+ - Cost: asleep, nothing. While they move, Rapier's step on one thread: 1.4 ms a tick for a hundred jagged pieces
+ of 200 voxels in a heap, under 0.5 ms for one building part of 96 k voxels landing. On the benchmark level
+ (hardware traversal) one thread holds 60 fps to about a hundred large bodies moving at once (the step is then
+ 10–13 ms).
+ - **Natively the world is stepped by Rapier's parallel solver**, in a pool of the physics' own: 4 threads, or the
+ machine's performance cores when it has fewer; `THREERT_PHYSICS_THREADS` sets another count, and 1 (0, off) is
+ sequential. It gives the sequential build's bits (which are wasm32's) at a third of the step's time: about
+ 450–500 bodies moving in a frame, and a level's cap of 300 voxel bodies (`maxBodies`) by measurement. wasm32
+ is sequential. How far "the bits do not depend on the thread count" was checked, and what was not: docs/VOXEL.md
+ "Voxel bodies", ROADMAP § 6 step 8 "Open".
+ - **A step is waited for with a kick** (`physics.rs` `in_pool`): Rapier's parallel step, made on a pool's worker,
+ can strand a job on that worker's deque and wait for it for good (about once in 10^5 steps when steps are
+ microseconds apart). While the step is out, the waiting thread injects an empty job into the pool every 0.5 ms,
+ which wakes a worker that then takes the stranded one. The frame log's `physics.kicks` counts them (long steps
+ get a few; they change nothing). `THREERT_PHYSICS_KICK=off` waits without, to reproduce the hang;
+ `cargo run --release --example physics_fuzz` is the CPU check, with a watchdog.
+ - Ids in a call (`body`, `collider`, `skip`, ...) are whole numbers however they are written: scene code hands
+ back an id it read from an answer as a double.
## The runtime's shape: Rust owns the world, the script engine is a guest
diff --git a/docs/VOXEL.md b/docs/VOXEL.md
index 1d6e92a..aacba0d 100644
--- a/docs/VOXEL.md
+++ b/docs/VOXEL.md
@@ -338,6 +338,186 @@ along the camera path, 2 rounds with an A/A; memory from an offline frame.
colours are for palettes of many colours in one material: a `.vox` model's up to 255 colours of one material are one
mesh instead of up to 255, and the browser's three.js draws one mesh per class.
+### Voxel bodies (ROADMAP § 6 step 8; 2026-11-11)
+
+The level collides and what comes loose is a rigid body. Code: `renderer/physics-core` (`Shape::Voxels`,
+`Physics::edit_voxels`), `renderer/voxel-core` (`Edit::cleared`, `Level::take`), `renderer/src/voxel.rs` (the
+level's colliders, the bodies). First what the CPU costs on its own (this Mac, release builds), then the level on
+the GPU ("Measured on the GPU" below).
+
+**The shape** is parry's `Voxels` (8³ chunks, a byte a cell, each cell knowing its neighbours), for the fixed
+level and for the moving parts. Measured against the others on Rapier (`physics-core/examples/voxel_shapes.rs`: a
+ground of 427 k cells of 0.1 m; pieces of 6³ cells with holes, about 200 solid):
+
+| the fixed ground | build | memory | an edit of 2,080 cells |
+| --- | --- | --- | --- |
+| voxels | 26 ms | 1.3 MiB | 0.10 ms, in place |
+| a compound of boxes (cells merged greedily) | 2.9 ms | 0.3 MiB | 3.7 ms: the object built again |
+| a triangle mesh of the faces | 107 ms | 53.7 MiB | 105 ms: built again |
+
+| 100 pieces dropped in a heap: moving / fixed | a tick while they fall: mean, worst | asleep after 15 s |
+| --- | --- | --- |
+| voxels / voxels | 1.38, 4.7 ms | 100 |
+| boxes / voxels | 1.66, 5.9 ms | 98 |
+| hull / voxels | 0.44, 2.4 ms | 29 |
+| voxels / triangle mesh | – | 0: all fell through the ground |
+| boxes / boxes | 0.46, 1.5 ms | 94 |
+
+Voxels against voxels: 400 pieces 7.1 ms a tick while they fall (at worst 19), 1,000 pieces 22.6 ms (52); asleep,
+0. The same bits natively and in wasm32.
+
+**On several threads.** Natively the world is stepped by Rapier's parallel solver with `enhanced-determinism`
+(physics-core's `parallel`; the renderer's native build has it on, in a pool of the physics' own: 4 threads, or the
+machine's performance cores when fewer; `THREERT_PHYSICS_THREADS` sets another count, 1 is sequential). wasm32 is
+sequential. The same heaps, a tick while they fall, mean and worst, ms:
+
+| pieces | sequential | 2 threads | 4 | 8 | 15 |
+| --- | --- | --- | --- | --- | --- |
+| 10 | 0.10, 0.99 | 0.08, 0.42 | 0.08, 0.41 | 0.09, 0.48 | 0.08, 0.59 |
+| 100 | 1.24, 3.84 | 0.74, 2.27 | 0.49, 1.71 | 0.47, 2.08 | 0.51, 2.04 |
+| 400 | 6.69, 17.75 | 3.72, 9.26 | 2.25, 6.12 | 1.68, 5.32 | 1.52, 6.58 |
+| 1,000 | 20.48, 50.81 | – | 6.27, 15.44 | 4.29, 12.76 | 3.66, 13.67 |
+
+Each row ends in the same bits at every thread count and sequentially (a hash of every piece's pose and velocity
+after 900 ticks). **That the result does not depend on the thread count is what we checked ourselves, and this is
+how far:**
+
+- On this machine (M5 Pro, 15 cores), at 1, 2, 4, 8 and 15 threads: the determinism check's script and its 1,500
+ random worlds (hulls, bodies of several colliders, joints with limits and motors, CCD on a triangle mesh with
+ kinematic bodies and queries, voxel lumps on voxel ground with edits: each a few to a few dozen bodies, 90
+ ticks); heaps of 10, 100, 400 and 1,000 voxel pieces on voxel ground, 900 ticks; 20,000 random voxel worlds
+ without a panic.
+- In CI (Linux, x86-64), on every change to the physics: the script and the 1,500 worlds at 2 and 4 threads
+ against the sequential native build, which is held to wasm32 and to the recorded hashes
+ (`tools/physics-determinism.ts`: native parallel = native sequential = wasm32 = recorded).
+- The renderer's own build, stepped as it steps (on the physics' own threads): the script, the 1,500 worlds and
+ the voxel adapter's script at 1, 2, 4 and 8 threads; the benchmark level run twice through explosions, the 30 m
+ cut and a crater gives the level and physics hashes the sequential build gave; the same bodies moving in every
+ frame of four destruction scenarios, sequential against 4 threads.
+- **Not checked**: other machines and other CPU families at thread counts beyond these (Rapier promises it; it also
+ promised the cross-platform bits that needed a patch to glamx); worlds with joints and thousands of bodies at once
+ (the worlds with joints here are small; the large ones have no joints); long runs (minutes) of large heaps.
+
+(Rapier's contact recycling stays on: with it off a heap of 400 pieces does not come to rest, 79 asleep after
+15 s.)
+
+**The parallel step can hang, and what the renderer does about it.** Rapier 0.36.1 hands the broad phase's tree
+optimisation to `rayon::spawn` and waits for it with a blocking `recv`. Stepped on a pool's worker (which is how
+the renderer steps, and how Rapier's own `configure_thread_pool` does) the job sits on the stepping worker's own
+deque, and if every other worker happens to be falling asleep at that instant none takes it: the step never
+returns. It needs steps microseconds apart (ticks back to back: a catch-up, an offline settle, a fuzz); a world of
+six bodies stepped back to back hangs after 30,000 to 500,000 steps, the review's fuzz in one run of fifty. The
+renderer's wait for a step therefore injects an empty job into the pool every 0.5 ms until the step is back
+(`renderer/src/physics.rs` `in_pool`): a worker wakes for it and takes the stranded job on its way. Neither crate
+is patched. `renderer/examples/physics_fuzz.rs` is the check (CPU only, with a watchdog): 500 fuzz runs in a row, 20 of the
+many-bodies variant and 26 million back-to-back steps without a hang; with the kick off the back-to-back world
+hangs in three runs of three.
+
+**The level's colliders.** Every object gets a fixed collider at load; an edit takes out the cells the object lost
+(`Edit::cleared`: by the cells, not by the object's size). A collider holds the object's cells within 4 of a cell
+that is not solid, a shell; an edit brings in the cells it bared, the neighbouring terrain tiles' too. On the
+benchmark level (4,172 objects; 515 M solid cells, 480 M of them the terrain's 1,600 tiles down to the bedrock):
+
+| colliders of | cells | build | memory |
+| --- | --- | --- | --- |
+| every solid cell | 515.3 M | 26.0 s | 1,279 MiB |
+| the shell | 61.6 M | 6.9 s (finding the cells 2.3) | 455 MiB |
+| the shell, objects of one file sharing a shape until one is edited | 61.6 M | **5.4 s** (finding the cells 2.1) | **303 MiB** |
+
+A collider holds its object's own cells and stands by the object's placement, so the 2,572 objects that are no
+terrain, which come from 630 files, have 630 shapes between them (`physics_core::SharedVoxels`); an edit gives the
+edited object cells of its own. What is left is the terrain: 1,600 tiles, whose shells depend on their neighbours,
+a shape each. Natively this is a fixed cost of a level of this size (ROADMAP § 6 step 8, "Open").
+
+**An edit on the level, on the CPU** (`voxel.rs` `voxel_level_physics`; at the foot of the largest building part):
+
+| edit | voxels | all | carve | colliders | meshes | parts and bodies |
+| --- | --- | --- | --- | --- | --- | --- |
+| explosion, 0.5 m | 296 | 5.1 ms | 0.13 | 0.89 | 4.00 | – |
+| 1 m | 2,857 | 6.3 ms | 0.27 | 1.33 | 4.72 | – |
+| 2 m | 19,919 | 9.0 ms | 0.64 | 2.54 | 5.76 | – |
+| 4 m | 144,344 | 19.8 ms | 2.96 | 8.50 | 8.27 | – |
+| the cut of 30 x 30 m, 1 m thick | 577,519 | 124 ms | 25.2 | 43.1 | 42.4 | 12.5: six bodies of 112,889 voxels, the largest 95,694 |
+
+After the cut the physics steps in 0.17 ms a frame (p95 0.44; a frame's physics at worst 2.7 ms) while the parts
+fall and land, all six sleep within five seconds, and then it is 0. In step 6 the same cut cost 26–28 ms a frame for as long as the building fell (its
+vertices written again every frame); now a part moves by its transform.
+
+**A body**: its grid in its own space, a mass from its voxels (a density per palette entry: by hardness 900 / 1,800 /
+2,400 / 7,800 kg/m³ unless the entry names one), drawn by driven objects. A carve reaches it through its pose; what
+is cut off is a body of its own. At most 300 at once (`maxBodies`; the number is measured, below). At the cap a
+new part takes the place of the body that matters least: asleep before awake, then the fewest voxels, then the
+oldest, and never one the same edit carved or made (a body being cut keeps its larger part and its id; its chips do
+not push out the bodies the same cut is going through). It does so only if that body has no more voxels than the
+part; else the part itself is debris. A settled body stays a body.
+
+**Measured on the GPU** (this Mac, M5 Pro; hardware traversal unless said; the benchmark level at 1280 x 720 at
+0.5, in lockstep at 1 / 60 s; `games/voxel-level/level-destruction.game.ts`'s scenarios; a frame's GPU time is
+5.2–5.7 ms throughout, its trace 1.8 ms).
+
+| | the edit's frame, CPU | frames after it, CPU p50 / p95 | physics step | bodies |
+| --- | --- | --- | --- | --- |
+| a still level | – | 5.3 ms | 0.01 ms | 0 |
+| explosions of 1, 2, 4 m (`singles`) | 10.5, 10.4, **18.4 ms** | 5.2 ms | – | 0 |
+| a 4 m crater in open ground (140,785 voxels) | **21.9 ms** | 5.2 ms | – | 0 |
+| the cut of 30 x 30 m (`fell`: 46,469 voxels, 20 parts) | 116.7 ms | **5.3–5.5 / 8.1 ms, none over 16.7** | p50 0.28, at worst 0.52 ms | 20 (the largest 32,680 voxels); 17 asleep after 9.5 s |
+| eight trees cut at the trunk (`topple`) | 6.9–14.9 ms | 5.5–7.2 / 8.7 ms | 2.25 ms while five crowns move | 5 (10,616–18,894 voxels); four asleep 5–6 s after the last cut, the fifth after 10 s (the CPU's run of the same cuts) |
+| 7 explosions a second for 10 s (`sustained`) | p50 9.2, p95 13.4 ms | – | at worst 1.35 ms | 2 |
+| an explosion a frame for 60 s (`endurance`) | – | 9–11 / 18 ms in the first 5 s, 5.2–5.5 after | p50 at most 4.4 ms | 9 from the fifth second to the end |
+
+The cut's 116.7 ms: the level's carve 21.6, its colliders 15.3, its meshes 5.3, the parts' meshes and bodies 27.8,
+the scene's commit of the new meshes 37.7, the physics' first step 5.6. In step 6 the same fall cost 26–28 ms a
+frame for as long as it lasted. The level's load is 10.7 s to the first frame with the colliders and 5.5 s without
+(`physics: false`).
+
+**How many bodies a frame holds, and the cap.** `shatter-dense`: the cut of `fell`, then 120 cuts 0.2 m thick half a
+metre apart, twenty a second, through what fell: slabs, then columns of buildings, tens to thousands of voxels
+each, in one heap, more than 500 of them. **The default configuration** (the parallel solver on 4 threads) with
+the default cap of 300: the count reaches 300 and stays there to the end of the run. Frames without an edit, by the
+bodies that moved in them (physics step and the frame's CPU time, p50 / p95; two runs, the same bodies in every
+frame, the second's figures in brackets):
+
+| bodies moving | frames | physics step | frame CPU | frames over 16.7 ms |
+| --- | --- | --- | --- | --- |
+| 0–49 | 661 | 0.36 / 0.77 ms | 5.7 / 7.8 ms | 0 |
+| 50–99 | 66 | 1.97 / 3.20 | 7.4 / 9.6 | 0 |
+| 100–149 | 78 | 3.30 / 4.64 | 8.1 / 10.2 | 1 (a step of 0.8 ms) |
+| 150–199 | 63 | 1.15 / 4.75 | 6.9 / 9.8 | 0 |
+| 200–249 | 123 | 1.85 / 5.12 | 8.0 / 9.9 | 0 |
+| 250–299 (every body of the cap in the air or landing) | 103 | 5.92 / 7.71 (6.18 / 8.23) | 10.7 / 12.8 (10.9 / 13.2) | 0 (0) |
+
+**No frame of 1,094 is over 16.7 ms on account of the physics** in either run (each has one stray, 17.9 and 17.2
+ms, with a step under 1 ms). That is why the cap is 300. With a cap of 400 the count holds too, and with every body
+in the air a frame is 13.1–13.2 ms at the median and 14.9–16.0 at p95, but in two runs of four a few frames go over
+(2 and 3 of 1,094, 17.0–19.3 ms, with 320–400 moving); with 512, 16.3 ms at the median and 5 of 22 such frames over.
+
+The same scenario with the cap at 512, sequential (`THREERT_PHYSICS_THREADS=1`) against the default's 4 threads:
+
+| bodies moving | frames | step, sequential | frame CPU, sequential | over 16.7 ms | step, 4 threads | frame CPU, 4 threads | over 16.7 ms |
+| --- | --- | --- | --- | --- | --- | --- | --- |
+| 50–99 | 51 | 5.02 / 7.89 ms | 9.2 / 12.1 ms | 1 | 2.10 / 2.96 ms | 7.5 / 9.0 ms | 1 |
+| 100–149 | 41 | 10.15 / 14.03 | 14.2 / 17.7 | 9 | 3.45 / 4.55 | 8.4 / 9.3 | 0 |
+| 200–249 | 8 | 17.46 / 18.57 | 21.7 / 22.2 | 8 | 5.65 / 5.75 | 9.5 / 11.5 | 0 |
+| 300–349 | 6 | 21.01 / 21.08 | 24.9 / 25.3 | 6 | 6.07 / 6.51 | 10.1 / 10.3 | 0 |
+| 450–499 | 46 | 35.38 / 39.61 | 39.4 / 43.6 | 46 | 10.41 / 11.99 | 14.7 / 17.1 | 5 |
+| 500–549 | 22 | 41.24 / 42.94 | 45.2 / 47.3 | 22 | 12.37 / 13.01 | 16.4 / 18.0 | 6 |
+
+**The number of bodies moving at once at which 60 fps is lost: on one thread about a hundred** (from 150 every
+frame is over); **on 4 threads about 450–500.** What takes the frame is Rapier's step (placing the parts is at most
+0.17 ms, the scene's commit about 2 ms, the GPU's frame does not change). The bodies and the bodies that moved are
+the same in every frame, sequential and parallel (and at 8 threads, which bring the step no gain on the frame).
+With few bodies the pool costs nothing that shows: `fell` (20 bodies) steps in 0.18–0.35 ms a frame either way,
+hello world in 0.03 ms. **With the parallel solver off the cap to set is 128** (`maxBodies: 128`): sequentially,
+with all 128 moving, a frame is 12.1 ms at the median and 7 frames of 1,095 are over 16.7 ms (the worst 22.0): about
+at the frame. A cut through the heap is itself a frame of 19–21 ms (p50; p95 32–36 ms) on 4 threads and 26–35 ms
+(p95 44–59 ms) on one: it carves, splits and meshes again every body it meets, and the frame's step is in it.
+
+**Under software traversal** (`THREERT_HWRT=0`: bodies are units; not optimised): no rebuild, the parts added and
+moved in place (records 10,459 to 10,503 for the 20 bodies of `fell`), the loop guard's count 0; the same bodies
+asleep at the same frames as under hardware traversal. Explosions of 1, 2, 4 m: 8.4, 8.6, 18.6 ms; the cut's frame
+194 ms (the parts' trees are built on the CPU: the commit is 117 ms of it); after it a frame's CPU p50 8.1, p95
+9.1 ms, none over 16.7 ms; a frame's GPU 7.5–8.1 ms (trace 4.2–4.6).
+
## Two published designs for destructible voxel worlds
- **Dense grids and a world occupancy volume** (the raster-era design):
diff --git a/games/voxel-level/level-destruction-lattice.game.ts b/games/voxel-level/level-destruction-lattice.game.ts
new file mode 100644
index 0000000..9dedc5e
--- /dev/null
+++ b/games/voxel-level/level-destruction-lattice.game.ts
@@ -0,0 +1,5 @@
+// The benchmark level under explosions as triangles, with the level's physics off (ROADMAP § 6 step 8's A/B): no
+// collider, and what comes loose falls straight down through the lattice until it rests, as in step 6
+// (level-destruction.game.ts).
+import { destructionGame } from "./level-destruction.game.ts";
+export default destructionGame("mesh", 1, false, false, false);
diff --git a/games/voxel-level/level-destruction.game.ts b/games/voxel-level/level-destruction.game.ts
index fe83f16..3451946 100644
--- a/games/voxel-level/level-destruction.game.ts
+++ b/games/voxel-level/level-destruction.game.ts
@@ -14,6 +14,11 @@
// cut loose, falls and rests on its stump (explosions that split)
// fell a saw cut (a box 1 m thick, 30 x 30 m) through everything from 0.5 m above the road ahead: trees, lamp
// posts, cars and the buildings there lose their footing and fall 1 m (the largest loose parts)
+// shatter `fell`, then from two seconds on a cut 0.2 m thick every tenth of a second through what fell, 30 a
+// metre apart across the road and 30 along it: the bodies are cut into more and more bodies (ROADMAP
+// § 6 step 8: how many bodies a frame holds, and the cap on them)
+// shatter-dense the same with the cuts half a metre apart and twenty a second: more bodies, sooner (past 500:
+// the level's cap is reached and held)
// With `debris`
// (level-destruction-debris.game.ts; ROADMAP § 6 step 2e), the voxels too few to make a piece are thrown out as
// instances of one unit cube (an `InstancedMesh`, coloured per instance from the palette), fall, bounce on the ground
@@ -29,11 +34,11 @@
// node tools/voxel-level/generate.ts --granularity object && node tools/bundle-game.ts games/voxel-level/level-destruction.game.ts
import { BoxGeometry, Color, DirectionalLight, GpuParticles, InstancedMesh, MaterialFunction, Mesh, MeshStandardMaterial, ParticleProgram, SimulatedSmoke, PerspectiveCamera, PlaneGeometry, ProceduralGeometry, ProceduralMesh, Scene, SkyAtmosphere } from "@threert/scene";
import { defineGame } from "@threert/gameplay";
-import { VOXEL_BRICKS, voxelCarve, voxelDebris, voxelExplode, voxelFrame, voxelHash, voxelLevel, type VoxelFrame } from "@threert/voxel";
+import { VOXEL_BRICKS, voxelBodies, voxelCarve, voxelDebris, voxelExplode, voxelFrame, voxelHash, voxelLevel, type VoxelFrame } from "@threert/voxel";
import { nativeObjects, nativePalette } from "./native.ts";
import { EDGE, PALETTE, SIZE, VOXEL, cameraPath, groundHeight, levelPlan, toScene } from "./plan.ts";
-type Scenario = "singles" | "sustained" | "peak" | "stress" | "endurance" | "show" | "crater" | "fell" | "topple";
+type Scenario = "singles" | "sustained" | "peak" | "stress" | "endurance" | "show" | "crater" | "fell" | "topple" | "shatter" | "shatter-dense";
interface State { scenario: Scenario | null; started: number }
/** Spots for explosions: alternately on the ground ahead of the camera and on the walls of the buildings nearest it
@@ -206,14 +211,17 @@ class Dust {
}
/** `debris`: the removed voxels thrown out as instances (`Debris`; logged per explosion), or "dust": as GPU particles.
- * `smoke`: the cells of the simulated smoke's grid. Falling objects are logged per frame as `batch {...}`. */
-export function destructionGame(route: "mesh" | "boxes", seed = 1, debris: boolean | "dust" = false, smoke: false | [number, number, number] = false) {
+ * `smoke`: the cells of the simulated smoke's grid. `physics` (ROADMAP § 6 step 8; on by default): the level
+ * collides and what comes loose is a rigid body, logged every half second while there are any as `bodies {...}`
+ * (how many, how many sleep, the fastest); off, loose parts fall through the lattice as in step 6 and are logged
+ * per frame as `batch {...}`. `maxBodies`: the level's cap on voxel bodies (300 unless given). */
+export function destructionGame(route: "mesh" | "boxes", seed = 1, debris: boolean | "dust" = false, smoke: false | [number, number, number] = false, physics = true, maxBodies?: number) {
const keys = cameraPath(seed);
const at = spots(seed);
// The ground points of the eight trees nearest ahead of the camera (`topple`).
const [camX, , camZ] = keys[0].pos;
const trunks = levelPlan(seed).props.filter((p) => p.kind === "tree").map((p) => toScene(p.x, p.y, p.z)).filter((p) => p[2] > camZ + 4).sort((a, b) => Math.hypot(a[0] - camX, a[2] - camZ) - Math.hypot(b[0] - camX, b[2] - camZ)).slice(0, 8);
- let next = 0, fired = 0, frames = 0, last = -1;
+ let next = 0, fired = 0, frames = 0, last = -1, hadBodies = false;
const flying = debris === true ? new Debris(seed) : null;
const dust = debris === "dust" ? new Dust() : null;
// Smoke: a box 22 x 14 x 36 m over the streets ahead of the camera (from 3 m ahead; the level's +z), `smoke` cells
@@ -257,17 +265,22 @@ export function destructionGame(route: "mesh" | "boxes", seed = 1, debris: boole
const fn = new ProceduralMesh(new ProceduralGeometry(VOXEL_BRICKS, [0, 0, 0, 0.1, 0.1, 0.1], new Array(12).fill(0)), ground);
fn.visible = false;
scene.add(fn);
- voxelLevel({ route, palette: nativePalette(false), function: VOXEL_BRICKS.name, objects: nativeObjects(seed), debris: !!debris, ...(dust ? { occupancy: 0.2 } : {}) });
+ voxelLevel({ route, palette: nativePalette(false), function: VOXEL_BRICKS.name, objects: nativeObjects(seed), debris: !!debris, physics, ...(maxBodies === undefined ? {} : { maxBodies }), ...(dust ? { occupancy: 0.2 } : {}) });
if (flying) scene.add(flying.mesh);
if (dust) scene.add(dust.node);
if (cloud) scene.add(cloud);
- return { scene, camera, options: { name: `voxel-level-destruction-${route}${debris === true ? "-debris" : debris ? "-dust" : ""}${smoke ? "-smoke" : ""}`, width: 1280, height: 720, preset: "cinematic" as const } };
+ return { scene, camera, options: { name: `voxel-level-destruction-${route}${debris === true ? "-debris" : debris ? "-dust" : ""}${smoke ? "-smoke" : ""}${physics ? "" : "-lattice"}`, width: 1280, height: 720, preset: "cinematic" as const } };
},
frame(f) {
frames++;
flying?.step(f.dt);
const b = voxelFrame(f.dt) as VoxelFrame; // (the level is loaded by the first frame)
if (b.batches > 0 || (b.settled ?? 0) > 0) console.log(`batch ${JSON.stringify(b)}`);
+ if (physics && frames % 30 === 0) {
+ const bodies = voxelBodies();
+ if (bodies.length > 0 || hadBodies) console.log(`bodies ${JSON.stringify({ frame: frames, n: bodies.length, asleep: bodies.filter((x) => x.asleep).length, voxels: bodies.reduce((n, x) => n + x.voxels, 0), largest: bodies.reduce((n, x) => Math.max(n, x.voxels), 0) })}`);
+ hadBodies = bodies.length > 0;
+ }
const s = f.state.scenario;
if (!s) return;
const t = (frames - f.state.started) / 60; // frames since the scenario began, at 60 per second of frame script
@@ -305,6 +318,24 @@ export function destructionGame(route: "mesh" | "boxes", seed = 1, debris: boole
const e = voxelCarve({ box: [x - 15, y + 0.5, z - 6, x + 15, y + 1.5, z + 24] });
console.log(`explosion ${JSON.stringify({ k: fired++, frame: frames, r: 0, cut: true, ...e })}`);
}
+ } else if (s === "shatter" || s === "shatter-dense") {
+ const [x, y, z] = at[2 * 62];
+ if (t >= 1 && last < 0) {
+ last = 0;
+ const e = voxelCarve({ box: [x - 15, y + 0.5, z - 6, x + 15, y + 1.5, z + 24] });
+ console.log(`explosion ${JSON.stringify({ k: fired++, frame: frames, r: 0, cut: true, ...e })}`);
+ }
+ // (From 0.3 m above the road up: the cuts go through what stands and what fell, not into the ground.)
+ // Cuts 0.2 m thick, `gap` m apart, `rate` a second: across the road's 30 m, then along them.
+ const [gap, rate] = s === "shatter" ? [1, 10] : [0.5, 20];
+ const n = 30 / gap, k = Math.floor((t - 3) * rate) + 1;
+ if (t >= 3 && k <= 2 * n && k !== last) {
+ last = k;
+ const along = k <= n;
+ const p = (along ? x - 15 : z - 6) + (along ? k : k - n) * gap - gap / 2;
+ const e = voxelCarve({ box: along ? [p - 0.1, y + 0.3, z - 6, p + 0.1, y + 40, z + 24] : [x - 15, y + 0.3, p - 0.1, x + 15, y + 40, p + 0.1] });
+ console.log(`explosion ${JSON.stringify({ k: fired++, frame: frames, r: 0, cut: true, ...e })}`);
+ }
} else if (s === "crater") {
// Ground spot 62: 9 m ahead on the road.
if (t >= 1 && last !== 0) {
@@ -331,9 +362,15 @@ export function destructionGame(route: "mesh" | "boxes", seed = 1, debris: boole
show: (tx) => { tx.state.scenario = "show"; tx.state.started = frames; last = -1; },
crater: (tx) => { tx.state.scenario = "crater"; tx.state.started = frames; last = -1; },
fell: (tx) => { tx.state.scenario = "fell"; tx.state.started = frames; last = -1; },
+ shatter: (tx) => { tx.state.scenario = "shatter"; tx.state.started = frames; last = -1; },
+ "shatter-dense": (tx) => { tx.state.scenario = "shatter-dense"; tx.state.started = frames; last = -1; },
topple: (tx) => { tx.state.scenario = "topple"; tx.state.started = frames; last = -1; },
// The level's hash, logged (`hash <16 hex digits>`): the same events at the same frames give the same one.
- hash: () => { console.log(`hash ${voxelHash()} frame ${frames}`); },
+ // With physics, the physics world's hash too (the bodies' poses and velocities, bit for bit).
+ hash: () => {
+ const world = physics ? (JSON.parse((globalThis as { __engine?: { physics?: (op: string, a: object) => string } }).__engine?.physics?.("hash", {}) ?? "{}") as { hash?: string }).hash : undefined;
+ console.log(`hash ${voxelHash()}${world ? ` physics ${world}` : ""} frame ${frames}`);
+ },
},
});
}
diff --git a/packages/scene/src/raycaster.ts b/packages/scene/src/raycaster.ts
index 549ce13..cfea6a3 100644
--- a/packages/scene/src/raycaster.ts
+++ b/packages/scene/src/raycaster.ts
@@ -9,7 +9,7 @@
// what a shape overlaps or meets when moved. Both see the world as the engine has it, with or without a tick since
// the last change; what the running script changed in the scene reaches the engine when it returns (docs/RUNTIME.md,
// World handlers).
-import { InstancedMesh, Mesh, type Object3D, type PerspectiveCamera, physicsBodies, physicsQuery, ProceduralGeometry, ProceduralMesh } from "./core.ts";
+import { InstancedMesh, Mesh, 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";
@@ -24,14 +24,35 @@ export interface Intersection {
instanceId?: number;
/** The surface's normal at the point, in the world (hits of the physics world). */
normal?: Vector3;
+ /** A hit on one of the engine's own colliders (`object` is `engineColliders`): the physics world's id of the
+ * collider. */
+ collider?: number;
+ /** On such a hit, the physics world's id of the body the collider is on: there on a voxel body (a part that came
+ * loose), absent on the voxel level itself, which is fixed and on no body. */
+ body?: number;
}
+/** The physics world's ids from here up are the engine's own bodies and colliders: a voxel level's objects (fixed
+ * colliders) and the parts that came loose from it (bodies). No scene object stands for them. */
+export const ENGINE_IDS = 2 ** 30;
+
+/**
+ * The `object` of a physics hit on one of the engine's own colliders (a voxel level: `@threert/voxel`). It is in no
+ * scene and has no `physics` (`hit.object.physics` is null): what was met is in the hit's `collider` and `body`.
+ * - The voxel level: `body` is absent. The level is fixed; `hit.object.physics?.type === "fixed"`, the test for a
+ * fixed scene object, does not say so here: test `hit.object === engineColliders && hit.body === undefined`.
+ * - A voxel body (a part that came loose): `body` is its id, the one `voxelBodies()` lists and `voxelImpulse` takes.
+ */
+export const engineColliders = new Object3D();
+engineColliders.name = "engine colliders";
+
/** 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 {
+ collider?: number;
body: number | null;
distance: number;
point: [number, number, number];
@@ -39,8 +60,10 @@ interface PhysicsHit {
}
function physicsIntersection(h: PhysicsHit): Intersection | null {
+ const hit = { distance: h.distance, point: new Vector3(...h.point), face: null, faceIndex: null, normal: new Vector3(...h.normal) };
+ if (h.collider !== undefined && h.collider >= ENGINE_IDS) return { ...hit, object: engineColliders, collider: h.collider, ...(h.body === null ? {} : { body: h.body }) };
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;
+ return object ? { ...hit, object } : null;
}
function skipOf(o: PhysicsQueryOptions): { skip?: number } {
@@ -200,10 +223,11 @@ export class Shapecaster {
/** 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 hits = physicsQuery("overlap", { ...this.at(), ...skipOf(options) }) as { collider?: number; body: number | null }[] | null;
const out = new Set<Object3D>();
for (const h of hits ?? []) {
- const o = h.body === null ? undefined : physicsBodies.get(h.body);
+ // (The engine's own colliders, a voxel level's: `engineColliders`, once.)
+ const o = h.collider !== undefined && h.collider >= ENGINE_IDS ? engineColliders : h.body === null ? undefined : physicsBodies.get(h.body);
if (o) out.add(o);
}
return [...out];
diff --git a/packages/scene/test/physics.test.ts b/packages/scene/test/physics.test.ts
index 952ab0f..8a0eae2 100644
--- a/packages/scene/test/physics.test.ts
+++ b/packages/scene/test/physics.test.ts
@@ -3,7 +3,7 @@
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,
+ BoxGeometry, CapsuleGeometry, engineColliders, Group, HingeJoint, IcosahedronGeometry, Mesh, type Object3D, PerspectiveCamera, PlaneGeometry, Raycaster, RecordingEngine, RopeJoint, Scene, SceneBinding,
Shapecaster, SphereGeometry, Vector3, type ContactEvent, type ObjectDesc,
} from "../src/index.ts";
@@ -441,6 +441,19 @@ test("rays and shapes ask the physics world; contacts arrive as events, in batch
engine.take();
binding.deliverPhysicsEvents();
assert.deepEqual(physics(), [["faults", {}]]);
+ // The engine's own colliders (a voxel level's objects and loose parts: ids from 2^30 up) are no scene object's: a
+ // hit on one has `engineColliders` for its object, the collider's id, and the body's when it is on one.
+ const E = 2 ** 30;
+ engine.answers.ray = [
+ { collider: E + 3, body: null, object: null, distance: 4, point: [0, 0, 4], normal: [0, 0, -1] },
+ { collider: E + 8, body: E + 7, object: null, distance: 6, point: [0, 0, 6], normal: [0, 0, -1] },
+ ];
+ const voxels = ray.intersectPhysics();
+ assert.deepEqual(voxels.map((h) => [h.object === engineColliders, h.collider, h.body, h.distance]), [[true, E + 3, undefined, 4], [true, E + 8, E + 7, 6]]);
+ engine.answers.overlap = [{ collider: E + 3, body: null, object: null }, { collider: E + 8, body: E + 7, object: null }, { collider: 9, body: null, object: null }];
+ assert.deepEqual(probe.overlap().map((o) => o.name), ["engine colliders"], "once; a static collider of no object is still left out");
+ engine.answers.sweep = { collider: E + 8, body: E + 7, object: null, distance: 0.5, point: [0, 2, 0], normal: [0, 1, 0] };
+ assert.deepEqual([probe.sweep(new Vector3(0, -1, 0))?.body, probe.sweep(new Vector3(0, -1, 0))?.object.name], [E + 7, "engine colliders"]);
});
test("a scene without physics makes no physics call; gravity is sent when it is not the default", () => {
diff --git a/packages/voxel/src/native.ts b/packages/voxel/src/native.ts
index a8b0aa9..aeef4d1 100644
--- a/packages/voxel/src/native.ts
+++ b/packages/voxel/src/native.ts
@@ -4,7 +4,14 @@
// The level is one lattice of the voxel size: every object stands in it, turned by quarter turns. Edits are shapes in
// world metres, applied in fixed point, so the same commands give the same voxels on every machine (`voxelHash`).
// After an edit, what no chain of voxels sharing a face joins to an anchor (the terrain, objects marked `anchor`) is
-// cut loose: a new object that falls until it rests on something. The removed voxels are debris (`voxelDebris`).
+// cut loose: a rigid body of the physics world (it tumbles, lands on the level and on other bodies, and sleeps; an
+// explosion carves it like the level). The removed voxels are debris (`voxelDebris`).
+//
+// The level collides without being asked: every object is a fixed collider of its voxels, kept up to date by edits, so
+// `Raycaster.intersectPhysics`, shape casts and the game's own bodies meet it. `physics: false` on the level turns
+// all of it off (no collider; loose parts fall straight down until they rest, as before); `collide: false` on an
+// object leaves that object without a collider.
+import { usePhysicsEngine } from "@threert/scene";
export type Hardness = "soft" | "medium" | "hard" | "indestructible";
@@ -15,12 +22,14 @@ export interface NativeLevel {
/** Index = voxel material. Linear colour. `emissive`: nits, the entry's colour, for voxels that glow and light what
* is near them on the mesh route. `hardness`: how far an explosion reaches it, as a share of its radius: soft (the
* default) all of it, medium 0.7, hard 0.4, indestructible never (cuts leave it too). */
- palette: { name: string; color: [number, number, number]; roughness: number; metalness: number; emissive?: number; hardness?: Hardness }[];
+ /** `density`: kg/m³ of its voxels in a rigid body (default by hardness: 900, 1,800, 2,400, 7,800). */
+ palette: { name: string; color: [number, number, number]; roughness: number; metalness: number; emissive?: number; hardness?: Hardness; density?: number }[];
function?: string;
/** `position`: metres, taken to the nearest voxel. `turn`: quarter turns about y. `tile`: a terrain tile (its
* neighbours hide each other's side faces; terrain is an anchor). `anchor`: it holds what touches it and never
* falls. */
- objects: { name: string; uri: string; position: [number, number, number]; turn?: number; tile?: [number, number]; anchor?: boolean }[];
+ /** `collide: false`: no collider for the object (bodies and rays pass through it). */
+ objects: { name: string; uri: string; position: [number, number, number]; turn?: number; tile?: [number, number]; anchor?: boolean; collide?: boolean }[];
/** Keep the removed voxels that are in no new object for `voxelDebris`. */
debris?: boolean;
/** "vertex": on the mesh route one mesh per class of palette entries (alike in all but their colour), each vertex its
@@ -29,6 +38,13 @@ export interface NativeLevel {
/** The cell size (m) of the occupancy grid `GpuParticles` with `collide.voxels` collide with (default: none); kept up
* to date as edits carve and loose parts land. */
occupancy?: number;
+ /** The level's physics (default true): colliders for its objects, rigid bodies for what comes loose. */
+ physics?: boolean;
+ /** The most voxel bodies at once (default 300: what holds 60 fps natively with all of them moving at once). At it,
+ * a new part takes the place of the body that matters least (asleep before awake, then the fewest voxels, then
+ * the oldest; never one the same edit carved or made), if that body is no larger; else the new part is debris.
+ * What goes is debris (`voxelDebris`). */
+ maxBodies?: number;
}
/** A shape in world metres. A voxel is inside when its centre is. */
@@ -64,6 +80,24 @@ export interface VoxelEdit {
triangles: number;
objects: number;
world_objects: number;
+ /** The colliders brought up to date, ms; the voxel bodies there are now. */
+ colliders_ms?: number;
+ bodies?: number;
+ /** A carve reaches the bodies too: the bodies it carved, their voxels removed, ms. */
+ bodies_carved?: number;
+ body_voxels?: number;
+ bodies_ms?: number;
+}
+
+/** A loose part as a rigid body. `body` and `collider` are the physics world's ids of it: ray and shape cast hits
+ * and contacts report them. */
+export interface VoxelBody {
+ body: number;
+ collider: number;
+ voxels: number;
+ asleep: boolean;
+ position: [number, number, number];
+ rotation: [number, number, number, number];
}
/** (The name before step 6.) */
export type Explosion = VoxelEdit;
@@ -87,14 +121,20 @@ interface NativeEngine {
voxelFrame?: (dt: number) => string;
voxelDebris?: () => Float32Array;
voxelHash?: () => string;
+ voxelBodies?: () => string;
+ physics?: (op: string, args: object) => string;
+ physicsPoses?: () => Float32Array;
}
const engine = () => (globalThis as { __engine?: NativeEngine }).__engine;
-/** Loads `level` natively (once the renderer knows its asset root, before the first frame). */
+/** Loads `level` natively (once the renderer knows its asset root, before the first frame). A level that collides
+ * (`physics` not false) is in the physics world whether or not any scene object has `physics`: the scene's queries
+ * (`Raycaster.intersectPhysics`, `Shapecaster`) ask that world from here on. */
export function voxelLevel(level: NativeLevel): void {
const e = engine();
if (!e?.voxelLevel) throw new Error("voxelLevel: needs the renderer's native voxels");
e.voxelLevel(level);
+ if (level.physics !== false && e.physics) usePhysicsEngine(e as Parameters<typeof usePhysicsEngine>[0]);
}
function edit(d: object): VoxelEdit | { queued: true } {
@@ -138,13 +178,38 @@ export function voxelDebris(): Float32Array {
return e.voxelDebris();
}
-/** Once a frame: the falling objects move (60 ticks a second) and come to rest. */
+/**
+ * Once a frame, on a level without physics (`physics: false`): the falling objects move (60 ticks a second) and come
+ * to rest. On a level that collides (the default) there is nothing for it to move: what comes loose is a body of the
+ * physics world, which the engine steps by the frame's clock and scene code cannot step. So `voxelFrame` calls in
+ * setup after an edit settle nothing there: a live run's bodies fall from its first frame, and an offline render at
+ * a scene time (`time`) has the world stepped that far (tests/render/voxel-cut-body.ts).
+ */
export function voxelFrame(dt: number): VoxelFrame | { queued: true } {
const e = engine();
if (!e?.voxelFrame) throw new Error("voxelFrame: needs the renderer's native voxels");
return JSON.parse(e.voxelFrame(dt)) as VoxelFrame | { queued: true };
}
+/** The voxel bodies there are now (loose parts the physics world moves), oldest first. */
+export function voxelBodies(): VoxelBody[] {
+ const e = engine();
+ if (!e?.voxelBodies) throw new Error("voxelBodies: needs the renderer's native voxels");
+ return JSON.parse(e.voxelBodies()) as VoxelBody[];
+}
+
+/**
+ * An impulse (N s) on a voxel body: at its centre of mass, or at a point of the world (which turns it too). `body` is
+ * the id `voxelBodies()` lists and a physics hit reports (`Raycaster.intersectPhysics`: `hit.body`; a hit on the
+ * level itself has `hit.object === engineColliders`, a null `hit.object.physics` and no `body`: the level is fixed).
+ * Throws if there is no such body (it may have been carved away, or retired for the cap, since the id was read).
+ */
+export function voxelImpulse(body: number, impulse: readonly [number, number, number], point?: readonly [number, number, number]): void {
+ const e = engine();
+ if (!e?.physics) throw new Error("voxelImpulse: needs the renderer's physics");
+ e.physics("impulse", { body, impulse: [...impulse], ...(point ? { point: [...point] } : {}) });
+}
+
/** A hash of the level's voxels and objects (16 hex digits; "" before it is loaded): the same commands in the same
* order give the same hash on every machine. */
export function voxelHash(): string {
diff --git a/packages/voxel/test/voxel.test.ts b/packages/voxel/test/voxel.test.ts
index fd36615..b9053de 100644
--- a/packages/voxel/test/voxel.test.ts
+++ b/packages/voxel/test/voxel.test.ts
@@ -77,3 +77,56 @@ test("bulk writes: brick() and fillBrick()", () => {
assert.equal(g.get(8, 0, -8), 0);
assert.equal(g.layout().stats.voxels, 1);
});
+
+test("voxel bodies: the list is the engine's, an impulse goes to the physics world by the body's id", async () => {
+ const { voxelBodies, voxelImpulse } = await import("../src/native.ts");
+ const calls: [string, object][] = [];
+ const g = globalThis as { __engine?: object };
+ const before = g.__engine;
+ g.__engine = {
+ voxelBodies: () => JSON.stringify([{ body: 2 ** 30 + 7, collider: 2 ** 30 + 8, voxels: 416, asleep: true, position: [0, 0.8, 0], rotation: [0, 0, 0, 1] }]),
+ physics: (op: string, args: object) => { calls.push([op, args]); return "null"; },
+ };
+ try {
+ const [b] = voxelBodies();
+ assert.deepEqual([b.body, b.voxels, b.asleep], [2 ** 30 + 7, 416, true]);
+ voxelImpulse(b.body, [0, 50, 0]);
+ voxelImpulse(b.body, [1, 0, 0], [0, 1, 0]);
+ assert.deepEqual(calls, [["impulse", { body: 2 ** 30 + 7, impulse: [0, 50, 0] }], ["impulse", { body: 2 ** 30 + 7, impulse: [1, 0, 0], point: [0, 1, 0] }]]);
+ } finally {
+ g.__engine = before;
+ }
+});
+
+test("a voxel level that collides is what the scene's physics queries ask, with no scene object that has physics: a ray's hit on a voxel body goes into voxelImpulse", async () => {
+ const { voxelLevel, voxelImpulse } = await import("../src/native.ts");
+ const { engineColliders, Raycaster, Vector3 } = await import("@threert/scene");
+ const calls: [string, object][] = [];
+ const [level, part] = [2 ** 30 + 1, 2 ** 30 + 7];
+ const g = globalThis as { __engine?: object };
+ const before = g.__engine;
+ g.__engine = {
+ voxelLevel: () => {},
+ physics: (op: string, args: { direction?: number[] }) => {
+ calls.push([op, args]);
+ if (op !== "ray") return "null";
+ // Down: the level (a fixed collider, on no body). Along z: a voxel body, then the level behind it.
+ const down = { collider: level, body: null, distance: 4.6, point: [1, 0.4, 1], normal: [0, 1, 0] };
+ return JSON.stringify(args.direction![1] < 0 ? [down] : [{ collider: part + 1, body: part, distance: 4.8, point: [0.05, 2.05, 0.2], normal: [0, 0, 1] }, { ...down, distance: 9 }]);
+ },
+ };
+ try {
+ voxelLevel({ route: "mesh", palette: [], objects: [] });
+ const [ground] = new Raycaster(new Vector3(1, 5, 1), new Vector3(0, -1, 0)).intersectPhysics();
+ // The level: `engineColliders` for its object (no scene object: `physics` is null), a collider, no body.
+ assert.equal(ground.object, engineColliders);
+ assert.equal(ground.object.physics, null);
+ assert.deepEqual([ground.collider, ground.body, ground.distance], [level, undefined, 4.6]);
+ const hits = new Raycaster(new Vector3(0.05, 2.05, 5), new Vector3(0, 0, -1)).intersectPhysics();
+ assert.deepEqual(hits.map((h) => [h.object === engineColliders, h.collider, h.body]), [[true, part + 1, part], [true, level, undefined]]);
+ voxelImpulse(hits[0].body!, [1500, 300, 0]);
+ assert.deepEqual(calls.at(-1), ["impulse", { body: part, impulse: [1500, 300, 0] }]);
+ } finally {
+ g.__engine = before;
+ }
+});
diff --git a/renderer/Cargo.lock b/renderer/Cargo.lock
index 135d6c7..40d9a0d 100644
--- a/renderer/Cargo.lock
+++ b/renderer/Cargo.lock
@@ -494,6 +494,15 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
+[[package]]
+name = "ena"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eabffdaee24bd1bf95c5ef7cec31260444317e72ea56c4c91750e8b7ee58d5f1"
+dependencies = [
+ "log",
+]
+
[[package]]
name = "equivalent"
version = "1.0.3"
@@ -672,6 +681,18 @@ dependencies = [
"bytemuck",
]
+[[package]]
+name = "glam"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "556f6b2ea90b8d15a74e0e7bb41671c9bdf38cd9f78c284d750b9ce58a2b5be7"
+
+[[package]]
+name = "glam"
+version = "0.32.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f70749695b063ecbf6b62949ccccde2e733ec3ecbbd71d467dca4e5c6c97cca0"
+
[[package]]
name = "glam"
version = "0.33.12"
@@ -1042,6 +1063,16 @@ version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
+[[package]]
+name = "matrixmultiply"
+version = "0.3.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
+dependencies = [
+ "autocfg",
+ "rawpointer",
+]
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -1132,7 +1163,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adc43a60c217b0c6ff46e47f26911015ad8d2e5a8be1af668c67e370d99a4346"
dependencies = [
"approx",
+ "glam 0.30.10",
+ "glam 0.31.1",
+ "glam 0.32.1",
"glam 0.33.12",
+ "matrixmultiply",
"nalgebra-macros",
"num-complex",
"num-rational",
@@ -1182,6 +1217,16 @@ dependencies = [
"jni-sys 0.3.1",
]
+[[package]]
+name = "num-bigint"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-complex"
version = "0.4.6"
@@ -1218,6 +1263,7 @@ version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
+ "num-bigint",
"num-integer",
"num-traits",
]
@@ -1616,6 +1662,7 @@ dependencies = [
"bitflags 2.13.2",
"downcast-rs 2.0.2",
"either",
+ "ena",
"foldhash",
"glamx",
"hashbrown 0.17.1",
@@ -1624,9 +1671,12 @@ dependencies = [
"num-derive",
"num-traits",
"ordered-float",
+ "rayon",
"rstar",
"simba",
+ "slab",
"smallvec",
+ "spade",
"static_assertions",
"thiserror 2.0.21",
]
@@ -1861,6 +1911,7 @@ dependencies = [
"num-traits",
"parry3d",
"profiling",
+ "rayon",
"serde",
"simba",
"static_assertions",
@@ -1895,6 +1946,12 @@ dependencies = [
"objc2-quartz-core 0.3.2",
]
+[[package]]
+name = "rawpointer"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
+
[[package]]
name = "rayon"
version = "1.12.0"
@@ -1963,6 +2020,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
+[[package]]
+name = "robust"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e27ee8bb91ca0adcf0ecb116293afa12d393f9c2b9b9cd54d33e8078fe19839"
+
[[package]]
name = "rquickjs"
version = "0.12.2"
@@ -2249,6 +2312,18 @@ dependencies = [
"serde",
]
+[[package]]
+name = "spade"
+version = "2.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9699399fd9349b00b184f5635b074f9ec93afffef30c853f8c875b32c0f8c7fa"
+dependencies = [
+ "hashbrown 0.16.1",
+ "num-traits",
+ "robust",
+ "smallvec",
+]
+
[[package]]
name = "spirv"
version = "0.4.0+sdk-1.4.341.0"
@@ -2357,6 +2432,7 @@ dependencies = [
"gltf",
"half",
"image",
+ "libc",
"naga",
"oidn",
"physics-core",
diff --git a/renderer/Cargo.toml b/renderer/Cargo.toml
index f6734d7..23b35bd 100644
--- a/renderer/Cargo.toml
+++ b/renderer/Cargo.toml
@@ -28,12 +28,21 @@ web-time = "1.1"
# engine's library builds without them for wasm32 (docs/RUNTIME.md "The engine's library in a browser"): there the
# page owns the window and the event loop, and scripts run in the browser's own engine.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+# Natively the physics world is stepped by Rapier's parallel solver (ROADMAP § 6 step 8; decided 2026-11-11), in a
+# pool of its own (src/physics.rs: 4 threads or the performance cores when fewer; THREERT_PHYSICS_THREADS changes it,
+# 1 is sequential). It steps to the sequential build's bits, which are wasm32's (tools/physics-determinism.ts holds
+# the three to the recorded hashes). wasm32 has no threads here and stays sequential: the dependency above.
+physics-core = { path = "physics-core", features = ["parallel"] }
pollster = "0.4"
winit = "0.30"
oidn = { version = "2.5", optional = true }
# Scene runtime of the render node (game bundles run in the renderer process, src/script.rs).
rquickjs = "0.12"
+# The performance cores' count (src/physics.rs: the physics' threads).
+[target.'cfg(target_os = "macos")'.dependencies]
+libc = "0.2"
+
# src/merged.rs's tests read the generated shaders with the compiler wgpu uses: they are valid, and no stage binds more
# storage buffers than a browser allows.
[dev-dependencies]
diff --git a/renderer/examples/physics_bits.rs b/renderer/examples/physics_bits.rs
index a989cf2..a9c10e7 100644
--- a/renderer/examples/physics_bits.rs
+++ b/renderer/examples/physics_bits.rs
@@ -15,3 +15,10 @@ pub extern "C" fn physics_script() -> u64 {
pub extern "C" fn physics_cases() -> u64 {
physics_core::check::cases()
}
+
+/// The voxel bodies' script (renderer/src/voxel.rs `VoxelWorld::check_script`: the level's colliders, a part that
+/// topples as a body, carved as it lies): the adapter between the voxels and the physics, in wasm32.
+#[no_mangle]
+pub extern "C" fn voxel_bodies_script() -> u64 {
+ threert_render::voxel::VoxelWorld::check_script()
+}
diff --git a/renderer/examples/physics_fuzz.rs b/renderer/examples/physics_fuzz.rs
new file mode 100644
index 0000000..4fccac9
--- /dev/null
+++ b/renderer/examples/physics_fuzz.rs
@@ -0,0 +1,251 @@
+//! Two CPU checks of the engine's own path through the voxel bodies and the physics (ROADMAP § 6 step 8), **with a
+//! watchdog**: a step that does not return is a failure, not a wait.
+//!
+//! - **The fuzz** (`--runs`): a small voxel level, and per iteration a random edit (carve, explosion, added voxels,
+//! paint; with wild numbers after the first third) or one of scene code's physics calls (on the voxel bodies too),
+//! then one to four frames' steps (`api::physics_advance`: on the physics' threads, as the renderer steps). After
+//! every iteration: each voxel body has its engine body, its collider's cells are its grid's, it is somewhere
+//! finite, and the cap holds.
+//! - **The stress** (`--stress`): a slab and six bars cut loose, kept moving, stepped back to back that many times.
+//! This is where the physics' step hung (src/physics.rs `in_pool` has the cause: Rapier waits on a channel, inside
+//! a rayon worker, for a job only another worker can take, and rayon does not promise one comes): with a tree
+//! optimisation spawned in nearly every step and the next step microseconds after the last, the unguarded step
+//! hangs after 30,000 to 400,000 steps (five runs of five; `THREERT_PHYSICS_KICK=off` brings it back). The fuzz
+//! found it first, in one run of fifty.
+//!
+//! - **The bits** (`--bits`): the physics' recorded hashes (physics_core::check: the script and the 1,500 random
+//! worlds) and the voxel adapter's (`VoxelWorld::check_script`), stepped on the physics' own threads as the
+//! renderer steps (`in_pool`, `THREERT_PHYSICS_THREADS`). tools/physics-determinism.ts holds the parallel build to
+//! the sequential one stepping from a thread outside any pool; this is the path the renderer takes.
+//!
+//! The same place for `--limit` seconds (30) ends the process with exit 3 and says where.
+//!
+//! cargo run --release --example physics_fuzz -- [--bits] [--runs 20] [--from 1] [--iterations 1500] [--many]
+//! [--stress 2000000] [--limit 30]
+//!
+//! `--many`: 480 bars cut loose at once and again, so more loose parts than the cap holds. Exit 0: every run ended and
+//! every check held. `kicks` counts the times a step's wait woke the physics' threads (`in_pool`): in the stress,
+//! whose steps take microseconds, each is a step that would have hung (or a thread the system held back).
+use serde_json::json;
+use std::sync::atomic::{AtomicU64, Ordering};
+use threert_render::api;
+use threert_render::physics::PhysicsWorld;
+use threert_render::voxel::{EditOp, VoxelWorld, MAX_BODIES};
+use threert_render::world::World;
+
+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
+ }
+ fn unit(&mut self) -> f64 {
+ (self.next() >> 11) as f64 / (1u64 << 53) as f64
+ }
+ fn range(&mut self, a: f64, b: f64) -> f64 {
+ a + (b - a) * self.unit()
+ }
+ fn below(&mut self, n: u64) -> u64 {
+ self.next() % n
+ }
+ fn chance(&mut self, p: f64) -> bool {
+ self.unit() < p
+ }
+}
+
+/// Where the fuzz is (seed in the high half, iteration in the low), for the watchdog.
+static AT: AtomicU64 = AtomicU64::new(0);
+
+/// One run; returns the kicks its steps took.
+fn run(seed: u64, iterations: u32, many: bool) -> u32 {
+ let mut r = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
+ let mut w = World::default();
+ let mut ph: Option<PhysicsWorld> = None;
+ // Two terrain tiles side by side and bars standing on them (a few of them anchors).
+ let mut blocks = vec![([0, 0, 0], [64, 6, 64], Some((0, 0)), true), ([64, 0, 0], [64, 6, 64], Some((1, 0)), true)];
+ if many {
+ for i in 0..24 {
+ for j in 0..20 {
+ blocks.push(([2 + i * 5, 6, 2 + j * 3], [2, 8 + r.below(12) as i32, 2], None, false));
+ }
+ }
+ } else {
+ for i in 0..10 {
+ for j in 0..5 {
+ blocks.push(([6 + i * 11, 6, 6 + j * 11], [2 + r.below(4) as i32, 6 + r.below(20) as i32, 2 + r.below(4) as i32], None, r.chance(0.1)));
+ }
+ }
+ }
+ let mut v = VoxelWorld::of_blocks(&blocks, &mut w, &mut ph);
+ if many {
+ // Every bar cut loose at its foot, then again: more loose parts than the cap holds.
+ for y in [0.7, 1.1] {
+ let _ = v.edit(&mut w, &mut ph, &EditOp::parse(&json!({ "op": "carve", "box": [0.0, y, 0.0, 12.8, y + 0.1, 6.4] })).unwrap());
+ w.take_changes();
+ }
+ }
+ let weird = |r: &mut Rng| -> f64 { [0.0, -1.0, 1e-9, 1e9, 1e30, -1e30, 12.9, 300.0, 0.05, 1e5, 104857.6][r.below(11) as usize] };
+ let pos = |r: &mut Rng, wild: bool| -> f64 {
+ if wild && r.chance(0.15) {
+ weird(r)
+ } else {
+ r.range(-1.0, 13.5)
+ }
+ };
+ let (mut edits, mut refused, mut calls_refused, mut most, mut kicks) = (0u32, 0u32, 0u32, 0usize, 0u32);
+ let mut advance = |v: &mut VoxelWorld, w: &mut World, ph: &mut Option<PhysicsWorld>| {
+ api::physics_advance(ph, v, w, 1.0 / 60.0);
+ w.take_changes();
+ kicks += ph.as_mut().map_or(0, |p| p.take_stats().kicks);
+ };
+ for it in 0..iterations {
+ AT.store(seed << 32 | it as u64, Ordering::Relaxed);
+ let wild = it > iterations / 3;
+ match r.below(10) {
+ 0..=4 => {
+ let op = ["carve", "carve", "explode", "add", "paint"][r.below(5) as usize];
+ let wild = wild && op != "add";
+ let rad = if wild && r.chance(0.2) { weird(&mut r) } else { r.range(0.1, 1.5) };
+ let d = match if many && r.chance(0.5) { 3 } else { r.below(3) } {
+ 3 => {
+ let y = r.range(0.5, 2.5);
+ json!({ "op": "carve", "box": [r.range(0.0, 6.0), y, 0.0, r.range(6.0, 12.8), y + 0.1, 6.4] })
+ }
+ 0 => json!({ "op": op, "material": 1, "sphere": [pos(&mut r, wild), r.range(0.0, 3.0), pos(&mut r, wild) * 0.5, rad] }),
+ 1 => {
+ let (x, y, z) = (pos(&mut r, wild), r.range(0.0, 3.0), pos(&mut r, wild) * 0.5);
+ let far = if wild && r.chance(0.2) { weird(&mut r) } else { r.range(-0.5, 3.0) };
+ json!({ "op": op, "material": 1, "box": [x, y, z, x + far, y + r.range(-0.2, 1.0), z + r.range(0.0, 3.0)] })
+ }
+ _ => json!({ "op": op, "material": 1, "capsule": [pos(&mut r, wild), r.range(0.0, 3.0), pos(&mut r, wild) * 0.5, pos(&mut r, wild), r.range(0.0, 3.0), pos(&mut r, wild) * 0.5, rad.min(3.0)] }),
+ };
+ match EditOp::parse(&d).and_then(|e| v.edit(&mut w, &mut ph, &e)) {
+ Ok(_) => edits += 1,
+ Err(_) => refused += 1,
+ }
+ }
+ 5 => {
+ let radius = if wild && r.chance(0.3) { [f64::NAN, f64::INFINITY, -f64::INFINITY, 1e300, -3.0][r.below(5) as usize] } else { r.range(0.2, 2.0) };
+ let _ = api::voxel_explode(&mut v, &mut w, &mut ph, pos(&mut r, wild), r.range(0.0, 3.0), pos(&mut r, wild) * 0.5, radius);
+ }
+ _ => {
+ // Scene code's physics calls, on the voxel bodies too.
+ let list = v.body_list(ph.as_ref().unwrap());
+ let ids: Vec<u64> = list.as_array().unwrap().iter().map(|b| b["body"].as_u64().unwrap()).collect();
+ let cols: Vec<u64> = list.as_array().unwrap().iter().map(|b| b["collider"].as_u64().unwrap()).collect();
+ let body = if ids.is_empty() || r.chance(0.2) { 1 + r.below(6) } else { ids[r.below(ids.len() as u64) as usize] };
+ let big = |r: &mut Rng| if r.chance(0.1) { 1e6 } else { r.range(-300.0, 300.0) };
+ let (op, args) = match r.below(12) {
+ 0 => ("impulse", json!({ "body": body, "impulse": [big(&mut r), big(&mut r), big(&mut r)], "point": [r.range(0.0, 12.0), 1.0, 3.0] })),
+ 1 => ("velocity", json!({ "body": body, "linvel": [r.range(-1e4, 1e4), r.range(-50.0, 50.0), 0.0], "angvel": [r.range(-1e3, 1e3), 0.0, 0.0] })),
+ 2 => ("pose", json!({ "body": body, "position": [pos(&mut r, false), r.range(-300.0, 20.0), 3.0], "rotation": [r.unit(), r.unit(), r.unit(), r.unit() + 0.01] })),
+ 3 => ("body", json!({ "id": 1 + r.below(6), "position": [r.range(0.0, 12.0), r.range(1.0, 6.0), 3.0], "kind": (["dynamic", "kinematic", "fixed"][r.below(3) as usize]) })),
+ 4 => ("collider", json!({ "id": 10 + r.below(12), "body": body, "shape": { "type": "box", "halfExtents": [r.range(0.05, 2.0), 0.2, 0.2] }, "mass": if r.chance(0.3) { 1e7 } else { 10.0 }, "events": true })),
+ 5 => ("joint", json!({ "id": 30 + r.below(8), "a": body, "b": if ids.is_empty() { 2 } else { ids[r.below(ids.len() as u64) as usize] }, "type": (["fixed", "revolute", "spherical", "rope", "prismatic"][r.below(5) as usize]), "length": 1.0, "limits": [-0.5, 0.5] })),
+ 6 => ("remove", json!({ "body": if r.chance(0.5) { body } else { 1 + r.below(6) }, "collider": if r.chance(0.5) && !cols.is_empty() { cols[0] } else { 10 + r.below(12) }, "joint": 30 + r.below(8) })),
+ 7 => ("force", json!({ "body": body, "force": [big(&mut r) * 100.0, 0.0, 0.0], "torque": [0.0, big(&mut r) * 100.0, 0.0] })),
+ 8 => ("ray", json!({ "origin": [r.range(0.0, 12.0), 8.0, r.range(0.0, 6.0)], "direction": [r.range(-0.2, 0.2), -1.0, 0.0], "all": r.chance(0.5), "skip": body })),
+ 9 => ("target", json!({ "body": body, "position": [1.0, 2.0, 3.0] })),
+ 10 => ("contacts", json!({})),
+ _ => ("overlap", json!({ "shape": { "type": "sphere", "radius": r.range(0.1, 3.0) }, "position": [r.range(0.0, 12.0), 1.0, 3.0] })),
+ };
+ if ph.as_mut().unwrap().call(&mut w, op, &args).is_err() {
+ calls_refused += 1;
+ }
+ }
+ }
+ w.take_changes();
+ for _ in 0..r.below(4) {
+ advance(&mut v, &mut w, &mut ph);
+ }
+ // What must hold (after a sync: a body the world took out is retired at the next sync).
+ advance(&mut v, &mut w, &mut ph);
+ let p = ph.as_ref().unwrap();
+ let list = v.body_list(p);
+ let list = list.as_array().unwrap();
+ most = most.max(list.len());
+ assert_eq!(list.len(), v.bodies(), "seed {seed}, iteration {it}: a voxel body without an engine body");
+ assert!(list.len() <= MAX_BODIES, "seed {seed}, iteration {it}: {} bodies", list.len());
+ for b in list {
+ let (id, collider, voxels) = (b["body"].as_u64().unwrap() as u32, b["collider"].as_u64().unwrap() as u32, b["voxels"].as_u64().unwrap() as usize);
+ assert!(voxels > 0, "seed {seed}, iteration {it}: body {id} has no voxel");
+ assert_eq!(p.bridge_ref().engine_voxels(collider), Some(voxels), "seed {seed}, iteration {it}: body {id}'s collider cells are not its grid's");
+ assert!(b["position"].as_array().unwrap().iter().all(|x| x.as_f64().is_some_and(f64::is_finite)), "seed {seed}, iteration {it}: body {id} at {}", b["position"]);
+ }
+ }
+ println!(
+ "seed {seed}: {iterations} iterations, edits {edits} (refused {refused}), calls refused {calls_refused}, most bodies {most}, retired {}, kicks {kicks}, hash {:016x}/{:016x}",
+ v.retired,
+ v.hash().unwrap_or(0),
+ ph.as_ref().unwrap().hash()
+ );
+ kicks
+}
+
+/// A small world stepped back to back: a slab and six bars cut loose, one of them thrown about every step (so the
+/// broad phase has a tree to tidy, which is the job that was stranded). Returns the kicks.
+fn stress(steps: u64) -> u32 {
+ let mut w = World::default();
+ let mut ph: Option<PhysicsWorld> = None;
+ let mut blocks = vec![([0, 0, 0], [64, 4, 64], Some((0, 0)), true)];
+ blocks.extend((0..6).map(|k| ([8 + 8 * k, 4, 8], [4, 12, 4], None, false)));
+ let mut v = VoxelWorld::of_blocks(&blocks, &mut w, &mut ph);
+ v.edit(&mut w, &mut ph, &EditOp::parse(&json!({ "op": "carve", "box": [0.0, 0.5, 0.0, 6.4, 0.6, 6.4] })).unwrap()).unwrap();
+ let ids: Vec<u64> = v.body_list(ph.as_ref().unwrap()).as_array().unwrap().iter().map(|b| b["body"].as_u64().unwrap()).collect();
+ assert_eq!(ids.len(), 6);
+ let (mut r, mut kicks) = (Rng(0x9E37_79B9_7F4A_7C15), 0);
+ for n in 0..steps {
+ AT.store(u64::MAX << 32 | (n & 0xffff_ffff), Ordering::Relaxed);
+ let body = ids[r.below(6) as usize];
+ ph.as_mut().unwrap().call(&mut w, "velocity", &json!({ "body": body, "linvel": [r.range(-2.0, 2.0), 3.0, r.range(-2.0, 2.0)] })).unwrap();
+ api::physics_advance(&mut ph, &mut v, &mut w, 1.0 / 60.0);
+ w.take_changes();
+ kicks += ph.as_mut().unwrap().take_stats().kicks;
+ }
+ assert_eq!(v.bodies(), 6, "the six bars are still bodies");
+ kicks
+}
+
+fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ let number = |name: &str, default: u64| args.iter().position(|a| a == name).and_then(|k| args.get(k + 1)).and_then(|v| v.parse().ok()).unwrap_or(default);
+ let (runs, from, iterations, steps, limit) = (number("--runs", 20), number("--from", 1), number("--iterations", 1500) as u32, number("--stress", 2_000_000), number("--limit", 30));
+ let many = args.iter().any(|a| a == "--many");
+ // The watchdog: the same place for `limit` seconds is a step (or an edit) that does not return.
+ std::thread::spawn(move || {
+ let (mut last, mut since) = (u64::MAX, std::time::Instant::now());
+ loop {
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ let at = AT.load(Ordering::Relaxed);
+ if at != last {
+ (last, since) = (at, std::time::Instant::now());
+ } else if since.elapsed().as_secs() >= limit {
+ let (seed, n) = (at >> 32, at & 0xffff_ffff);
+ eprintln!("physics fuzz: STUCK: {} has not returned in {limit} s", if seed == u32::MAX as u64 { format!("the stress's step {n} (modulo 2^32)") } else { format!("seed {seed}, iteration {n}") });
+ std::process::exit(3);
+ }
+ }
+ });
+ if args.iter().any(|a| a == "--bits") {
+ use physics_core::check;
+ let t = std::time::Instant::now();
+ let (mut script, mut cases) = (0, 0);
+ threert_render::physics::in_pool(|| (script, cases) = (check::script(600), check::cases()));
+ let voxels = threert_render::voxel::VoxelWorld::check_script();
+ let threads = std::env::var("THREERT_PHYSICS_THREADS").unwrap_or_default();
+ println!("physics bits on the physics' threads (THREERT_PHYSICS_THREADS={threads:?}): script {script:016x} (recorded {:016x}), cases {cases:016x} ({:016x}), voxel bodies {voxels:016x} ({:016x}); {:.1} s", check::EXPECTED, check::EXPECTED_CASES, threert_render::voxel::EXPECTED_SCRIPT, t.elapsed().as_secs_f64());
+ assert_eq!((script, cases, voxels), (check::EXPECTED, check::EXPECTED_CASES, threert_render::voxel::EXPECTED_SCRIPT), "the recorded hashes");
+ }
+ let t = std::time::Instant::now();
+ let kicks: u32 = (from..from + runs).map(|seed| run(seed, iterations, many)).sum();
+ if runs > 0 {
+ println!("physics fuzz: {runs} runs of {iterations} iterations in {:.1} s, every check held, no step hung; kicks {kicks}", t.elapsed().as_secs_f64());
+ }
+ if steps > 0 {
+ let t = std::time::Instant::now();
+ let kicks = stress(steps);
+ println!("physics stress: {steps} steps back to back in {:.1} s ({:.1} us a step), none hung; kicks {kicks}", t.elapsed().as_secs_f64(), t.elapsed().as_secs_f64() * 1e6 / steps as f64);
+ }
+}
diff --git a/renderer/physics-core/Cargo.lock b/renderer/physics-core/Cargo.lock
index e983201..8637b7a 100644
--- a/renderer/physics-core/Cargo.lock
+++ b/renderer/physics-core/Cargo.lock
@@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 4
+[[package]]
+name = "allocator-api2"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+
[[package]]
name = "approx"
version = "0.5.1"
@@ -41,6 +47,31 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
+
[[package]]
name = "downcast-rs"
version = "2.0.2"
@@ -53,6 +84,15 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
+[[package]]
+name = "ena"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eabffdaee24bd1bf95c5ef7cec31260444317e72ea56c4c91750e8b7ee58d5f1"
+dependencies = [
+ "log",
+]
+
[[package]]
name = "equivalent"
version = "1.0.3"
@@ -65,6 +105,24 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+[[package]]
+name = "glam"
+version = "0.30.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
+
+[[package]]
+name = "glam"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "556f6b2ea90b8d15a74e0e7bb41671c9bdf38cd9f78c284d750b9ce58a2b5be7"
+
+[[package]]
+name = "glam"
+version = "0.32.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f70749695b063ecbf6b62949ccccde2e733ec3ecbbd71d467dca4e5c6c97cca0"
+
[[package]]
name = "glam"
version = "0.33.12"
@@ -80,7 +138,7 @@ name = "glamx"
version = "0.3.1"
dependencies = [
"approx",
- "glam",
+ "glam 0.33.12",
"nalgebra",
"num-traits",
"simba",
@@ -95,6 +153,17 @@ dependencies = [
"byteorder",
]
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash",
+]
+
[[package]]
name = "hashbrown"
version = "0.17.1"
@@ -121,7 +190,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
- "hashbrown",
+ "hashbrown 0.17.1",
"serde",
"serde_core",
]
@@ -144,6 +213,16 @@ version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
+[[package]]
+name = "matrixmultiply"
+version = "0.3.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
+dependencies = [
+ "autocfg",
+ "rawpointer",
+]
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -157,7 +236,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adc43a60c217b0c6ff46e47f26911015ad8d2e5a8be1af668c67e370d99a4346"
dependencies = [
"approx",
- "glam",
+ "glam 0.30.10",
+ "glam 0.31.1",
+ "glam 0.32.1",
+ "glam 0.33.12",
+ "matrixmultiply",
"nalgebra-macros",
"num-complex",
"num-rational",
@@ -177,6 +260,16 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "num-bigint"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-complex"
version = "0.4.6"
@@ -212,6 +305,7 @@ version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
+ "num-bigint",
"num-integer",
"num-traits",
]
@@ -246,17 +340,21 @@ dependencies = [
"bitflags",
"downcast-rs",
"either",
+ "ena",
"foldhash",
"glamx",
- "hashbrown",
+ "hashbrown 0.17.1",
"indexmap",
"log",
"num-derive",
"num-traits",
"ordered-float",
+ "rayon",
"rstar",
"simba",
+ "slab",
"smallvec",
+ "spade",
"static_assertions",
"thiserror",
]
@@ -323,6 +421,7 @@ dependencies = [
"num-traits",
"parry3d",
"profiling",
+ "rayon",
"serde",
"simba",
"static_assertions",
@@ -330,6 +429,38 @@ dependencies = [
"wide",
]
+[[package]]
+name = "rawpointer"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
+
+[[package]]
+name = "rayon"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "robust"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e27ee8bb91ca0adcf0ecb116293afa12d393f9c2b9b9cd54d33e8078fe19839"
+
[[package]]
name = "rstar"
version = "0.13.1"
@@ -406,12 +537,30 @@ dependencies = [
"wide",
]
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
[[package]]
name = "smallvec"
version = "1.16.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"
+[[package]]
+name = "spade"
+version = "2.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9699399fd9349b00b184f5635b074f9ec93afffef30c853f8c875b32c0f8c7fa"
+dependencies = [
+ "hashbrown 0.16.1",
+ "num-traits",
+ "robust",
+ "smallvec",
+]
+
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
diff --git a/renderer/physics-core/Cargo.toml b/renderer/physics-core/Cargo.toml
index f61686e..3662b87 100644
--- a/renderer/physics-core/Cargo.toml
+++ b/renderer/physics-core/Cargo.toml
@@ -12,6 +12,10 @@ default = ["enhanced-determinism"]
# 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"]
+# Rapier's parallel solver and narrow phase (rayon): for native builds only (wasm32 has no threads here). Off in this
+# crate's own default; the renderer's native build turns it on (ROADMAP § 6 step 8). The world steps to the same bits
+# with it, at any thread count we ran (docs/VOXEL.md "Voxel bodies"; tools/physics-determinism.ts holds it in CI).
+parallel = ["rapier3d/parallel"]
# 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.
@@ -40,6 +44,10 @@ name = "determinism"
name = "determinism_wasm"
crate-type = ["cdylib"]
+# Which collision shape voxel objects get (docs/VOXEL.md "Voxel bodies"): a measurement.
+[[example]]
+name = "voxel_shapes"
+
# 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
diff --git a/renderer/physics-core/examples/voxel_shapes.rs b/renderer/physics-core/examples/voxel_shapes.rs
new file mode 100644
index 0000000..f2eeb57
--- /dev/null
+++ b/renderer/physics-core/examples/voxel_shapes.rs
@@ -0,0 +1,239 @@
+//! Which collision shape voxel objects get (ROADMAP § 6 step 8; docs/VOXEL.md "Voxel bodies"): a measurement, no test.
+//! The candidates, on Rapier as the world steps it (`enhanced-determinism`, one thread, the tick of 1 / 60 s):
+//! voxels parry's `Voxels` (8³ chunks of a byte a cell, each cell knowing which neighbours it has)
+//! boxes a compound of boxes, the cells merged greedily
+//! trimesh the cells' outer faces as triangles (fixed colliders only: a trimesh has no volume)
+//! hull the convex hull of the cells' corners (moving bodies only)
+//! Measured: the memory and time to build a fixed ground of cells, an edit of it (a sphere of cells cleared), and
+//! pieces of debris dropped onto it in a heap: the tick's time while they fall and when they rest, how many come to
+//! rest and sleep, whether any went through the ground.
+//!
+//! cargo run --release --example voxel_shapes [pieces = 100] [ground cells a side = 256] [only: e.g. voxels/voxels]
+//!
+//! With `only`, that pair alone, and no table of the fixed ground. Each row ends with a hash of every piece's pose and
+//! velocity, bit for bit: `--features parallel` (Rapier's parallel solver) and `RAYON_NUM_THREADS` must not change it.
+use rapier3d::prelude::*;
+use std::alloc::{GlobalAlloc, Layout, System};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::time::Instant;
+
+struct Counting;
+static HELD: AtomicUsize = AtomicUsize::new(0);
+unsafe impl GlobalAlloc for Counting {
+ unsafe fn alloc(&self, l: Layout) -> *mut u8 {
+ HELD.fetch_add(l.size(), Ordering::Relaxed);
+ System.alloc(l)
+ }
+ unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
+ HELD.fetch_sub(l.size(), Ordering::Relaxed);
+ System.dealloc(p, l)
+ }
+}
+#[global_allocator]
+static A: Counting = Counting;
+
+const SIZE: f32 = 0.1;
+
+struct Rng(u64);
+impl Rng {
+ fn f(&mut self) -> f32 {
+ self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ ((self.0 >> 40) as f32) / (1u64 << 24) as f32
+ }
+}
+
+type Cells = Vec<[i32; 3]>;
+
+/// A ground `n` cells a side and 6 deep with low hills, and a few walls on it.
+fn ground(n: i32) -> Cells {
+ let mut c = vec![];
+ for x in 0..n {
+ for z in 0..n {
+ let h = 6 + (((x as f32 * 0.07).sin() + (z as f32 * 0.05).cos()) * 1.5) as i32;
+ for y in 0..h {
+ c.push([x, y, z]);
+ }
+ if (x % 64 == 20 && z % 8 < 6) || (z % 64 == 40 && x % 8 < 6) {
+ for y in h..h + 20 {
+ c.push([x, y, z]);
+ }
+ }
+ }
+ }
+ c
+}
+
+/// A piece of debris: a lump of `n` cells a side with cells missing (connected through its core).
+fn piece(rng: &mut Rng, n: i32) -> Cells {
+ let mut c = vec![];
+ for x in 0..n {
+ for y in 0..n {
+ for z in 0..n {
+ let core = (x - n / 2).abs() <= 1 || (y - n / 2).abs() <= 1 || (z - n / 2).abs() <= 1;
+ if core || rng.f() < 0.55 {
+ c.push([x, y, z]);
+ }
+ }
+ }
+ }
+ c
+}
+
+/// The cells as boxes: each cell not yet in one grown along x, then z, then y. (lo, hi) in cells, hi exclusive.
+fn boxes(cells: &Cells) -> Vec<([i32; 3], [i32; 3])> {
+ let lo = (0..3).map(|a| cells.iter().map(|c| c[a]).min().unwrap()).collect::<Vec<_>>();
+ let hi = (0..3).map(|a| cells.iter().map(|c| c[a]).max().unwrap() + 1).collect::<Vec<_>>();
+ let d = [(hi[0] - lo[0]) as usize, (hi[1] - lo[1]) as usize, (hi[2] - lo[2]) as usize];
+ let at = |x: usize, y: usize, z: usize| (y * d[2] + z) * d[0] + x;
+ let mut solid = vec![false; d[0] * d[1] * d[2]];
+ for c in cells {
+ solid[at((c[0] - lo[0]) as usize, (c[1] - lo[1]) as usize, (c[2] - lo[2]) as usize)] = true;
+ }
+ let mut out = vec![];
+ for y in 0..d[1] {
+ for z in 0..d[2] {
+ for x in 0..d[0] {
+ if !solid[at(x, y, z)] {
+ continue;
+ }
+ let mut x1 = x + 1;
+ while x1 < d[0] && solid[at(x1, y, z)] {
+ x1 += 1;
+ }
+ let mut z1 = z + 1;
+ while z1 < d[2] && (x..x1).all(|i| solid[at(i, y, z1)]) {
+ z1 += 1;
+ }
+ let mut y1 = y + 1;
+ while y1 < d[1] && (z..z1).all(|k| (x..x1).all(|i| solid[at(i, y1, k)])) {
+ y1 += 1;
+ }
+ for j in y..y1 {
+ for k in z..z1 {
+ for i in x..x1 {
+ solid[at(i, j, k)] = false;
+ }
+ }
+ }
+ out.push(([x as i32 + lo[0], y as i32 + lo[1], z as i32 + lo[2]], [x1 as i32 + lo[0], y1 as i32 + lo[1], z1 as i32 + lo[2]]));
+ }
+ }
+ }
+ out
+}
+
+fn iv(c: &Cells) -> Vec<IVector> {
+ c.iter().map(|c| IVector::new(c[0], c[1], c[2])).collect()
+}
+
+fn shape(kind: &str, cells: &Cells) -> SharedShape {
+ match kind {
+ "voxels" => SharedShape::voxels(Vector::splat(SIZE), &iv(cells)),
+ "boxes" => SharedShape::compound(
+ boxes(cells)
+ .into_iter()
+ .map(|(lo, hi)| {
+ let (a, b) = (Vector::new(lo[0] as f32, lo[1] as f32, lo[2] as f32) * SIZE, Vector::new(hi[0] as f32, hi[1] as f32, hi[2] as f32) * SIZE);
+ (Pose::from_translation((a + b) * 0.5), SharedShape::cuboid((b.x - a.x) * 0.5, (b.y - a.y) * 0.5, (b.z - a.z) * 0.5))
+ })
+ .collect(),
+ ),
+ "trimesh" => {
+ let v = rapier3d::parry::shape::Voxels::new(Vector::splat(SIZE), &iv(cells));
+ let (vertices, indices) = v.to_trimesh();
+ SharedShape::trimesh(vertices, indices).unwrap()
+ }
+ "hull" => {
+ let pts: Vec<Vector> = cells.iter().flat_map(|c| (0..8).map(move |k| Vector::new((c[0] + (k & 1)) as f32, (c[1] + ((k >> 1) & 1)) as f32, (c[2] + ((k >> 2) & 1)) as f32) * SIZE)).collect();
+ SharedShape::convex_hull(&pts).unwrap()
+ }
+ _ => unreachable!(),
+ }
+}
+
+fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ let pieces: usize = args.get(1).and_then(|a| a.parse().ok()).unwrap_or(100);
+ let n: i32 = args.get(2).and_then(|a| a.parse().ok()).unwrap_or(256);
+ let only = args.get(3).cloned();
+ let g = ground(n);
+ println!("ground: {n} x {n} cells of {SIZE} m, {} solid; {} pieces of 6³ cells (about {} solid each)", g.len(), pieces, piece(&mut Rng(1), 6).len());
+ // The fixed ground: memory, build, an edit.
+ println!("\nfixed ground build ms heap MiB parts edit ms (a 1 m sphere cleared: {} cells)", {
+ let c = [n / 2, 6, n / 2];
+ g.iter().filter(|p| (0..3).map(|a| (p[a] - c[a]).pow(2)).sum::<i32>() <= 100).count()
+ });
+ for kind in ["voxels", "boxes", "trimesh"].into_iter().filter(|_| only.is_none()) {
+ let before = HELD.load(Ordering::Relaxed);
+ let t = Instant::now();
+ let mut s = shape(kind, &g);
+ let build = t.elapsed().as_secs_f64() * 1e3;
+ let heap = HELD.load(Ordering::Relaxed) - before;
+ let c = [n / 2, 6, n / 2];
+ let gone: Cells = g.iter().copied().filter(|p| (0..3).map(|a| (p[a] - c[a]).pow(2)).sum::<i32>() <= 100).collect();
+ let t = Instant::now();
+ let parts = match kind {
+ "voxels" => {
+ let v = s.make_mut().as_voxels_mut().unwrap();
+ for k in &gone {
+ v.set_voxel(IVector::new(k[0], k[1], k[2]), false);
+ }
+ g.len() - gone.len()
+ }
+ // (No edit in place: the shape is made again from the cells that are left.)
+ _ => {
+ let left: Cells = g.iter().copied().filter(|p| (0..3).map(|a| (p[a] - c[a]).pow(2)).sum::<i32>() > 100).collect();
+ s = shape(kind, &left);
+ match kind {
+ "boxes" => s.as_compound().unwrap().shapes().len(),
+ _ => s.as_trimesh().unwrap().indices().len(),
+ }
+ }
+ };
+ let edit = t.elapsed().as_secs_f64() * 1e3;
+ println!(" {kind:<16} {build:>9.1} {:>10.1} {parts:>8} {edit:>12.2}{}", heap as f64 / 1048576.0, if kind == "voxels" { " (in place)" } else { " (built again)" });
+ drop(s);
+ }
+ // Debris onto the ground.
+ println!("\nmoving / fixed tick ms: falling (mean, worst) resting (mean) asleep at 15 s through the ground fastest at the end, m/s");
+ for (moving, fixed) in [("voxels", "voxels"), ("boxes", "voxels"), ("hull", "voxels"), ("voxels", "trimesh"), ("boxes", "trimesh"), ("boxes", "boxes"), ("voxels", "boxes")].into_iter().filter(|(m, f)| only.as_ref().is_none_or(|o| *o == format!("{m}/{f}"))) {
+ let mut w = PhysicsWorld::new();
+ w.integration_parameters.dt = 1.0 / 60.0;
+ w.insert_collider(ColliderBuilder::new(shape(fixed, &g)), None);
+ let mut rng = Rng(7);
+ let mid = n as f32 * SIZE * 0.5;
+ let mut bodies = vec![];
+ for k in 0..pieces {
+ let cells = piece(&mut rng, 6);
+ let at = Vector::new(mid + (rng.f() - 0.5) * 6.0, 2.5 + 0.9 * (k / 16) as f32 + rng.f() * 0.3, mid + (rng.f() - 0.5) * 6.0);
+ let b = w.insert_body(RigidBodyBuilder::dynamic().translation(at).rotation(Vector::new(rng.f(), rng.f(), rng.f())));
+ w.insert_collider(ColliderBuilder::new(shape(moving, &cells)).density(2000.0).friction(0.6), Some(b));
+ bodies.push(b);
+ }
+ let (mut fall, mut worst, mut rest) = (0.0f64, 0.0f64, 0.0f64);
+ for tick in 0..900 {
+ let t = Instant::now();
+ w.step();
+ let ms = t.elapsed().as_secs_f64() * 1e3;
+ if tick < 240 {
+ fall += ms / 240.0;
+ } else if tick >= 780 {
+ rest += ms / 120.0;
+ }
+ worst = worst.max(ms);
+ }
+ let asleep = bodies.iter().filter(|&&b| w.bodies[b].is_sleeping()).count();
+ let through = bodies.iter().filter(|&&b| w.bodies[b].translation().y < 0.2).count();
+ let fastest = bodies.iter().map(|&b| w.bodies[b].linvel().length()).fold(0.0f32, f32::max);
+ let mut hash = 0xcbf2_9ce4_8422_2325u64;
+ for &b in &bodies {
+ let b = &w.bodies[b];
+ for x in b.translation().to_array().into_iter().chain(b.rotation().to_array()).chain(b.linvel().to_array()).chain(b.angvel().to_array()) {
+ for byte in x.to_bits().to_le_bytes() {
+ hash = (hash ^ byte as u64).wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ }
+ }
+ println!(" {:<17} {fall:>14.2} {worst:>8.2} {rest:>18.3} {asleep:>12} of {pieces} {through:>16} {fastest:>22.3} {hash:016x}", format!("{moving} / {fixed}"));
+ }
+}
diff --git a/renderer/physics-core/src/bridge.rs b/renderer/physics-core/src/bridge.rs
index b47c696..a2092cd 100644
--- a/renderer/physics-core/src/bridge.rs
+++ b/renderer/physics-core/src/bridge.rs
@@ -21,6 +21,13 @@ 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;
+/// Ids from here up are the engine's own bodies and colliders (the voxel world's: ROADMAP § 6 step 8). Scene code
+/// cannot make or remove one, and can name one wherever a call takes a body or a collider (an impulse, a velocity, a
+/// joint's end, a query's `skip`); hits and contacts report them like any other.
+pub const ENGINE_IDS: u32 = 1 << 30;
+/// The most bodies and colliders the engine itself makes (a level's objects are a collider each).
+pub const MAX_ENGINE_BODIES: usize = 20_000;
+pub const MAX_ENGINE_COLLIDERS: usize = 40_000;
/// Floats a slot of `poses()` holds: position xyz, rotation xyzw.
pub const POSE: usize = 7;
@@ -103,8 +110,14 @@ fn num(a: &Value, key: &str, default: f32) -> Result<f32, String> {
}
}
+/// A whole number from 0 to `u32::MAX`, however the caller's JSON wrote it. (A script engine has one kind of number:
+/// an id it read out of an answer, a hit's `body`, comes back as `1073741837.0`.)
+fn whole(v: &Value) -> Option<u32> {
+ v.as_u64().or_else(|| v.as_f64().filter(|x| *x >= 0.0 && *x <= u32::MAX as f64 && x.fract() == 0.0).map(|x| x as u64)).filter(|&x| x <= u32::MAX as u64).map(|x| x as u32)
+}
+
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"))
+ whole(&a[key]).ok_or_else(|| format!("physics: {key} must be an id"))
}
fn opt_id(a: &Value, key: &str) -> Result<Option<u32>, String> {
@@ -184,7 +197,7 @@ impl Bridge {
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 index = whole;
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 }
}
@@ -207,6 +220,9 @@ impl Bridge {
return Err(format!("physics: more than {MAX_BODIES} bodies"));
}
let bid = id(a, "id")?;
+ if bid >= ENGINE_IDS {
+ return Err(format!("physics: ids from {ENGINE_IDS} up are the engine's"));
+ }
if self.bodies.contains_key(&bid) {
return Err(format!("physics: body {bid} exists"));
}
@@ -271,6 +287,9 @@ impl Bridge {
return Err(format!("physics: more than {MAX_COLLIDERS} colliders"));
}
let cid = id(a, "id")?;
+ if cid >= ENGINE_IDS {
+ return Err(format!("physics: ids from {ENGINE_IDS} up are the engine's"));
+ }
if self.colliders.contains_key(&cid) {
return Err(format!("physics: collider {cid} exists"));
}
@@ -330,6 +349,9 @@ impl Bridge {
"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 body.is_some_and(|b| b >= ENGINE_IDS) || collider.is_some_and(|c| c >= ENGINE_IDS) {
+ return Err("physics: the engine's bodies and colliders are not scene code's to remove (a voxel object's go with its voxels)".into());
+ }
if let Some(b) = body.and_then(|b| self.bodies.get(&b).copied()) {
self.forget_body(b);
}
@@ -453,6 +475,91 @@ impl Bridge {
})
}
+ /// A body of the engine's own (id from `ENGINE_IDS` up): it drives no scene object through the bridge (the engine
+ /// places what it stands for: `engine_pose`).
+ pub fn engine_body(&mut self, id: u32, d: &BodyDesc) -> Result<(), String> {
+ if id < ENGINE_IDS || self.bodies.contains_key(&id) {
+ return Err(format!("physics: engine body {id} exists or is below {ENGINE_IDS}"));
+ }
+ if self.bodies.range(ENGINE_IDS..).count() >= MAX_ENGINE_BODIES {
+ return Err(format!("physics: more than {MAX_ENGINE_BODIES} engine bodies"));
+ }
+ let b = self.core.add_body(d)?;
+ self.bodies.insert(id, b);
+ self.body_ids.insert(b, id);
+ self.faulted.remove(&id);
+ Ok(())
+ }
+
+ /// A collider of the engine's own, on one of its bodies or fixed in the world.
+ pub fn engine_collider(&mut self, id: u32, body: Option<u32>, d: &ColliderDesc) -> Result<(), String> {
+ if id < ENGINE_IDS || self.colliders.contains_key(&id) {
+ return Err(format!("physics: engine collider {id} exists or is below {ENGINE_IDS}"));
+ }
+ if self.colliders.range(ENGINE_IDS..).count() >= MAX_ENGINE_COLLIDERS {
+ return Err(format!("physics: more than {MAX_ENGINE_COLLIDERS} engine colliders"));
+ }
+ let owner = match body {
+ Some(b) => Some(*self.bodies.get(&b).ok_or_else(|| format!("physics: unknown body {b}"))?),
+ None => None,
+ };
+ let c = self.core.add_collider(owner, d)?;
+ self.colliders.insert(id, c);
+ self.collider_ids.insert(c, (id, body));
+ Ok(())
+ }
+
+ /// An engine voxel collider's cells changed (`Physics::edit_voxels`). Returns the cells it has; with none left
+ /// it is gone, its id with it.
+ pub fn engine_edit_voxels(&mut self, id: u32, clear: &[[i32; 3]], fill: &[[i32; 3]]) -> Result<usize, String> {
+ let c = *self.colliders.get(&id).filter(|_| id >= ENGINE_IDS).ok_or_else(|| format!("physics: unknown engine collider {id}"))?;
+ let left = self.core.edit_voxels(c, clear, fill);
+ if !self.core.has_collider(c) {
+ self.colliders.remove(&id);
+ self.collider_ids.remove(&c);
+ }
+ left
+ }
+
+ /// An engine body with its colliders and joints, or an engine collider, gone. (Unknown ids: nothing.)
+ pub fn engine_remove(&mut self, body: Option<u32>, collider: Option<u32>) {
+ if let Some(b) = body.filter(|&b| b >= ENGINE_IDS).and_then(|b| self.bodies.get(&b).copied()) {
+ self.forget_body(b);
+ }
+ if let Some(c) = collider.filter(|&c| c >= ENGINE_IDS).and_then(|c| self.colliders.remove(&c)) {
+ self.core.remove_collider(c);
+ self.collider_ids.remove(&c);
+ }
+ }
+
+ /// Where a body is (any body, by its caller's id): position, rotation, and whether it sleeps. None: no such body
+ /// (never made, removed, or taken out by the world after a tick: `faults`).
+ pub fn engine_pose(&self, id: u32) -> Option<([f32; 3], [f32; 4], bool)> {
+ let b = *self.bodies.get(&id)?;
+ self.core.pose(b).map(|(p, q)| (p, q, self.core.sleeping(b)))
+ }
+
+ /// A body's velocities set (the engine's: a part that comes loose keeps moving as what it broke from did).
+ pub fn engine_velocity(&mut self, id: u32, linvel: [f32; 3], angvel: [f32; 3]) -> Result<(), String> {
+ let b = *self.bodies.get(&id).ok_or_else(|| format!("physics: unknown body {id}"))?;
+ self.core.set_velocity(b, Some(linvel), Some(angvel))
+ }
+
+ /// A body's linear and angular velocity.
+ pub fn engine_velocity_of(&self, id: u32) -> Option<([f32; 3], [f32; 3])> {
+ self.core.velocity(*self.bodies.get(&id)?)
+ }
+
+ /// The memory of the world's voxel shapes, bytes (`Physics::voxel_bytes`).
+ pub fn voxel_bytes(&self) -> usize {
+ self.core.voxel_bytes()
+ }
+
+ /// A voxel collider's solid cells, counted (None: none, or no voxel shape).
+ pub fn engine_voxels(&self, id: u32) -> Option<usize> {
+ self.core.voxels(*self.colliders.get(&id)?)
+ }
+
/// 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)?;
@@ -765,10 +872,15 @@ mod tests {
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();
+ // An impulse wakes it; it moves again. (The id as a script engine hands back one it read from an answer: a
+ // whole number written as a double. One that is not whole, or negative, or past 2^32, is no id.)
+ b.call(&mut s, "impulse", &json!({ "body": 2.0, "impulse": [0, 300, 0] })).unwrap();
assert!(run(&mut b, &mut s, 10) >= 10);
assert!(s.at[&2].0[1] > 0.5);
+ for bad in [json!(2.5), json!(-2.0), json!(4294967296.0), json!("2"), json!(f64::MAX)] {
+ let e = b.call(&mut s, "impulse", &json!({ "body": bad, "impulse": [0, 300, 0] })).unwrap_err();
+ assert!(e.contains("must be an id"), "{bad}: {e}");
+ }
}
/// Scene code moves a body's object: a dynamic body is there at once with its velocity; a kinematic one goes there
diff --git a/renderer/physics-core/src/check.rs b/renderer/physics-core/src/check.rs
index 6878502..4da824f 100644
--- a/renderer/physics-core/src/check.rs
+++ b/renderer/physics-core/src/check.rs
@@ -75,7 +75,7 @@ pub fn pile(n: u32, ticks: u32) -> u64 {
/// 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); 4] = [
+pub const KINDS: [(&str, u32); 5] = [
("convex hulls", 400),
("bodies of several colliders", 400),
("joints with limits and motors", 200),
@@ -83,10 +83,14 @@ pub const KINDS: [(&str, u32); 4] = [
// it is checked against): continuous collision detection, a static triangle mesh, a kinematic body, fixed and ball
// joints, and the answers of rays, overlaps and sweeps (asked with and without a tick since the last change).
("ccd on a trimesh with a kinematic body, fixed and ball joints and queries", 200),
+ // Step 8's shape: lumps of voxels that tumble onto a ground of voxels and onto each other, a box and a ball among
+ // them; the ground carved under them and a lump carved as it lies (`Physics::edit_voxels`: mass, centre of mass
+ // and inertia made again from the cells that are left, another eigen decomposition); a ray's answer on voxels.
+ ("voxel lumps on voxel ground, carved", 300),
];
/// The hash of all the cases (`cases()`) with `enhanced-determinism`, natively and in wasm32 alike.
-pub const EXPECTED_CASES: u64 = 0x6fd1_eba4_551b_8d39;
+pub const EXPECTED_CASES: u64 = 0xcf74_cd21_1f5c_152f;
/// A generator of integers only: a float made from one is exact arithmetic, the same bits on every platform.
struct Rng(u64);
@@ -126,6 +130,9 @@ pub fn case(kind: u32, seed: u32) -> u64 {
let hull = |r: &mut Rng| Shape::ConvexHull((0..8).map(|_| r.v3(0.5)).collect());
// (Kind 3's kinematic body: where it is driven, and how it is turned.)
let mut pusher: Option<(BodyId, [f32; 3], [f32; 4])> = None;
+ // (Kind 4's ground, and its lumps: body, collider, cells a side.)
+ let mut voxel_ground: Option<ColliderId> = None;
+ let mut voxel_lumps: Vec<(BodyId, ColliderId, i32)> = vec![];
match kind {
// Two tumbling hulls of 8 random points that meet over the ground.
0 => {
@@ -159,6 +166,39 @@ pub fn case(kind: u32, seed: u32) -> u64 {
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();
}
+ // Voxels: a ground of cells with relief, three lumps of cells with holes, a box and a ball.
+ 4 => {
+ let mut ground = vec![];
+ for x in -20i32..20 {
+ for z in -20i32..20 {
+ for y in 0..2 + (r.next() % 3) as i32 {
+ ground.push([x, y, z]);
+ }
+ }
+ }
+ voxel_ground = Some(p.add_collider(None, &ColliderDesc { friction: r.range(0.2, 0.9), ..ColliderDesc::new(Shape::Voxels { size: 0.1, cells: ground }) }).unwrap());
+ for k in 0..3 {
+ let n = 3 + (r.next() % 3) as i32;
+ let mut cells = vec![];
+ for x in 0..n {
+ for y in 0..n {
+ for z in 0..n {
+ if x == n / 2 || y == n / 2 || r.next() % 3 != 0 {
+ cells.push([x - n / 2, y - n / 2, z - n / 2]);
+ }
+ }
+ }
+ }
+ let at = [0.4 * r.unit(), 1.2 + 0.8 * k as f32, 0.4 * r.unit()];
+ let b = body(&mut p, &mut r, at);
+ let c = p.add_collider(Some(b), &ColliderDesc { density: r.range(500.0, 3000.0), ..ColliderDesc::new(Shape::Voxels { size: 0.1, cells }) }).unwrap();
+ voxel_lumps.push((b, c, n));
+ }
+ let b = body(&mut p, &mut r, [0.3, 3.8, -0.2]);
+ p.add_collider(Some(b), &ColliderDesc::new(Shape::Box([r.range(0.05, 0.3), r.range(0.05, 0.3), r.range(0.05, 0.3)]))).unwrap();
+ let b = body(&mut p, &mut r, [-0.3, 4.4, 0.2]);
+ p.add_collider(Some(b), &ColliderDesc::new(Shape::Sphere(r.range(0.05, 0.3)))).unwrap();
+ }
// Fast small bodies with CCD onto a static triangle mesh with relief, a kinematic box driven through them,
// two boxes held by a fixed joint and a capsule on a ball joint.
_ => {
@@ -192,8 +232,42 @@ pub fn case(kind: u32, seed: u32) -> u64 {
p.set_kinematic_target(b, [-3.0 + v[0] * s, 0.8, v[2] * s], q).unwrap();
}
p.step();
+ if let Some(g) = voxel_ground.filter(|_| t == 45 || t == 60) {
+ if t == 45 {
+ // A pit under where they fell: what rests there falls on.
+ let (cx, cz, w) = ((r.next() % 9) as i32 - 4, (r.next() % 9) as i32 - 4, 2 + (r.next() % 4) as i32);
+ let gone: Vec<[i32; 3]> = (cx - w..=cx + w).flat_map(|x| (cz - w..=cz + w).flat_map(move |z| (0..4).map(move |y| [x, y, z]))).collect();
+ fold(p.edit_voxels(g, &gone, &[[cx, 0, cz]]).unwrap() as u64);
+ } else {
+ // A lump loses a slab of its cells, another gains a row; one cut down to nothing goes.
+ let (b, c, n) = voxel_lumps[(r.next() % 3) as usize];
+ let cut = (r.next() % (n as u64 + 1)) as i32 - n / 2;
+ let gone: Vec<[i32; 3]> = (-n..=n).flat_map(|x| (-n..=n).flat_map(move |z| (cut..=n).map(move |y| [x, y, z]))).collect();
+ let left = p.edit_voxels(c, &gone, &[]).unwrap();
+ fold(left as u64);
+ if left == 0 {
+ p.remove_body(b);
+ }
+ let (_, c, n) = voxel_lumps[(r.next() % 3) as usize];
+ if p.has_collider(c) {
+ fold(p.edit_voxels(c, &[], &(0..n + 2).map(|x| [x, n, 0]).collect::<Vec<_>>()).unwrap() as u64);
+ }
+ }
+ }
if t % 10 == 9 {
fold(p.hash());
+ if kind == 4 {
+ let at = [r.unit() * 1.5, 6.0, r.unit() * 1.5];
+ match p.cast_ray(at, [r.unit() * 0.2, -1.0, r.unit() * 0.2], 20.0, None).unwrap() {
+ Some(x) => {
+ fold(x.collider as u64);
+ for f in [x.distance].into_iter().chain(x.point).chain(x.normal) {
+ fold(crate::world::hash_bits(f) as u64);
+ }
+ }
+ None => fold(u64::MAX),
+ }
+ }
if kind == 3 {
// Queries, their answers folded in bit for bit: a ray and a ball swept down at a place, what a box
// overlaps; then the same once more after a body is moved by a call (no tick since: `Physics::fresh`).
@@ -270,6 +344,17 @@ mod tests {
assert_eq!((s.to_bits(), c.to_bits()), (ls.to_bits(), lc.to_bits()));
}
+ /// A soak of the voxel worlds (`case` 4) past the seeds the determinism check runs: none panics. (With parry's own
+ /// contacts between a voxel shape and a ball, 4 of the first 300 did: world.rs `VoxelsWithBalls`.)
+ /// cargo test --release --lib voxel_worlds_never_panic -- --ignored
+ #[test]
+ #[ignore = "a soak: 20,000 worlds, minutes"]
+ fn voxel_worlds_never_panic() {
+ for seed in 0..20_000 {
+ super::case(4, seed);
+ }
+ }
+
/// A triangle mesh is built without the flags that make parry compute pseudo normals, which takes the angles of
/// every triangle with the platform's `acos` (parry vector_ext.rs `angle`; upstream's list, ROADMAP § 6 step 9).
#[test]
@@ -281,3 +366,4 @@ mod tests {
assert!(!mesh.flags().intersects(TriMeshFlags::ORIENTED | TriMeshFlags::FIX_INTERNAL_EDGES));
}
}
+
diff --git a/renderer/physics-core/src/lib.rs b/renderer/physics-core/src/lib.rs
index bf36616..21c303f 100644
--- a/renderer/physics-core/src/lib.rs
+++ b/renderer/physics-core/src/lib.rs
@@ -11,7 +11,7 @@ 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,
+ limits, BodyDesc, BodyId, BodyKind, ColliderDesc, ColliderId, Contact, CustomShape, Fault, Hit, JointDesc, JointId, Limits, Motor, Physics, Shape, SharedVoxels, 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
index 2d19401..fc8d392 100644
--- a/renderer/physics-core/src/robustness.rs
+++ b/renderer/physics-core/src/robustness.rs
@@ -489,6 +489,21 @@ impl Rng {
/// panics, the pose table stays finite, and the world's hash can always be taken.
#[test]
fn random_calls_never_panic() {
+ fuzz(false);
+}
+
+/// The same in a world that has the engine's voxel shapes (ROADMAP § 6 step 8): a ground of cells and lumps of cells
+/// on bodies of the engine's ids, which the random calls name too (impulses, velocities, poses, joints to them, a
+/// `remove` that is refused), while the engine carves and fills their cells and takes them out, with ordinary and
+/// with absurd cells.
+#[test]
+fn random_calls_on_voxel_shapes_never_panic() {
+ fuzz(true);
+}
+
+fn fuzz(voxels: bool) {
+ use crate::bridge::ENGINE_IDS;
+ use crate::world::{BodyDesc, ColliderDesc, Shape};
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);
@@ -496,8 +511,34 @@ fn random_calls_never_panic() {
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 }));
}
+ if voxels {
+ let cells = |r: &mut Rng, n: i32, y: i32| -> Vec<[i32; 3]> { (-n..n).flat_map(|x| (-n..n).flat_map(move |z| (0..y).map(move |h| [x, h, z]))).filter(|_| r.chance(0.8)).collect() };
+ b.engine_collider(ENGINE_IDS, None, &ColliderDesc::new(Shape::Voxels { size: 0.1, cells: cells(&mut r, 12, 2) })).unwrap();
+ for k in 1..=3u32 {
+ b.engine_body(ENGINE_IDS + k, &BodyDesc { position: [r.unit() as f32, 0.5 + k as f32 * 0.6, r.unit() as f32], ..Default::default() }).unwrap();
+ b.engine_collider(ENGINE_IDS + 10 + k, Some(ENGINE_IDS + k), &ColliderDesc::new(Shape::Voxels { size: 0.1, cells: cells(&mut r, 2, 3) })).unwrap();
+ }
+ }
for _ in 0..100 {
- let id = 1 + r.below(10);
+ let mut id = 1 + r.below(10);
+ if voxels && r.chance(0.35) {
+ id = (ENGINE_IDS + r.below(5) as u32) as u64;
+ }
+ if voxels && r.chance(0.1) {
+ // The engine's own: cells carved and filled (at the higher levels anywhere, any number), a body or
+ // a collider taken out. Refused or done, never a panic.
+ let cell = |r: &mut Rng| -> [i32; 3] { [0, 1, 2].map(|_| if level >= 3 && r.chance(0.2) { [i32::MIN, i32::MAX, 1 << 20, -(1 << 20) - 1, 123_456_789][r.below(5) as usize] } else { r.below(9) as i32 - 4 }) };
+ let clear: Vec<[i32; 3]> = (0..r.below(40)).map(|_| cell(&mut r)).collect();
+ let fill: Vec<[i32; 3]> = (0..r.below(40)).map(|_| cell(&mut r)).collect();
+ let c = ENGINE_IDS + [0, 11, 12, 13, 77][r.below(5) as usize];
+ let _ = b.engine_edit_voxels(c, &clear, &fill);
+ if r.chance(0.1) {
+ b.engine_remove(Some(ENGINE_IDS + 1 + r.below(3) as u32), None);
+ }
+ if r.chance(0.05) {
+ b.engine_remove(None, Some(c));
+ }
+ }
let (op, a): (&str, Value) = match r.below(26) {
0..=4 => {
let kind = ["dynamic", "dynamic", "dynamic", "fixed", "kinematic"][r.below(5) as usize];
diff --git a/renderer/physics-core/src/world.rs b/renderer/physics-core/src/world.rs
index 14d3b48..a2c8368 100644
--- a/renderer/physics-core/src/world.rs
+++ b/renderer/physics-core/src/world.rs
@@ -50,6 +50,11 @@ pub mod limits {
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;
+ /// A voxel shape: its cells' size, m; each cell's coordinates (so the shape reaches at most 2^20 cells from its
+ /// origin, and `size` x that within `MAX_COORD`); the cells one shape holds.
+ pub const VOXEL_SIZE: [f32; 2] = [1e-2, 1e2];
+ pub const MAX_VOXEL_COORD: i32 = 1 << 20;
+ pub const MAX_VOXELS: usize = 1 << 24;
}
use limits::*;
@@ -106,9 +111,30 @@ pub enum Shape {
/// 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]> },
+ /// Solid cells of a lattice of cubes `size` metres wide: cell (x, y, z) fills from (x, y, z) x size to (x + 1,
+ /// y + 1, z + 1) x size in the collider's space. The engine's shape for voxel objects (ROADMAP § 6 step 8): the
+ /// level's, fixed, and the parts that come loose, which move. Its cells can be changed where it is
+ /// (`Physics::edit_voxels`). On a moving body its mass is its cells' volume at the collider's density, its centre
+ /// of mass and inertia those of the cells.
+ Voxels { size: f32, cells: Vec<[i32; 3]> },
+ /// A voxel shape made once (`SharedVoxels::new`) and given to several colliders: they share its cells until one
+ /// of them is edited, which then gets cells of its own (`Physics::edit_voxels`). Objects of one voxel file placed
+ /// many times: one shape's memory and build for all of them.
+ SharedVoxels(SharedVoxels),
Custom(Box<dyn CustomShape>),
}
+/// A voxel shape that colliders can share (`Shape::SharedVoxels`). Cloning it is another reference to the same cells.
+#[derive(Clone)]
+pub struct SharedVoxels(SharedShape);
+
+impl SharedVoxels {
+ /// As `Shape::Voxels { size, cells }`, with its checks.
+ pub fn new(size: f32, cells: Vec<[i32; 3]>) -> Result<SharedVoxels, String> {
+ Shape::Voxels { size, cells }.shared().map(SharedVoxels)
+ }
+}
+
/// 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,
@@ -313,11 +339,167 @@ impl Shape {
}
SharedShape::trimesh(vertices.iter().map(|&p| v(p)).collect(), indices.clone()).map_err(|e| format!("physics: the trimesh cannot be built ({e})"))
}
+ Shape::Voxels { size, cells } => {
+ between(*size, VOXEL_SIZE[0], VOXEL_SIZE[1], "a voxel shape's cell size")?;
+ if cells.is_empty() || cells.len() > MAX_VOXELS {
+ return Err(format!("physics: a voxel shape needs from 1 to {MAX_VOXELS} cells"));
+ }
+ voxel_cells(*size, cells)?;
+ let cells: Vec<IVector> = cells.iter().map(|c| IVector::new(c[0], c[1], c[2])).collect();
+ Ok(SharedShape::voxels(Vector::splat(*size), &cells))
+ }
+ Shape::SharedVoxels(s) => Ok(s.0.clone()),
Shape::Custom(c) => Ok(c.shared()),
}
}
}
+/// A voxel shape's cells are within `MAX_VOXEL_COORD` of its origin, and no further than `MAX_COORD` metres.
+fn voxel_cells(size: f32, cells: &[[i32; 3]]) -> Result<(), String> {
+ let most = (MAX_VOXEL_COORD as f32).min(MAX_COORD / size) as i32;
+ if cells.iter().all(|c| c.iter().all(|&x| x >= -most && x < most)) {
+ Ok(())
+ } else {
+ Err(format!("physics: a voxel shape's cells must be within ±{most} of its origin"))
+ }
+}
+
+/// Contacts between a voxel shape and a ball, found as between a voxel shape and any other shape. Parry has a
+/// function of its own for the pair (contact_manifolds_voxels_ball.rs), the only one of its voxel functions that
+/// keeps no workspace; and a pair without a workspace is to Rapier 0.36 a pair of one manifold whose place in its
+/// list never changes, so the solver keeps a reference to it from one step to the next. A ball on voxels has a
+/// manifold a cell it touches: when one went, the solver came to "stale ContactRef manifold ordinal" and panicked
+/// (a ball rolling on a voxel ground: `voxel_worlds_never_panic`, `random_calls_on_voxel_shapes_never_panic`). The
+/// general function keeps a workspace, which is what tells Rapier to look the pair's manifolds up afresh. Every
+/// other pair is parry's own dispatch, so a world without voxel shapes is stepped bit for bit as it was.
+struct VoxelsWithBalls;
+
+mod dispatch {
+ use super::VoxelsWithBalls;
+ use rapier3d::parry::math::{Pose, Real, Vector};
+ use rapier3d::parry::query::details::{contact_manifolds_voxels_shape_shapes, NonlinearRigidMotion, NormalConstraints, ShapeCastOptions};
+ use rapier3d::parry::query::{ClosestPoints, Contact, ContactManifold, ContactManifoldsWorkspace, DefaultQueryDispatcher, PersistentQueryDispatcher, QueryDispatcher, ShapeCastHit, ShapeDistance, ShapeIntersection, Unsupported};
+ use rapier3d::parry::shape::Shape;
+
+ impl QueryDispatcher for VoxelsWithBalls {
+ fn intersection_test(&self, _: &Pose, _: &dyn Shape, _: &dyn Shape) -> Result<ShapeIntersection, Unsupported> {
+ Err(Unsupported)
+ }
+ fn distance(&self, _: &Pose, _: &dyn Shape, _: &dyn Shape) -> Result<ShapeDistance, Unsupported> {
+ Err(Unsupported)
+ }
+ fn contact(&self, _: &Pose, _: &dyn Shape, _: &dyn Shape, _: Real) -> Result<Option<Contact>, Unsupported> {
+ Err(Unsupported)
+ }
+ fn closest_points(&self, _: &Pose, _: &dyn Shape, _: &dyn Shape, _: Real) -> Result<ClosestPoints, Unsupported> {
+ Err(Unsupported)
+ }
+ fn cast_shapes(&self, _: &Pose, _: Vector, _: &dyn Shape, _: &dyn Shape, _: ShapeCastOptions) -> Result<Option<ShapeCastHit>, Unsupported> {
+ Err(Unsupported)
+ }
+ fn cast_shapes_nonlinear(&self, _: &NonlinearRigidMotion, _: &dyn Shape, _: &NonlinearRigidMotion, _: &dyn Shape, _: Real, _: Real, _: bool) -> Result<Option<ShapeCastHit>, Unsupported> {
+ Err(Unsupported)
+ }
+ }
+
+ impl<M: Default + Clone + Send + Sync, C: Default + Copy + Send + Sync> PersistentQueryDispatcher<M, C> for VoxelsWithBalls {
+ fn contact_manifolds(&self, pos12: &Pose, g1: &dyn Shape, g2: &dyn Shape, prediction: Real, manifolds: &mut Vec<ContactManifold<M, C>>, workspace: &mut Option<ContactManifoldsWorkspace>) -> Result<(), Unsupported> {
+ if (g1.as_voxels().is_some() && g2.as_ball().is_some()) || (g1.as_ball().is_some() && g2.as_voxels().is_some()) {
+ contact_manifolds_voxels_shape_shapes(&DefaultQueryDispatcher, pos12, g1, g2, prediction, manifolds, workspace);
+ return Ok(());
+ }
+ Err(Unsupported)
+ }
+ fn contact_manifold_convex_convex(&self, _: &Pose, _: &dyn Shape, _: &dyn Shape, _: Option<&dyn NormalConstraints>, _: Option<&dyn NormalConstraints>, _: Real, _: &mut ContactManifold<M, C>) -> Result<(), Unsupported> {
+ Err(Unsupported)
+ }
+ }
+}
+
+/// A ray against a voxel shape placed at `at`, the cells walked one by one (Amanatides and Woo): the distance to the
+/// first solid cell within `max` and the normal of the face it is entered by (a ray that starts in a solid cell: 0,
+/// and against the ray). Parry's own (ray_voxels.rs) tests each cell's box with the ray and takes the next cell by
+/// the box's bounds, both in floating point: **a ray that lies on a plane of the lattice and runs along it misses
+/// every cell** (straight down at x = 1.5 onto cells of 0.1 m, which is where a game asks for the ground). Here a
+/// point belongs to the cell its coordinates floor to, the cell is stepped as an integer, and a cell that is solid
+/// is a hit.
+fn voxel_ray(v: &rapier3d::parry::shape::Voxels, at: &Pose, ray: &Ray, max: f32) -> Option<(f32, Vector)> {
+ let size = v.voxel_size().x;
+ let (o, d) = (at.inverse_transform_point(ray.origin).to_array(), at.inverse_transform_vector(ray.dir).to_array());
+ let [lo, hi] = v.domain();
+ let (lo, hi) = (lo.to_array(), hi.to_array());
+ // The stretch of the ray inside the box of the shape's cells.
+ let (mut t0, mut t1, mut entered) = (0.0f32, max, 3usize);
+ for a in 0..3 {
+ let (min, max) = (lo[a] as f32 * size, hi[a] as f32 * size);
+ if d[a] == 0.0 {
+ if o[a] < min || o[a] >= max {
+ return None;
+ }
+ continue;
+ }
+ let (ta, tb) = ((min - o[a]) / d[a], (max - o[a]) / d[a]);
+ let (near, far) = (ta.min(tb), ta.max(tb));
+ if near > t0 {
+ (t0, entered) = (near, a);
+ }
+ t1 = t1.min(far);
+ }
+ if !(t0 <= t1) {
+ return None;
+ }
+ // The cell the ray is in there, held inside the box (it enters on a face, to rounding).
+ let mut cell = [0i32; 3];
+ for a in 0..3 {
+ cell[a] = (((o[a] + d[a] * t0) / size).floor() as i32).clamp(lo[a], hi[a] - 1);
+ }
+ let normal = |axis: usize| {
+ let mut n = [0.0f32; 3];
+ if axis < 3 {
+ n[axis] = if d[axis] > 0.0 { -1.0 } else { 1.0 };
+ at.transform_vector(Vector::new(n[0], n[1], n[2]))
+ } else {
+ -ray.dir.normalize_or_zero()
+ }
+ };
+ let mut t = t0;
+ let mut axis = entered;
+ // (At most every cell of the box's three sides: the walk leaves the box.)
+ loop {
+ if v.voxel_state(IVector::new(cell[0], cell[1], cell[2])).is_some_and(|s| !s.is_empty()) {
+ return Some((t, normal(axis)));
+ }
+ // The next lattice plane on each axis; the nearest is crossed (the lower axis first when they are equal).
+ let mut next = (f32::INFINITY, 3usize);
+ for a in 0..3 {
+ if d[a] != 0.0 {
+ let plane = (cell[a] + (d[a] > 0.0) as i32) as f32 * size;
+ let ta = ((plane - o[a]) / d[a]).max(t);
+ if ta < next.0 {
+ next = (ta, a);
+ }
+ }
+ }
+ if next.1 == 3 || next.0 > t1 {
+ return None;
+ }
+ (t, axis) = next;
+ cell[axis] += if d[axis] > 0.0 { 1 } else { -1 };
+ if cell[axis] < lo[axis] || cell[axis] >= hi[axis] {
+ return None;
+ }
+ }
+}
+
+/// A ray against a collider's shape placed at `at` (the collider's pose, or where a fresh one is): the distance and
+/// the normal. Parry's answer, but for a voxel shape (`voxel_ray`).
+fn shape_ray(c: &Collider, at: &Pose, ray: &Ray, max: f32) -> Option<(f32, Vector)> {
+ match c.shape().as_voxels() {
+ Some(v) => voxel_ray(v, at, ray, max),
+ None => c.shape().cast_ray_and_get_normal(at, ray, max, true).map(|i| (i.time_of_impact, i.normal)),
+ }
+}
+
/// 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 {
@@ -336,6 +518,8 @@ pub struct Physics {
/// Each collider with its shape's data (`Shape::data`), and their sum.
colliders: BTreeMap<ColliderId, (ColliderHandle, usize)>,
shape_data: usize,
+ /// The voxel colliders there are: rays are cast at them here (`voxel_ray`), not by the broad phase's query.
+ voxel_colliders: std::collections::BTreeSet<ColliderId>,
joints: BTreeMap<JointId, ImpulseJointHandle>,
/// The kinematic bodies (`awake`: the islands hold dynamic ones only).
kinematic: std::collections::BTreeSet<BodyId>,
@@ -361,6 +545,10 @@ impl Default for Physics {
impl Physics {
pub fn new(gravity: [f32; 3]) -> Physics {
let mut world = PhysicsWorld::new();
+ {
+ use rapier3d::parry::query::{DefaultQueryDispatcher, QueryDispatcher};
+ world.narrow_phase = NarrowPhase::with_query_dispatcher(VoxelsWithBalls.chain(DefaultQueryDispatcher));
+ }
world.gravity = v(gravity);
world.integration_parameters.dt = TICK;
Physics {
@@ -369,6 +557,7 @@ impl Physics {
bodies: BTreeMap::new(),
colliders: BTreeMap::new(),
shape_data: 0,
+ voxel_colliders: Default::default(),
joints: BTreeMap::new(),
kinematic: Default::default(),
next: 0,
@@ -441,6 +630,7 @@ impl Physics {
self.world.remove_body_with_colliders(h, true);
for c in &gone {
self.fresh.remove(c);
+ self.voxel_colliders.remove(c);
if let Some((_, data)) = self.colliders.remove(c) {
self.shape_data -= data;
}
@@ -487,6 +677,9 @@ impl Physics {
self.colliders.insert(id, (h, data));
self.shape_data += data;
self.fresh.insert(id);
+ if matches!(d.shape, Shape::Voxels { .. } | Shape::SharedVoxels(_)) {
+ self.voxel_colliders.insert(id);
+ }
Ok(id)
}
@@ -495,6 +688,7 @@ impl Physics {
self.world.remove_collider(h);
self.shape_data -= data;
self.fresh.remove(&id);
+ self.voxel_colliders.remove(&id);
}
}
@@ -604,6 +798,96 @@ impl Physics {
self.colliders.contains_key(&id)
}
+ /// Changes a voxel collider's cells: `clear` emptied, then `fill` made solid (cells already so are left). What it
+ /// costs is by the cells named, not by the shape's size (a shape other colliders share is copied first, once). A
+ /// moving body's mass, centre of mass and inertia follow its cells; every body touching the collider is woken
+ /// (what rested on a cell that is gone must fall). Returns the solid cells it has now. **With none left the
+ /// collider is gone** (an empty shape meets nothing, and a moving body of no mass cannot be stepped: the caller
+ /// removes a body left without colliders). Err: no such collider, not a voxel shape, a cell out of bounds;
+ /// nothing is changed then.
+ ///
+ /// The collider is taken out of Rapier and put back with its cells changed, under the same id. Changed where it
+ /// sits (`Collider::shape_mut`), its pairs would keep the contacts found on the old cells for as long as they
+ /// do not move (Rapier's contact recycling: a pair that has hardly moved is not looked at again), and what
+ /// rested on a cell that is gone would rest on nothing. Put back, it meets everything anew.
+ pub fn edit_voxels(&mut self, id: ColliderId, clear: &[[i32; 3]], fill: &[[i32; 3]]) -> Result<usize, String> {
+ let &(h, data) = self.colliders.get(&id).ok_or("physics: unknown collider")?;
+ let size = match self.world.colliders[h].shape().as_voxels() {
+ Some(v) => v.voxel_size().x,
+ None => return Err("physics: not a voxel collider".into()),
+ };
+ voxel_cells(size, clear)?;
+ voxel_cells(size, fill)?;
+ // What touches it now, before it goes.
+ let touching: Vec<RigidBodyHandle> = self
+ .world
+ .narrow_phase
+ .contact_pairs_with(h)
+ .filter_map(|p| self.world.colliders.get(if p.collider1 == h { p.collider2 } else { p.collider1 }).and_then(|c| c.parent()))
+ .collect();
+ let parent = self.world.colliders[h].parent();
+ let mut c = self.world.remove_collider(h).expect("the collider is there");
+ let voxels = c.shape_mut().as_voxels_mut().expect("a voxel shape");
+ // (A cell that is already as asked is left alone: a look, not an edit.)
+ let solid = |v: &rapier3d::parry::shape::Voxels, k: IVector| v.voxel_state(k).is_some_and(|s| !s.is_empty());
+ for k in clear {
+ let k = IVector::new(k[0], k[1], k[2]);
+ if solid(voxels, k) {
+ voxels.set_voxel(k, false);
+ }
+ }
+ for k in fill {
+ let k = IVector::new(k[0], k[1], k[2]);
+ if !solid(voxels, k) {
+ voxels.set_voxel(k, true);
+ }
+ }
+ let left = voxels.voxels().filter(|v| !v.state.is_empty()).count();
+ for b in touching.into_iter().chain(parent) {
+ if let Some(b) = self.world.bodies.get_mut(b) {
+ b.wake_up(true);
+ }
+ }
+ if left == 0 || left > MAX_VOXELS {
+ self.colliders.remove(&id);
+ self.shape_data -= data;
+ self.fresh.remove(&id);
+ self.voxel_colliders.remove(&id);
+ return if left == 0 { Ok(0) } else { Err(format!("physics: a voxel shape holds at most {MAX_VOXELS} cells (the collider is gone)")) };
+ }
+ let h = self.world.insert_collider(c, parent);
+ if let Some(p) = parent {
+ // (Its mass now, not at the next step: a collider put on a body adds its mass to what the body had, and
+ // the one taken out is taken off only when the world is stepped.)
+ let world = &mut self.world;
+ world.bodies[p].recompute_mass_properties_from_colliders(&world.colliders);
+ }
+ self.colliders.insert(id, (h, data));
+ // (The broad phase does not have it until the next step: queries test it where and as it is.)
+ self.fresh.insert(id);
+ Ok(left)
+ }
+
+ /// The memory the world's voxel shapes hold, bytes (parry's own count of each: cells, chunk tables, their tree).
+ /// A shape several colliders share is counted once.
+ pub fn voxel_bytes(&self) -> usize {
+ let mut seen = std::collections::BTreeSet::new();
+ self.voxel_colliders
+ .iter()
+ .filter_map(|id| {
+ let shape = self.world.colliders.get(self.colliders.get(id)?.0)?.shared_shape();
+ let first = seen.insert(std::sync::Arc::as_ptr(&shape.0) as *const () as usize);
+ shape.as_voxels().filter(|_| first).map(|v| v.total_memory_size())
+ })
+ .sum()
+ }
+
+ /// A voxel collider's solid cells, counted; None if it is none.
+ pub fn voxels(&self, id: ColliderId) -> Option<usize> {
+ let &(h, _) = self.colliders.get(&id)?;
+ self.world.colliders.get(h)?.shape().as_voxels().map(|v| v.voxels().filter(|v| !v.state.is_empty()).count())
+ }
+
pub fn has_joint(&self, id: JointId) -> bool {
self.joints.contains_key(&id)
}
@@ -820,11 +1104,11 @@ impl Physics {
/// 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 settled = |_: ColliderHandle, c: &Collider| !self.fresh.contains(&(c.user_data as u32));
+ let settled = |_: ColliderHandle, c: &Collider| !self.fresh.contains(&(c.user_data as u32)) && c.shape().as_voxels().is_none();
let mut best = self.world.cast_ray_and_get_normal(&ray, max, true, self.filter(skip, &settled)).and_then(|(h, i)| self.hit(h, i.time_of_impact, ray.point_at(i.time_of_impact), i.normal));
- for (h, c, at) in self.fresh(skip) {
- if let Some(i) = c.shape().cast_ray_and_get_normal(&at, &ray, max, true) {
- best = Self::nearer(best, self.hit(h, i.time_of_impact, ray.point_at(i.time_of_impact), i.normal));
+ for (h, c, at) in self.fresh(skip).chain(self.voxels_on(&ray, max, skip)) {
+ if let Some((t, n)) = shape_ray(c, &at, &ray, max) {
+ best = Self::nearer(best, self.hit(h, t, ray.point_at(t), n));
}
}
Ok(best)
@@ -833,11 +1117,11 @@ impl Physics {
/// 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 settled = |_: ColliderHandle, c: &Collider| !self.fresh.contains(&(c.user_data as u32));
+ let settled = |_: ColliderHandle, c: &Collider| !self.fresh.contains(&(c.user_data as u32)) && c.shape().as_voxels().is_none();
let mut hits: Vec<Hit> = self.world.intersect_ray(ray, max, true, self.filter(skip, &settled)).filter_map(|(h, _, i)| self.hit(h, i.time_of_impact, ray.point_at(i.time_of_impact), i.normal)).collect();
- for (h, c, at) in self.fresh(skip) {
- if let Some(i) = c.shape().cast_ray_and_get_normal(&at, &ray, max, true) {
- hits.extend(self.hit(h, i.time_of_impact, ray.point_at(i.time_of_impact), i.normal));
+ for (h, c, at) in self.fresh(skip).chain(self.voxels_on(&ray, max, skip)) {
+ if let Some((t, n)) = shape_ray(c, &at, &ray, max) {
+ hits.extend(self.hit(h, t, ray.point_at(t), n));
}
}
// (Equal distances in collider order: the same answer on every machine.)
@@ -846,6 +1130,21 @@ impl Physics {
Ok(hits)
}
+ /// The settled voxel colliders whose boxes a ray passes within `max` (the broad phase's tree; not `skip`'s), each
+ /// where it is: the rays' own test of them (`voxel_ray`). None in a world without voxel shapes.
+ fn voxels_on<'a>(&'a self, ray: &'a Ray, max: f32, skip: Option<BodyId>) -> impl Iterator<Item = (ColliderHandle, &'a Collider, Pose)> + 'a {
+ let skip = skip.and_then(|b| self.bodies.get(&b)).copied();
+ let any = !self.voxel_colliders.is_empty();
+ let tree = self.world.query_pipeline().bvh;
+ tree.leaves(move |node: &rapier3d::parry::partitioning::BvhNode| any && node.aabb().intersects_local_ray(ray, max)).filter_map(move |leaf| {
+ let (c, h) = self.world.colliders.get_unknown_gen(leaf)?;
+ if !c.is_enabled() || c.shape().as_voxels().is_none() || self.fresh.contains(&(c.user_data as u32)) || (skip.is_some() && c.parent() == skip) {
+ return None;
+ }
+ Some((h, c, *c.position()))
+ })
+ }
+
/// 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")?;
@@ -872,8 +1171,8 @@ impl Physics {
Some(&h) => QueryFilter::default().exclude_rigid_body(h),
None => QueryFilter::default(),
};
- // (Nothing fresh, as after every tick: the plain filter.)
- if self.fresh.is_empty() {
+ // (Nothing fresh, as after every tick, and no voxel shape: the plain filter.)
+ if self.fresh.is_empty() && self.voxel_colliders.is_empty() {
f
} else {
f.predicate(settled)
@@ -1334,6 +1633,194 @@ mod tests {
assert!((p.mass(hull).unwrap() - 0.6 * 0.4 * 0.6 * 1000.0).abs() < 1.0);
}
+ /// Cells `lo..hi` (hi exclusive).
+ fn block(lo: [i32; 3], hi: [i32; 3]) -> Vec<[i32; 3]> {
+ (lo[0]..hi[0]).flat_map(|x| (lo[1]..hi[1]).flat_map(move |y| (lo[2]..hi[2]).map(move |z| [x, y, z]))).collect()
+ }
+
+ /// Voxel shapes (step 8): a block of cells rests on a ground of cells where its cells end, and sleeps; another
+ /// rests on it; mass, centre of mass and a ray are the cells'.
+ #[test]
+ fn voxel_shapes_rest_and_stack() {
+ let mut p = Physics::default();
+ // A ground of cells of 0.1 m, 4 m a side, its top at y = 0.3.
+ let ground = p.add_collider(None, &ColliderDesc::new(Shape::Voxels { size: 0.1, cells: block([-20, 0, -20], [20, 3, 20]) })).unwrap();
+ // Blocks of 4 x 3 x 4 cells whose cells start at the body's origin: 0.4 x 0.3 x 0.4 m.
+ let lump = |p: &mut Physics, at: [f32; 3]| {
+ let b = p.add_body(&BodyDesc { position: at, ..Default::default() }).unwrap();
+ let c = p.add_collider(Some(b), &ColliderDesc { density: 2000.0, ..ColliderDesc::new(Shape::Voxels { size: 0.1, cells: block([0, 0, 0], [4, 3, 4]) }) }).unwrap();
+ (b, c)
+ };
+ let (a, ca) = lump(&mut p, [0.0, 0.6, 0.0]);
+ let (b, _) = lump(&mut p, [0.05, 1.4, 0.05]);
+ assert!((p.mass(a).unwrap() - 48.0 * 0.001 * 2000.0).abs() < 1e-2, "{:?}", p.mass(a));
+ assert_eq!((p.voxels(ca), p.voxels(ground)), (Some(48), Some(40 * 40 * 3)));
+ run(&mut p, 240);
+ let (ya, yb) = (p.pose(a).unwrap().0[1], p.pose(b).unwrap().0[1]);
+ assert!((ya - 0.3).abs() < 5e-3 && (yb - 0.6).abs() < 1e-2, "{ya}, {yb}");
+ assert!(p.sleeping(a) && p.sleeping(b));
+ // It stood where it fell: no drift, no turn.
+ let (pa, qa) = p.pose(a).unwrap();
+ assert!(pa[0].abs() < 5e-3 && pa[2].abs() < 5e-3 && qa[3] > 0.9999, "{pa:?} {qa:?}");
+ // A ray down onto the upper block, and one beside both onto the ground.
+ let hit = p.cast_ray([0.2, 5.0, 0.2], [0.0, -1.0, 0.0], 10.0, None).unwrap().unwrap();
+ assert!(hit.body == Some(b) && (hit.point[1] - 0.9).abs() < 1e-2 && hit.normal[1] > 0.99, "{hit:?}");
+ let hit = p.cast_ray([1.5, 5.0, 1.5], [0.0, -1.0, 0.0], 10.0, None).unwrap().unwrap();
+ assert!(hit.collider == ground && (hit.point[1] - 0.3).abs() < 1e-3, "{hit:?}");
+ // A ball swept down meets the ground's cells; a box over the blocks overlaps both.
+ let hit = p.sweep(&Shape::Sphere(0.2), [-1.0, 3.0, -1.0], [0.0, 0.0, 0.0, 1.0], [0.0, -1.0, 0.0], 10.0, None).unwrap().unwrap();
+ assert!(hit.collider == ground && (hit.distance - 2.5).abs() < 1e-2, "{hit:?}");
+ assert_eq!(p.overlap(&Shape::Box([0.1, 1.0, 0.1]), [0.2, 0.8, 0.2], [0.0, 0.0, 0.0, 1.0], None).unwrap().len(), 3);
+ }
+
+ /// A voxel shape's cells are changed where it is: the ground carved under a sleeping block wakes it and it
+ /// falls to the new floor (a query sees the pit before any tick); a block carved weighs what is left, and one
+ /// carved to nothing is gone; bad edits change nothing.
+ #[test]
+ fn voxel_shapes_are_edited() {
+ let mut p = Physics::default();
+ let ground = p.add_collider(None, &ColliderDesc::new(Shape::Voxels { size: 0.1, cells: block([-20, 0, -20], [20, 6, 20]) })).unwrap();
+ let b = p.add_body(&BodyDesc { position: [-0.2, 0.7, -0.2], ..Default::default() }).unwrap();
+ let c = p.add_collider(Some(b), &ColliderDesc::new(Shape::Voxels { size: 0.1, cells: block([0, 0, 0], [4, 4, 4]) })).unwrap();
+ run(&mut p, 180);
+ assert!((p.pose(b).unwrap().0[1] - 0.6).abs() < 5e-3 && p.sleeping(b), "{:?}", p.pose(b));
+ // A pit 0.8 m wide and three cells deep under it.
+ let left = p.edit_voxels(ground, &block([-4, 3, -4], [4, 6, 4]), &[]).unwrap();
+ assert_eq!(left, 40 * 40 * 6 - 8 * 8 * 3);
+ assert!(!p.sleeping(b), "woken");
+ let hit = p.cast_ray([0.3, 5.0, 0.3], [0.0, -1.0, 0.0], 10.0, Some(b)).unwrap().unwrap();
+ assert!(hit.collider == ground && (hit.point[1] - 0.3).abs() < 1e-3, "the pit's floor before any tick: {hit:?}");
+ run(&mut p, 180);
+ assert!((p.pose(b).unwrap().0[1] - 0.3).abs() < 5e-3 && p.sleeping(b), "{:?}", p.pose(b));
+ // The ground filled again under a corner of the pit: cells that are solid stay as they are.
+ assert_eq!(p.edit_voxels(ground, &[], &block([-4, 3, -4], [-2, 6, -2])).unwrap(), 40 * 40 * 6 - 8 * 8 * 3 + 2 * 2 * 3);
+ assert_eq!(p.edit_voxels(ground, &[], &block([-4, 3, -4], [-2, 6, -2])).unwrap(), 40 * 40 * 6 - 8 * 8 * 3 + 2 * 2 * 3);
+ // The block loses its upper half: half the mass, the centre of mass lower; it stays where it is.
+ let m = p.mass(b).unwrap();
+ assert_eq!(p.edit_voxels(c, &block([0, 2, 0], [4, 4, 4]), &[]).unwrap(), 32);
+ assert!((p.mass(b).unwrap() - m / 2.0).abs() < 1e-3 * m, "{:?} of {m}", p.mass(b));
+ run(&mut p, 120);
+ assert!((p.pose(b).unwrap().0[1] - 0.3).abs() < 5e-3, "{:?}", p.pose(b));
+ // Bad edits: not a voxel collider, an unknown one, a cell out of bounds. Nothing changes.
+ let ball = body(&mut p, [3.0, 3.0, 3.0], Shape::Sphere(0.2));
+ let _ = ball;
+ let plain = p.add_collider(None, &ColliderDesc { position: [9.0, 0.0, 9.0], ..ColliderDesc::new(Shape::Box([0.5; 3])) }).unwrap();
+ assert!(p.edit_voxels(plain, &[[0, 0, 0]], &[]).is_err() && p.edit_voxels(9999, &[], &[]).is_err());
+ assert!(p.edit_voxels(c, &[[0, 0, 0]], &[[1 << 21, 0, 0]]).is_err() && p.edit_voxels(c, &[[i32::MIN, 0, 0]], &[]).is_err());
+ assert_eq!(p.voxels(c), Some(32));
+ // Carved to nothing: the collider is gone, the body is the caller's to remove.
+ assert_eq!(p.edit_voxels(c, &block([0, 0, 0], [4, 2, 4]), &[]).unwrap(), 0);
+ assert!(!p.has_collider(c) && p.voxels(c).is_none());
+ assert!(p.remove_body(b).is_empty());
+ run(&mut p, 30);
+ assert!(p.take_faults().is_empty());
+ }
+
+ /// A ray at a voxel shape meets what testing every solid cell's box finds, for random rays at a turned shape; and
+ /// a ray that lies on a plane of the lattice and runs along it meets the cells (parry's own walk misses them all).
+ #[test]
+ fn rays_at_voxel_shapes() {
+ use rapier3d::parry::query::RayCast;
+ let mut seed = 0x2545_f491_4f6c_dd1du64;
+ let mut rnd = move || {
+ seed ^= seed << 13;
+ seed ^= seed >> 7;
+ seed ^= seed << 17;
+ (seed >> 40) as f32 / 16_777_216.0
+ };
+ let cells: Vec<[i32; 3]> = block([-6, -3, -5], [7, 4, 6]).into_iter().filter(|_| rnd() < 0.3).collect();
+ let voxels = rapier3d::parry::shape::Voxels::new(Vector::splat(0.25), &cells.iter().map(|c| IVector::new(c[0], c[1], c[2])).collect::<Vec<_>>());
+ let at = pose([0.3, -0.2, 0.1], [0.2, -0.4, 0.1, 0.9]).unwrap();
+ let (mut hits, mut misses) = (0, 0);
+ for _ in 0..4000 {
+ let o = Vector::new(rnd() * 8.0 - 4.0, rnd() * 8.0 - 4.0, rnd() * 8.0 - 4.0);
+ // (Towards the shape, about the origin, or anywhere.)
+ let to = Vector::new(rnd() - 0.5, rnd() - 0.5, rnd() - 0.5) * if rnd() < 0.7 { 3.0 } else { 30.0 };
+ let d = (to - o).normalize();
+ let ray = Ray::new(o, d);
+ let max = 1.0 + rnd() * 8.0;
+ let brute = cells
+ .iter()
+ .filter_map(|c| {
+ let centre = at.transform_point(Vector::new(c[0] as f32 + 0.5, c[1] as f32 + 0.5, c[2] as f32 + 0.5) * 0.25);
+ Cuboid::new(Vector::splat(0.125)).cast_ray(&Pose::from_parts(centre, at.rotation), &ray, max, true)
+ })
+ .fold(f32::INFINITY, f32::min);
+ match voxel_ray(&voxels, &at, &ray, max) {
+ Some((t, n)) => {
+ assert!((t - brute).abs() < 1e-4, "{t} for {brute}: from {o:?} along {d:?}");
+ assert!((n.length() - 1.0).abs() < 1e-4 && (t == 0.0 || n.dot(d) < 1e-4), "{n:?}");
+ hits += 1;
+ }
+ None => {
+ assert!(brute == f32::INFINITY, "missed a cell at {brute}: from {o:?} along {d:?}");
+ misses += 1;
+ }
+ }
+ }
+ assert!(hits > 800 && misses > 800, "{hits} hits, {misses} misses");
+ // On the lattice's planes, along them: a slab of cells of 0.1 m from above at every corner of its cells.
+ let slab = rapier3d::parry::shape::Voxels::new(Vector::splat(0.1), &block([-20, 0, -20], [20, 3, 20]).iter().map(|c| IVector::new(c[0], c[1], c[2])).collect::<Vec<_>>());
+ let still = Pose::identity();
+ let mut parry_missed = 0;
+ for x in -19..19 {
+ for z in -19..19 {
+ let ray = Ray::new(Vector::new(x as f32 * 0.1, 5.0, z as f32 * 0.1), Vector::new(0.0, -1.0, 0.0));
+ let (t, n) = voxel_ray(&slab, &still, &ray, 10.0).unwrap_or_else(|| panic!("a ray down at ({x}, {z}) x 0.1 m misses the slab"));
+ assert!((t - 4.7).abs() < 1e-4 && n.y == 1.0, "{t} {n:?}");
+ parry_missed += slab.cast_ray(&still, &ray, 10.0, true).is_none() as u32;
+ }
+ }
+ // (Why the walk is here. If parry mends its own, this count falls to 0 and the walk can go.)
+ assert!(parry_missed > 0, "parry's ray meets them all now");
+ // Along the top face, in it: nothing above the cells is met; one cell lower the first cell is.
+ assert!(voxel_ray(&slab, &still, &Ray::new(Vector::new(-5.0, 0.3, 0.05), Vector::new(1.0, 0.0, 0.0)), 20.0).is_none());
+ let (t, n) = voxel_ray(&slab, &still, &Ray::new(Vector::new(-5.0, 0.2, 0.05), Vector::new(1.0, 0.0, 0.0)), 20.0).unwrap();
+ assert!((t - 3.0).abs() < 1e-5 && n.x == -1.0);
+ // From inside a cell: at once, against the ray.
+ let (t, n) = voxel_ray(&slab, &still, &Ray::new(Vector::new(0.05, 0.15, 0.05), Vector::new(0.0, 1.0, 0.0)), 20.0).unwrap();
+ assert!(t == 0.0 && n.y == -1.0);
+ }
+
+ /// Colliders that share one voxel shape: its memory is counted once; an edit of one gives that one cells of its
+ /// own and leaves the others as they were.
+ #[test]
+ fn voxel_shapes_are_shared_until_edited() {
+ let mut p = Physics::default();
+ let shape = SharedVoxels::new(0.1, block([0, 0, 0], [8, 2, 8])).unwrap();
+ let at = |x: f32| ColliderDesc { position: [x, 0.0, 0.0], ..ColliderDesc::new(Shape::SharedVoxels(shape.clone())) };
+ let (a, b, c) = (p.add_collider(None, &at(0.0)).unwrap(), p.add_collider(None, &at(2.0)).unwrap(), p.add_collider(None, &at(4.0)).unwrap());
+ let one = p.voxel_bytes();
+ assert!(one > 0 && (p.voxels(a), p.voxels(b), p.voxels(c)) == (Some(128), Some(128), Some(128)));
+ // A hole through the second: only it has the hole (a ray down at the same place of each).
+ assert_eq!(p.edit_voxels(b, &block([3, 0, 3], [5, 2, 5]), &[]).unwrap(), 120);
+ assert_eq!((p.voxels(a), p.voxels(b), p.voxels(c)), (Some(128), Some(120), Some(128)));
+ assert!(p.voxel_bytes() > one, "the edited one has cells of its own");
+ let down = |p: &Physics, x: f32| p.cast_ray([x + 0.35, 5.0, 0.35], [0.0, -1.0, 0.0], 10.0, None).unwrap().map(|h| h.collider);
+ assert_eq!((down(&p, 0.0), down(&p, 2.0), down(&p, 4.0)), (Some(a), None, Some(c)));
+ // What a shape refuses, it refuses here.
+ assert!(SharedVoxels::new(0.1, vec![]).is_err() && SharedVoxels::new(f32::NAN, vec![[0, 0, 0]]).is_err());
+ // A body dropped on the third rests on it.
+ let ball = body(&mut p, [4.4, 1.0, 0.4], Shape::Box([0.1; 3]));
+ run(&mut p, 120);
+ assert!((p.pose(ball).unwrap().0[1] - 0.3).abs() < 5e-3, "{:?}", p.pose(ball));
+ }
+
+ /// What a voxel shape refuses.
+ #[test]
+ fn voxel_shapes_are_checked() {
+ let mut p = Physics::default();
+ let bad = |p: &mut Physics, size: f32, cells: Vec<[i32; 3]>| p.add_collider(None, &ColliderDesc::new(Shape::Voxels { size, cells })).is_err();
+ assert!(bad(&mut p, 0.1, vec![]) && bad(&mut p, 0.0, vec![[0, 0, 0]]) && bad(&mut p, f32::NAN, vec![[0, 0, 0]]) && bad(&mut p, 1e3, vec![[0, 0, 0]]));
+ assert!(bad(&mut p, 0.1, vec![[0, 1 << 20, 0]]) && bad(&mut p, 0.1, vec![[i32::MIN, 0, 0]]) && bad(&mut p, 100.0, vec![[1001, 0, 0]]));
+ // The same cell twice is one cell.
+ let c = p.add_collider(None, &ColliderDesc::new(Shape::Voxels { size: 0.1, cells: vec![[0, 0, 0], [0, 0, 0], [1, 0, 0]] })).unwrap();
+ assert_eq!(p.voxels(c), Some(2));
+ // A sensor of cells, and cells at the far end of what a shape may reach.
+ p.add_collider(None, &ColliderDesc { sensor: true, ..ColliderDesc::new(Shape::Voxels { size: 0.01, cells: vec![[(1 << 20) - 1, 0, -(1 << 20)]] }) }).unwrap();
+ run(&mut p, 5);
+ }
+
/// Bad input adds nothing; removing a body takes its colliders and joints with it.
#[test]
fn bad_input_and_removal() {
@@ -1376,3 +1863,4 @@ mod tests {
assert_eq!(a, crate::check::EXPECTED, "the script's end changed: if meant, record {a:#x}");
}
}
+
diff --git a/renderer/src/api.rs b/renderer/src/api.rs
index 61dd7ad..38c6afb 100644
--- a/renderer/src/api.rs
+++ b/renderer/src/api.rs
@@ -59,14 +59,39 @@ pub fn voxel_level(v: &mut VoxelWorld, d: &Value) -> Result<()> {
}
/// An explosion: what it did, as JSON.
-pub fn voxel_explode(v: &mut VoxelWorld, w: &mut World, x: f64, y: f64, z: f64, r: f64) -> Result<String> {
- Ok(v.explode(w, Vec3::new(x as f32, y as f32, z as f32), r as f32)?.to_string())
+pub fn voxel_explode(v: &mut VoxelWorld, w: &mut World, p: &mut Option<PhysicsWorld>, x: f64, y: f64, z: f64, r: f64) -> Result<String> {
+ Ok(v.explode(w, p, Vec3::new(x as f32, y as f32, z as f32), r as f32)?.to_string())
}
/// An edit of the level (`voxelEdit({ op, sphere | box | capsule, material })`; voxel.rs `EditOp`).
-pub fn voxel_edit(v: &mut VoxelWorld, w: &mut World, d: &Value) -> Result<String> {
+pub fn voxel_edit(v: &mut VoxelWorld, w: &mut World, p: &mut Option<PhysicsWorld>, d: &Value) -> Result<String> {
let op = crate::voxel::EditOp::parse(d)?;
- Ok(v.edit(w, &op)?.to_string())
+ Ok(v.edit(w, p, &op)?.to_string())
+}
+
+/// The voxel bodies (loose parts the physics world moves): each one's body id for `physics` calls, its voxels,
+/// whether it sleeps, where it is. "[]" without any.
+pub fn voxel_bodies(v: &VoxelWorld, p: &Option<PhysicsWorld>) -> String {
+ p.as_ref().map_or("[]".into(), |p| v.body_list(p).to_string())
+}
+
+/// A frame of the physics world (`dt` seconds: the whole ticks that fit), and the voxel bodies' objects placed
+/// where the bodies are. False without a world.
+pub fn physics_advance(p: &mut Option<PhysicsWorld>, v: &mut VoxelWorld, w: &mut World, dt: f64) -> bool {
+ let Some(p) = p.as_mut() else { return false };
+ p.advance(w, dt);
+ let t = web_time::Instant::now();
+ v.sync_bodies(w, p);
+ p.add_sync_ms(t.elapsed().as_secs_f64() * 1e3);
+ true
+}
+
+/// The physics world `ticks` ticks on in all (an offline render at a scene time), the voxel bodies' objects with it.
+pub fn physics_settle(p: &mut Option<PhysicsWorld>, v: &mut VoxelWorld, w: &mut World, ticks: u32) {
+ if let Some(p) = p.as_mut() {
+ p.settle(w, ticks);
+ v.sync_bodies(w, p);
+ }
}
/// The level's hash (16 hex digits; "" before a level): the same commands give the same hash.
diff --git a/renderer/src/live.rs b/renderer/src/live.rs
index e46f518..b02fe5a 100644
--- a/renderer/src/live.rs
+++ b/renderer/src/live.rs
@@ -4428,7 +4428,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, "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(), "top": core.top_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, "guard": core.guard_count(),
+ "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(), "top": core.top_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, "kicks": s.kicks }) }), "scale": core.render_scale, "history": core.history_len, "guard": core.guard_count(),
});
writeln!(l, "{line}")?;
}
diff --git a/renderer/src/main.rs b/renderer/src/main.rs
index 328b9c2..d12b57a 100644
--- a/renderer/src/main.rs
+++ b/renderer/src/main.rs
@@ -98,7 +98,7 @@ impl Hosts {
host.setup(&job.room, job.seed)?;
// A native voxel level the scene code asked for (`voxelLevel`), loaded now that the asset root is known: the
// offline reference of the live view's level (ROADMAP § 6 step 4). Its changes are the setup's, dropped.
- let realized = host.voxels.borrow_mut().realize(&mut host.world.borrow_mut(), &job.assets)?;
+ let realized = host.voxels.borrow_mut().realize(&mut host.world.borrow_mut(), &mut host.physics.borrow_mut(), &job.assets)?;
if let Some(r) = realized {
eprintln!("voxels: {r}");
host.world.borrow_mut().take_changes();
diff --git a/renderer/src/physics.rs b/renderer/src/physics.rs
index 67c5c10..952aebf 100644
--- a/renderer/src/physics.rs
+++ b/renderer/src/physics.rs
@@ -15,7 +15,7 @@ use serde_json::Value;
use web_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.
+/// bodies and how many of them moved; and the times the step's wait kicked the physics' threads (`in_pool`).
#[derive(Clone, Copy, Debug, Default)]
pub struct Stats {
pub ticks: u32,
@@ -23,6 +23,7 @@ pub struct Stats {
pub sync_ms: f64,
pub bodies: usize,
pub moved: usize,
+ pub kicks: u32,
}
impl Scene for World {
@@ -77,6 +78,15 @@ impl PhysicsWorld {
r
}
+ /// The bridge itself, for the engine's own bodies and colliders (the voxel world's: voxel.rs).
+ pub fn bridge(&mut self) -> &mut Bridge {
+ &mut self.bridge
+ }
+
+ pub fn bridge_ref(&self) -> &Bridge {
+ &self.bridge
+ }
+
/// The scene removed these objects: their bodies go (`Bridge::objects_removed`).
pub fn objects_removed(&mut self, objects: &[u32]) {
self.bridge.objects_removed(objects);
@@ -94,9 +104,19 @@ impl PhysicsWorld {
/// `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 bridge = &mut self.bridge;
+ #[allow(unused_mut)]
+ let mut tick = move || {
+ for _ in 0..ticks {
+ bridge.tick();
+ }
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ self.stats.kicks += in_pool(tick);
}
+ #[cfg(target_arch = "wasm32")]
+ tick();
let t1 = Instant::now();
let moved = self.bridge.sync(w);
self.stats.ticks += ticks;
@@ -122,6 +142,12 @@ impl PhysicsWorld {
}
}
+ /// Time the engine spent placing what its own bodies stand for (the voxel bodies' objects: voxel.rs
+ /// `sync_bodies`), counted with the frame's sync.
+ pub fn add_sync_ms(&mut self, ms: f64) {
+ self.stats.sync_ms += ms;
+ }
+
/// The frame's figures, and a fresh count for the next.
pub fn take_stats(&mut self) -> Stats {
std::mem::take(&mut self.stats)
@@ -133,6 +159,133 @@ impl PhysicsWorld {
}
}
+/// The threads the physics world is stepped on natively (Rapier's parallel solver: physics-core's `parallel`): a pool
+/// of the physics' own, not the process's, which has every core for the renderer's own work. **4 threads, or the
+/// machine's performance cores when it has fewer**; `THREERT_PHYSICS_THREADS` sets another count (1 to 16), and 1 (or
+/// 0, or "off") is sequential: the solver on one thread, which costs what the sequential build does. Measured
+/// (docs/VOXEL.md "Voxel bodies"): 4 threads take a third of the sequential step's time, 8 gain nothing on the frame,
+/// and with little moving the pool costs 0.03 ms. The bits do not depend on the count (the recorded hashes at 1 to
+/// 15 threads on this machine: ROADMAP § 6 step 8 says what was checked and what was not). wasm32 has no threads
+/// here: there the world is stepped where it is called.
+/// None when the threads could not be made: the world is then stepped on the calling thread (sequential, the same
+/// bits), said once.
+#[cfg(not(target_arch = "wasm32"))]
+fn pool() -> Option<&'static rayon::ThreadPool> {
+ static POOL: std::sync::OnceLock<Option<rayon::ThreadPool>> = std::sync::OnceLock::new();
+ POOL.get_or_init(|| {
+ let env = std::env::var("THREERT_PHYSICS_THREADS").ok();
+ let threads = threads_from(env.as_deref(), performance_cores()).unwrap_or_else(|default| {
+ eprintln!("physics: THREERT_PHYSICS_THREADS={:?} is no thread count (1 to 16; 1, 0, off: sequential): {default} threads", env.as_deref().unwrap_or(""));
+ default
+ });
+ rayon::ThreadPoolBuilder::new()
+ .num_threads(threads)
+ .thread_name(|k| format!("physics-{k}"))
+ .build()
+ .map_err(|e| eprintln!("physics: the physics' {threads} threads could not be made ({e}): stepped on the frame's thread"))
+ .ok()
+ })
+ .as_ref()
+}
+
+/// How long a step is waited for before the physics' threads are kicked, and again after each kick.
+#[cfg(not(target_arch = "wasm32"))]
+const KICK: std::time::Duration = std::time::Duration::from_micros(500);
+
+/// Runs `f` (a frame's ticks) on one of the physics' threads and waits for it; returns the kicks it took.
+///
+/// **Why not `pool().install(f)`**, which is what this was: Rapier 0.36.1's step hangs there, about once in 10^5
+/// steps of a small world stepped back to back (a fuzz of 1,500 edits and calls: one run in fifty). Its step hands the
+/// broad phase's tree optimisation to `rayon::spawn` and later waits for it with a channel's `recv`
+/// (`physics_pipeline/solve.rs`, `mod.rs` `join_deferred_bvh_optimize`). Inside a pool the spawn goes onto the
+/// stepping worker's own deque, and the `recv` blocks that worker outside rayon, so only another worker can run the
+/// job: one that steals it. rayon does not promise that another worker comes: waking for a job in a worker's deque is
+/// best effort (the push's index store and the pusher's read of the sleep counters have no store-to-load barrier
+/// between them; crossbeam-deque stores the index relaxed), because in rayon's own waits the pusher runs the job
+/// itself in the end. When all the other workers happen to be falling asleep at that instant they all miss it, and
+/// the step never returns. Rapier's own `configure_thread_pool` steps the same way and has the same hole.
+///
+/// So the caller, which only waits anyway, **kicks**: while the step has not returned, every `KICK` it injects an
+/// empty job into the pool. An injected job always wakes a sleeping worker (that path is the one `install` itself
+/// rests on), and a worker that wakes looks through every deque before it sleeps again: it takes the stranded job.
+/// A step that hung costs `KICK` once; a long step gets a few empty jobs, which change nothing (the bits do not
+/// depend on which thread runs what). With one thread Rapier runs that pass inline and there is nothing to strand.
+/// `THREERT_PHYSICS_KICK=off` waits without kicking, to reproduce the hang (the fuzz, `examples/physics_fuzz.rs`,
+/// finds it in a few dozen runs).
+#[cfg(not(target_arch = "wasm32"))]
+pub fn in_pool(f: impl FnOnce() + Send) -> u32 {
+ use std::sync::{Condvar, Mutex, PoisonError};
+ // (`THREERT_PHYSICS_KICK`: "off" or 0, or the period in microseconds.)
+ static PERIOD: std::sync::OnceLock<Option<std::time::Duration>> = std::sync::OnceLock::new();
+ let period = *PERIOD.get_or_init(|| match std::env::var("THREERT_PHYSICS_KICK").ok().as_deref() {
+ Some("off") | Some("0") => None,
+ Some(v) => Some(v.parse().ok().filter(|us| (1..=1_000_000).contains(us)).map_or(KICK, std::time::Duration::from_micros)),
+ None => Some(KICK),
+ });
+ let Some(pool) = pool() else {
+ f();
+ return 0;
+ };
+ let Some(period) = period.filter(|_| pool.current_num_threads() > 1) else {
+ pool.install(f);
+ return 0;
+ };
+ // Set when `f` has returned, or unwound: the wait ends either way, and the scope then carries the panic on.
+ struct Done<'a>(&'a (Mutex<bool>, Condvar));
+ impl Drop for Done<'_> {
+ fn drop(&mut self) {
+ *self.0 .0.lock().unwrap_or_else(PoisonError::into_inner) = true;
+ self.0 .1.notify_one();
+ }
+ }
+ let done = (Mutex::new(false), Condvar::new());
+ let mut kicks = 0;
+ pool.in_place_scope(|s| {
+ s.spawn(|_| {
+ let _done = Done(&done);
+ f();
+ });
+ let mut finished = done.0.lock().unwrap_or_else(PoisonError::into_inner);
+ while !*finished {
+ let (guard, wait) = done.1.wait_timeout(finished, period).unwrap_or_else(PoisonError::into_inner);
+ finished = guard;
+ if !*finished && wait.timed_out() {
+ kicks += 1;
+ pool.spawn(|| {});
+ }
+ }
+ });
+ kicks
+}
+
+/// The pool's size: what `THREERT_PHYSICS_THREADS` says (1 to 16; 0, "off", "false", "no", any case: 1, sequential),
+/// else 4 or the performance cores when fewer. Err(that default) for a value that is none of these: the caller says so.
+#[cfg(not(target_arch = "wasm32"))]
+fn threads_from(env: Option<&str>, cores: usize) -> Result<usize, usize> {
+ let default = cores.clamp(1, 4);
+ match env.map(|v| v.trim().to_ascii_lowercase()).as_deref() {
+ None => Ok(default),
+ Some("off" | "false" | "no" | "0") => Ok(1),
+ Some(v) => v.parse::<usize>().ok().filter(|n| (1..=16).contains(n)).ok_or(default),
+ }
+}
+
+/// The machine's performance cores: on Apple silicon the first performance level's physical cores (the efficiency
+/// cores are left to the rest of the process); elsewhere the cores the process may use.
+#[cfg(not(target_arch = "wasm32"))]
+fn performance_cores() -> usize {
+ #[cfg(target_os = "macos")]
+ {
+ let (mut n, mut size) = (0i32, std::mem::size_of::<i32>());
+ // SAFETY: the name is a C string, and the value is read into an i32 whose size is passed with it.
+ let read = unsafe { libc::sysctlbyname(c"hw.perflevel0.physicalcpu".as_ptr(), (&mut n as *mut i32).cast(), &mut size, std::ptr::null_mut(), 0) };
+ if read == 0 && n > 0 {
+ return n as usize;
+ }
+ }
+ std::thread::available_parallelism().map_or(1, |n| n.get())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -180,6 +333,20 @@ mod tests {
assert_eq!(p.take_stats().bodies, 0);
}
+ /// The physics' threads: 4, the performance cores when fewer, what the environment says when it says a count;
+ /// 1 (0, "off") is sequential.
+ #[test]
+ fn the_physics_threads() {
+ assert_eq!([threads_from(None, 5), threads_from(None, 12), threads_from(None, 2), threads_from(None, 0)], [Ok(4), Ok(4), Ok(2), Ok(1)]);
+ assert_eq!([threads_from(Some("8"), 5), threads_from(Some("1"), 5), threads_from(Some("0"), 5), threads_from(Some("off"), 5), threads_from(Some(" 2 "), 5)], [Ok(8), Ok(1), Ok(1), Ok(1), Ok(2)]);
+ assert_eq!([threads_from(Some("OFF"), 5), threads_from(Some("False"), 5), threads_from(Some("no"), 5)], [Ok(1), Ok(1), Ok(1)]);
+ // Not understood: the default, and the caller says so.
+ assert_eq!([threads_from(Some("64"), 5), threads_from(Some("many"), 2), threads_from(Some(""), 5), threads_from(Some("-1"), 5)], [Err(4), Err(2), Err(4), Err(4)]);
+ assert!(performance_cores() >= 1);
+ let asked = threads_from(std::env::var("THREERT_PHYSICS_THREADS").ok().as_deref(), performance_cores());
+ assert_eq!(pool().unwrap().current_num_threads(), asked.unwrap_or_else(|d| d));
+ }
+
/// 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.
@@ -188,6 +355,22 @@ mod tests {
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));
+ // And stepped as the renderer steps its world: on one of the physics' threads, with their count. (Called
+ // from here the checks above run their parallel parts on the process's pool, whatever its size.)
+ let (mut script, mut cases) = (0, 0);
+ in_pool(|| (script, cases) = (check::script(600), check::cases()));
+ assert_eq!(format!("{script:016x}"), format!("{:016x}", check::EXPECTED), "on the physics' threads");
+ assert_eq!(format!("{cases:016x}"), format!("{:016x}", check::EXPECTED_CASES), "on the physics' threads");
+ }
+
+ /// A step's wait ends when the step unwinds, and the panic comes through; the pool steps again after it.
+ #[test]
+ fn a_step_that_panics_is_not_waited_for() {
+ let r = std::panic::catch_unwind(|| in_pool(|| panic!("in the step")));
+ assert!(r.is_err());
+ let mut ran = false;
+ in_pool(|| ran = true);
+ assert!(ran);
}
/// Two events with no tick between them: the body the first one's script added is in the engine once that script
diff --git a/renderer/src/script.rs b/renderer/src/script.rs
index ec283cb..c6f9680 100644
--- a/renderer/src/script.rs
+++ b/renderer/src/script.rs
@@ -66,11 +66,64 @@ const SETUP_MS: u64 = 120_000;
const EVENT_MS: u64 = 1_000;
const FRAME_MS: u64 = 50;
+/// The most engine time one entry into the script (a frame, an event, setup) is lent, µs: past it the time the engine
+/// spends in voxel calls counts against the script's budget again. 250 ms: the largest single edit measured on the
+/// benchmark level, the 30 x 30 m cut, takes 115 ms of engine time, so two of those fit; a frame that spends more in
+/// the engine than that is a hitch of a quarter of a second whatever the script does, and a script that keeps asking
+/// is then ended at its budget like one that spins.
+const LEND_US: u64 = 250_000;
+
+/// The script's clock for one entry: its deadline in µs since the host's epoch (0: none), checked by the interrupt
+/// handler, and the engine time lent to it so far.
+struct Budget {
+ epoch: Instant,
+ deadline: AtomicU64,
+ lent: AtomicU64,
+}
+
+impl Budget {
+ /// Past the deadline (with what was lent): the script's time is up.
+ fn up(&self) -> bool {
+ let d = self.deadline.load(Ordering::Relaxed);
+ d != 0 && self.epoch.elapsed().as_micros() as u64 > d
+ }
+}
+
+/// The engine's time inside a voxel call is not the script's: when the call returns (or throws), the deadline moves
+/// by the time it took, as it was, up to `LEND_US` in all for the entry. (A cut through a hundred voxel bodies takes
+/// 50 ms and more; without this the script that asked for it would be ended at its next statement, the rest of its
+/// frame lost.) A script that spins, or loops on cheap calls, is ended as before.
+///
+/// A voxel call made when the time is already up throws "interrupted" at once: the script engine looks at its
+/// deadline only every so many of its own operations, and a loop whose every turn is a call of some milliseconds
+/// makes few of those (it ran for seconds past its budget before).
+struct Lent<'a>(&'a Budget, Instant);
+
+impl<'a> Lent<'a> {
+ fn new(ctx: &Ctx<'_>, budget: &'a Budget) -> rquickjs::Result<Self> {
+ if budget.up() {
+ return Err(fail(ctx, anyhow!("interrupted (the script's time is up)")));
+ }
+ Ok(Lent(budget, Instant::now()))
+ }
+}
+
+impl Drop for Lent<'_> {
+ fn drop(&mut self) {
+ let took = self.1.elapsed().as_micros() as u64;
+ let give = took.min(LEND_US.saturating_sub(self.0.lent.load(Ordering::Relaxed)));
+ // (0: no deadline is set, and none is made.)
+ if give > 0 && self.0.deadline.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |d| (d != 0).then_some(d + give)).is_ok() {
+ self.0.lent.fetch_add(give, Ordering::Relaxed);
+ }
+ }
+}
+
pub struct ScriptHost {
_rt: Runtime,
ctx: Context,
- /// Abort deadline in ms since `epoch` (0 = none), checked by the interrupt handler.
- deadline: Arc<AtomicU64>,
+ /// The deadline of the entry running now and the engine time lent to it (`Budget`).
+ budget: Arc<Budget>,
epoch: Instant,
/// `describe()`: handlers, keys, whether the game has a frame script.
pub info: serde_json::Value,
@@ -138,7 +191,7 @@ fn thrown(ctx: &Ctx, e: crate::api::Error) -> rquickjs::Error {
/// The engine API (`globalThis.__engine`), see packages/scene/src/engine.ts: each call's arguments out of QuickJS,
/// then what the call does (api.rs: the same code a browser's exports run, renderer/web).
-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<()> {
+fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<RefCell<crate::voxel::VoxelWorld>>, physics: &Rc<RefCell<Option<crate::physics::PhysicsWorld>>>, budget: &Arc<Budget>) -> rquickjs::Result<()> {
use crate::api;
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
@@ -156,18 +209,22 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<R
// knows the asset root; an explosion returns what it did as JSON.
let v = voxels.clone();
e.set("voxelLevel", Function::new(ctx.clone(), move |ctx: Ctx, d: Value| -> rquickjs::Result<()> { api::voxel_level(&mut v.borrow_mut(), &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;
- let (v, w) = (voxels.clone(), world.clone());
- e.set("voxelExplode", Function::new(ctx.clone(), move |ctx: Ctx, x: f64, y: f64, z: f64, r: f64| -> rquickjs::Result<String> { api::voxel_explode(&mut v.borrow_mut(), &mut w.borrow_mut(), x, y, z, r).map_err(|e| thrown(&ctx, e)) })?)?;
+ let (v, w, p, d) = (voxels.clone(), world.clone(), physics.clone(), budget.clone());
+ e.set("voxelExplode", Function::new(ctx.clone(), move |ctx: Ctx, x: f64, y: f64, z: f64, r: f64| -> rquickjs::Result<String> { let _lent = Lent::new(&ctx, &d)?; api::voxel_explode(&mut v.borrow_mut(), &mut w.borrow_mut(), &mut p.borrow_mut(), x, y, z, r).map_err(|e| thrown(&ctx, e)) })?)?;
// An edit of the level (`voxelEdit({ op, sphere | box | capsule, material })`; voxel.rs `EditOp`), and the level's
// hash (16 hex digits; "" before a level): the same commands give the same hash.
- let (v, w) = (voxels.clone(), world.clone());
- e.set("voxelEdit", Function::new(ctx.clone(), move |ctx: Ctx<'js>, d: Value<'js>| -> rquickjs::Result<String> { api::voxel_edit(&mut v.borrow_mut(), &mut w.borrow_mut(), &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;
+ let (v, w, p, dl) = (voxels.clone(), world.clone(), physics.clone(), budget.clone());
+ e.set("voxelEdit", Function::new(ctx.clone(), move |ctx: Ctx<'js>, d: Value<'js>| -> rquickjs::Result<String> { let _lent = Lent::new(&ctx, &dl)?; api::voxel_edit(&mut v.borrow_mut(), &mut w.borrow_mut(), &mut p.borrow_mut(), &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;
+ // The voxel bodies (ROADMAP § 6 step 8), as JSON: [{ body, collider, voxels, asleep, position, rotation }]. `body`
+ // is the physics world's id: `physics("impulse", { body, ... })` and the other calls take it.
+ let (v, p) = (voxels.clone(), physics.clone());
+ e.set("voxelBodies", Function::new(ctx.clone(), move || -> String { api::voxel_bodies(&v.borrow(), &p.borrow()) })?)?;
let v = voxels.clone();
e.set("voxelHash", Function::new(ctx.clone(), move || -> String { api::voxel_hash(&v.borrow()) })?)?;
let v = voxels.clone();
e.set("voxelDebris", Function::new(ctx.clone(), move |ctx: Ctx<'js>| -> rquickjs::Result<TypedArray<'js, f32>> { TypedArray::new(ctx, v.borrow_mut().take_debris()) })?)?;
- let (v, w) = (voxels.clone(), world.clone());
- e.set("voxelFrame", Function::new(ctx.clone(), move |ctx: Ctx, dt: f64| -> rquickjs::Result<String> { api::voxel_frame(&mut v.borrow_mut(), &mut w.borrow_mut(), dt).map_err(|e| thrown(&ctx, e)) })?)?;
+ let (v, w, d) = (voxels.clone(), world.clone(), budget.clone());
+ e.set("voxelFrame", Function::new(ctx.clone(), move |ctx: Ctx, dt: f64| -> rquickjs::Result<String> { let _lent = Lent::new(&ctx, &d)?; api::voxel_frame(&mut v.borrow_mut(), &mut w.borrow_mut(), dt).map_err(|e| thrown(&ctx, e)) })?)?;
let w = world.clone();
// (…, groups?, colors?): the optional arguments as the rest (rquickjs takes seven parameters at most).
e.set("geometry", Function::new(ctx.clone(), move |ctx: Ctx<'js>, id: u32, p: TypedArray<f32>, n: TypedArray<f32>, uv: TypedArray<f32>, idx: TypedArray<u32>, rest: rquickjs::function::Rest<Value<'js>>| -> rquickjs::Result<()> {
@@ -285,23 +342,20 @@ impl ScriptHost {
let rt = Runtime::new()?;
rt.set_memory_limit(1 << 30);
rt.set_max_stack_size(4 << 20);
- let deadline = Arc::new(AtomicU64::new(0));
let epoch = Instant::now();
- let d = deadline.clone();
- rt.set_interrupt_handler(Some(Box::new(move || {
- let limit = d.load(Ordering::Relaxed);
- limit != 0 && epoch.elapsed().as_millis() as u64 > limit
- })));
+ let budget = Arc::new(Budget { epoch, deadline: AtomicU64::new(0), lent: AtomicU64::new(0) });
+ let b = budget.clone();
+ rt.set_interrupt_handler(Some(Box::new(move || b.up())));
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, physics: Default::default() };
- let (w, v, ph) = (h.world.clone(), h.voxels.clone(), h.physics.clone());
+ let mut h = ScriptHost { _rt: rt, ctx, budget, epoch, info: serde_json::Value::Null, world, voxels, physics: Default::default() };
+ let (w, v, ph, d2) = (h.world.clone(), h.voxels.clone(), h.physics.clone(), h.budget.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, &ph)?;
+ install_engine(ctx, &w, &v, &ph, &d2)?;
ctx.eval::<(), _>(PRELUDE)?;
code(ctx)?;
host(ctx)?.get::<_, Function>("describe")?.call(())
@@ -312,9 +366,10 @@ impl ScriptHost {
/// Runs `f` in the engine under a time budget; JS exceptions become errors with their message and stack.
fn call<T>(&self, budget_ms: u64, f: impl for<'js> FnOnce(&Ctx<'js>) -> rquickjs::Result<T>) -> Result<T> {
- self.deadline.store(self.epoch.elapsed().as_millis() as u64 + budget_ms, Ordering::Relaxed);
+ self.budget.lent.store(0, Ordering::Relaxed);
+ self.budget.deadline.store(self.epoch.elapsed().as_micros() as u64 + budget_ms * 1000, Ordering::Relaxed);
let r = self.ctx.with(|ctx| f(&ctx).catch(&ctx).map_err(|e| anyhow!("{e}")));
- self.deadline.store(0, Ordering::Relaxed);
+ self.budget.deadline.store(0, Ordering::Relaxed);
r
}
@@ -392,20 +447,12 @@ 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,
- }
+ crate::api::physics_advance(&mut self.physics.borrow_mut(), &mut self.voxels.borrow_mut(), &mut self.world.borrow_mut(), dt as f64)
}
/// 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);
- }
+ crate::api::physics_settle(&mut self.physics.borrow_mut(), &mut self.voxels.borrow_mut(), &mut self.world.borrow_mut(), ticks);
}
/// Runs the frame script for one rendered frame.
@@ -505,7 +552,7 @@ impl GameSession {
/// that follows includes it, so its changes are dropped here (as the setup's are, `load`).
fn realize_voxels(&self, assets: &std::path::Path) -> Result<()> {
let mut w = self.host.world.borrow_mut();
- if let Some(r) = self.host.voxels.borrow_mut().realize(&mut w, assets)? {
+ if let Some(r) = self.host.voxels.borrow_mut().realize(&mut w, &mut self.host.physics.borrow_mut(), assets)? {
eprintln!("voxels: {r}");
w.take_changes();
}
@@ -782,6 +829,63 @@ mod tests {
}
}
+ /// The engine's time in a voxel edit is not the script's: a frame's worth of script that spends 150 ms in edits
+ /// (three times its budget) goes on to its end, and one that spins after its edits is still ended.
+ #[test]
+ fn the_engines_time_in_a_voxel_call_is_not_the_scripts() {
+ let h = ScriptHost::new(GAME).unwrap();
+ *h.voxels.borrow_mut() = crate::voxel::VoxelWorld::of_blocks(&[([0, 0, 0], [64, 16, 64], Some((0, 0)), true)], &mut h.world.borrow_mut(), &mut h.physics.borrow_mut());
+ let edits = "let t = __host_now(), n = 0; while (__host_now() - t < 150) { __engine.voxelEdit({ op: 'carve', box: [0.5, 0.5, 0.5, 5.5, 1.5, 5.5] }); __engine.voxelEdit({ op: 'add', box: [0.5, 0.5, 0.5, 5.5, 1.5, 5.5], material: 1 }); n++; }";
+ let n: i32 = h.call(FRAME_MS, |ctx| ctx.eval(format!("{edits} let s = 0; for (let i = 0; i < 100000; i++) s += i; n"))).unwrap();
+ assert!(n >= 1);
+ let t = Instant::now();
+ let err = h.call(FRAME_MS, |ctx| ctx.eval::<(), _>(format!("{{ {edits} }} spin()"))).unwrap_err();
+ assert!(format!("{err}").contains("interrupted"), "{err}");
+ assert!(t.elapsed().as_millis() < 2000, "{} ms", t.elapsed().as_millis());
+ }
+
+ /// The engine's time is lent as it was, not rounded up, and at most `LEND_US` an entry (the review of #24: each
+ /// call moved the deadline by a millisecond at least, so a frame script looping on cheap voxel calls, or on ones
+ /// that throw, ran for ever). Each loop is ended within its budget, and real edits past what may be lent are too.
+ #[test]
+ fn a_script_looping_on_voxel_calls_is_ended() {
+ let h = ScriptHost::new(GAME).unwrap();
+ // Without a level: voxelFrame does nothing, voxelEdit and voxelExplode throw.
+ for body in ["__engine.voxelFrame(0)", "try { __engine.voxelEdit({}) } catch (e) {}", "try { __engine.voxelExplode(0, 0, 0, 1) } catch (e) {}"] {
+ let t = Instant::now();
+ let err = h.call(FRAME_MS, |ctx| ctx.eval::<(), _>(format!("for (;;) {{ {body}; }}"))).unwrap_err();
+ assert!(format!("{err}").contains("interrupted"), "{body}: {err}");
+ assert!(t.elapsed().as_millis() < 200, "{body}: ended after {} ms", t.elapsed().as_millis());
+ }
+ // With a level, edits that each take real time, for ever: lent up to 250 ms, then the budget's 50.
+ *h.voxels.borrow_mut() = crate::voxel::VoxelWorld::of_blocks(&[([0, 0, 0], [64, 16, 64], Some((0, 0)), true)], &mut h.world.borrow_mut(), &mut h.physics.borrow_mut());
+ let t = Instant::now();
+ let err = h.call(FRAME_MS, |ctx| ctx.eval::<(), _>("for (;;) { __engine.voxelEdit({ op: 'carve', box: [0.5, 0.5, 0.5, 5.5, 1.5, 5.5] }); __engine.voxelEdit({ op: 'add', box: [0.5, 0.5, 0.5, 5.5, 1.5, 5.5], material: 1 }); }")).unwrap_err();
+ assert!(format!("{err}").contains("interrupted"), "{err}");
+ let ms = t.elapsed().as_millis();
+ assert!((250..800).contains(&ms), "ended after {ms} ms (50 of script and at most 250 lent)");
+ }
+
+ /// An id scene code read out of an answer goes back into a call: a ray's hit on a voxel body, its `body` into an
+ /// impulse. (Parsed out of the answer the id is a double in the script engine, and comes back as `1073741837.0`:
+ /// the bridge reads a whole number as the id it is.)
+ #[test]
+ fn an_id_a_script_read_from_a_hit_goes_into_a_call() {
+ let h = ScriptHost::new(GAME).unwrap();
+ // A slab and a bar standing on it, cut loose: 336 voxels of 1,000 kg/m³.
+ let mut v = crate::voxel::VoxelWorld::of_blocks(&[([0, 0, 0], [64, 4, 64], Some((0, 0)), true), ([28, 4, 28], [4, 24, 4], None, false)], &mut h.world.borrow_mut(), &mut h.physics.borrow_mut());
+ v.edit(&mut h.world.borrow_mut(), &mut h.physics.borrow_mut(), &crate::voxel::EditOp::parse(&serde_json::json!({ "op": "carve", "box": [2.7, 0.5, 2.7, 3.3, 0.7, 3.3] })).unwrap()).unwrap();
+ assert_eq!(v.bodies(), 1);
+ *h.voxels.borrow_mut() = v;
+ let up: f64 = h.call(100, |ctx| ctx.eval(r#"
+ const hit = JSON.parse(__engine.physics("ray", { origin: [3.05, 1.55, 10], direction: [0, 0, -1], max: 20 }));
+ if (hit.body !== JSON.parse(__engine.voxelBodies())[0].body) throw new Error("the hit is not the body: " + JSON.stringify(hit));
+ __engine.physics("impulse", { body: hit.body, impulse: [0, 500, 0] });
+ JSON.parse(__engine.physics("state", { body: hit.body })).linvel[1]
+ "#)).unwrap();
+ assert!((up - 500.0 / 336.0).abs() < 0.05, "{up} m/s");
+ }
+
#[test]
fn budgets_and_errors() {
let h = ScriptHost::new(GAME).unwrap();
diff --git a/renderer/src/units_cost.rs b/renderer/src/units_cost.rs
index 1f03f5a..0b00c5b 100644
--- a/renderer/src/units_cost.rs
+++ b/renderer/src/units_cost.rs
@@ -225,7 +225,7 @@ fn units_cost() {
let host = crate::script::ScriptHost::new(&std::fs::read_to_string(&bundle).unwrap()).unwrap();
host.setup("r", None).unwrap();
// (A voxel level the scene code asked for: loaded before the first scene build, as the session does.)
- if host.voxels.borrow_mut().realize(&mut host.world.borrow_mut(), &assets).unwrap().is_some() {
+ if host.voxels.borrow_mut().realize(&mut host.world.borrow_mut(), &mut host.physics.borrow_mut(), &assets).unwrap().is_some() {
let _ = host.world.borrow_mut().take_changes();
}
let world = host.world.borrow();
@@ -323,7 +323,7 @@ fn units_pile() {
let ns: Vec<usize> = std::env::var("UNITS_PILE_N").unwrap_or("0,250,1000,4000,16000".into()).split(',').map(|v| v.parse().unwrap()).collect();
let host = crate::script::ScriptHost::new(&std::fs::read_to_string(&bundle).unwrap()).unwrap();
host.setup("r", None).unwrap();
- if host.voxels.borrow_mut().realize(&mut host.world.borrow_mut(), &assets).unwrap().is_some() {
+ if host.voxels.borrow_mut().realize(&mut host.world.borrow_mut(), &mut host.physics.borrow_mut(), &assets).unwrap().is_some() {
let _ = host.world.borrow_mut().take_changes();
}
let world = host.world.borrow();
diff --git a/renderer/src/voxel.rs b/renderer/src/voxel.rs
index 026956b..59cb73a 100644
--- a/renderer/src/voxel.rs
+++ b/renderer/src/voxel.rs
@@ -14,11 +14,13 @@
//! new object that falls (`voxelFrame` ticks the level 60 times a second: its mesh is written again where it is, in
//! place) until it rests on something; there it is static again.
+use crate::physics::PhysicsWorld;
use crate::world::{Geometry, Kind, World};
+use physics_core::{BodyDesc, ColliderDesc};
use anyhow::{anyhow, Result};
use glam::{Mat4, Quat, Vec3};
use serde::Deserialize;
-use std::collections::{BTreeSet, HashMap};
+use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::Path;
use std::rc::Rc;
use web_time::Instant;
@@ -33,6 +35,28 @@ const TILE: i32 = 64;
/// The level's ticks a second (falling objects), and the most it makes up in one frame.
const TICK_RATE: f64 = 60.0;
const MAX_TICKS: u32 = 8;
+/// The most voxel bodies a level holds unless it says otherwise (`LevelDesc::max_bodies`): past it one goes, its
+/// voxels debris (`add_body` says which, and when the new part is debris instead). 300 is what was measured to hold
+/// 60 fps with every one of them in the air at once, natively on 4 threads (docs/VOXEL.md "Voxel bodies": at 400 a
+/// few frames of a thousand went over; with the physics on one thread, `THREERT_PHYSICS_THREADS=1`, 128 is about at
+/// the frame).
+pub const MAX_BODIES: usize = 300;
+/// The most edits and frames scene code can ask for before the level is loaded (in setup), kept until it is: they are
+/// outside the script engine's memory, so they are counted. 4,096: a setup that cuts a level into its starting state
+/// takes a few dozen edits and a second of frames (the tests: one cut and 60 frames); one that asks for thousands is
+/// doing work that belongs after the load, in frames.
+pub const MAX_QUEUED: usize = 4096;
+/// A level object's collider holds its cells within this many cells of one that is not solid (six-connected steps):
+/// a shell. The benchmark level has 515 million solid cells, 480 million of them terrain down to the bedrock; a
+/// collider of every one took 26 s to build and 1.3 GiB. Four cells are 0.4 m of voxels of 0.1 m: a body would have
+/// to cross them in one tick (24 m/s, a fall of 29 m) to get behind the shell, and one that does falls out under
+/// the level and is taken out (`sync_bodies`). An edit keeps the shell whole around what it carved.
+const SHELL: i32 = 4;
+/// Friction of voxel colliders (the level's and the bodies').
+const FRICTION: f32 = 0.6;
+/// kg/m³ of a palette entry that names no density, by its hardness: soft (earth, wood), medium (brick), hard
+/// (concrete), indestructible (steel).
+const DENSITY: [f32; 4] = [900.0, 1800.0, 2400.0, 7800.0];
/// What scene code sends (`voxelLevel`): the route, the palette (index = voxel material), the procedural geometry
/// function's name (boxes; the scene registers it), and the objects: their file, placement and, for terrain tiles, the
@@ -55,6 +79,15 @@ pub struct LevelDesc {
/// default). Kept up to date as edits carve and parts land.
#[serde(default)]
pub occupancy: f64,
+ /// Physics of the level (ROADMAP § 6 step 8), on unless `false`: every object is a fixed collider of its voxels,
+ /// kept up to date as edits carve it (rays and sweeps of the physics world meet the level, bodies rest on it), and
+ /// what an edit leaves hanging on no anchor is a rigid body. `false`: no collider, and loose parts fall straight
+ /// down through the lattice as before step 8 (`voxel_core::Level::tick`).
+ #[serde(default)]
+ pub physics: Option<bool>,
+ /// The most voxel bodies at once (`MAX_BODIES` by default; at most `physics_core::bridge::MAX_ENGINE_BODIES`).
+ #[serde(default, rename = "maxBodies")]
+ pub max_bodies: Option<f64>,
}
#[derive(Deserialize, Debug, Clone)]
@@ -71,6 +104,9 @@ pub struct PaletteEntry {
/// "indestructible" (never: cuts leave it too).
#[serde(default)]
pub hardness: String,
+ /// kg/m³ of its voxels in a rigid body (0, the default: by its hardness, `DENSITY`).
+ #[serde(default)]
+ pub density: f32,
}
#[derive(Deserialize, Debug, Clone)]
@@ -87,6 +123,10 @@ pub struct ObjectDesc {
/// It holds what touches it and never falls (terrain tiles are anchors without it).
#[serde(default)]
pub anchor: bool,
+ /// `false`: no collider for this object (bodies and rays pass through it); a part that comes loose from it is a
+ /// body all the same.
+ #[serde(default)]
+ pub collide: Option<bool>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -115,8 +155,36 @@ struct VoxelObject {
flying: Option<Vec<MeshPart>>,
}
+/// What `VoxelWorld::check_script` ends in, natively and in wasm32 alike (recorded: a change of the voxel bodies'
+/// behaviour, of the physics or of a platform's arithmetic shows here).
+pub const EXPECTED_SCRIPT: u64 = 0xd26e_5461_62ad_7eec;
+
+/// A brick as a collider's shell reads it (`VoxelWorld::brick_at`).
+#[derive(Clone, Copy)]
+enum BrickRef<'a> {
+ Solid,
+ Empty,
+ Cells(&'a [u8; 512]),
+}
+
+/// A loose part as a rigid body (ROADMAP § 6 step 8): the level no longer holds it. Its voxels are its own grid, in
+/// the body's space (cell (x, y, z) from (x, y, z) x size); the physics world moves it and the world objects that
+/// draw it follow (`VoxelWorld::sync_bodies`).
+struct VoxelBody {
+ /// The engine's body and its voxel collider (ids of the bridge's engine range).
+ body: u32,
+ collider: u32,
+ grid: VoxelGrid,
+ /// Where its objects were last placed.
+ pose: ([f32; 3], [f32; 4]),
+}
+
/// What scene code asked of the level before it was loaded (in setup: edits and the ticks after them, so the live
-/// view and the offline render start from the same world), done once it is (`realize`).
+/// view and the offline render start from the same world), done once it is (`realize`). The ticks are the lattice's
+/// (`frame`: parts falling cell by cell on a level without physics). On a level that collides a queued edit's loose
+/// parts are bodies as soon as it is replayed and the queued ticks have nothing to move: the physics world is
+/// stepped by the engine's clock only (`api::physics_advance`, `physics_settle` for an offline render's scene time),
+/// never from scene code, so that a live run and an offline one tick it alike.
enum Queued {
Edit(EditOp),
Frame(f64),
@@ -205,6 +273,23 @@ pub struct VoxelWorld {
entry_color: Vec<[f32; 3]>,
/// The occupancy grid (`LevelDesc::occupancy`), shared with the world (`World::voxel_occupancy`).
occupancy: Option<std::sync::Arc<std::sync::RwLock<crate::world::Occupancy>>>,
+ /// Physics (`LevelDesc::physics`): each level object's fixed collider (same index; None: none, or carved away),
+ /// the loose parts that are bodies (by their index in `objects`), each palette entry's density, the cap on
+ /// bodies, and how many it retired.
+ physics: bool,
+ colliders: Vec<Option<u32>>,
+ bodies: BTreeMap<usize, VoxelBody>,
+ density: Vec<f32>,
+ max_bodies: usize,
+ pub retired: u64,
+ /// Parts that came loose at the cap and were made debris, not bodies (`add_body`).
+ pub capped: u64,
+ /// The bodies the edit being made has carved or made: none of them is retired for the cap while it runs.
+ this_edit: std::collections::BTreeSet<usize>,
+ /// Under this height (m) a body has left the level: 100 m below its lowest cell.
+ floor: f32,
+ /// Time spent finding the colliders' cells (`shell`), ms: of the load, and of every edit since.
+ pub shell_ms: f64,
}
/// Debris voxels kept between two `take_debris` calls, and of one edit.
@@ -240,8 +325,10 @@ impl VoxelWorld {
/// Loads the requested level into the world: decodes the files, places the objects (meshed or as boxes). Returns
/// what it did (ms, objects, triangles) for the log.
- pub fn realize(&mut self, w: &mut World, assets: &Path) -> Result<Option<serde_json::Value>> {
+ pub fn realize(&mut self, w: &mut World, ph: &mut Option<PhysicsWorld>, assets: &Path) -> Result<Option<serde_json::Value>> {
let Some(d) = self.pending.take() else { return Ok(None) };
+ self.physics = d.physics.unwrap_or(true);
+ self.max_bodies = d.max_bodies.map_or(MAX_BODIES, |n| (n.max(0.0) as usize).min(physics_core::bridge::MAX_ENGINE_BODIES));
let t0 = Instant::now();
let route = if d.route == "mesh" { Route::Mesh } else { Route::Boxes };
self.route = Some(route);
@@ -310,6 +397,10 @@ impl VoxelWorld {
"indestructible" => voxel_core::INDESTRUCTIBLE,
other => return Err(anyhow!("voxelLevel: palette entry {}: hardness \"{other}\" is none of soft, medium, hard, indestructible", p.name)),
};
+ if !(p.density == 0.0 || (p.density.is_finite() && (10.0..=30_000.0).contains(&p.density))) {
+ return Err(anyhow!("voxelLevel: palette entry {}: density must be from 10 to 30000 kg/m³ (or 0: by its hardness)", p.name));
+ }
+ self.density.push(if p.density > 0.0 { p.density } else { DENSITY[(level.hardness[k] & 3) as usize] });
}
// Every object in the level's lattice: its position to the nearest voxel, its turn in quarters.
let mut snapped = 0usize;
@@ -383,12 +474,31 @@ impl VoxelWorld {
w.voxel_occupancy = self.occupancy.clone();
}
let occupancy_ms = t_occ.elapsed().as_secs_f64() * 1e3;
+ // The level's colliders: every object a fixed voxel shape of its cells in the world's lattice.
+ let t_col = Instant::now();
+ let (mut colliders, mut collider_cells) = (0usize, 0usize);
+ self.colliders = vec![None; self.objects.len()];
+ self.floor = self.level.as_ref().map_or(f32::MIN, |l| l.objects.iter().flatten().map(|o| o.lo[1]).min().map_or(f32::MIN, |y| y as f32 * size - 100.0));
+ if self.physics {
+ let p = ph.get_or_insert_with(Default::default);
+ let (mut full, mut shapes) = (HashMap::new(), HashMap::new());
+ for k in 0..self.objects.len() {
+ if d.objects.get(k).is_some_and(|o| o.collide == Some(false)) {
+ continue;
+ }
+ if let Some(n) = self.collide(p, k, &mut full, &mut shapes) {
+ colliders += 1;
+ collider_cells += n;
+ }
+ }
+ }
+ let colliders_ms = t_col.elapsed().as_secs_f64() * 1e3;
let queued = std::mem::take(&mut self.queued);
let (edits, frames) = (queued.iter().filter(|q| matches!(q, Queued::Edit(..))).count(), queued.iter().filter(|q| matches!(q, Queued::Frame(_))).count());
for q in queued {
match q {
Queued::Edit(op) => {
- self.edit(w, &op)?;
+ self.edit(w, ph, &op)?;
}
Queued::Frame(dt) => {
self.frame(w, dt)?;
@@ -400,9 +510,54 @@ impl VoxelWorld {
"place_ms": place_ms, "triangles": triangles, "explosions": edits, "frames": frames,
"lattice_ms": lattice_ms, "lattice_bricks": lattice_bricks, "lattice_mb": lattice_mb, "floating_groups": floating.0, "floating_voxels": floating.1, "snapped": snapped,
"occupancy_ms": occupancy_ms, "occupancy_bytes": self.occupancy.as_ref().map_or(0, |o| o.read().unwrap().words.len() * 4),
+ "colliders": colliders, "collider_cells": collider_cells, "colliders_ms": colliders_ms, "shell_ms": self.shell_ms,
})))
}
+ /// Level object `k`'s fixed collider: the shell of its cells (`shell`), in its grid's own cells, placed as the
+ /// object is (`collider_pose`). Objects of one file have one grid between them and so one shape (`shapes`: by
+ /// grid, the shape and its cells): they share it until an edit gives one of them cells of its own
+ /// (`Physics::edit_voxels`). A terrain tile's shell depends on its neighbours: its own shape. Returns the
+ /// collider's cells, or None if it got none (no voxel; a cell past what a shape may reach: said once).
+ fn collide(&mut self, p: &mut PhysicsWorld, k: usize, full: &mut HashMap<(usize, (i32, i32, i32)), bool>, shapes: &mut HashMap<usize, (physics_core::SharedVoxels, usize)>) -> Option<usize> {
+ let o = self.level.as_ref()?.objects.get(k)?.as_ref()?;
+ let (grid, place) = (Rc::as_ptr(&o.grid) as usize, o.place);
+ let alone = self.objects.get(k)?.as_ref()?.tile.is_some();
+ let made = match shapes.get(&grid).filter(|_| !alone) {
+ Some(s) => Ok(s.clone()),
+ None => {
+ let t = Instant::now();
+ let cells = self.shell(k, None, full);
+ self.shell_ms += t.elapsed().as_secs_f64() * 1e3;
+ if cells.is_empty() {
+ return None;
+ }
+ let n = cells.len();
+ physics_core::SharedVoxels::new(self.size, cells).map(|s| {
+ if !alone {
+ shapes.insert(grid, (s.clone(), n));
+ }
+ (s, n)
+ })
+ }
+ };
+ let id = self.id();
+ let (position, rotation) = collider_pose(&place, self.size);
+ match made.and_then(|(shape, n)| p.bridge().engine_collider(id, None, &ColliderDesc { position, rotation, friction: FRICTION, ..ColliderDesc::new(physics_core::Shape::SharedVoxels(shape)) }).map(|()| n)) {
+ Ok(n) => {
+ if self.colliders.len() <= k {
+ self.colliders.resize(k + 1, None);
+ }
+ self.colliders[k] = Some(id);
+ Some(n)
+ }
+ Err(e) => {
+ eprintln!("voxels: {} has no collider ({e})", self.objects[k].as_ref().map_or("?", |o| o.name.as_str()));
+ None
+ }
+ }
+ }
+
/// Object `k`'s geometry where it is: per material (mesh) or one procedural geometry (boxes). Returns (material,
/// geometry id) per part.
fn make_geometry(&mut self, w: &mut World, k: usize, mut counts: Option<&mut (usize, usize)>) -> Result<Vec<(u8, u32)>> {
@@ -465,23 +620,33 @@ impl VoxelWorld {
Ok(tris)
}
+ /// An edit or a frame asked for before the level is loaded, kept for `realize`: at most `MAX_QUEUED`.
+ fn queue(&mut self, q: Queued) -> Result<()> {
+ if self.queued.len() >= MAX_QUEUED {
+ return Err(anyhow!("voxels: at most {MAX_QUEUED} edits and frames can be asked for before the level is loaded"));
+ }
+ self.queued.push(q);
+ Ok(())
+ }
+
/// Scene code's `voxelExplode`: an explosion at a world position (m) of a radius, each material within its
/// hardness's share of it.
- pub fn explode(&mut self, w: &mut World, center: Vec3, radius: f32) -> Result<serde_json::Value> {
- self.edit(w, &EditOp { shape: ShapeM::Sphere(center.to_array(), radius), kind: EditKind::Carve(RADII) })
+ pub fn explode(&mut self, w: &mut World, ph: &mut Option<PhysicsWorld>, center: Vec3, radius: f32) -> Result<serde_json::Value> {
+ self.edit(w, ph, &EditOp { shape: ShapeM::Sphere(center.to_array(), radius), kind: EditKind::Carve(RADII) })
}
/// An edit (`voxelEdit`): the level's voxels changed (`voxel_core::Level`), the touched objects drawn again in place,
/// the loose parts made falling objects, the removed objects gone. Returns what it did and how long each part took.
- pub fn edit(&mut self, w: &mut World, op: &EditOp) -> Result<serde_json::Value> {
+ pub fn edit(&mut self, w: &mut World, ph: &mut Option<PhysicsWorld>, op: &EditOp) -> Result<serde_json::Value> {
if self.route.is_none() && self.pending.is_some() {
- self.queued.push(Queued::Edit(op.clone()));
+ self.queue(Queued::Edit(op.clone()))?;
return Ok(serde_json::json!({ "queued": true }));
}
if self.route.is_none() {
return Err(anyhow!("voxelEdit: no voxel level loaded"));
}
self.ticks.0 += 1;
+ self.this_edit.clear();
let size = self.size as f64;
let fp = |p: [f32; 3]| p.map(|v| to_fp(v as f64 / size));
let shape = match op.shape {
@@ -501,15 +666,78 @@ impl VoxelWorld {
let (lo, hi) = shape.cells();
let s = self.size;
let bounds = (Vec3::new(lo[0] as f32, lo[1] as f32, lo[2] as f32) * s, Vec3::new(hi[0] as f32 + 1.0, hi[1] as f32 + 1.0, hi[2] as f32 + 1.0) * s);
- let mut out = self.apply(w, &e, vec![bounds])?;
+ let mut out = self.apply(w, ph, &e, vec![bounds])?;
out["carve_ms"] = carve_ms.into();
+ // The bodies the shape reaches are carved too (a carve only: paint and added voxels are the level's).
+ if let (EditKind::Carve(radii), Some(p)) = (op.kind, ph.as_mut().filter(|_| !self.bodies.is_empty())) {
+ let t = Instant::now();
+ let b = self.carve_bodies(w, p, op.shape, radii)?;
+ out["body_voxels"] = b.0.into();
+ out["bodies_carved"] = b.1.into();
+ out["bodies_ms"] = (t.elapsed().as_secs_f64() * 1e3).into();
+ }
+ out["bodies"] = self.bodies.len().into();
Ok(out)
}
/// What an edit of the level did, drawn: `boxes` are the world boxes whose occupancy (for particles) to set again.
- fn apply(&mut self, w: &mut World, e: &Edit, mut boxes: Vec<(Vec3, Vec3)>) -> Result<serde_json::Value> {
+ fn apply<'e>(&mut self, w: &mut World, ph: &mut Option<PhysicsWorld>, e: &'e Edit, mut boxes: Vec<(Vec3, Vec3)>) -> Result<serde_json::Value> {
let size = self.size;
let route = self.route.unwrap();
+ // The colliders of the objects that lost cells lose them (by the cells, not by the object's size); those of
+ // the objects that are gone go.
+ let t_col = Instant::now();
+ if let Some(p) = ph.as_mut().filter(|_| self.physics) {
+ // (Each object's lost cells out, and its shell made whole around them: the cells an edit brought within
+ // `SHELL` of the open. A terrain tile carved at its edge bares its neighbours' sides: theirs too, over
+ // the carved tile's bounds, whether or not the neighbour lost cells of its own: each object is made whole
+ // over the box around its own bounds and every carved neighbour's.)
+ let mut work: BTreeMap<usize, (&'e [[i32; 3]], ([i32; 3], [i32; 3]))> = BTreeMap::new();
+ let mut over = |k: usize, cells: Option<&'e [[i32; 3]]>, (lo, hi): ([i32; 3], [i32; 3])| {
+ let w = work.entry(k).or_insert((&[][..], (lo, hi)));
+ if let Some(c) = cells {
+ w.0 = c;
+ }
+ w.1 = ([0, 1, 2].map(|a| w.1 .0[a].min(lo[a])), [0, 1, 2].map(|a| w.1 .1[a].max(hi[a])));
+ };
+ for (&k, cells) in &e.cleared {
+ let Some(&(lo, hi)) = e.bounds.get(&k) else { continue };
+ let around = (lo.map(|x| x - SHELL - 1), hi.map(|x| x + SHELL + 1));
+ over(k as usize, Some(cells.as_slice()), around);
+ if let Some((tx, tz)) = self.objects.get(k as usize).and_then(|o| o.as_ref()).and_then(|o| o.tile) {
+ for n in [(-1, 0), (1, 0), (0, -1), (0, 1)].iter().filter_map(|d| self.tiles.get(&(tx + d.0, tz + d.1))) {
+ over(*n, None, around);
+ }
+ }
+ }
+ let mut full = HashMap::new();
+ for (k, (cells, (lo, hi))) in work {
+ let Some(c) = self.colliders.get(k).copied().flatten() else { continue };
+ // (In the object's own cells, as its collider has them. An object that is gone: its collider goes below.)
+ let Some(o) = self.level.as_ref().and_then(|l| l.objects.get(k)?.as_ref()) else { continue };
+ let t = Instant::now();
+ let fill = self.shell(k, Some(o.place.box_to_grid(lo, hi)), &mut full);
+ self.shell_ms += t.elapsed().as_secs_f64() * 1e3;
+ let cells: Vec<[i32; 3]> = cells.iter().map(|&w| o.place.to_grid(w)).collect();
+ match p.bridge().engine_edit_voxels(c, &cells, &fill) {
+ Ok(0) => self.colliders[k] = None,
+ Ok(_) => {}
+ Err(err) => {
+ eprintln!("voxels: a collider was not edited ({err})");
+ // (One the edit took out, past the cells a shape holds, is gone: no id is kept for it.)
+ if p.bridge_ref().engine_voxels(c).is_none() {
+ self.colliders[k] = None;
+ }
+ }
+ }
+ }
+ for &k in &e.removed {
+ if let Some(c) = self.colliders.get_mut(k as usize).and_then(|c| c.take()) {
+ p.bridge().engine_remove(None, Some(c));
+ }
+ }
+ }
+ let colliders_ms = t_col.elapsed().as_secs_f64() * 1e3;
// Rebuild: new geometry for each touched object, swapped in place. A terrain tile beside a touched one shows
// faces it hid where voxels went at their shared edge (mesh route).
let t1 = Instant::now();
@@ -554,6 +782,16 @@ impl VoxelWorld {
if self.objects.len() <= k {
self.objects.resize_with(k + 1, || None);
}
+ // A loose part is a rigid body: the level hands it out, the physics world has it from here.
+ if let (true, Some(p)) = (falling && self.physics, ph.as_mut()) {
+ let o = self.level.as_mut().unwrap().take(id).expect("a falling object");
+ let grid = Rc::try_unwrap(o.grid).unwrap_or_else(|g| (*g).clone());
+ boxes.push((Vec3::new(lo[0] as f32, lo[1] as f32, lo[2] as f32) * size, Vec3::new(hi[0] as f32 + 1.0, hi[1] as f32 + 1.0, hi[2] as f32 + 1.0) * size));
+ let tm = Instant::now();
+ self.add_body(w, p, k, grid, corner, Quat::IDENTITY, ([0.0; 3], [0.0; 3]))?;
+ piece_mesh_ms += tm.elapsed().as_secs_f64() * 1e3;
+ continue;
+ }
let mut v = VoxelObject { name: format!("part{k}"), world: Mat4::IDENTITY, corner, off: t, tile: None, lo: Vec3::ZERO, hi: Vec3::ZERO, shared: None, parts: vec![], flying: None };
(v.lo, v.hi) = (Vec3::new(lo[0] as f32, lo[1] as f32, lo[2] as f32) * size, Vec3::new(hi[0] as f32 + 1.0, hi[1] as f32 + 1.0, hi[2] as f32 + 1.0) * size);
// (Where it was is no longer occupied; where it lands will be.)
@@ -582,6 +820,10 @@ impl VoxelWorld {
let tw = Instant::now();
self.place(w, k, &geometry)?;
piece_world_ms += tw.elapsed().as_secs_f64() * 1e3;
+ // (Added voxels that hold: a collider of their own.)
+ if let (false, true, Some(p)) = (falling, self.physics, ph.as_mut()) {
+ self.collide(p, k, &mut HashMap::new(), &mut HashMap::new());
+ }
}
let pieces_ms = t2.elapsed().as_secs_f64() * 1e3;
if self.keep_debris && !e.debris.is_empty() {
@@ -598,10 +840,501 @@ impl VoxelWorld {
"rebuild_ms": rebuild_ms, "pieces_ms": pieces_ms, "voxels": e.voxels, "touched": dirty.len(), "pieces": e.pieces, "piece_voxels": e.piece_voxels,
"dropped": e.debris.len(), "removed": e.removed.len(), "piece_mesh_ms": piece_mesh_ms, "piece_world_ms": piece_world_ms,
"batches": self.level.as_ref().unwrap().falling(), "faces": counts.0, "triangles": counts.1, "objects": self.objects.iter().flatten().count(),
- "occupancy_ms": occupancy_ms, "world_objects": self.world_objects(),
+ "occupancy_ms": occupancy_ms, "world_objects": self.world_objects(), "colliders_ms": colliders_ms,
}))
}
+ /// Brick `key` of level object `k`'s grid as its collider's shell sees it: the object's own; and for a terrain
+ /// tile, what lies beside and under it: solid under the bedrock, the neighbouring tile's brick beside it (tiles
+ /// stand side by side on one lattice of bricks; one that does not is taken as standing alone, its sides bare).
+ /// With the brick, the object and key it is at (the fullness cache's key).
+ fn brick_at(&self, k: usize, key: (i32, i32, i32)) -> (BrickRef<'_>, (usize, (i32, i32, i32))) {
+ let own = |k: usize, key: (i32, i32, i32)| match self.level.as_ref().and_then(|l| l.objects.get(k)?.as_ref()).and_then(|o| o.grid.bricks.get(&key)) {
+ Some(b) => (BrickRef::Cells(b), (k, key)),
+ None => (BrickRef::Empty, (k, key)),
+ };
+ let Some(o) = self.objects.get(k).and_then(|o| o.as_ref()) else { return (BrickRef::Empty, (k, key)) };
+ let (Some((tx, tz)), true) = (o.tile, o.off.iter().all(|x| x % 8 == 0)) else { return own(k, key) };
+ // In the tile's own bricks: 8 a side from its corner.
+ let q = (key.0 + o.off[0] / 8, key.1 + o.off[1] / 8, key.2 + o.off[2] / 8);
+ if q.1 < 0 {
+ return (BrickRef::Solid, (k, key));
+ }
+ let side = TILE / 8;
+ if (0..side).contains(&q.0) && (0..side).contains(&q.2) {
+ return own(k, key);
+ }
+ let Some(&n) = self.tiles.get(&(tx + q.0.div_euclid(side), tz + q.2.div_euclid(side))) else { return (BrickRef::Empty, (k, key)) };
+ match self.objects[n].as_ref().filter(|t| t.off.iter().all(|x| x % 8 == 0)) {
+ Some(t) => own(n, (q.0.rem_euclid(side) - t.off[0] / 8, q.1 - t.off[1] / 8, q.2.rem_euclid(side) - t.off[2] / 8)),
+ None => (BrickRef::Empty, (k, key)),
+ }
+ }
+
+ /// The cells of brick `key` of object `k` that are in its collider's shell (`SHELL`), added to `out` (grid cells).
+ /// `full`: which bricks are solid through, remembered over a pass of many bricks (a brick is asked about by each
+ /// of its 26 neighbours; the level has a million of them, most deep in the ground).
+ fn shell_of(&self, k: usize, key: (i32, i32, i32), out: &mut Vec<[i32; 3]>, full: &mut HashMap<(usize, (i32, i32, i32)), bool>) {
+ let mut around = [BrickRef::Empty; 27];
+ let mut all = true;
+ for (i, b) in around.iter_mut().enumerate() {
+ let d = ((i % 3) as i32 - 1, ((i / 3) % 3) as i32 - 1, (i / 9) as i32 - 1);
+ let (brick, at) = self.brick_at(k, (key.0 + d.0, key.1 + d.1, key.2 + d.2));
+ *b = brick;
+ all &= match brick {
+ BrickRef::Solid => true,
+ BrickRef::Empty => false,
+ BrickRef::Cells(c) => *full.entry(at).or_insert_with(|| c.iter().all(|&m| m != 0)),
+ };
+ // (Not solid all around: the rest are read below as they are needed.)
+ if !all && i > 13 {
+ for (j, b) in around.iter_mut().enumerate().skip(i + 1) {
+ let d = ((j % 3) as i32 - 1, ((j / 3) % 3) as i32 - 1, (j / 9) as i32 - 1);
+ *b = self.brick_at(k, (key.0 + d.0, key.1 + d.1, key.2 + d.2)).0;
+ }
+ break;
+ }
+ }
+ let BrickRef::Cells(centre) = around[13] else { return };
+ // (Solid all around: every cell is more than `SHELL` from an empty one.)
+ if all {
+ return;
+ }
+ // The brick and `SHELL` cells around it, a row of bits along x for each (y, z): the cells that are not solid,
+ // then those within `SHELL` steps of one.
+ const W: usize = 8 + 2 * SHELL as usize;
+ let mut reach = [[0u32; W]; W];
+ for (wy, plane) in reach.iter_mut().enumerate() {
+ for (wz, row) in plane.iter_mut().enumerate() {
+ let (sy, sz) = (wy + 8 - SHELL as usize, wz + 8 - SHELL as usize);
+ for wx in 0..W {
+ let sx = wx + 8 - SHELL as usize;
+ let solid = match around[(sx >> 3) + 3 * (sy >> 3) + 9 * (sz >> 3)] {
+ BrickRef::Solid => true,
+ BrickRef::Empty => false,
+ BrickRef::Cells(c) => c[(sx & 7) + 8 * (sy & 7) + 64 * (sz & 7)] != 0,
+ };
+ *row |= (!solid as u32) << wx;
+ }
+ }
+ }
+ for _ in 0..SHELL {
+ let was = reach;
+ for y in 0..W {
+ for z in 0..W {
+ let mut r = was[y][z] | (was[y][z] << 1) | (was[y][z] >> 1);
+ if y > 0 {
+ r |= was[y - 1][z];
+ }
+ if y + 1 < W {
+ r |= was[y + 1][z];
+ }
+ if z > 0 {
+ r |= was[y][z - 1];
+ }
+ if z + 1 < W {
+ r |= was[y][z + 1];
+ }
+ reach[y][z] = r;
+ }
+ }
+ }
+ for (v, &m) in centre.iter().enumerate() {
+ let (x, y, z) = (v & 7, (v >> 3) & 7, v >> 6);
+ if m != 0 && reach[y + SHELL as usize][z + SHELL as usize] >> (x + SHELL as usize) & 1 != 0 {
+ out.push([key.0 * 8 + x as i32, key.1 * 8 + y as i32, key.2 * 8 + z as i32]);
+ }
+ }
+ }
+
+ /// The cells of level object `k`'s collider (grid cells): its shell, whole, or of the bricks that reach into the
+ /// box `within` of its grid.
+ fn shell(&self, k: usize, within: Option<([i32; 3], [i32; 3])>, full: &mut HashMap<(usize, (i32, i32, i32)), bool>) -> Vec<[i32; 3]> {
+ let mut out = vec![];
+ let Some(o) = self.level.as_ref().and_then(|l| l.objects.get(k)?.as_ref()) else { return out };
+ match within {
+ None => {
+ for &key in o.grid.bricks.keys() {
+ self.shell_of(k, key, &mut out, full);
+ }
+ }
+ Some((lo, hi)) => {
+ for bx in lo[0] >> 3..=hi[0] >> 3 {
+ for by in lo[1] >> 3..=hi[1] >> 3 {
+ for bz in lo[2] >> 3..=hi[2] >> 3 {
+ if o.grid.bricks.contains_key(&(bx, by, bz)) {
+ self.shell_of(k, (bx, by, bz), &mut out, full);
+ }
+ }
+ }
+ }
+ }
+ }
+ out
+ }
+
+ /// A level of solid blocks of palette entry 1 made here, no file (the checks' and the tests'): each block's corner
+ /// cell, its size in cells, its terrain tile if it is one, and whether it is an anchor. Voxels of 0.1 m, the mesh
+ /// route, the level's physics on.
+ pub fn of_blocks(blocks: &[([i32; 3], [i32; 3], Option<(i32, i32)>, bool)], w: &mut World, ph: &mut Option<PhysicsWorld>) -> VoxelWorld {
+ let mut v = VoxelWorld { route: Some(Route::Mesh), size: 0.1, palette: vec![0, 0], physics: true, max_bodies: MAX_BODIES, density: vec![1000.0; 2], floor: -100.0, ..Default::default() };
+ let mut level = Level::new(gravity_for(0.1, TICK_RATE));
+ for (n, &(at, size, tile, anchor)) in blocks.iter().enumerate() {
+ let mut grid = VoxelGrid::default();
+ for x in 0..size[0] {
+ for y in 0..size[1] {
+ for z in 0..size[2] {
+ grid.set(x, y, z, 1);
+ }
+ }
+ }
+ let k = level.add_object(Rc::new(grid), Placement::new(at, 0, [0, 0, 0]), anchor) as usize;
+ let corner = Vec3::new(at[0] as f32, at[1] as f32, at[2] as f32) * 0.1;
+ v.objects.push(Some(VoxelObject { name: format!("block{n}"), world: Mat4::from_translation(corner), corner: Vec3::ZERO, off: [0; 3], tile, lo: corner, hi: corner + Vec3::new(size[0] as f32, size[1] as f32, size[2] as f32) * 0.1, shared: None, parts: vec![], flying: None }));
+ if let Some(t) = tile {
+ v.tiles.insert(t, k);
+ }
+ }
+ level.settle();
+ v.level = Some(level);
+ for k in 0..blocks.len() {
+ let g = v.make_geometry(w, k, None).expect("a block's mesh");
+ v.place(w, k, &g).expect("a block's object");
+ }
+ v.colliders = vec![None; blocks.len()];
+ let p = ph.get_or_insert_with(Default::default);
+ let (mut full, mut shapes) = (HashMap::new(), HashMap::new());
+ for k in 0..blocks.len() {
+ v.collide(p, k, &mut full, &mut shapes);
+ }
+ v
+ }
+
+ /// The voxel bodies' determinism script (tools/physics-determinism.ts runs it natively and in wasm32, in the
+ /// renderer's graph): a tower on two terrain tiles is undercut on one side, so what is above the cut is a body
+ /// that lands on the stump off its balance and topples; an explosion where it lies carves it as it is turned (its
+ /// cells' centres through the body's pose) and cuts it in bodies; the ground under them is carved. The level's
+ /// hash and the physics world's, folded every 20 ticks and after every edit.
+ pub fn check_script() -> u64 {
+ let mut w = World::default();
+ let mut ph: Option<PhysicsWorld> = None;
+ let mut v = VoxelWorld::of_blocks(&[([0, 0, 0], [64, 8, 64], Some((0, 0)), true), ([64, 0, 0], [64, 8, 64], Some((1, 0)), true), ([52, 8, 28], [6, 40, 6], None, false)], &mut w, &mut ph);
+ let mut h = 0xcbf2_9ce4_8422_2325u64;
+ let fold = |h: &mut u64, v: &VoxelWorld, ph: &Option<PhysicsWorld>| {
+ for x in [v.hash().unwrap_or(0), ph.as_ref().map_or(0, |p| p.hash()), v.bodies() as u64] {
+ *h = (*h ^ x).wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ };
+ let run = |h: &mut u64, v: &mut VoxelWorld, w: &mut World, ph: &mut Option<PhysicsWorld>, ticks: u32| {
+ for t in 0..ticks {
+ crate::api::physics_advance(ph, v, w, 1.0 / 60.0);
+ w.take_changes();
+ if t % 20 == 19 {
+ fold(h, v, ph);
+ }
+ }
+ };
+ let edit = |h: &mut u64, v: &mut VoxelWorld, w: &mut World, ph: &mut Option<PhysicsWorld>, shape: ShapeM| {
+ v.edit(w, ph, &EditOp { shape, kind: EditKind::Carve([256; 4]) }).expect("an edit");
+ w.take_changes();
+ fold(h, v, ph);
+ };
+ // The undercut: a ball out of the tower's foot on its +x side, then a cut through what is left of that level:
+ // 1,260 voxels come down on a stump with a hollow in it.
+ edit(&mut h, &mut v, &mut w, &mut ph, ShapeM::Sphere([5.9, 1.1, 3.1], 0.45));
+ edit(&mut h, &mut v, &mut w, &mut ph, ShapeM::Box([5.0, 1.0, 2.6], [5.9, 1.2, 3.6]));
+ run(&mut h, &mut v, &mut w, &mut ph, 240);
+ // Where the body stands now: an explosion into its foot (it is carved through its pose, and goes over), then
+ // a pit in the ground under it.
+ let at = ph.as_ref().and_then(|p| v.body_list(p).as_array().and_then(|l| l.iter().max_by_key(|b| b["voxels"].as_u64()).map(|b| [0, 1, 2].map(|k| b["position"][k].as_f64().unwrap_or(0.0) as f32)))).unwrap_or([5.5, 1.0, 3.1]);
+ edit(&mut h, &mut v, &mut w, &mut ph, ShapeM::Sphere([at[0] + 0.3, at[1] + 0.3, at[2] + 0.3], 0.5));
+ run(&mut h, &mut v, &mut w, &mut ph, 120);
+ edit(&mut h, &mut v, &mut w, &mut ph, ShapeM::Sphere([at[0], 0.8, at[2]], 0.9));
+ run(&mut h, &mut v, &mut w, &mut ph, 240);
+ h
+ }
+
+ /// A voxel grid as a rigid body at a pose: the objects that draw it (its mesh in its own space, placed by the
+ /// pose, driven: a move is a transform), the body and its voxel collider. Its mass is its voxels' (each palette
+ /// entry's density), spread evenly over its cells. At `max_bodies` one goes first, or this part is debris (below).
+ /// A grid the physics world refuses (no cell, a cell too far) is not drawn either: its voxels are
+ /// debris.
+ fn add_body(&mut self, w: &mut World, p: &mut PhysicsWorld, k: usize, grid: VoxelGrid, position: Vec3, rotation: Quat, velocity: ([f32; 3], [f32; 3])) -> Result<()> {
+ let size = self.size;
+ let debris = |s: &mut Self, grid: &VoxelGrid| s.keep(grid.voxels().map(|(g, m)| (position + rotation * ((Vec3::new(g[0] as f32, g[1] as f32, g[2] as f32) + 0.5) * size), m)));
+ // At the cap, one goes to make room, if one may: never a body this edit carved or made (the remainder of a
+ // body being cut, the parts it is cut into, the other parts of one explosion); of the rest the one that
+ // matters least: asleep before awake, then the fewest voxels, then the oldest. It goes only if it has no
+ // more voxels than the part that would take its place; else that part is debris itself (a chip cut off at
+ // the cap does not make a bigger body vanish).
+ let count = grid.count();
+ while self.bodies.len() >= self.max_bodies.max(1) {
+ let least = self
+ .bodies
+ .iter()
+ .filter(|(k, _)| !self.this_edit.contains(k))
+ .map(|(&k, b)| (!p.bridge_ref().engine_pose(b.body).is_none_or(|s| s.2), b.grid.count(), k))
+ .min();
+ match least {
+ Some((_, n, k)) if n <= count => self.retire(w, p, k, true),
+ _ => {
+ debris(self, &grid);
+ self.capped += 1;
+ return Ok(());
+ }
+ }
+ }
+ let cells: Vec<[i32; 3]> = grid.voxels().map(|(g, _)| g).collect();
+ // (A body's density is its voxels' mean: carved, it weighs what its cells still do.)
+ let density = (grid.voxels().map(|(_, m)| self.density.get(m as usize).copied().unwrap_or(DENSITY[0]) as f64).sum::<f64>() / cells.len().max(1) as f64) as f32;
+ let (body, collider) = (self.id(), self.id());
+ let made = p.bridge().engine_body(body, &BodyDesc { position: position.to_array(), rotation: rotation.to_array(), linvel: velocity.0, angvel: velocity.1, ..Default::default() }).and_then(|_| {
+ let d = ColliderDesc { density, friction: FRICTION, ..ColliderDesc::new(physics_core::Shape::Voxels { size, cells }) };
+ p.bridge().engine_collider(collider, Some(body), &d)
+ });
+ if let Err(e) = made {
+ eprintln!("voxels: a loose part is no body ({e}): its voxels are debris");
+ p.bridge().engine_remove(Some(body), None);
+ debris(self, &grid);
+ return Ok(());
+ }
+ self.this_edit.insert(k);
+ let parts = self.body_parts(w, k, &grid, position, rotation)?;
+ if self.objects.len() <= k {
+ self.objects.resize_with(k + 1, || None);
+ }
+ let mut v = VoxelObject { name: format!("part{k}"), world: Mat4::from_rotation_translation(rotation, position), corner: Vec3::ZERO, off: [0; 3], tile: None, lo: Vec3::ZERO, hi: Vec3::ZERO, shared: None, parts, flying: None };
+ v.bounds(&grid, size);
+ self.objects[k] = Some(v);
+ self.bodies.insert(k, VoxelBody { body, collider, grid, pose: (position.to_array(), rotation.to_array()) });
+ Ok(())
+ }
+
+ /// The world objects that draw a body's grid at a pose: new ones, driven (added in place, moved as instances).
+ fn body_parts(&mut self, w: &mut World, k: usize, grid: &VoxelGrid, position: Vec3, rotation: Quat) -> Result<Vec<(u8, u32, u32)>> {
+ let size = self.size;
+ let mut parts = vec![];
+ let place = |w: &mut World, id: u32, kind: Kind, m: u8| -> Result<()> {
+ w.set_object(id, format!("part{k}#{m}"), None, kind, true, false)?;
+ w.set_transform(id, position, rotation, Vec3::ONE)?;
+ w.set_driven(id)
+ };
+ match self.route {
+ Some(Route::Boxes) => {
+ let l = layout(grid, Granularity::Object, [0.0; 3], size);
+ if !l.boxes.is_empty() {
+ let (gid, id) = (self.id(), self.id());
+ w.set_proc_geometry(gid, self.function.clone(), l.boxes, l.data)?;
+ place(w, id, Kind::Procedural { geometry: gid, materials: self.palette.clone() }, 0)?;
+ parts.push((0, id, gid));
+ }
+ }
+ _ => {
+ let mut mesh = greedy_mesh(grid, [0.0; 3], size, &mut |_, _, _| false);
+ if self.vertex_colors {
+ mesh.parts = voxel_core::merge_by_class(mesh.parts, &self.class_of, &self.entry_color);
+ }
+ for part in mesh.parts {
+ let (gid, id, m) = (self.id(), self.id(), part.material);
+ w.set_geometry(gid, part_geometry(part, Vec3::ZERO))?;
+ place(w, id, Kind::Mesh { geometry: gid, material: self.palette.get(m as usize).copied().unwrap_or(0), own_blas: true, materials: vec![] }, m)?;
+ parts.push((m, id, gid));
+ }
+ }
+ }
+ Ok(parts)
+ }
+
+ /// Voxels kept as debris for scene code (`LevelDesc::debris`): world centre and palette entry, within the caps.
+ fn keep(&mut self, voxels: impl Iterator<Item = (Vec3, u8)>) {
+ if !self.keep_debris {
+ return;
+ }
+ for (c, m) in voxels.take(EDIT_DEBRIS) {
+ if self.debris.len() / 4 >= MAX_DEBRIS {
+ break;
+ }
+ self.debris.extend([c.x, c.y, c.z, m as f32]);
+ }
+ }
+
+ /// Body `k` gone: its objects, its body and collider. `debris`: its voxels are kept as debris where they are (it
+ /// was retired for the cap; one that left the world leaves nothing).
+ fn retire(&mut self, w: &mut World, p: &mut PhysicsWorld, k: usize, debris: bool) {
+ let Some(b) = self.bodies.remove(&k) else { return };
+ if debris {
+ let m = Mat4::from_rotation_translation(Quat::from_array(b.pose.1), Vec3::from(b.pose.0));
+ let size = self.size;
+ self.keep(b.grid.voxels().map(|(g, mat)| (m.transform_point3((Vec3::new(g[0] as f32, g[1] as f32, g[2] as f32) + 0.5) * size), mat)));
+ self.retired += 1;
+ }
+ p.bridge().engine_remove(Some(b.body), None);
+ if let Some(o) = self.objects.get_mut(k).and_then(|o| o.take()) {
+ for part in o.parts {
+ w.remove(part.1);
+ }
+ }
+ }
+
+ /// After the physics world's ticks: every voxel body's objects where the body is now (a body that did not move
+ /// costs a comparison); a body the world took out (it fell off the level) goes with its objects. Returns how many
+ /// moved and how many went.
+ pub fn sync_bodies(&mut self, w: &mut World, p: &mut PhysicsWorld) -> (usize, usize) {
+ let (mut moved, mut gone) = (0, vec![]);
+ // (A body far under the level's lowest cell got through the ground: it goes.)
+ let floor = self.floor;
+ for (&k, b) in self.bodies.iter_mut() {
+ match p.bridge_ref().engine_pose(b.body) {
+ None => gone.push(k),
+ Some((at, ..)) if at[1] < floor => gone.push(k),
+ Some((at, rot, _)) if (at, rot) != b.pose => {
+ b.pose = (at, rot);
+ let (t, r) = (Vec3::from(at), Quat::from_array(rot));
+ if let Some(o) = self.objects.get_mut(k).and_then(|o| o.as_mut()) {
+ o.world = Mat4::from_rotation_translation(r, t);
+ for part in &o.parts {
+ w.place_driven(part.1, t, r);
+ }
+ }
+ moved += 1;
+ }
+ Some(_) => {}
+ }
+ }
+ for &k in &gone {
+ self.retire(w, p, k, false);
+ }
+ (moved, gone.len())
+ }
+
+ /// A carve reaches the bodies too: of each body the shape meets, the voxels whose centres are inside it (each
+ /// palette entry within its hardness's share of the radius) go. What is left of a body stays the body (its
+ /// collider loses the cells, its mesh is made again); what the carve cut off it is a body of its own, moving as
+ /// it did (parts under `MIN_PIECE` voxels: debris); a body with nothing left is gone. Returns the voxels carved
+ /// and the bodies carved.
+ fn carve_bodies(&mut self, w: &mut World, p: &mut PhysicsWorld, shape: ShapeM, radii: [i32; 4]) -> Result<(usize, usize)> {
+ let size = self.size;
+ let hardness = self.level.as_ref().map_or([0u8; 256], |l| l.hardness);
+ // The shape as the level's carve takes it (voxel_core `Shape::checked`, `contains`): a radius within 0 and
+ // `MAX_RADIUS` voxels, each class's share of it; a box whole for every class it reaches at all.
+ let cap = voxel_core::MAX_RADIUS as f32 * size;
+ let shape = match shape {
+ ShapeM::Sphere(c, r) => ShapeM::Sphere(c, if r.is_nan() { 0.0 } else { r.clamp(0.0, cap) }),
+ ShapeM::Capsule(a, b, r) => ShapeM::Capsule(a, b, if r.is_nan() { 0.0 } else { r.clamp(0.0, cap) }),
+ other => other,
+ };
+ let inside = |q: Vec3, scale: f32| -> bool {
+ match shape {
+ ShapeM::Sphere(c, r) => q.distance_squared(Vec3::from(c)) <= (r * scale) * (r * scale),
+ ShapeM::Box(a, b) => {
+ let (c, h) = ((Vec3::from(a) + Vec3::from(b)) * 0.5, (Vec3::from(b) - Vec3::from(a)).abs() * 0.5);
+ (q - c).abs().cmple(h).all()
+ }
+ ShapeM::Capsule(a, b, r) => {
+ let (a, ab) = (Vec3::from(a), Vec3::from(b) - Vec3::from(a));
+ let t = if ab.length_squared() > 0.0 { ((q - a).dot(ab) / ab.length_squared()).clamp(0.0, 1.0) } else { 0.0 };
+ q.distance_squared(a + ab * t) <= (r * scale) * (r * scale)
+ }
+ }
+ };
+ // The shape's reach, for a body's bounding sphere.
+ let (centre, reach) = match shape {
+ ShapeM::Sphere(c, r) => (Vec3::from(c), r),
+ ShapeM::Box(a, b) => ((Vec3::from(a) + Vec3::from(b)) * 0.5, (Vec3::from(b) - Vec3::from(a)).length() * 0.5),
+ ShapeM::Capsule(a, b, r) => ((Vec3::from(a) + Vec3::from(b)) * 0.5, (Vec3::from(b) - Vec3::from(a)).length() * 0.5 + r),
+ };
+ let (mut voxels, mut carved) = (0usize, 0usize);
+ let keys: Vec<usize> = self.bodies.keys().copied().collect();
+ for k in keys {
+ // (A body retired for the cap by a part cut off an earlier one in this same carve is no longer there.)
+ let Some(b) = self.bodies.get(&k) else { continue };
+ let Some((at, rot, _)) = p.bridge_ref().engine_pose(b.body) else { continue };
+ let m = Mat4::from_rotation_translation(Quat::from_array(rot), Vec3::from(at));
+ let centre_of = |g: [i32; 3]| m.transform_point3((Vec3::new(g[0] as f32, g[1] as f32, g[2] as f32) + 0.5) * size);
+ let Some((lo, hi)) = b.grid.bounds() else { continue };
+ // (The grid's bounds are its bricks': from `lo` up to `hi`, not through it.)
+ let (lo, hi) = (Vec3::new(lo[0] as f32, lo[1] as f32, lo[2] as f32), Vec3::new(hi[0] as f32, hi[1] as f32, hi[2] as f32));
+ let (mid, half) = ((lo + hi) * 0.5 * size, ((hi - lo) * 0.5 * size).length());
+ if m.transform_point3(mid).distance(centre) > reach + half {
+ continue;
+ }
+ let gone: Vec<([i32; 3], u8)> = b.grid.voxels().filter(|&(g, mat)| { let r = radii[(hardness[mat as usize] & 3) as usize]; r > 0 && inside(centre_of(g), r as f32 / 256.0) }).collect();
+ if gone.is_empty() {
+ continue;
+ }
+ voxels += gone.len();
+ carved += 1;
+ // (What is left of it is not retired for the cap while this carve makes the parts it cut off.)
+ self.this_edit.insert(k);
+ self.keep(gone.iter().map(|&(g, mat)| (centre_of(g), mat)));
+ let b = self.bodies.get_mut(&k).unwrap();
+ for &(g, _) in &gone {
+ b.grid.take(g[0], g[1], g[2]);
+ }
+ let mut cleared: Vec<[i32; 3]> = gone.iter().map(|g| g.0).collect();
+ // What is left, in six-connected parts: the largest stays this body.
+ let mut parts = components(&b.grid);
+ parts.sort_by(|x, y| y.len().cmp(&x.len()).then(x[0].cmp(&y[0])));
+ let velocity = p.bridge_ref().engine_velocity_of(b.body).unwrap_or(([0.0; 3], [0.0; 3]));
+ let mut loose: Vec<Vec<([i32; 3], u8)>> = vec![];
+ for part in parts.into_iter().skip(1) {
+ let with: Vec<([i32; 3], u8)> = part.iter().map(|&g| (g, b.grid.take(g[0], g[1], g[2]))).collect();
+ cleared.extend(part);
+ loose.push(with);
+ }
+ let (collider, left) = (b.collider, b.grid.count());
+ if left == 0 {
+ self.retire(w, p, k, false);
+ } else {
+ if let Err(e) = p.bridge().engine_edit_voxels(collider, &cleared, &[]) {
+ eprintln!("voxels: a body's collider was not edited ({e})");
+ }
+ // Its mesh again: new objects in the old ones' place (a driven object given another geometry would
+ // rebuild the scene; one removed and one added are both in place).
+ let old = std::mem::take(&mut self.objects[k].as_mut().unwrap().parts);
+ for part in old {
+ w.remove(part.1);
+ }
+ let grid = self.bodies[&k].grid.clone();
+ let parts = self.body_parts(w, k, &grid, Vec3::from(at), Quat::from_array(rot))?;
+ let o = self.objects[k].as_mut().unwrap();
+ o.parts = parts;
+ o.bounds(&grid, size);
+ }
+ for part in loose {
+ if part.len() < MIN_PIECE {
+ self.keep(part.iter().map(|&(g, mat)| (centre_of(g), mat)));
+ continue;
+ }
+ // Its own grid from its lowest corner, placed where that corner is.
+ let lo = [0, 1, 2].map(|a| part.iter().map(|(g, _)| g[a]).min().unwrap());
+ let mut grid = VoxelGrid::default();
+ for &(g, mat) in &part {
+ grid.set(g[0] - lo[0], g[1] - lo[1], g[2] - lo[2], mat);
+ }
+ let corner = m.transform_point3(Vec3::new(lo[0] as f32, lo[1] as f32, lo[2] as f32) * size);
+ let n = self.objects.len().max(self.level.as_ref().map_or(0, |l| l.objects.len()));
+ // (The level's next object would take this index: it gets a hole there.)
+ if let Some(l) = self.level.as_mut() {
+ l.objects.resize_with(n + 1, || None);
+ }
+ self.add_body(w, p, n, grid, corner, Quat::from_array(rot), velocity)?;
+ }
+ }
+ Ok((voxels, carved))
+ }
+
+ /// Voxel bodies now.
+ pub fn bodies(&self) -> usize {
+ self.bodies.len()
+ }
+
+ /// The bodies as scene code may name them: the physics world's body id of each (`__engine.physics` calls take
+ /// it), its voxels, whether it sleeps, and where it is.
+ pub fn body_list(&self, p: &PhysicsWorld) -> serde_json::Value {
+ serde_json::Value::Array(self.bodies.values().filter_map(|b| p.bridge_ref().engine_pose(b.body).map(|(at, rot, asleep)| serde_json::json!({ "body": b.body, "collider": b.collider, "voxels": b.grid.count(), "asleep": asleep, "position": at, "rotation": rot }))).collect())
+ }
+
/// Scene code's `voxelDebris`: the debris kept since the last call (x, y, z, palette index per voxel).
pub fn take_debris(&mut self) -> Vec<f32> {
std::mem::take(&mut self.debris)
@@ -611,7 +1344,7 @@ impl VoxelWorld {
/// `MAX_TICKS` a call), the falling objects written again where they are now, the landed ones where they rest.
pub fn frame(&mut self, w: &mut World, dt: f64) -> Result<serde_json::Value> {
if self.route.is_none() && self.pending.is_some() {
- self.queued.push(Queued::Frame(dt));
+ self.queue(Queued::Frame(dt))?;
return Ok(serde_json::json!({ "queued": true }));
}
let Some(level) = self.level.as_mut() else { return Ok(serde_json::json!({ "batches": 0 })) };
@@ -887,10 +1620,67 @@ impl VoxelWorld {
/// The level's hash (`voxel_core::Level::hash`: every object's placement, state and voxels), None before a level.
pub fn hash(&self) -> Option<u64> {
- self.level.as_ref().map(|l| l.hash())
+ let mut h = self.level.as_ref()?.hash();
+ // The bodies' voxels (where the bodies are is the physics world's hash): in their order, each grid's cells
+ // in the grid's.
+ for (&k, b) in &self.bodies {
+ for x in [k as u32, b.grid.count() as u32].into_iter().chain(b.grid.voxels().flat_map(|(g, m)| [g[0] as u32, g[1] as u32, g[2] as u32, m as u32])) {
+ for byte in x.to_le_bytes() {
+ h = (h ^ byte as u64).wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ }
+ }
+ Some(h)
}
}
+/// Where a level object's collider stands, its cells being the object's own: the rotation of its quarter turns about
+/// y and the translation that puts the cube of its cell g on the cube of world cell `place.to_world(g)` (a turned
+/// cube's lowest corner is not the turned corner: `voxel_core::Placement`).
+fn collider_pose(place: &Placement, size: f32) -> ([f32; 3], [f32; 4]) {
+ const S: f32 = std::f32::consts::FRAC_1_SQRT_2;
+ let (rotation, corner) = match place.turn & 3 {
+ 0 => ([0.0, 0.0, 0.0, 1.0], [0, 0, 0]),
+ 1 => ([0.0, S, 0.0, S], [0, 0, -1]),
+ 2 => ([0.0, 1.0, 0.0, 0.0], [-1, 0, -1]),
+ _ => ([0.0, S, 0.0, -S], [-1, 0, 0]),
+ };
+ ([0, 1, 2].map(|a| (place.t[a] - corner[a]) as f32 * size), rotation)
+}
+
+/// A grid's solid cells in six-connected parts, each part's cells in the grid's order (so the parts and their order
+/// are the same on every machine).
+fn components(grid: &VoxelGrid) -> Vec<Vec<[i32; 3]>> {
+ let cells: Vec<[i32; 3]> = grid.voxels().map(|(g, _)| g).collect();
+ let index: HashMap<[i32; 3], usize> = cells.iter().enumerate().map(|(i, &c)| (c, i)).collect();
+ let mut part = vec![usize::MAX; cells.len()];
+ let mut out: Vec<Vec<[i32; 3]>> = vec![];
+ for start in 0..cells.len() {
+ if part[start] != usize::MAX {
+ continue;
+ }
+ let id = out.len();
+ let mut members = vec![start];
+ part[start] = id;
+ let mut next = 0;
+ while next < members.len() {
+ let c = cells[members[next]];
+ next += 1;
+ for d in [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]] {
+ if let Some(&j) = index.get(&[c[0] + d[0], c[1] + d[1], c[2] + d[2]]) {
+ if part[j] == usize::MAX {
+ part[j] = id;
+ members.push(j);
+ }
+ }
+ }
+ }
+ members.sort_unstable();
+ out.push(members.into_iter().map(|i| cells[i]).collect());
+ }
+ out
+}
+
/// A mesh part as a geometry, its positions moved by `at`.
fn part_geometry(p: MeshPart, at: Vec3) -> Geometry {
let n = p.positions.len() / 3;
@@ -944,9 +1734,15 @@ mod tests {
/// The level of tests/render/voxel-cut-falls.ts: a slab (anchor) and two posts, one on the other, with the particles'
/// occupancy grid.
fn level(w: &mut World) -> VoxelWorld {
+ level_with(w, &mut None, false)
+ }
+
+ /// The same with the level's physics on (`ph` gets the world) or off (as before step 8: parts fall through the
+ /// lattice).
+ fn level_with(w: &mut World, ph: &mut Option<PhysicsWorld>, physics: bool) -> VoxelWorld {
let mut v = VoxelWorld::default();
let d: LevelDesc = serde_json::from_value(serde_json::json!({
- "route": "mesh", "debris": true, "occupancy": 0.2,
+ "route": "mesh", "debris": true, "occupancy": 0.2, "physics": physics,
"palette": [{ "name": "none", "color": [0, 0, 0], "roughness": 1, "metalness": 0 }, { "name": "black", "color": [0, 0, 0], "roughness": 1, "metalness": 0 },
{ "name": "post", "color": [1, 1, 1], "roughness": 1, "metalness": 0, "hardness": "hard" }],
"objects": [{ "name": "slab", "uri": "tests/render/data/voxel-slab.tpg", "position": [0, 0, 0], "anchor": true },
@@ -955,7 +1751,8 @@ mod tests {
}))
.unwrap();
v.request(d).unwrap();
- let r = v.realize(w, &assets()).unwrap().unwrap();
+ let r = v.realize(w, ph, &assets()).unwrap().unwrap();
+ assert_eq!(r["colliders"].as_u64(), Some(if physics { 3 } else { 0 }), "{r}");
assert_eq!((r["floating_groups"].as_u64(), r["snapped"].as_u64()), (Some(0), Some(0)), "{r}");
v
}
@@ -974,7 +1771,7 @@ mod tests {
let mut v = level(&mut w);
let (h0, objects) = (v.hash().unwrap(), v.world_objects());
assert_eq!(objects, 3);
- let e = v.edit(&mut w, &op(serde_json::json!({ "op": "carve", "box": [-0.5, 0.8, -0.5, 0.5, 1.0, 0.5] }))).unwrap();
+ let e = v.edit(&mut w, &mut None, &op(serde_json::json!({ "op": "carve", "box": [-0.5, 0.8, -0.5, 0.5, 1.0, 0.5] }))).unwrap();
assert_eq!((e["voxels"].as_u64(), e["pieces"].as_u64(), e["piece_voxels"].as_u64(), e["removed"].as_u64()), (Some(32), Some(1), Some(16 * (10 + 16)), Some(1)), "{e}");
assert_eq!(v.take_debris().len(), 32 * 4);
assert_eq!(v.world_objects(), 3, "the stump, the slab, the loose part (the upper post is gone)");
@@ -991,7 +1788,7 @@ mod tests {
assert!(v.objects[part].as_ref().unwrap().flying.is_none());
assert_eq!(v.frame(&mut w, 1.0 / 60.0).unwrap()["batches"], 0);
// An explosion at the stump: the post is hard (0.4 of the radius), the slab soft (a crater 0.3 m deep under it).
- let e = v.explode(&mut w, Vec3::new(0.0, 0.6, 0.0), 0.5).unwrap();
+ let e = v.explode(&mut w, &mut None, Vec3::new(0.0, 0.6, 0.0), 0.5).unwrap();
assert!(e["voxels"].as_u64().unwrap() > 100, "{e}");
// (It took the stump's foot: what stood on it falls into the crater. Edits reach static voxels only: let it
// land.)
@@ -1000,9 +1797,9 @@ mod tests {
}
assert_eq!(v.frame(&mut w, 1.0 / 60.0).unwrap()["batches"], 0);
// Paint and added voxels.
- let e = v.edit(&mut w, &op(serde_json::json!({ "op": "paint", "sphere": [0.0, 2.0, 0.0, 0.4], "material": 1 }))).unwrap();
+ let e = v.edit(&mut w, &mut None, &op(serde_json::json!({ "op": "paint", "sphere": [0.0, 2.0, 0.0, 0.4], "material": 1 }))).unwrap();
assert!(e["voxels"].as_u64().unwrap() > 0 && e["pieces"] == 0, "{e}");
- let e = v.edit(&mut w, &op(serde_json::json!({ "op": "add", "box": [0.5, 0.4, 0.5, 0.7, 0.6, 0.7], "material": 2 }))).unwrap();
+ let e = v.edit(&mut w, &mut None, &op(serde_json::json!({ "op": "add", "box": [0.5, 0.4, 0.5, 0.7, 0.6, 0.7], "material": 2 }))).unwrap();
assert_eq!(e["voxels"], 8, "{e}");
for _ in 0..120 {
v.frame(&mut w, 1.0 / 60.0).unwrap();
@@ -1023,6 +1820,386 @@ mod tests {
assert_ne!(a.0, a.1);
}
+ /// Step 8: the level collides and what comes loose is a rigid body. The level's objects are fixed voxel colliders
+ /// (a physics ray meets the slab and the posts); the cut that dropped the upper part through the lattice now
+ /// makes it a body, which lands on the stump 0.2 m lower, rests and sleeps, its objects where it is; an
+ /// explosion under it carves the colliders it stood on and it falls on; a carve through the body itself cuts it
+ /// in two bodies. The same commands twice end in the same voxels and the same physics bits.
+ #[test]
+ fn the_level_collides_and_loose_parts_are_bodies() {
+ use physics_core::bridge::ENGINE_IDS;
+ let run = || {
+ let mut w = World::default();
+ let mut ph: Option<PhysicsWorld> = None;
+ let mut v = level_with(&mut w, &mut ph, true);
+ assert!(ph.is_some(), "the level made the physics world");
+ let call = |ph: &mut Option<PhysicsWorld>, w: &mut World, op: &str, a: serde_json::Value| ph.as_mut().unwrap().call(w, op, &a);
+ let step = |v: &mut VoxelWorld, w: &mut World, ph: &mut Option<PhysicsWorld>, frames: u32| {
+ for _ in 0..frames {
+ assert!(crate::api::physics_advance(ph, v, w, 1.0 / 60.0));
+ assert_eq!(v.frame(w, 1.0 / 60.0).unwrap()["batches"], 0, "nothing falls through the lattice");
+ }
+ };
+ // A ray down beside the posts meets the slab's top (y = 0.4); over them, the upper post's (y = 3.6).
+ let hit = call(&mut ph, &mut w, "ray", serde_json::json!({ "origin": [0.6, 5.0, 0.6], "direction": [0, -1, 0], "max": 10 })).unwrap();
+ assert!(hit["collider"].as_u64().unwrap() >= ENGINE_IDS as u64 && (hit["point"][1].as_f64().unwrap() - 0.4).abs() < 1e-4, "{hit}");
+ let hit = call(&mut ph, &mut w, "ray", serde_json::json!({ "origin": [0.0, 5.0, 0.0], "direction": [0, -1, 0], "max": 10 })).unwrap();
+ assert!((hit["point"][1].as_f64().unwrap() - 3.6).abs() < 1e-4, "{hit}");
+ // The cut.
+ let e = v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [-0.5, 0.8, -0.5, 0.5, 1.0, 0.5] }))).unwrap();
+ assert_eq!((e["voxels"].as_u64(), e["pieces"].as_u64(), e["piece_voxels"].as_u64(), e["bodies"].as_u64()), (Some(32), Some(1), Some(16 * (10 + 16)), Some(1)), "{e}");
+ assert_eq!((v.bodies(), v.level.as_ref().unwrap().falling()), (1, 0));
+ let part = *v.bodies.keys().next().unwrap();
+ let objects: Vec<u32> = v.objects[part].as_ref().unwrap().parts.iter().map(|p| p.1).collect();
+ assert!(!objects.is_empty() && objects.iter().all(|id| w.objects[id].driven));
+ let at0 = w.objects[&objects[0]].position;
+ let y0 = at0.y;
+ assert!((at0 - Vec3::new(-0.2, 1.0, -0.2)).length() < 1e-5, "the part's lowest corner is the cut's top: {at0}");
+ let list = v.body_list(ph.as_ref().unwrap());
+ let body = list[0]["body"].as_u64().unwrap();
+ assert_eq!((list.as_array().unwrap().len(), list[0]["voxels"].as_u64(), list[0]["asleep"].as_bool()), (1, Some(416), Some(false)), "{list}");
+ // 416 voxels of a hard entry: 2,400 kg/m³ x 0.001 m³ each.
+ let state = call(&mut ph, &mut w, "state", serde_json::json!({ "body": body })).unwrap();
+ assert!((state["mass"].as_f64().unwrap() - 416.0 * 2.4).abs() < 0.05, "{state}");
+ step(&mut v, &mut w, &mut ph, 180);
+ let at = w.objects[&objects[0]].position;
+ assert!((y0 - at.y - 0.2).abs() < 5e-3 && (at.x - at0.x).abs() < 5e-3 && (at.z - at0.z).abs() < 5e-3, "it fell {} m to {at:?}", y0 - at.y);
+ assert!(v.body_list(ph.as_ref().unwrap())[0]["asleep"] == true);
+ // Scene code names the body in its calls, and cannot remove it or make one in the engine's ids.
+ assert!(call(&mut ph, &mut w, "remove", serde_json::json!({ "body": body })).is_err());
+ assert!(call(&mut ph, &mut w, "body", serde_json::json!({ "id": body + 100 })).is_err());
+ call(&mut ph, &mut w, "impulse", serde_json::json!({ "body": body, "impulse": [0, 5, 0] })).unwrap();
+ step(&mut v, &mut w, &mut ph, 120);
+ // The stump and the slab under it carved away: the colliders lose those cells and the part falls on, to the
+ // crater's floor (the posts are hard: a cut through everything takes them).
+ let e = v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [-0.5, 0.2, -0.5, 0.5, 0.8, 0.5] }))).unwrap();
+ assert!(e["voxels"].as_u64().unwrap() >= 16 * 4 && e["pieces"] == 0, "{e}");
+ step(&mut v, &mut w, &mut ph, 180);
+ let at = w.objects[&objects[0]].position;
+ assert!((at.y - 0.2).abs() < 5e-3, "on the slab's carved floor: {at:?}");
+ let hit = call(&mut ph, &mut w, "ray", serde_json::json!({ "origin": [0.05, 0.75, 5.0], "direction": [0, 0, -1], "max": 10 })).unwrap();
+ assert_eq!(hit["body"].as_u64(), Some(body), "a ray from the side meets the part: {hit}");
+ // A cut through the body, 0.2 m thick at its middle: two bodies, each with its own objects; the first
+ // one's objects are new ones (its mesh changed).
+ let before = v.bodies[&part].grid.count();
+ let e = v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [-0.5, 1.4, -0.5, 0.5, 1.6, 0.5] }))).unwrap();
+ assert_eq!((e["bodies_carved"].as_u64(), e["body_voxels"].as_u64(), e["bodies"].as_u64()), (Some(1), Some(32), Some(2)), "{e}");
+ let cells: usize = v.bodies.values().map(|b| b.grid.count()).sum();
+ assert_eq!(cells + 32, before);
+ assert!(v.objects[part].as_ref().unwrap().parts.iter().all(|p| !objects.contains(&p.1) && w.objects[&p.1].driven));
+ assert!(objects.iter().all(|id| !w.objects.contains_key(id)));
+ step(&mut v, &mut w, &mut ph, 240);
+ let list = v.body_list(ph.as_ref().unwrap());
+ assert!(list.as_array().unwrap().iter().all(|b| b["asleep"] == true), "{list}");
+ // The upper one came down the 0.2 m of the cut onto the lower.
+ let top = v.bodies.keys().copied().max().unwrap();
+ let y = w.objects[&v.objects[top].as_ref().unwrap().parts[0].1].position.y;
+ assert!((y - (0.2 + 1.2)).abs() < 1e-2, "{y}");
+ // A carve that takes a body whole: gone, with its objects.
+ let e = v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [-1.0, 1.3, -1.0, 1.0, 9.0, 1.0] }))).unwrap();
+ assert_eq!(e["bodies"].as_u64(), Some(1), "{e}");
+ assert!(v.objects[top].is_none());
+ (v.hash().unwrap(), ph.as_ref().unwrap().hash(), v.take_debris().len())
+ };
+ let (a, b) = (run(), run());
+ assert_eq!(a, b);
+ assert!(a.2 > 0);
+ }
+
+ /// The solid world cells of a level within `SHELL` steps of one that is not (under the bedrock, y < 0, counts as
+ /// solid when `bedrock`): what the colliders must hold, by brute force.
+ fn shell_by_brute_force(v: &VoxelWorld, bedrock: bool) -> usize {
+ let level = v.level.as_ref().unwrap();
+ let solid: std::collections::HashSet<[i32; 3]> = level.objects.iter().flatten().flat_map(|o| o.grid.voxels().map(|(g, _)| o.place.to_world(g))).collect();
+ let is = |c: [i32; 3]| solid.contains(&c) || (bedrock && c[1] < 0);
+ solid
+ .iter()
+ .filter(|c| {
+ (-SHELL..=SHELL).any(|dx| (-SHELL + dx.abs()..=SHELL - dx.abs()).any(|dy| { let r = SHELL - dx.abs() - dy.abs(); (-r..=r).any(|dz| !is([c[0] + dx, c[1] + dy, c[2] + dz])) }))
+ })
+ .count()
+ }
+
+ fn collider_cells(v: &VoxelWorld, ph: &Option<PhysicsWorld>) -> usize {
+ v.colliders.iter().flatten().map(|&c| ph.as_ref().unwrap().bridge_ref().engine_voxels(c).unwrap_or(0)).sum()
+ }
+
+ /// A level object's collider is the shell of its cells near a surface, not its volume, and edits keep it so: a
+ /// block of 32³ cells has the four layers under its faces; a pit carved into it brings the pit's walls and floor
+ /// in (a ray finds the floor, which no collider held before), and what the colliders hold is what brute force
+ /// says, before and after. Terrain tiles side by side cover each other's sides, down to the bedrock, until one is
+ /// carved at the edge they share.
+ #[test]
+ fn a_collider_is_the_shell_of_its_cells() {
+ let mut w = World::default();
+ let mut ph: Option<PhysicsWorld> = None;
+ let mut v = VoxelWorld::of_blocks(&[([0, 0, 0], [32, 32, 32], None, true)], &mut w, &mut ph);
+ assert_eq!(collider_cells(&v, &ph), 32 * 32 * 32 - 24 * 24 * 24);
+ assert_eq!(collider_cells(&v, &ph), shell_by_brute_force(&v, false));
+ let ray = |ph: &mut Option<PhysicsWorld>, w: &mut World, x: f32, z: f32| ph.as_mut().unwrap().call(w, "ray", &serde_json::json!({ "origin": [x, 9.0, z], "direction": [0, -1, 0], "max": 20 })).unwrap()["point"][1].as_f64().unwrap();
+ assert!((ray(&mut ph, &mut w, 1.65, 1.65) - 3.2).abs() < 1e-4);
+ // A pit 0.8 m wide, 1.2 m deep, in the middle of the top.
+ let e = v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [1.2, 2.0, 1.2, 2.0, 3.3, 2.0] }))).unwrap();
+ assert_eq!(e["voxels"].as_u64(), Some(8 * 8 * 12), "{e}");
+ assert_eq!(collider_cells(&v, &ph), shell_by_brute_force(&v, false));
+ assert!((ray(&mut ph, &mut w, 1.65, 1.65) - 2.0).abs() < 1e-4, "the pit's floor");
+ // Deeper, through cells no collider held, and out through the bottom: a shaft.
+ v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [1.4, -0.1, 1.4, 1.8, 2.1, 1.8] }))).unwrap();
+ assert_eq!(collider_cells(&v, &ph), shell_by_brute_force(&v, false));
+ // Two terrain tiles (64 x 64 cells, 16 deep) side by side on the bedrock: the top four layers and the outer
+ // sides; nothing of the side they share, nor of their undersides.
+ let mut w = World::default();
+ let mut ph: Option<PhysicsWorld> = None;
+ let mut v = VoxelWorld::of_blocks(&[([0, 0, 0], [64, 16, 64], Some((0, 0)), true), ([64, 0, 0], [64, 16, 64], Some((1, 0)), true)], &mut w, &mut ph);
+ assert_eq!(collider_cells(&v, &ph), shell_by_brute_force(&v, true));
+ assert_eq!(collider_cells(&v, &ph), 128 * 64 * 16 - 120 * 56 * 12);
+ // A trench in the second tile along the edge they share, six cells deep: the first tile's side is bare there,
+ // and its collider has those cells now.
+ let before = ph.as_ref().unwrap().bridge_ref().engine_voxels(v.colliders[0].unwrap()).unwrap();
+ v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [6.4, 1.0, 1.0, 6.8, 1.7, 5.0] }))).unwrap();
+ assert_eq!(collider_cells(&v, &ph), shell_by_brute_force(&v, true));
+ assert!(ph.as_ref().unwrap().bridge_ref().engine_voxels(v.colliders[0].unwrap()).unwrap() > before, "the first tile's side");
+ // A ray along the trench's floor from inside the second tile meets the first tile's bared side.
+ let hit = ph.as_mut().unwrap().call(&mut w, "ray", &serde_json::json!({ "origin": [6.75, 1.25, 3.05], "direction": [-1, 0, 0], "max": 5 })).unwrap();
+ assert!((hit["point"][0].as_f64().unwrap() - 6.4).abs() < 1e-4 && hit["collider"].as_u64() == v.colliders[0].map(|c| c as u64), "{hit}");
+ // A crater that crosses the border by one cell (the review of #24): the second tile loses a few cells of its
+ // own, and its shell must still be made whole over all the first tile's crater bared. (It was not: rays
+ // across the crater went through the whole second tile, to its far side.)
+ let mut w = World::default();
+ let mut ph: Option<PhysicsWorld> = None;
+ let mut v = VoxelWorld::of_blocks(&[([0, 0, 0], [64, 64, 64], Some((0, 0)), true), ([64, 0, 0], [64, 64, 64], Some((1, 0)), true)], &mut w, &mut ph);
+ let e = v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "sphere": [0.47, 3.05, 3.05, 6.0] }))).unwrap();
+ assert!(e["touched"].as_u64() == Some(2), "both tiles lose cells: {e}");
+ assert_eq!(collider_cells(&v, &ph), shell_by_brute_force(&v, true));
+ for (y, z, wall) in [(3.05, 3.05, 0.5), (4.05, 3.05, 0.4), (4.15, 3.05, 0.4), (3.05, 4.05, 0.4), (2.05, 3.05, 0.4)] {
+ let hit = ph.as_mut().unwrap().call(&mut w, "ray", &serde_json::json!({ "origin": [6.0, y, z], "direction": [1, 0, 0], "max": 50 })).unwrap();
+ assert!((hit["distance"].as_f64().unwrap() - wall).abs() < 1e-3, "a ray along +x from (6.0, {y}, {z}) meets the crater's wall {wall} m away: {hit}");
+ }
+ }
+
+ /// A collider's pose puts every cell of the object where the level has it, whatever its turn.
+ #[test]
+ fn a_colliders_pose_is_the_objects_placement() {
+ for turn in 0..4 {
+ let place = Placement::new([7, -3, 12], turn, [2, 0, -5]);
+ let (at, rot) = collider_pose(&place, 0.1);
+ let m = Mat4::from_rotation_translation(Quat::from_array(rot), Vec3::from(at));
+ for g in [[0, 0, 0], [1, 0, 0], [0, 0, 1], [5, 9, -4], [-3, 2, 6]] {
+ let w = place.to_world(g);
+ let centre = m.transform_point3((Vec3::new(g[0] as f32, g[1] as f32, g[2] as f32) + 0.5) * 0.1);
+ assert!((centre - (Vec3::new(w[0] as f32, w[1] as f32, w[2] as f32) + 0.5) * 0.1).length() < 1e-5, "turn {turn}, cell {g:?}: {centre} for world cell {w:?}");
+ }
+ }
+ }
+
+ /// The voxel bodies' script ends in the recorded bits (tools/physics-determinism.ts: in wasm32 too), and in it a
+ /// tower toppled, was cut in bodies and they came to rest.
+ #[test]
+ fn voxel_bodies_step_to_the_recorded_bits() {
+ assert_eq!(format!("{:016x}", VoxelWorld::check_script()), format!("{:016x}", EXPECTED_SCRIPT));
+ }
+
+ /// tests/render/voxel-cut-body.ts on the CPU: the cut is asked for in setup, before the level is loaded, so it is
+ /// made at the load, where the part it frees becomes a body; an offline render then settles the physics to its
+ /// scene time (2 s), and the part stands on the stump. And what scene code gets back from a ray is enough to act
+ /// on the body: the hit's `body` is the id the physics calls take (an impulse through it moves the part).
+ #[test]
+ fn a_cut_made_in_setup_frees_a_body_at_the_load_and_a_rays_hit_names_it() {
+ let mut w = World::default();
+ let mut ph: Option<PhysicsWorld> = None;
+ let mut v = VoxelWorld::default();
+ let d: LevelDesc = serde_json::from_value(serde_json::json!({
+ "route": "mesh",
+ "palette": [{ "name": "none", "color": [0, 0, 0], "roughness": 1, "metalness": 0 }, { "name": "black", "color": [0, 0, 0], "roughness": 1, "metalness": 0 },
+ { "name": "glow", "color": [1, 1, 1], "roughness": 1, "metalness": 0, "emissive": 5 }],
+ "objects": [{ "name": "slab", "uri": "tests/render/data/voxel-slab.tpg", "position": [0, 0, 0], "anchor": true },
+ { "name": "post", "uri": "tests/render/data/voxel-post.tpg", "position": [0.0, 0.4, 0.0] },
+ { "name": "post-above", "uri": "tests/render/data/voxel-post.tpg", "position": [0.0, 2.0, 0.0], "turn": 1 }],
+ }))
+ .unwrap();
+ v.request(d).unwrap();
+ assert_eq!(v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [-0.5, 0.8, -0.5, 0.5, 1.0, 0.5] }))).unwrap()["queued"], true);
+ // (Ticks asked for in setup after the cut are the lattice's: on a level that collides they move nothing. The
+ // body is where the cut left it until the engine steps the physics world.)
+ for _ in 0..60 {
+ assert_eq!(v.frame(&mut w, 1.0 / 60.0).unwrap()["queued"], true);
+ }
+ let r = v.realize(&mut w, &mut ph, &assets()).unwrap().unwrap();
+ assert_eq!((r["explosions"].as_u64(), r["frames"].as_u64(), v.bodies()), (Some(1), Some(60), 1), "{r}");
+ let spawned = w.objects[&v.objects[*v.bodies.keys().next().unwrap()].as_ref().unwrap().parts[0].1].position;
+ assert!((spawned - Vec3::new(-0.2, 1.0, -0.2)).length() < 1e-4, "{spawned}");
+ // (The two posts are one file: one shape between their colliders until the cut gave the lower one its own.)
+ assert_eq!(r["colliders"].as_u64(), Some(3));
+ crate::api::physics_settle(&mut ph, &mut v, &mut w, 120);
+ let part = *v.bodies.keys().next().unwrap();
+ let at = w.objects[&v.objects[part].as_ref().unwrap().parts[0].1].position;
+ assert!((at - Vec3::new(-0.2, 0.8, -0.2)).length() < 5e-3, "{at}");
+ // A ray from the side at the part: its hit's body, straight into an impulse.
+ let p = ph.as_mut().unwrap();
+ let hit = p.call(&mut w, "ray", &serde_json::json!({ "origin": [0.05, 2.05, 5.0], "direction": [0, 0, -1], "max": 10 })).unwrap();
+ let body = hit["body"].as_u64().expect("the ray meets the part");
+ assert_eq!(Some(body), v.body_list(p)[0]["body"].as_u64());
+ p.call(&mut w, "impulse", &serde_json::json!({ "body": body, "impulse": [0, 2000, 0] })).unwrap();
+ let up = p.call(&mut w, "state", &serde_json::json!({ "body": body })).unwrap()["linvel"][1].as_f64().unwrap();
+ assert!((up - 2000.0 / (416.0 * 0.9)).abs() < 0.05, "416 voxels of a soft entry (900 kg/m³) take 2,000 N s as {up} m/s");
+ for _ in 0..12 {
+ crate::api::physics_advance(&mut ph, &mut v, &mut w, 1.0 / 60.0);
+ }
+ assert!(w.objects[&v.objects[part].as_ref().unwrap().parts[0].1].position.y > 1.2, "the part went up with it");
+ }
+
+ /// A carve that cuts bodies at the cap (the review of #24, and before it the benchmark level's `shatter` with a cap
+ /// of 128, which ended the renderer when a body retired mid-carve was looked up: gpu-runs-8.md L7). What the carve
+ /// is cutting is not retired for its own chips: every body keeps its id and the larger part, the chips are debris.
+ /// And what goes at the cap otherwise: the least of the rest (asleep, then fewest voxels, then oldest), and only
+ /// for a part at least as large.
+ #[test]
+ fn a_carve_that_passes_the_cap_while_cutting_bodies() {
+ let mut w = World::default();
+ let mut ph: Option<PhysicsWorld> = None;
+ // A slab and six bars standing on it in a row, each cut loose in turn: six bodies; the cap is six. Beside
+ // them a thick column and a thin post, cut loose at the end.
+ let mut blocks = vec![([0, 0, 0], [64, 4, 64], Some((0, 0)), true)];
+ blocks.extend((0..6).map(|k| ([8 + 8 * k, 4, 8], [4, 24, 4], None, false)));
+ blocks.extend([([8, 4, 40], [8, 30, 8], None, false), ([40, 4, 40], [2, 8, 2], None, false)]);
+ let mut v = VoxelWorld::of_blocks(&blocks, &mut w, &mut ph);
+ v.max_bodies = 6;
+ v.keep_debris = true;
+ let cut = |v: &mut VoxelWorld, w: &mut World, ph: &mut Option<PhysicsWorld>, lo: [f32; 3], hi: [f32; 3]| v.edit(w, ph, &EditOp { shape: ShapeM::Box(lo, hi), kind: EditKind::Carve([256; 4]) }).unwrap();
+ for k in 0..6 {
+ let x = 0.8 + 0.8 * k as f32;
+ cut(&mut v, &mut w, &mut ph, [x - 0.1, 0.5, 0.7], [x + 0.5, 0.7, 1.3]);
+ }
+ assert_eq!(v.bodies(), 6);
+ let settle = |v: &mut VoxelWorld, w: &mut World, ph: &mut Option<PhysicsWorld>| {
+ for _ in 0..180 {
+ crate::api::physics_advance(ph, v, w, 1.0 / 60.0);
+ }
+ };
+ settle(&mut v, &mut w, &mut ph);
+ let ids: Vec<usize> = v.bodies.keys().copied().collect();
+ // Cuts across all six at once: each body in two, the larger part kept as the body, the chip debris.
+ let mut carved = 0;
+ for y in [1.0, 1.6, 2.2] {
+ let e = cut(&mut v, &mut w, &mut ph, [0.0, y, 0.0], [6.4, y + 0.1, 3.0]);
+ carved += e["bodies_carved"].as_u64().unwrap();
+ assert!(v.bodies() <= 6, "{} bodies", v.bodies());
+ }
+ assert!(carved >= 12, "{carved} bodies carved");
+ assert_eq!(v.bodies.keys().copied().collect::<Vec<_>>(), ids, "every body is the one it was");
+ assert_eq!(v.retired, 0, "none retired for a chip");
+ assert!(v.capped >= 12, "{} chips debris", v.capped);
+ assert!(v.bodies.values().all(|b| b.grid.count() < 336 && b.grid.count() >= 64), "{:?}", v.bodies.values().map(|b| b.grid.count()).collect::<Vec<_>>());
+ // Every body there is has its objects, and no object is left of one that went.
+ let parts: usize = v.bodies.keys().map(|&k| v.objects[k].as_ref().unwrap().parts.len()).sum();
+ assert_eq!(v.world_objects(), 1 + 6 + 2 + parts);
+ settle(&mut v, &mut w, &mut ph);
+ assert!(!v.take_debris().is_empty());
+ // The thick column cut loose: larger than any body, so the least of them goes (all asleep: the fewest voxels,
+ // then the oldest).
+ let least = v.bodies.iter().map(|(&k, b)| (b.grid.count(), k)).min().unwrap().1;
+ cut(&mut v, &mut w, &mut ph, [0.7, 0.5, 3.9], [1.7, 0.7, 4.9]);
+ assert_eq!((v.bodies(), v.retired), (6, 1));
+ assert!(!v.bodies.contains_key(&least), "the least body went");
+ // The thin post cut loose: 2 x 2 x 5 cells, smaller than every body: debris, and no body goes for it.
+ let (before, capped) = (v.bodies.keys().copied().collect::<Vec<_>>(), v.capped);
+ cut(&mut v, &mut w, &mut ph, [3.9, 0.5, 3.9], [4.3, 0.7, 4.3]);
+ assert_eq!(v.bodies.keys().copied().collect::<Vec<_>>(), before);
+ assert_eq!((v.retired, v.capped), (1, capped + 1));
+ }
+
+ /// What scene code asks of a level before it is loaded is kept, and counted: past `MAX_QUEUED` an edit or a frame
+ /// is refused (the review of #24: a setup looping on edits grew the queue without bound, outside the script
+ /// engine's memory limit).
+ #[test]
+ fn edits_before_the_load_are_bounded() {
+ let mut v = VoxelWorld::default();
+ let d: LevelDesc = serde_json::from_value(serde_json::json!({ "route": "mesh", "palette": [{ "name": "none", "color": [0, 0, 0], "roughness": 1, "metalness": 0 }], "objects": [] })).unwrap();
+ v.request(d).unwrap();
+ let (mut w, mut ph) = (World::default(), None);
+ for k in 0..MAX_QUEUED {
+ let r = if k % 2 == 0 { v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [0, 0, 0, 1, 1, 1] }))) } else { v.frame(&mut w, 1.0 / 60.0) };
+ assert_eq!(r.unwrap()["queued"], true);
+ }
+ let e = v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [0, 0, 0, 1, 1, 1] }))).unwrap_err();
+ assert!(format!("{e}").contains("at most 4096"), "{e}");
+ assert!(v.frame(&mut w, 1.0 / 60.0).is_err());
+ }
+
+ /// A carve takes a body's voxels as it takes the level's (the review of #24): a radius clamped to `MAX_RADIUS`
+ /// voxels and to 0 below, and a box whole for every class it reaches, not shrunk by the class's share.
+ #[test]
+ fn a_carve_takes_bodies_as_it_takes_the_level() {
+ let one = || {
+ let mut w = World::default();
+ let mut ph: Option<PhysicsWorld> = None;
+ let mut v = VoxelWorld::of_blocks(&[([0, 0, 0], [64, 4, 64], Some((0, 0)), true), ([28, 4, 28], [4, 24, 4], None, false)], &mut w, &mut ph);
+ v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [2.7, 0.5, 2.7, 3.3, 0.7, 3.3] }))).unwrap();
+ assert_eq!(v.bodies(), 1);
+ (w, ph, v)
+ };
+ let body_voxels = |v: &VoxelWorld| v.bodies.values().map(|b| b.grid.count()).sum::<usize>();
+ // A sphere of 600 m centred 500 m away: 12.8 m as the level takes it, which does not reach.
+ let (mut w, mut ph, mut v) = one();
+ if let Ok(e) = v.edit(&mut w, &mut ph, &EditOp { shape: ShapeM::Sphere([500.0, 0.0, 0.0], 600.0), kind: EditKind::Carve([256; 4]) }) {
+ assert_eq!((e["voxels"].as_u64(), e["body_voxels"].as_u64().unwrap_or(0)), (Some(0), 0), "{e}");
+ }
+ assert_eq!(body_voxels(&v), 336);
+ // A negative radius at the body: nothing, as in the level.
+ let (mut w, mut ph, mut v) = one();
+ let e = v.edit(&mut w, &mut ph, &EditOp { shape: ShapeM::Sphere([3.0, 1.5, 3.0], -2.0), kind: EditKind::Carve([256; 4]) }).unwrap();
+ assert_eq!(e["body_voxels"].as_u64().unwrap_or(0), 0, "{e}");
+ assert_eq!(body_voxels(&v), 336);
+ // A box over the body's upper half with every class at half its share: the half, whole.
+ let (mut w, mut ph, mut v) = one();
+ let e = v.edit(&mut w, &mut ph, &EditOp { shape: ShapeM::Box([2.5, 1.75, 2.5], [3.5, 3.0, 3.5]), kind: EditKind::Carve([128; 4]) }).unwrap();
+ assert_eq!(e["body_voxels"].as_u64(), Some(16 * 11), "{e}");
+ }
+
+ /// The cap on bodies: past it a sleeping body as large as the new one goes, its voxels debris; and a body the physics world took
+ /// out goes with its objects.
+ #[test]
+ fn voxel_bodies_are_bounded() {
+ let mut w = World::default();
+ let mut ph: Option<PhysicsWorld> = None;
+ let mut v = VoxelWorld::default();
+ // Four posts on a slab, each cut loose in turn; at most two bodies.
+ let at = |k: usize| ([-0.4, 0.4][k & 1], [-0.4, 0.4][k >> 1]);
+ let posts: Vec<serde_json::Value> = (0..4).map(|k| serde_json::json!({ "name": format!("post{k}"), "uri": "tests/render/data/voxel-post.tpg", "position": [at(k).0, 0.4, at(k).1] })).collect();
+ let mut objects = vec![serde_json::json!({ "name": "slab", "uri": "tests/render/data/voxel-slab.tpg", "position": [0, 0, 0], "anchor": true })];
+ objects.extend(posts);
+ let d: LevelDesc = serde_json::from_value(serde_json::json!({
+ "route": "mesh", "debris": true, "maxBodies": 2,
+ "palette": [{ "name": "none", "color": [0, 0, 0], "roughness": 1, "metalness": 0 }, { "name": "black", "color": [0, 0, 0], "roughness": 1, "metalness": 0 },
+ { "name": "post", "color": [1, 1, 1], "roughness": 1, "metalness": 0, "density": 500 }],
+ "objects": objects,
+ }))
+ .unwrap();
+ v.request(d).unwrap();
+ v.realize(&mut w, &mut ph, &assets()).unwrap();
+ let mut seen = 0;
+ for k in 0..4 {
+ let (x, z) = at(k);
+ let e = v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [x - 0.3, 0.5, z - 0.3, x + 0.3, 0.7, z + 0.3] }))).unwrap();
+ assert_eq!(e["pieces"], 1, "{e}");
+ seen += 1;
+ for _ in 0..120 {
+ crate::api::physics_advance(&mut ph, &mut v, &mut w, 1.0 / 60.0);
+ }
+ assert_eq!(v.bodies(), seen.min(2), "after {seen} cuts");
+ }
+ assert_eq!(v.retired, 2);
+ assert!(v.take_debris().len() / 4 > 2 * 100, "the retired bodies' voxels are debris");
+ assert_eq!(v.world_objects(), 1 + 4 + 2, "the slab, four stumps, two parts");
+ // A body the physics world no longer has (it took it out: one that fell off the level, `Physics::step`): at the
+ // next sync it is gone with its objects, and nothing of it is kept.
+ let body = v.body_list(ph.as_ref().unwrap())[0]["body"].as_u64().unwrap() as u32;
+ ph.as_mut().unwrap().bridge().engine_remove(Some(body), None);
+ crate::api::physics_advance(&mut ph, &mut v, &mut w, 1.0 / 60.0);
+ assert!(v.take_debris().is_empty());
+ assert_eq!((v.bodies(), v.retired, v.world_objects()), (1, 2, 1 + 4 + 1), "{}", v.body_list(ph.as_ref().unwrap()));
+ }
+
/// A terrain tile carved away whole, with its neighbour carved at their shared edge: the edit goes through (the
/// neighbour is meshed again, not the tile that is gone), the tile leaves the tiles' table, and a later edit of the
/// neighbour's edge does too.
@@ -1032,24 +2209,24 @@ mod tests {
let mut v = VoxelWorld::default();
let tile = |tx: i32| serde_json::json!({ "name": format!("tile-{tx}"), "uri": "tests/render/data/voxel-slab.tpg", "position": [6.4 * tx as f64, 0.0, 0.0], "tile": [tx, 0] });
let d: LevelDesc = serde_json::from_value(serde_json::json!({
- "route": "mesh",
+ "route": "mesh", "physics": false,
"palette": [{ "name": "none", "color": [0, 0, 0], "roughness": 1, "metalness": 0 }, { "name": "ground", "color": [0.5, 0.5, 0.5], "roughness": 1, "metalness": 0 }],
"objects": [tile(0), tile(1), tile(2)],
}))
.unwrap();
v.request(d).unwrap();
- v.realize(&mut w, &assets()).unwrap();
+ v.realize(&mut w, &mut None, &assets()).unwrap();
assert_eq!((v.tiles.len(), v.world_objects()), (3, 3));
// Everything of tile 0 (x -0.8 .. 0.8 m) and tile 1's voxels up to its own x = 0 (world 6.4 m).
- let e = v.edit(&mut w, &op(serde_json::json!({ "op": "carve", "box": [-1.0, -1.0, -1.0, 6.4, 1.0, 1.0] }))).unwrap();
+ let e = v.edit(&mut w, &mut None, &op(serde_json::json!({ "op": "carve", "box": [-1.0, -1.0, -1.0, 6.4, 1.0, 1.0] }))).unwrap();
assert_eq!((e["removed"].as_u64(), e["touched"].as_u64()), (Some(1), Some(1)), "{e}");
assert_eq!(e["voxels"].as_u64(), Some(1024 + 512));
assert_eq!((v.tiles.len(), v.world_objects()), (2, 2));
assert!(!v.tiles.contains_key(&(0, 0)) && v.objects[0].is_none());
// Tile 1's left edge again (its neighbour there is gone), and tile 2 whole: tile 1 is meshed again for both.
- let e = v.edit(&mut w, &op(serde_json::json!({ "op": "carve", "box": [6.4, -1.0, -1.0, 6.5, 1.0, 1.0] }))).unwrap();
+ let e = v.edit(&mut w, &mut None, &op(serde_json::json!({ "op": "carve", "box": [6.4, -1.0, -1.0, 6.5, 1.0, 1.0] }))).unwrap();
assert_eq!((e["removed"].as_u64(), e["touched"].as_u64(), e["voxels"].as_u64()), (Some(0), Some(1), Some(64)), "{e}");
- let e = v.edit(&mut w, &op(serde_json::json!({ "op": "carve", "box": [11.0, -1.0, -1.0, 14.0, 1.0, 1.0] }))).unwrap();
+ let e = v.edit(&mut w, &mut None, &op(serde_json::json!({ "op": "carve", "box": [11.0, -1.0, -1.0, 14.0, 1.0, 1.0] }))).unwrap();
assert_eq!((e["removed"].as_u64(), e["touched"].as_u64()), (Some(1), Some(1)), "tile 2 gone, tile 1 beside it drawn again: {e}");
assert_eq!((v.tiles.len(), v.world_objects()), (1, 1));
}
@@ -1070,14 +2247,144 @@ mod tests {
}
let mut w = World::default();
let mut v = VoxelWorld::default();
- assert!(v.edit(&mut w, &op(serde_json::json!({ "op": "carve", "sphere": [0, 0, 0, 1] }))).is_err());
+ assert!(v.edit(&mut w, &mut None, &op(serde_json::json!({ "op": "carve", "sphere": [0, 0, 0, 1] }))).is_err());
let mut v = level(&mut w);
// A box of a kilometre is refused; a huge radius is cut down to the largest (12.8 m).
- assert!(v.edit(&mut w, &op(serde_json::json!({ "op": "carve", "box": [-500, -500, -500, 500, 500, 500] }))).is_err());
- let e = v.edit(&mut w, &op(serde_json::json!({ "op": "explode", "sphere": [0, 0, 0, 1e9] }))).unwrap();
+ assert!(v.edit(&mut w, &mut None, &op(serde_json::json!({ "op": "carve", "box": [-500, -500, -500, 500, 500, 500] }))).is_err());
+ let e = v.edit(&mut w, &mut None, &op(serde_json::json!({ "op": "explode", "sphere": [0, 0, 0, 1e9] }))).unwrap();
assert!(e["voxels"].as_u64().unwrap() > 0);
}
+ /// Step 8 on the benchmark level, on the CPU (no GPU; a measurement):
+ /// VOXEL_PHYSICS=../out/bundles/voxel-level-destruction-mesh.js cargo test --release --lib voxel_level_physics -- --ignored --nocapture
+ /// The level's colliders (how many, their cells, the time to build them, their memory); explosions of 0.5 to 4 m
+ /// at a building's foot (the edit's parts: the level's carve, the colliders, the meshes, the bodies); then a cut
+ /// under the whole building (it comes loose as bodies) and the physics' ticks after each: step and sync ms a
+ /// frame, the bodies and how many sleep.
+ #[test]
+ #[ignore = "a measurement: VOXEL_PHYSICS=<bundle.js>"]
+ fn voxel_level_physics() {
+ let Ok(bundle) = std::env::var("VOXEL_PHYSICS") else { return println!("VOXEL_PHYSICS=<bundle.js>") };
+ let assets = assets();
+ let host = crate::script::ScriptHost::new(&std::fs::read_to_string(&bundle).unwrap()).unwrap();
+ host.setup("r", None).unwrap();
+ let (mut v, mut w, mut ph) = (host.voxels.borrow_mut(), host.world.borrow_mut(), host.physics.borrow_mut());
+ let t = Instant::now();
+ let r = v.realize(&mut w, &mut ph, &assets).unwrap().unwrap();
+ println!("level: {} objects, {} triangles; realize {:.2} s; colliders: {} of {} cells in {:.0} ms (of it finding the cells {:.0}), {:.1} MiB (parry's count)", r["objects"], r["triangles"], t.elapsed().as_secs_f64(), r["colliders"], r["collider_cells"], r["colliders_ms"].as_f64().unwrap(), r["shell_ms"].as_f64().unwrap(), ph.as_ref().unwrap().bridge_ref().voxel_bytes() as f64 / 1048576.0);
+ w.take_changes();
+ {
+ let level = v.level.as_ref().unwrap();
+ let tiles: Vec<usize> = (0..v.objects.len()).filter(|&k| v.objects[k].as_ref().is_some_and(|o| o.tile.is_some())).collect();
+ let cells: usize = tiles.iter().map(|&k| level.objects[k].as_ref().unwrap().grid.count()).sum();
+ let aligned = tiles.iter().filter(|&&k| { let (o, l) = (v.objects[k].as_ref().unwrap(), level.objects[k].as_ref().unwrap()); l.place.turn == 0 && o.off.iter().all(|x| x % 8 == 0) && l.place.t.iter().all(|x| x.rem_euclid(8) == 0) }).count();
+ let o = v.objects[tiles[0]].as_ref().unwrap();
+ let l = level.objects[tiles[0]].as_ref().unwrap();
+ println!("terrain: {} tiles of {} cells in all ({} aligned to the world's bricks); the first: off {:?}, placed at {:?} turn {}, cells {:?}..{:?}", tiles.len(), cells, aligned, o.off, l.place.t, l.place.turn, l.lo, l.hi);
+ let houses: BTreeMap<String, usize> = v.objects.iter().flatten().filter(|o| o.tile.is_none()).fold(BTreeMap::new(), |mut m, o| { *m.entry(o.name.split('-').next().unwrap_or("").to_string()).or_default() += 1; m });
+ println!("objects by kind: {houses:?}");
+ let anchors = (0..v.objects.len()).filter(|&k| v.objects[k].as_ref().is_some_and(|o| o.tile.is_none()) && level.objects[k].as_ref().is_some_and(|o| o.anchor)).count();
+ println!("anchors that are no tiles: {anchors}");
+ }
+ // The building with the most voxels, and the ground under its middle.
+ let level = v.level.as_ref().unwrap();
+ let (k, cells) = (0..v.objects.len()).filter(|&k| v.objects[k].as_ref().is_some_and(|o| o.name.starts_with("house") && o.tile.is_none())).map(|k| (k, level.objects[k].as_ref().map_or(0, |o| o.grid.count()))).max_by_key(|x| x.1).expect("a house");
+ let (lo, hi) = (v.objects[k].as_ref().unwrap().lo, v.objects[k].as_ref().unwrap().hi);
+ println!("the largest building part: {} ({cells} voxels), {:.1} x {:.1} x {:.1} m at {:?}", v.objects[k].as_ref().unwrap().name, hi.x - lo.x, hi.y - lo.y, hi.z - lo.z, lo);
+ let frames = |v: &mut VoxelWorld, w: &mut World, ph: &mut Option<PhysicsWorld>, n: usize, what: &str| {
+ let (mut step, mut sync, mut worst) = (vec![], vec![], 0.0f64);
+ for _ in 0..n {
+ let t = Instant::now();
+ crate::api::physics_advance(ph, v, w, 1.0 / 60.0);
+ let all = t.elapsed().as_secs_f64() * 1e3;
+ let s = ph.as_mut().unwrap().take_stats();
+ step.push(s.step_ms);
+ sync.push(all - s.step_ms);
+ worst = worst.max(all);
+ w.take_changes();
+ }
+ step.sort_by(f64::total_cmp);
+ sync.sort_by(f64::total_cmp);
+ let list = v.body_list(ph.as_ref().unwrap());
+ let asleep = list.as_array().unwrap().iter().filter(|b| b["asleep"] == true).count();
+ println!(" {what}: {n} frames: step p50 {:.3} p95 {:.3} ms, placing p50 {:.3} ms, a frame at worst {:.2} ms; {} bodies, {asleep} asleep", step[n / 2], step[n * 95 / 100], sync[n / 2], worst, v.bodies());
+ };
+ frames(&mut v, &mut w, &mut ph, 60, "the level at rest");
+ let foot = Vec3::new(lo.x + 0.3, lo.y + 1.0, (lo.z + hi.z) * 0.5);
+ for (n, r) in [0.5f32, 1.0, 2.0, 4.0].into_iter().enumerate() {
+ let at = foot + Vec3::new(0.0, 0.0, (n as f32 - 1.5) * (hi.z - lo.z) * 0.2);
+ let t = Instant::now();
+ let e = v.explode(&mut w, &mut ph, at, r).unwrap();
+ let ms = t.elapsed().as_secs_f64() * 1e3;
+ println!("explosion of {r} m: {ms:.2} ms in all: carve {:.2}, colliders {:.2}, meshes {:.2}, parts {:.2} (meshes and bodies {:.2}), bodies carved {:.2}; {} voxels, {} objects touched, {} parts of {} voxels; bodies now {}", e["carve_ms"].as_f64().unwrap(), e["colliders_ms"].as_f64().unwrap(), e["rebuild_ms"].as_f64().unwrap(), e["pieces_ms"].as_f64().unwrap(), e["piece_mesh_ms"].as_f64().unwrap(), e["bodies_ms"].as_f64().unwrap_or(0.0), e["voxels"], e["touched"], e["pieces"], e["piece_voxels"], e["bodies"]);
+ w.take_changes();
+ frames(&mut v, &mut w, &mut ph, 120, "after it");
+ }
+ // The cut (the bench's `fell`): a slab 1 m thick through everything, half a metre above the building's foot,
+ // 30 x 30 m about its middle: the buildings, trees, lamps and cars there lose their footing.
+ let t = Instant::now();
+ let (cx, cz) = ((lo.x + hi.x) * 0.5, (lo.z + hi.z) * 0.5);
+ let e = v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [cx - 15.0, lo.y + 0.5, cz - 15.0, cx + 15.0, lo.y + 1.5, cz + 15.0] }))).unwrap();
+ let ms = t.elapsed().as_secs_f64() * 1e3;
+ println!("the cut under the building: {ms:.2} ms in all: carve {:.2}, colliders {:.2}, meshes {:.2}, parts {:.2}; {} voxels, {} objects touched, {} parts of {} voxels; bodies now {}", e["carve_ms"].as_f64().unwrap(), e["colliders_ms"].as_f64().unwrap(), e["rebuild_ms"].as_f64().unwrap(), e["pieces_ms"].as_f64().unwrap(), e["voxels"], e["touched"], e["pieces"], e["piece_voxels"], e["bodies"]);
+ let mut sizes: Vec<usize> = v.bodies.values().map(|b| b.grid.count()).collect();
+ sizes.sort_unstable();
+ println!(" bodies by voxels: the largest {:?}, the median {:?}, {} in all voxels; voxel shapes now {:.1} MiB", sizes.last(), sizes.get(sizes.len() / 2), sizes.iter().sum::<usize>(), ph.as_ref().unwrap().bridge_ref().voxel_bytes() as f64 / 1048576.0);
+ w.take_changes();
+ frames(&mut v, &mut w, &mut ph, 60, "the first second");
+ frames(&mut v, &mut w, &mut ph, 240, "the next four");
+ frames(&mut v, &mut w, &mut ph, 300, "the next five");
+ // An explosion into what fell.
+ let t = Instant::now();
+ let e = v.explode(&mut w, &mut ph, Vec3::new((lo.x + hi.x) * 0.5, lo.y + 2.0, (lo.z + hi.z) * 0.5), 3.0).unwrap();
+ println!("an explosion of 3 m into it: {:.2} ms in all: carve {:.2}, colliders {:.2}, bodies carved {:.2} ({} bodies, {} voxels); bodies now {}", t.elapsed().as_secs_f64() * 1e3, e["carve_ms"].as_f64().unwrap(), e["colliders_ms"].as_f64().unwrap(), e["bodies_ms"].as_f64().unwrap_or(0.0), e["bodies_carved"], e["body_voxels"], e["bodies"]);
+ w.take_changes();
+ frames(&mut v, &mut w, &mut ph, 300, "five seconds after");
+ println!("retired for the cap: {}", v.retired);
+ }
+
+ /// The trees of the benchmark level cut at the trunk (the destruction game's `topple`): what each crown does as a
+ /// body, a second at a time: its speed, its spin, whether it sleeps; and the step's time.
+ #[test]
+ #[ignore = "a measurement: VOXEL_PHYSICS=<bundle.js>"]
+ fn voxel_level_topple() {
+ let Ok(bundle) = std::env::var("VOXEL_PHYSICS") else { return println!("VOXEL_PHYSICS=<bundle.js>") };
+ let assets = assets();
+ let host = crate::script::ScriptHost::new(&std::fs::read_to_string(&bundle).unwrap()).unwrap();
+ host.setup("r", None).unwrap();
+ let (mut v, mut w, mut ph) = (host.voxels.borrow_mut(), host.world.borrow_mut(), host.physics.borrow_mut());
+ v.realize(&mut w, &mut ph, &assets).unwrap().unwrap();
+ w.take_changes();
+ // (The game's eight trunks with seed 1, as its `trunks` gives them; an explosion of 0.6 m at 0.8 m up each.)
+ let trunks = [[-100.6f32, 9.3, -92.0], [-103.9, 9.1, -93.0], [-86.7, 9.8, -91.1], [-105.9, 9.2, -88.8], [-89.3, 10.0, -88.1], [-105.8, 9.2, -86.5], [-88.1, 10.1, -87.0], [-83.9, 10.0, -90.7]];
+ for t in trunks {
+ let at = Vec3::new(t[0], t[1] + 0.8, t[2]);
+ let e = v.explode(&mut w, &mut ph, at, 0.6).unwrap();
+ println!("a trunk cut at {at:?}: {} voxels carved, {} parts of {} voxels", e["voxels"], e["pieces"], e["piece_voxels"]);
+ w.take_changes();
+ for _ in 0..30 {
+ crate::api::physics_advance(&mut ph, &mut v, &mut w, 1.0 / 60.0);
+ w.take_changes();
+ }
+ }
+ for second in 1..=20 {
+ let mut step = vec![];
+ for _ in 0..60 {
+ crate::api::physics_advance(&mut ph, &mut v, &mut w, 1.0 / 60.0);
+ step.push(ph.as_mut().unwrap().take_stats().step_ms);
+ w.take_changes();
+ }
+ step.sort_by(f64::total_cmp);
+ let p = ph.as_ref().unwrap();
+ let each: Vec<String> = v.bodies.values().map(|b| {
+ let (at, _, asleep) = p.bridge_ref().engine_pose(b.body).unwrap();
+ let (lin, ang) = p.bridge_ref().engine_velocity_of(b.body).unwrap();
+ format!("{}{} y {:.2} v {:.3} w {:.3}", b.grid.count(), if asleep { " asleep" } else { "" }, at[1], Vec3::from(lin).length(), Vec3::from(ang).length())
+ }).collect();
+ println!(" second {second}: step p50 {:.3} ms; {}", step[30], each.join(" | "));
+ }
+ }
+
/// Meshing time on the benchmark level's files (`cargo test --release voxel_mesh_timing -- --ignored --nocapture`;
/// THREERT_ASSETS: the asset root, default ../assets): every terrain tile (64 x 64 columns) and building part,
/// median and maximum.
diff --git a/renderer/voxel-core/src/level.rs b/renderer/voxel-core/src/level.rs
index d6c41f7..03c7479 100644
--- a/renderer/voxel-core/src/level.rs
+++ b/renderer/voxel-core/src/level.rs
@@ -58,6 +58,10 @@ pub struct Edit {
pub created: Vec<u32>,
pub removed: Vec<u32>,
pub debris: Vec<([i32; 3], u8)>,
+ /// By object: the world cells it lost (carved away, or gone into a loose part or debris), in the order they went.
+ /// What a collider of the object's cells takes out (ROADMAP § 6 step 8): by the cells that changed, not by the
+ /// object's size.
+ pub cleared: BTreeMap<u32, Vec<[i32; 3]>>,
/// Per changed object, the world cells (inclusive bounds) its removed voxels were in.
pub bounds: BTreeMap<u32, ([i32; 3], [i32; 3])>,
/// Voxels the shape removed, painted or added.
@@ -328,6 +332,7 @@ impl Level {
let o = self.objects[id as usize].as_mut().unwrap();
let grid = Rc::make_mut(&mut o.grid);
let keys = edit.changed.entry(id).or_default();
+ let lost = edit.cleared.entry(id).or_default();
let (mut blo, mut bhi) = ([i32::MAX; 3], [i32::MIN; 3]);
for (key, mask) in gone {
let b = grid.bricks.get_mut(&key).unwrap();
@@ -344,6 +349,7 @@ impl Level {
}
edit.debris.push((w, m));
edit.voxels += 1;
+ lost.push(w);
if !anchor {
cleared.push(w);
}
@@ -522,11 +528,14 @@ impl Level {
for (id, list) in taken {
grow(&mut edit.bounds, id, lo, hi);
let o = self.objects[id as usize].as_mut().unwrap();
+ let place = o.place;
let grid = Rc::make_mut(&mut o.grid);
let keys = edit.changed.entry(id).or_default();
+ let lost = edit.cleared.entry(id).or_default();
for g in list {
grid.take(g[0], g[1], g[2]);
keys.insert(brick_of(g));
+ lost.push(place.to_world(g));
}
for k in keys.iter() {
grid.prune(*k);
@@ -621,6 +630,16 @@ impl Level {
out
}
+ /// A falling object handed out of the level for good (ROADMAP § 6 step 8: it is a rigid body from here on, the
+ /// physics world's to move): its grid and where it is. The level no longer holds, ticks or hashes it; its id is
+ /// not used again. None: no such object, or one that is not falling.
+ pub fn take(&mut self, id: u32) -> Option<Object> {
+ if !self.falling.remove(&id) {
+ return None;
+ }
+ self.objects.get_mut(id as usize)?.take()
+ }
+
/// Objects falling now.
pub fn falling(&self) -> usize {
self.falling.len()
@@ -858,4 +877,35 @@ mod tests {
assert_eq!(crate::check::script(), crate::check::script());
assert_eq!(crate::check::script(), crate::check::EXPECTED, "the script's level changed: if meant, record {:#x}", crate::check::script());
}
+
+ /// What an edit says a collider of an object's cells must lose (`Edit::cleared`): exactly the cells that are no
+ /// longer the object's, those carved and those gone into a loose part; and a loose part handed out (`take`) is
+ /// the level's no more.
+ #[test]
+ fn an_edit_names_the_cells_each_object_lost() {
+ let mut l = ground();
+ let tower = l.add_object(block([0, 0, 0], [3, 29, 3], 2), Placement::new([10, 1, 10], 0, [0, 0, 0]), false);
+ l.settle();
+ let before: BTreeSet<[i32; 3]> = { let o = l.objects[tower as usize].as_ref().unwrap(); o.grid.voxels().map(|(g, _)| o.place.to_world(g)).collect() };
+ let e = l.carve(sphere([11.5, 12.5, 11.5], 2.5), [256; 4]);
+ assert_eq!(e.created.len(), 1, "the top is loose");
+ let after: BTreeSet<[i32; 3]> = { let o = l.objects[tower as usize].as_ref().unwrap(); o.grid.voxels().map(|(g, _)| o.place.to_world(g)).collect() };
+ let lost: BTreeSet<[i32; 3]> = e.cleared[&tower].iter().copied().collect();
+ assert_eq!(lost.len(), e.cleared[&tower].len(), "no cell twice");
+ assert_eq!(lost, before.difference(&after).copied().collect::<BTreeSet<_>>());
+ assert!(lost.len() > e.voxels, "the carved cells and the top's");
+ // The ground lost nothing here; an anchor's carved cells are named too.
+ assert!(e.cleared.keys().all(|&k| k == tower));
+ let e2 = l.carve(sphere([25.5, 3.5, 25.5], 1.5), [256; 4]);
+ assert!(e2.cleared.values().map(|c| c.len()).sum::<usize>() == e2.voxels && e2.voxels > 0);
+ // The loose top, taken: gone from the level, which then has nothing falling; twice is None.
+ let top = e.created[0];
+ let (hash, falling) = (l.hash(), l.falling());
+ let o = l.take(top).unwrap();
+ assert!(o.fall.is_some() && o.grid.count() > 0);
+ assert_eq!((l.falling(), falling), (0, 1));
+ assert!(l.take(top).is_none() && l.take(tower).is_none() && l.take(9999).is_none());
+ assert!(l.objects[top as usize].is_none() && l.hash() != hash);
+ assert!(l.tick().falling.is_empty());
+ }
}
diff --git a/renderer/web/Cargo.lock b/renderer/web/Cargo.lock
index 485c36d..eebe149 100644
--- a/renderer/web/Cargo.lock
+++ b/renderer/web/Cargo.lock
@@ -494,6 +494,15 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
+[[package]]
+name = "ena"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eabffdaee24bd1bf95c5ef7cec31260444317e72ea56c4c91750e8b7ee58d5f1"
+dependencies = [
+ "log",
+]
+
[[package]]
name = "equivalent"
version = "1.0.3"
@@ -671,6 +680,18 @@ dependencies = [
"bytemuck",
]
+[[package]]
+name = "glam"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "556f6b2ea90b8d15a74e0e7bb41671c9bdf38cd9f78c284d750b9ce58a2b5be7"
+
+[[package]]
+name = "glam"
+version = "0.32.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f70749695b063ecbf6b62949ccccde2e733ec3ecbbd71d467dca4e5c6c97cca0"
+
[[package]]
name = "glam"
version = "0.33.12"
@@ -1041,6 +1062,16 @@ version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
+[[package]]
+name = "matrixmultiply"
+version = "0.3.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
+dependencies = [
+ "autocfg",
+ "rawpointer",
+]
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -1153,7 +1184,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adc43a60c217b0c6ff46e47f26911015ad8d2e5a8be1af668c67e370d99a4346"
dependencies = [
"approx",
+ "glam 0.30.10",
+ "glam 0.31.1",
+ "glam 0.32.1",
"glam 0.33.12",
+ "matrixmultiply",
"nalgebra-macros",
"num-complex",
"num-rational",
@@ -1203,6 +1238,16 @@ dependencies = [
"jni-sys 0.3.1",
]
+[[package]]
+name = "num-bigint"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-complex"
version = "0.4.6"
@@ -1238,6 +1283,7 @@ version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
+ "num-bigint",
"num-integer",
"num-traits",
]
@@ -1625,6 +1671,7 @@ dependencies = [
"bitflags 2.13.2",
"downcast-rs 2.0.2",
"either",
+ "ena",
"foldhash",
"glamx",
"hashbrown 0.17.1",
@@ -1633,9 +1680,12 @@ dependencies = [
"num-derive",
"num-traits",
"ordered-float",
+ "rayon",
"rstar",
"simba",
+ "slab",
"smallvec",
+ "spade",
"static_assertions",
"thiserror 2.0.21",
]
@@ -1841,6 +1891,7 @@ dependencies = [
"num-traits",
"parry3d",
"profiling",
+ "rayon",
"serde",
"simba",
"static_assertions",
@@ -1866,6 +1917,12 @@ dependencies = [
"objc2-quartz-core 0.3.2",
]
+[[package]]
+name = "rawpointer"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
+
[[package]]
name = "rayon"
version = "1.12.0"
@@ -1928,6 +1985,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
+[[package]]
+name = "robust"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e27ee8bb91ca0adcf0ecb116293afa12d393f9c2b9b9cd54d33e8078fe19839"
+
[[package]]
name = "rquickjs"
version = "0.12.2"
@@ -2214,6 +2277,18 @@ dependencies = [
"serde",
]
+[[package]]
+name = "spade"
+version = "2.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9699399fd9349b00b184f5635b074f9ec93afffef30c853f8c875b32c0f8c7fa"
+dependencies = [
+ "hashbrown 0.16.1",
+ "num-traits",
+ "robust",
+ "smallvec",
+]
+
[[package]]
name = "spirv"
version = "0.4.0+sdk-1.4.341.0"
@@ -2328,6 +2403,7 @@ dependencies = [
"gltf",
"half",
"image",
+ "libc",
"physics-core",
"pollster",
"rayon",
diff --git a/renderer/web/src/lib.rs b/renderer/web/src/lib.rs
index eba16e3..dc24a33 100644
--- a/renderer/web/src/lib.rs
+++ b/renderer/web/src/lib.rs
@@ -101,13 +101,19 @@ pub fn voxel_level(d: &str) -> Result<(), JsValue> {
#[wasm_bindgen(js_name = voxelExplode)]
pub fn voxel_explode(x: f64, y: f64, z: f64, r: f64) -> Result<String, JsValue> {
- engine(|e| api::voxel_explode(&mut e.voxels, &mut e.world, x, y, z, r)).map_err(thrown)
+ engine(|e| api::voxel_explode(&mut e.voxels, &mut e.world, &mut e.physics, x, y, z, r)).map_err(thrown)
}
#[wasm_bindgen(js_name = voxelEdit)]
pub fn voxel_edit(d: &str) -> Result<String, JsValue> {
let d = desc("voxelEdit", d)?;
- engine(|e| api::voxel_edit(&mut e.voxels, &mut e.world, &d)).map_err(thrown)
+ engine(|e| api::voxel_edit(&mut e.voxels, &mut e.world, &mut e.physics, &d)).map_err(thrown)
+}
+
+/// The voxel bodies as JSON (`api::voxel_bodies`).
+#[wasm_bindgen(js_name = voxelBodies)]
+pub fn voxel_bodies() -> String {
+ engine(|e| api::voxel_bodies(&e.voxels, &e.physics))
}
#[wasm_bindgen(js_name = voxelHash)]
@@ -357,7 +363,7 @@ pub async fn start(canvas: web_sys::HtmlCanvasElement, width: u32, height: u32,
// level the scene asked for is loaded now.
let mut core = engine(|e| {
e.world.take_changes();
- if e.voxels.realize(&mut e.world, Path::new(""))?.is_some() {
+ if e.voxels.realize(&mut e.world, &mut e.physics, Path::new(""))?.is_some() {
e.world.take_changes();
}
LiveCore::new(g, &e.world, Path::new(""), Path::new(""), width, height)
@@ -474,9 +480,7 @@ pub fn frame_end(dt: f32) -> Result<String, JsValue> {
let now = web_time_now;
let p0 = now();
engine(|e| {
- if let Some(p) = e.physics.as_mut() {
- p.advance(&mut e.world, dt as f64);
- }
+ api::physics_advance(&mut e.physics, &mut e.voxels, &mut e.world, dt as f64);
});
let p1 = now();
let rebuilt = commit_view(v)?;
@@ -571,9 +575,7 @@ pub fn commit(seq: f64) -> Result<bool, JsValue> {
#[wasm_bindgen]
pub fn tick(dt: f32) -> String {
engine(|e| {
- if let Some(p) = e.physics.as_mut() {
- p.advance(&mut e.world, dt as f64);
- }
+ api::physics_advance(&mut e.physics, &mut e.voxels, &mut e.world, dt as f64);
e.world.take_changes();
json!(e.physics.as_mut().map(|p| { let s = p.take_stats(); json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved }) })).to_string()
})
diff --git a/renderer/web/www/engine.ts b/renderer/web/www/engine.ts
index 9d08f44..813d834 100644
--- a/renderer/web/www/engine.ts
+++ b/renderer/web/www/engine.ts
@@ -14,6 +14,7 @@ export interface EngineExports {
voxelEdit(d: string): string;
voxelHash(): string;
voxelDebris(): Float32Array;
+ voxelBodies(): string;
voxelFrame(dt: number): string;
geometry(id: number, p: Float32Array, n: Float32Array, uv: Float32Array, idx: Uint32Array, groups?: Uint32Array | null, colors?: Float32Array | null): void;
texture(id: number, d: string, data?: Uint8Array | null): void;
@@ -52,6 +53,7 @@ export interface VoxelCalls {
voxelFrame(dt: number): string;
voxelDebris(): Float32Array;
voxelHash(): string;
+ voxelBodies(): string;
}
export type WebEngine = Engine & VoxelCalls & { physicsPoses(): Float32Array };
@@ -68,6 +70,7 @@ export function webEngine(w: EngineExports): WebEngine {
voxelEdit: (d) => w.voxelEdit(json(d)),
voxelHash: () => w.voxelHash(),
voxelDebris: () => w.voxelDebris(),
+ voxelBodies: () => w.voxelBodies(),
voxelFrame: (dt) => w.voxelFrame(dt),
geometry: (id, p, n, uv, idx, groups, colors) => w.geometry(id, p, n, uv, idx, groups, colors),
texture: (id, d, data) => w.texture(id, json(d), data),
diff --git a/tests/render/voxel-cut-body-live.ts b/tests/render/voxel-cut-body-live.ts
new file mode 100644
index 0000000..9382b4f
--- /dev/null
+++ b/tests/render/voxel-cut-body-live.ts
@@ -0,0 +1,25 @@
+// voxel/cut-body in the real-time renderer: the cut is made by the frame script at its third frame; the loose part is
+// added as a body's driven objects in place, falls as an instance (no vertex is written again, no rebuild) and rests
+// on the stump: the cut's band reads 5 nits.
+import { defineGame } from "@threert/gameplay";
+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { test as base } from "./voxel-cut-body.ts";
+import { cut, level } from "./voxel-cut-falls.ts";
+
+export const test: TestMeta = { ...base, id: "voxel/cut-body-live", temporal: true, time: undefined, live: 200 };
+
+let frames = 0;
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ frames = 0;
+ const scene = sceneWithSky(0);
+ level(true);
+ return result(scene, camera(scene, [0, 2, 8], [0, 2, 0]));
+ },
+ frame(f) {
+ if (f.dt <= 0) return;
+ if (++frames === 3) cut();
+ },
+ handlers: {},
+});
diff --git a/tests/render/voxel-cut-body-push.ts b/tests/render/voxel-cut-body-push.ts
new file mode 100644
index 0000000..66c54d5
--- /dev/null
+++ b/tests/render/voxel-cut-body-push.ts
@@ -0,0 +1,48 @@
+// What a ray gives scene code is enough to act on a voxel body (ROADMAP § 6 step 8): voxel/cut-body-live's cut, and
+// once the loose part stands on the stump the frame script casts two rays at the physics world. One straight down
+// at the slab: a hit on the voxel level, whose `object` is `engineColliders` (no scene object: its `physics` is
+// null) and which has no `body` (the level is fixed). One from the camera's side at the part: the same `object`,
+// and a `body`, the id `voxelBodies()` lists. That id goes into `voxelImpulse`, sideways: the part is thrown off
+// the stump. So where the part stood (y 2.9 .. 3.2) reads 0 against the stump, which is the level's and stays
+// (y 0.45 .. 0.75, 5 nits). A ray that does not report the level or the body as said, or an impulse that does not
+// move the part, leaves the part standing: the ratio is 1.
+import { engineColliders, Raycaster, Vector3 } from "@threert/scene";
+import { defineGame } from "@threert/gameplay";
+import { voxelBodies, voxelImpulse } from "@threert/voxel";
+import { camera, result, sceneWithSky, type Region, type TestMeta } from "./lib.ts";
+import { test as base } from "./voxel-cut-body.ts";
+import { BELOW, cut, level } from "./voxel-cut-falls.ts";
+
+const STUMP: Region = [0.485, 0.795, 0.515, 0.855];
+
+export const test: TestMeta = {
+ ...base, id: "voxel/cut-body-push", temporal: true, time: undefined, live: 240,
+ metric: { kind: "ratio", a: BELOW, b: STUMP, expected: 0, tolerance: 0.02 },
+ note: "as voxel/cut-body-live; at frame 90 a ray's hit names the body and voxelImpulse throws it off the stump",
+};
+
+let frames = 0;
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ frames = 0;
+ const scene = sceneWithSky(0);
+ level(true);
+ return result(scene, camera(scene, [0, 2, 8], [0, 2, 0]));
+ },
+ frame(f) {
+ if (f.dt <= 0) return;
+ frames++;
+ if (frames === 3) cut();
+ if (frames !== 90) return;
+ // The level (the slab is 1.6 m square about the origin): fixed, no scene object, no body.
+ const ground = new Raycaster(new Vector3(0.55, 5, 0.55), new Vector3(0, -1, 0)).intersectPhysics()[0];
+ if (!ground || ground.object !== engineColliders || ground.object.physics !== null || ground.body !== undefined || ground.collider === undefined) return;
+ // The part: a body, the one the level lists.
+ const hit = new Raycaster(new Vector3(0.05, 2.05, 5), new Vector3(0, 0, -1)).intersectPhysics()[0];
+ if (!hit || hit.object !== engineColliders || hit.body === undefined || !voxelBodies().some((b) => b.body === hit.body)) return;
+ // 416 voxels of 900 kg/m³: 374 kg; 1,500 N s is 4 m/s sideways.
+ voxelImpulse(hit.body, [1500, 300, 0]);
+ },
+ handlers: {},
+});
diff --git a/tests/render/voxel-cut-body-top.ts b/tests/render/voxel-cut-body-top.ts
new file mode 100644
index 0000000..783ee3f
--- /dev/null
+++ b/tests/render/voxel-cut-body-top.ts
@@ -0,0 +1,9 @@
+// voxel/cut-body from the other end: the top 0.2 m of the upper post is empty once the body has come down. Its radiance
+// over the post's just below: 0 (not fallen: 1).
+import def, { test as base } from "./voxel-cut-body.ts";
+import { BELOW, TOP } from "./voxel-cut-falls.ts";
+import type { TestMeta } from "./lib.ts";
+
+export const test: TestMeta = { ...base, id: "voxel/cut-body-top", metric: { kind: "ratio", a: TOP, b: BELOW, expected: 0, tolerance: 0.02 } };
+
+export default def;
diff --git a/tests/render/voxel-cut-body.ts b/tests/render/voxel-cut-body.ts
new file mode 100644
index 0000000..4db2303
--- /dev/null
+++ b/tests/render/voxel-cut-body.ts
@@ -0,0 +1,22 @@
+// What a cut leaves hanging on nothing is a rigid body (ROADMAP § 6 step 8). The level of voxel/cut-falls with its
+// physics on (the default): the slab and the posts are fixed colliders, and the cut frees the lower post's upper part
+// with the post on it, 416 voxels, as one body of the physics world. It comes down the 0.2 m of the cut onto the
+// stump, stands and sleeps (renderer/src/voxel.rs `the_level_collides_and_loose_parts_are_bodies` has the numbers:
+// 0.2 m within 5 mm, no drift). Seen from the side after 2 s (120 ticks), black sky: the cut has closed, so its band
+// reads 5 nits (still in the air, toppled or fallen through the slab: 0).
+import { defineGame } from "@threert/gameplay";
+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { cut, level, test as base } from "./voxel-cut-falls.ts";
+
+export const test: TestMeta = { ...base, id: "voxel/cut-body", features: ["voxel", "edits", "physics"], time: 2, note: "as voxel/cut-falls, the level's physics on: the loose part is a body" };
+
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ const scene = sceneWithSky(0);
+ level(true);
+ cut();
+ return result(scene, camera(scene, [0, 2, 8], [0, 2, 0]));
+ },
+ handlers: {},
+});
diff --git a/tests/render/voxel-cut-falls.ts b/tests/render/voxel-cut-falls.ts
index 89fab2a..f4a162b 100644
--- a/tests/render/voxel-cut-falls.ts
+++ b/tests/render/voxel-cut-falls.ts
@@ -4,6 +4,8 @@
// A saw cut (`voxelCarve`, a box) takes the lower post's layers y 0.8 .. 1.0. Its upper part and the whole second post
// then hang on nothing: one loose part of two objects' voxels, which falls 0.2 m onto the stump (60 ticks in setup).
// Seen from the side, black sky: the cut has closed, so the band y 0.8 .. 1.0 reads 5 nits (not fallen: 0).
+// The level's physics is off here (`physics: false`): this is the fall through the lattice, cell by cell, which a
+// level without physics still has. With it on, the loose part is a rigid body: voxel-cut-body.ts.
import { defineGame } from "@threert/gameplay";
import { voxelCarve, voxelFrame, voxelLevel } from "@threert/voxel";
import { camera, result, sceneWithSky, type Region, type TestMeta } from "./lib.ts";
@@ -19,9 +21,10 @@ export const test: TestMeta = {
note: "posts at x = z = 0, the cut at y 0.8 .. 1.0; camera at z = 8, y = 2",
};
-export function level(): void {
+export function level(physics = false): void {
voxelLevel({
route: "mesh",
+ physics,
palette: [
{ name: "none", color: [0, 0, 0], roughness: 1, metalness: 0 },
{ name: "black", color: [0, 0, 0], roughness: 1, metalness: 0 },
diff --git a/tools/physics-determinism.ts b/tools/physics-determinism.ts
index 9ddeee3..4b6b8e8 100644
--- a/tools/physics-determinism.ts
+++ b/tools/physics-determinism.ts
@@ -12,6 +12,10 @@
// first run passes and the second fails.
// Then the renderer's dependency graph, built for wasm32 (renderer/examples/physics_bits.rs), against the recorded
// hashes: the engine's library in a browser.
+// Then Rapier's parallel solver (physics-core's `parallel` feature: what the renderer's native build steps the world
+// with, ROADMAP § 6 step 8), on 2 and on 4 threads: the script and every one of the random worlds against the
+// sequential native build's, which the steps above hold to wasm32 and the recorded hashes. So native parallel =
+// native sequential = wasm32 = recorded: a native build steps as a browser does.
// `--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";
@@ -27,11 +31,15 @@ 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;
+// The sequential native build's script and cases (the first build's), for the parallel build below.
+let sequential: { script: string; cases: string } | null = null;
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(" "));
+ const casesOut = cargo([...run, "--", "--cases"]).trim();
+ const nativeCases = casesOut.split("\n").map((l) => l.split(" "));
+ sequential ??= { script: native, cases: casesOut };
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, {});
@@ -57,15 +65,39 @@ for (const [label, features] of builds) {
console.log(`physics determinism${label}: cases: native ${hex(folded)}, recorded ${constant("EXPECTED_CASES")}`);
failed ||= hex(folded) !== constant("EXPECTED_CASES");
}
+// Rapier's parallel solver: the same bits as the sequential build, whatever the thread count.
+if (!without && sequential) {
+ const run = ["run", "--release", "--locked", "--quiet", "--features", "parallel", "--example", "determinism"];
+ for (const threads of ["2", "4"]) {
+ const parallel = (args: string[]) => execFileSync("cargo", args, { cwd: crate, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"], maxBuffer: 1 << 26, env: { ...process.env, RAYON_NUM_THREADS: threads } }).trim();
+ const [script, cases] = [parallel(run), parallel([...run, "--", "--cases"])];
+ const [mine, theirs] = [cases.split("\n"), sequential.cases.split("\n")];
+ const differ = mine.filter((l, k) => l !== theirs[k]);
+ console.log(`physics determinism (parallel, ${threads} threads): script ${script}, sequential ${sequential.script}, recorded ${constant("EXPECTED")}; ${mine.length - differ.length} of ${theirs.length} worlds equal the sequential build's`);
+ for (const d of differ.slice(0, 3)) console.log(` ${d}`);
+ failed ||= script !== sequential.script || script !== constant("EXPECTED") || mine.length !== theirs.length || differ.length > 0;
+ }
+}
// The renderer's own dependency graph built for wasm32 (the engine's library in a browser): the same recorded hashes.
// (It holds the wasm32 side; a glamx patch left out shows natively, in the renderer's own test, not here.)
if (!without) {
const renderer = join(import.meta.dirname, "../renderer");
execFileSync("cargo", ["build", "--release", "--locked", "--quiet", "--target", "wasm32-unknown-unknown", "--example", "physics_bits"], { cwd: renderer, stdio: ["ignore", "ignore", "inherit"] });
- const bits = await WebAssembly.instantiate(readFileSync(join(renderer, "target/wasm32-unknown-unknown/release/examples/physics_bits.wasm")), {});
+ // (The voxel adapter is in the renderer's library, whose clock and logging are the browser's: imports this check
+ // has no use for. Each is given a function that returns 0; the scripts read no clock and log nothing.)
+ const module = await WebAssembly.compile(readFileSync(join(renderer, "target/wasm32-unknown-unknown/release/examples/physics_bits.wasm")));
+ const imports: Record<string, Record<string, () => number>> = {};
+ for (const i of WebAssembly.Module.imports(module)) (imports[i.module] ??= {})[i.name] = () => 0;
+ const bits = { instance: await WebAssembly.instantiate(module, imports) };
const [script, cases] = [hex((bits.instance.exports.physics_script as () => bigint)()), hex((bits.instance.exports.physics_cases as () => bigint)())];
console.log(`physics determinism (the renderer's graph, wasm32): script ${script}, cases ${cases}`);
failed ||= script !== constant("EXPECTED") || cases !== constant("EXPECTED_CASES");
+ // The voxel bodies' script (renderer/src/voxel.rs `VoxelWorld::check_script`: ROADMAP § 6 step 8): the adapter between
+ // the voxels and the physics. The native side is the renderer's test `voxel_bodies_step_to_the_recorded_bits`.
+ const voxel = hex((bits.instance.exports.voxel_bodies_script as () => bigint)());
+ const recorded = /EXPECTED_SCRIPT: u64 = 0x([0-9a-f_]+);/.exec(readFileSync(join(renderer, "src/voxel.rs"), "utf8"))![1].replaceAll("_", "").padStart(16, "0");
+ console.log(`physics determinism (the renderer's graph, wasm32): voxel bodies ${voxel}, recorded ${recorded}`);
+ failed ||= voxel !== recorded;
}
if (without) process.exit(0);
if (failed) {
diff --git a/tools/voxel-determinism-level.ts b/tools/voxel-determinism-level.ts
index 55fbe9b..781babd 100644
--- a/tools/voxel-determinism-level.ts
+++ b/tools/voxel-determinism-level.ts
@@ -2,7 +2,8 @@
// run twice in lockstep (every frame 1 / 60 s, so both runs tick alike) through the same events: the explosions of
// `singles` (0.5 to 4 m, ground and walls), the saw cut of `fell` (trees, posts, cars and buildings cut loose, falling
// and landing) and the 4 m `crater`. The level's hash (`voxelHash`: every object's placement, state and voxels) is
-// logged after each; the two runs must agree, and the hash must change from event to event. Exit 1 otherwise.
+// logged after each, and with it the physics world's (ROADMAP § 6 step 8: the loose parts are rigid bodies, so where
+// they are is the physics'); the two runs must agree, and the hash must change from event to event. Exit 1 otherwise.
// (voxel-core's own check, native against wasm32, is tools/voxel-determinism.ts.) The GPU lock is held.
// node tools/voxel-determinism-level.ts
import { execFileSync } from "node:child_process";
@@ -36,7 +37,8 @@ async function run(): Promise<string[]> {
await step(2);
}
await live.quit();
- return live.lines.map((l) => /hash ([0-9a-f]{16}) frame/.exec(l)?.[1]).filter((h): h is string => !!h);
+ // (Since step 8 the line has the physics world's hash too: where the parts that came loose are, bit for bit.)
+ return live.lines.map((l) => /hash ([0-9a-f]{16})(?: physics ([0-9a-f]{16}))? frame/.exec(l)).filter((m): m is RegExpExecArray => !!m).map((m) => (m[2] ? `${m[1]}+${m[2]}` : m[1]));
}
const [a, b] = [await run(), await run()];