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.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
World handlers: on[type](world, ev) changes the scene as the event arrives; queries see what the engine was told without a tick; the runtime's shape and step 9's preconditions in the docs (#2)
Yujiaef1357ff9e71
diff --git a/README.md b/README.mdindex ccc6f8d..3362167 100644--- a/README.md+++ b/README.md@@ -2,7 +2,7 @@A real-time GPU path tracer for games and scenes written in a Three-like TypeScript DSL.-- **Scenes** are written with `packages/scene`, a Three-like DSL. **Gameplay** uses `packages/gameplay`: Verse-inspired transactional handlers and per-frame scripts.+- **Scenes** are written with `packages/scene`, a Three-like DSL. **Gameplay** uses `packages/gameplay`: Verse-inspired transactional handlers, per-frame scripts, and world handlers that change the scene as an event arrives.- That code runs inside the **native renderer**, `renderer/`: Rust and wgpu, a GPU path tracer with UE5-matched shading and post, and an embedded QuickJS runtime. Scene code drives the engine API directly; there is no scene interchange format.- **UE5 renders are the ground truth** (`ue5/`). **three.js** is the baseline it is compared against (`tools/three`, `compare/`).- **The voxel engine** around it is described in [`docs/VOXEL.md`](docs/VOXEL.md).@@ -19,7 +19,7 @@ Mirror: [`doodlewind/ThreeRT`](https://github.com/doodlewind/ThreeRT).|---|---|| `renderer/` | The engine: Rust + wgpu path tracer, live viewport, denoiser, post, embedded QuickJS (`threert-render`); `renderer/voxel-core` and `renderer/physics-core` (Rapier; both also build for wasm32); `renderer/third_party/glamx` (a patched dependency of Rapier's, see its PATCH.md) || `packages/scene` | The Three-like scene DSL (`@threert/scene`) |-| `packages/gameplay` | Games: state, transactional handlers, frame scripts (`@threert/gameplay`) |+| `packages/gameplay` | Games: state, transactional handlers, world handlers (`on`), frame scripts (`@threert/gameplay`) || `packages/voxel` | The voxel engine's TypeScript side (`@threert/voxel`) || `scenes/` | The reference catalog (Cornell box, material grid, Bistro, Zero Day, …) || `games/` | Playable content: Kabukichō Night, Bistro slice / district / crowd, Zero Day, Tokyo, the voxel level, Light Room, … |@@ -62,7 +62,7 @@ npm run test:render # the render test suite on the GPU**Scene code runs in the renderer** ([`docs/RUNTIME.md`](docs/RUNTIME.md)): `threert-render play out/bundles/kabukicho.js` runs the game inside the embedded QuickJS.- Setup builds the scene through the engine API.-- Clicks and keys run handlers that commit game state.+- Clicks and keys run handlers that commit game state, and world handlers (`on`) that change the scene at once.- The game's `frame` script (UE's Director Tick: neon flicker, wet / dry ramps, moods, power cut) derives the scene from that state every frame. Parameter changes rewrite GPU tables in place.**Tokyo** (`games/tokyo/`, `tools/tokyo/`): the open city, Shinjuku and Shiba, compiled by `tools/city` from public data. Live time of day uses the dynamic sky, windows switched by the clock, moonlight and the night sky.diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 7482eb0..539c857 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -3655,9 +3655,11 @@ benchmark level. The order follows the dependencies; a step that meets a further- The review's fuzz (random calls, ordinary and absurd numbers; a small version is in the crate's tests):611 panics in 120,000 runs at its two mildest levels before, none in 210,000 runs at all five after.- **Determinism:** the same bits natively and in wasm32, in physics-core's own build and in the renderer's, on- what is checked: the script (`113d50eb06a47636`), 1,000 random worlds (tumbling convex hulls, bodies of- several colliders, hinges and sliders with limits and motors, a rope; `check::case`, folded hash- `9e16a6771fa8f317`), each compared (`tools/physics-determinism.ts`, CI), and 32,000 runs of the review's+ what is checked: the script (`113d50eb06a47636`), 1,200 random worlds (tumbling convex hulls, bodies of+ several colliders, hinges and sliders with limits and motors, a rope; and, added with the world handlers,+ continuous collision detection on a triangle mesh, a kinematic body, fixed and ball joints, with the answers+ of rays, sweeps and overlaps folded in; `check::case`, folded hash `6fd1eba4551b8d39`, `9e16a6771fa8f317`+ for the first 1,000), each compared (`tools/physics-determinism.ts`, CI), and 32,000 runs of the review'srandom calls. It takes three things:- Rapier's `enhanced-determinism` (on in physics-core): without it none of the 1,000 worlds agree (thescript: `dfdc13fb0be5cd0b` natively). It costs 1–3 % on the script (0.029 ms a tick) and 3–5 % on a pile of@@ -3716,7 +3718,7 @@ benchmark level. The order follows the dependencies; a step that meets a furtherrest: step 0.03 ms, sync 0.0003 ms, commit 0.003 ms).- The frame log has `physics: { ticks, step, sync, bodies, moved }` and `commit`.- **Open:** the first instance of a scene rebuilds it; a sleeping body does not follow a parent of its object that- moves; a query sees a collider from the tick after it was added; reading every body's pose every frame at+ moves; reading every body's pose every frame at10,000 bodies is 5 ms of script (the typed array itself is not handed to scripts yet); a body made anew(`physics` set again, the object re-parented or rescaled) starts at rest; where physics is authoritative, thenode or the room, is step 9's.@@ -3724,15 +3726,79 @@ benchmark level. The order follows the dependencies; a step that meets a furtherbodies), not on what a tick costs: N one-metre dynamic boxes made at one point take 62 ms for their first tickat 250, 0.46 s at 500, 2.8 s at 1,000 and 45 s at 2,000 (M5 Pro, one run). It belongs to the security reviewbefore the cloud opens.+ - **World handlers** (2026-11-10, branch `world-handlers`; the user's decision of that day, with the runtime's+ shape: three.js-style scripts, Rust as the main runtime, four channels across the boundary, layout C on the web.+ docs/RUNTIME.md has the decisions, the layouts considered and the probe's measurements).+ - **`on[type](world, ev)`** (`packages/gameplay/src/world.ts`): an event's handler on the node that owns the+ scene and the physics world. It runs as the event arrives, before the next tick, and what it changes goes to+ the engine through the scene binding when it returns: no commit, no frame script run for it. Before, a handler+ could only write the JSON state (it may run in a room, where there is no scene), so a click that adds a body was+ recorded by a handler and acted on by the frame script.+ - With `handlers[type]` too: the world handler first, on the state before the event; then the transaction; then+ what the world handler emitted (`world.emit`, a state transaction). `keys` map to either; a game of world+ handlers needs no `handlers`. One that throws does not stop the world (its changes are synced, the error is in+ the event's log). In a room they do not run: an event with a world handler only is an error there.+ - **Only local authority.** Who owns the physics when a room is the authority is a product question, not+ decided. What a world handler adds is not in the game state, so a restored state does not have it (step 9).+ - **Queries see what the engine was told, with or without a tick since.** Rapier's broad phase is the last+ step's: a collider added since was not found, and a body moved by a call was found where it had been. Two+ events with no tick between them (a frame rate above the tick rate) are where an author meets it. Colliders+ added, or moved by a call, since the last step are now tested one by one beside the broad phase's answer+ (`Physics::fresh`; nothing of Rapier's state is touched; with none, a query is what it was). What the running+ script itself changed reaches the engine when it returns, so a handler's own query does not see what it just+ added: the one rule left, in RUNTIME.md.+ - **Events without a frame script.** The node host's `frame` now runs every frame for a game with a frame+ script, with world handlers, or whose scene has a physics world, so contacts and `outofworld` reach their+ listeners every frame (before: only when a handler committed). A scene with none of the three pays nothing.+ - **Hello world** is rewritten: `on.click` casts the ray and adds the box; no state, no handler, no frame+ script. `tools/physics-hello.ts` is unchanged and passes. A click's script time, two runs each on one build:+ 0.33–0.62 ms before (0.30–0.54 ms in step 7's table), 0.16–0.37 ms now; the commit and the first frame after a+ click as before (0.29–0.53 ms in place, 3.9–4.0 ms). The frame's script time with no frame script is 0.083 ms+ mean (0.094 ms with the old frame script): the host's call, the events and an empty sync.8. **[engine] Voxel bodies.** The voxel collision shape and debris as bodies.- Acceptance: about a hundred debris bodies within the frame budget on the level, with the CPU split recorded.- Then the decision: keep Rapier or write our own.9. **[ThreeRT] World data and command replay.** Binary world blocks on the node outside the JSON game state, changed bydeterministic commands the room logs and replays to late joiners.- Acceptance: a room replayed from its log gives bit-identical world data.+ - **The log carries world-hash checkpoints** (required by the supervisor of this line, 2026-11-10): at a fixed+ 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.+ - **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.- From step 7, for the physics' part of the log:- It rests on step 7's determinism, which holds for one build of the engine on the platforms checked; a newplatform or a new Rapier runs `tools/physics-determinism.ts` first.+ - **Precondition: the platform math calls upstream knows of, against what our worlds reach** (dimforge/rapier+ issue #1054 and its reproductions, for Rapier 0.36.1 / parry 0.31.1 / glamx 0.3.1; read 2026-11-10). We build+ `rapier3d` with `dim3`, `f32`, `alloc` and `enhanced-determinism`: no `parallel`, no soft bodies, no multibody+ joints, and a game's calls make bodies, the five impulse joints (limits on hinges and sliders, velocity motors),+ box / sphere / capsule / hull / static trimesh colliders, CCD, contact events and ray / overlap / sweep queries.++ | upstream item | call | on our path | what holds it |+ | --- | --- | --- | --- |+ | inertia diagonalization ("suspicious", no repro upstream) | glamx `eigen3.rs` acos, cos | **yes**: every convex hull and body of several colliders | patched (third_party/glamx); 48 of 1,000 worlds differed before; cases 0 and 1 |+ | angular limits (2D repro) | `joint_constraint_helper.rs` sin_cos of the limits' centre, also the 3D line | **yes**: a hinge with limits | limits handed over centred, so the centre is 0 and exact (`add_joint`); case 2, `revolute_limits_off_centre` |+ | BVH optimizer ("suspicious") | parry `bvh_optimize.rs` log2 | **yes**: the broad phase, every world | tested: the same subtree count with the platform's log2 and libm's for every collider count up to 80,000, on each platform the tests run on |+ | arc geometry | parry `vector_ext.rs` `angle()` acos | no: its callers are a trimesh's pseudo normals (only with the `ORIENTED` / `FIX_INTERNAL_EDGES` flags) and arc generation | tested: a trimesh is built with no flags (`a_trimesh_has_no_pseudo_normals`); case 3 has a trimesh |+ | revolute angle | `RevoluteJoint::angle()` asin | no: neither Rapier's solver nor we call it | |+ | angular motor (2D repro) | `generic_joint_constraint_builder.rs` sin of a motor's target angle | no: the multibody path, and a position motor; ours are impulse joints with velocity motors (the impulse path's position motor uses simba's asin) | a position motor is not offered to games; adding one re-opens this |+ | contact coefficients | `CoefficientCombineRule::Max` on ±0 | no: we never set a combine rule (the default averages, which IEEE defines) | |+ | singular vectors | glamx `svd2.rs` | no: 2D | |+ | deformation damping, elasticity, cloth bending, tear smoothing, plasticity, elastic cap, disk / tube geometry, rest angle (9 repros) | soft bodies | no: no soft body is made | |+ | inverse kinematics | multibody | no | |+ | missed tear | `parallel` and soft bodies | no | |+ | Delaunay refinement, equal-key sorts ("suspicious") | soft bodies, spade | no (spade is not in our build) | |++ Also read in the sources and not in upstream's list: a convex hull's feature lookup takes the sine and cosine of+ one constant (tested equal to libm's); `Aabb::intersects_spiral` and the interval arithmetic under it have no+ caller in our build; the remaining method-syntax calls are in 2D or test code. Case 3 of+ `physics_core::check` (200 worlds: CCD on a trimesh, a kinematic body, fixed and ball joints, the answers of+ queries) is the evidence for the rest of the path: 200 of 200 equal natively and in wasm32, both ways. A new+ feature of the physics offered to games (soft bodies, position motors, multibody joints, another combine rule,+ trimesh flags) is checked against this table first.- The log needs the tick each call was made at, and the syncs: a frame makes 0 to 5 ticks from the wall clock's`dt`, and a force lasts "the ticks of its frame", so the calls alone do not replay.- A body that drives an object starts at `Scene::world_pose`, which is the renderer's own glam arithmetic (notdiff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 4718638..358e78a 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -28,6 +28,9 @@ runtime, and drives the engine directly, the way a UE game drives its actors:+ `@threert/gameplay` + the node host in one script); in the cloud the agent's ES module plus the shared runtimemodule. A node builds the scene from it (deterministic per room seed).* **The world is the game state.** Handlers change `tx.state` only (OCC, log, replay). They never touch the scene.+* **What lives only where the engine is has its own handlers.** The physics world exists on the node that owns the+ scene, so an event that needs it (a click that casts a ray and adds a body) is handled there: `on[type](world, ev)`,+ a world handler, changes the scene as the event arrives (World handlers, below).* **The scene is a function of the state.** `frame(f)` (an actor's Tick on a UE client) reads the committed state andsets the scene: transforms, visibility, `power`, light and material parameters, the environment, the camera, objectsadded or removed, plus animation (flicker, ramps). It runs every frame in Play, and with `dt = 0` after setup and@@ -46,6 +49,7 @@ runtime, and drives the engine directly, the way a UE game drives its actors:| 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`. || 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()`. || Game session | `renderer/src/script.rs` `GameSession` | A runtime + its live view: events, clicks (CPU pick → `click {target, point, ray: {origin, direction}}`, with `instanceId` on an `InstancedMesh`; `ray` is the view ray, for a `Raycaster`), frame script, the physics world's ticks, editor edits, each followed by a commit. Shared by `play`, `live` and the playground. || Physics | `renderer/physics-core` (`Physics` on Rapier, `bridge::Bridge`), `renderer/src/physics.rs`, `packages/scene` (`Object3D.physics`, joints, `Raycaster.intersectPhysics`, `Shapecaster`) | The session's physics world, made by the first physics call (none: nothing runs). The engine steps it at 1 / 60 s after the frame script (at most 5 ticks a frame; offline renders step to their scene time) and places the objects of the bodies that moved: instances, so a move is a TLAS transform. Scripts cannot step it. See "Physics" below. |@@ -71,6 +75,61 @@ The playground runs the opened scene the same way: its host holds the `GameSessicatalog, the selection, the undo stack (Details edits as `{node, path, before, after}`) and the Play flow. Stopre-runs setup and replays the editor's edits (UE PIE: Play changes are discarded).+## World handlers++A handler is a transaction on the JSON state and may run in a room, where there is no scene and no physics world; the+scene then follows the state in `frame`. For an event whose point is the scene itself, that is a detour: a click that+adds a box had to be recorded in the state by a handler and acted on by the frame script. A world handler is the+event's handler on the node that owns the scene:++```ts+export default defineGame({+ state: {},+ setup,+ on: {+ click(world, ev) {+ raycaster.set(new Vector3(...ev.ray.origin), new Vector3(...ev.ray.direction));+ const hit = raycaster.intersectPhysics()[0];+ if (!hit) return;+ const box = new Mesh(geometry, wood);+ box.position.copy(hit.point).addScaledVector(hit.normal, 1.5);+ box.physics = "dynamic";+ world.scene.add(box); // in the engine, with its body, when the handler returns+ world.emit("placed", { by: ev.player }); // a state transaction, if the game keeps a score: handlers.placed+ },+ },+});+```++- **Where:** on the node that owns the scene and the physics world (`play`, `live`, the playground: wherever events+ arrive at a node). Not in a room.+- **When:** as the event arrives, synchronously, before the engine's next physics tick. What it changed goes to the+ engine through the scene binding when it returns: no commit, and `frame` is not run again for it.+- **The context** (`world`): `scene`, `camera`, the committed `state` (read-only), `object(id)`, `time` (the frame+ clock, s), `now` (the event's time, ms), `random()` (the event's own stream; `Math.random` and `Date` in the handler+ are the event's too), and `emit(type, payload)`, which starts a state transaction (`handlers[type]`).+- **With `handlers[type]` for the same event:** the world handler runs first, on the state as committed before the+ event; then the handler's transaction; then what the world handler emitted, in order; then the frame script shows+ the new state. A room that is the authority runs `handlers` on its own, so neither may rely on the other having run.+- **`keys`** map to either; `describe()` lists them as `on`; a game of world handlers only needs no `handlers`.+- **Synchronous:** no await, as for handlers.+- **A world handler that throws** does not stop the world, as a frame script that throws does not: what it had changed+ is synced, the event's handler and the next tick run all the same, and the error is in the event's log.+- **In a room:** they do not run. A node that follows a room gets committed state, not events; an event with a world+ handler only, sent to a room, is an error there that says so. Who owns the physics when a room is the authority is+ not decided (ROADMAP § 6 step 9); today world handlers are for a node that is its own authority.+- **What they add is not in the game state.** A state restored on another node (`setState`, a render of a room's+ state, `f.snap`) does not bring it back. Every change they make passes through the scene binding, which is where it+ will be logged and replayed from (step 9); until then, keep in the state what must survive a restore.+- **Queries and the scene's queue** (this holds for the frame script too):+ - What a script changes in the scene (`scene.add`, a move, `physics = ...`, an impulse) reaches the engine when the+ script returns. A query in the same handler asks the engine as it was before: it does not see the box the handler+ just added.+ - A query sees everything the engine has been told, with or without a physics tick since: the next event's query+ sees that box, also when no frame passed between the two events, and a body moved by a script is found where it+ was put.+- An event with neither a handler nor a world handler is the error it was.+## PhysicsScene code describes bodies on objects, three.js style; the engine owns the world (ROADMAP § 6 step 7).@@ -141,15 +200,99 @@ crate.position.set(0, 5, 0); // a write moves the body there- A tick has no time bound yet: thousands of bodies made at one point take seconds (ROADMAP § 6 step 7, Open).- Queries: `Raycaster.intersectPhysics({ exclude })` (every body the ray passes through, nearest first, with thesurface's normal) and `Shapecaster` (`overlap()`, `sweep(direction)`) for a box, sphere or capsule. They see the- world as of its last tick.-- Contacts (`physics.contacts`): once a frame, before the frame script, `contactstart` / `contactend` events on the two- objects (`event.other`) and one `contacts` event on the scene with the whole batch.+ world as the engine has it, with or without a tick since the last change; what the running script itself changed+ reaches the engine when it returns (World handlers, above).+- Contacts (`physics.contacts`): once a frame, `contactstart` / `contactend` events on the two objects+ (`event.other`) and one `contacts` event on the scene with the whole batch. They come before the frame script when+ the game has one, and every frame without one too (a game of world handlers, or listeners added in `setup`): a+ scene with bodies has the node host run every frame.- Cost: a body moves its object in the engine; no script runs for it. Poses reach the script only when read: the firstread of a frame fetches one typed array of every body's pose, each object then takes its seven numbers on its ownfirst read. Numbers: ROADMAP § 6 step 7.- The engine call under it is `__engine.physics(op, args)` (JSON; `renderer/physics-core/src/bridge.rs` lists thecalls, `faults` and `state`'s `{ removed }` among them) and `__engine.physicsPoses()`.+## The runtime's shape: Rust owns the world, the script engine is a guest++Decided by the user on 2026-11-10, with the measurements below.++- **Scripts are three.js-style TypeScript and nothing else.** An object is a `Mesh`; `mesh.physics = "dynamic"` and+ `scene.add(mesh)` put it in the physics world. No world, no step, no sync loop in the script.+- **Rust is the main runtime.** It owns the scene, the physics world, the voxel data and the fixed 1 / 60 s tick. The+ script decides what to add, push and remove, and when.+- **The boundary is four channels**, and it is the contract that stays when the script engine changes:++ | channel | direction | when | for |+ | --- | --- | --- | --- |+ | commands | script → Rust | queued in the script, sent once when it returns (the scene binding's sync) | many small writes (`scene.add`, impulses, joints) in a defined order; what step 9 logs |+ | poses | Rust → script | one table (7 floats a body), fetched at most once a tick; an object takes its own seven on first read | thousands of bodies move, the script reads a few; a body nobody reads costs the script nothing |+ | events | Rust → script | batched, once a frame | contacts, bodies that left the world: no polling |+ | queries | script ⇄ Rust | at once | rays, overlaps, sweeps: the script needs the answer to go on |++ A body's pose goes from the physics to the renderer (instance record, TLAS) without passing through the script.+- **The script engine can be swapped; the `Engine` interface is not tied to one.** Natively it is QuickJS embedded in+ the Rust application, as now, and nothing in the design needs a JIT.+- **On the web: layout C.** The Rust engine (scene, Rapier, voxels) is compiled to wasm, and the gameplay TypeScript+ runs in the browser's own JS engine, calling the wasm module's exports: the same game code and the same four+ channels, with the `Engine` interface implemented by the wasm exports and a thin layer of JS. Not built yet (it is+ what follows the world handlers; ROADMAP § 6). The layouts considered:++ | layout | what | why not / why |+ | --- | --- | --- |+ | A | everything in one wasm module: QuickJS compiled in beside the Rust engine | the same structure as native and a sandbox for free; scripts 1.5–1.8× slower than natively, heavy script code 190–478× slower than Rust, a C toolchain in the build; built and run in Node only (below) |+ | B | three.js as the runtime in the browser, physics in JS | physics, voxel edits and every later system written twice, and no determinism shared with the native build |+ | **C** | Rust engine in wasm, scripts in the browser's engine | **chosen.** One Rust engine, a pure Rust build, a call across the boundary costs about 1 ns, heavy script code about 3× Rust. The binding's glue is written a second time (wasm exports + thin JS), and isolating the script (a Worker or an iframe) is ours to do |+- **Heavy computation has standard ways out of the script**, because QuickJS is an interpreter (natively too):+ 1. the engine's own operations in Rust (voxel edits, meshing, connectivity, procedural geometry, physics queries):+ one call from the script;+ 2. WGSL program contracts (geometry functions, GPU particles, density-grid programs): the game gives a piece of+ shader, the engine runs it on the GPU;+ 3. a wasm compute module the game brings (arrays in, arrays out): **not built**; it waits for a real need.++ A script's time is in the frame log, so an author sees when their TypeScript is the cost.++### The measurements behind it (runtime probe, 2026-11-10)++Conditions: Apple M5 Pro, macOS 26.5, rustc 1.96, release profile as the renderer's; rquickjs 0.12.2 (QuickJS-ng+0.15.1); **Node 24.21 (V8 13.6) stands in for a browser, and nothing was run in a real browser**; single-threaded,+medians, on a machine another agent was using (load 3–5): differences under about 10 % are noise, and ratios are worth+more than the milliseconds. The harness and the full report are not in the repository (a copy of the report is kept+beside the checkout, `out/runtime-probe/REPORT.md`).++| crossing the boundary | native QuickJS | QuickJS in wasm (in Node) | V8 calling a wasm export |+| --- | ---: | ---: | ---: |+| a call with no argument | 18 ns | 26 ns | 1.2 ns (3.0 ns without V8's inlining of the call) |+| a call with three f64 | 37 ns | 67 ns | 0.9 ns (3.6 ns) |+| reading 1,000 bodies' poses from one table | 0.096 ms | 0.148 ms | 0.005 ms |+| reading 10,000 bodies' poses from one table | 0.94 ms | 1.48 ms | 0.051 ms |+| reading 10,000 poses, a call and a new array per body | 4.24 ms | 4.18 ms | not measured |++One table is 4.5× cheaper than a call per body, which is why poses are a table. Of QuickJS's 0.94 ms for 10,000+poses, the script's own read loop is 0.97 ms (the same within noise): the interpreter reading the numbers is the+cost, not the crossing. For orchestration, all three are enough in a 16.67 ms frame.++| the same algorithm, ms (× native Rust) | heightfield 256², mesh | greedy mesh of 64³ voxels |+| --- | ---: | ---: |+| Rust, native | 0.58 (1×) | 1.25 (1×) |+| Rust in wasm32, in Node | 0.65 (1.1×) | 1.92 (1.5×) |+| JS in V8, warmed up | 1.64 (2.8×) | 4.05 (3.2×) |+| JS in native QuickJS | 171 (295×) | 135 (108×) |+| JS in QuickJS in wasm | 273–277 (472–478×) | 237–238 (190×) |+| JS in Boa (a JS engine in Rust), native | 696 (1,202×) | 696 (557×) |++Every configuration produced the same output hash. A 64³ mesh in QuickJS is 8 to 14 frames: hence the ways out+above, natively as much as on the web. Authoring is checked natively (QuickJS), so under layout C a script is only+ever faster for a player than it was for its author.++Building a script engine into the wasm module (layout A), as far as it was taken:+- rquickjs does not build for `wasm32-unknown-unknown` with plain cargo (no libc headers for the target). It builds+ for `wasm32-wasip1` (wasi-sdk, fetched by its build script), and into one `wasm32-unknown-unknown` module beside+ wasm-bindgen with a recipe (QuickJS's C compiled by wasi-sdk's clang, wasi-libc linked, five WASI imports shimmed in+ JS): 1.2 MB, run in Node, same hashes.+- Boa builds for `wasm32-unknown-unknown` with one feature (10.4 MB) and is 4–8× slower than QuickJS.+- Not verified by the probe: a real browser; wgpu in the same module as a script engine; the software BVH traversal's+ frame rate in a browser (WebGPU has no hardware ray queries: the web's largest unknown, whichever layout).+## Correctness* `threert-render edit-check` builds the GPU tables both ways for a list of events: edited in place, and built freshdiff --git a/docs/VOXEL.md b/docs/VOXEL.mdindex 05e8775..596a9f0 100644--- a/docs/VOXEL.md+++ b/docs/VOXEL.md@@ -428,6 +428,10 @@ Where it runs (the user, 2026-11-10):- The GPU render farm (`/play`) only makes images for agents authoring in GPU-less sandboxes; nothing is streamed.- Players play in the browser, the client running the game (most likely #27's `web/`); native apps come later.+- How (the user, 2026-11-10; docs/RUNTIME.md "The runtime's shape"): the Rust engine compiled to wasm, with the+ gameplay TypeScript in the browser's own JS engine calling its exports (layout C). Natively the script engine stays+ QuickJS, and nothing depends on a JIT. Scripts are three.js-style; Rust owns the scene, the physics and the voxels;+ commands, poses, events and queries are the four channels between them. Not run in a real browser yet.- So voxel editing, meshing and physics (Rapier) build for wasm (`wasm32-unknown-unknown`: no wgpu, no file system,threads optional), and the browser has no ray queries (WebGPU). How the browser renders is the user's decision.- The triangle route's output renders in `web/` as it is: standard meshes or glTF with palette materials, each voxel'sdiff --git a/games/physics/hello.game.ts b/games/physics/hello.game.tsindex 1c1911c..32ce968 100644--- a/games/physics/hello.game.ts+++ b/games/physics/hello.game.ts@@ -3,11 +3,11 @@// the ramp, the rock), a box with `physics = "dynamic"` is added to the scene 1.5 m off that surface along its normal:// it falls, lands on what is fixed and piles up with the boxes before it (click the same spot of the wall again and// they stack). Where it meets a box, the box is kicked along the ground, away from the camera.-// The chain is the engine's whole path for gameplay physics: click -> the `click` handler records it in the game state-// -> the frame script (run again right after the commit) casts the ray and calls `scene.add` -> the binding makes the-// object and its body in the engine -> the engine steps the world and moves the object; nothing runs per object per-// frame in the script. The scene: a ground plane and a rock that are triangle-mesh colliders, a wall and a ramp that-// are boxes.+// The chain is the engine's whole path for gameplay physics: click -> the `click` world handler (`on`: it runs on the+// node that owns the scene as the event arrives) casts the ray and calls `world.scene.add` -> the binding makes the+// object and its body in the engine when the handler returns -> the engine steps the world and moves the object.+// There is no game state, no handler and no frame script: nothing runs per object per frame in the script. The scene:+// a ground plane and a rock that are triangle-mesh colliders, a wall and a ramp that are boxes.// node tools/bundle-game.ts games/physics/hello.game.ts -o out/bundles/physics-hello.js// renderer/target/release/threert-render play out/bundles/physics-hello.js (a window: click; R reports)// node tools/physics-hello.ts (the same game, scripted clicks, numbers)@@ -26,12 +26,9 @@ export const BOX = 0.5;export const DENSITY = 400;export const KICK = 3;-interface State {- /** The clicks so far, and the last one's view ray. */- clicks: number;- ray: { origin: [number, number, number]; direction: [number, number, number] } | null;- /** Asks the frame script for a report (R). */- reports: number;+/** A click's view ray, as the renderer sends it. */+interface Click {+ ray?: { origin: [number, number, number]; direction: [number, number, number] };}const COLOURS = [0xc8553d, 0x3d7ec8, 0x58a05c, 0xd9a441, 0x8a5cc8, 0x4fb3b3];@@ -39,7 +36,7 @@ const geometry = new BoxGeometry(BOX, BOX, BOX);const materials = COLOURS.map((color, k) => new MeshStandardMaterial({ name: `box${k}`, color, roughness: 0.7 }));const raycaster = new Raycaster();const boxes: Mesh[] = [];-let seen = 0, reported = 0, kicks = 0;+let clicks = 0, kicks = 0;/** A mesh that stands still: a fixed body, its collider from its geometry (a box for a box, else its triangles). */function fixed(name: string, mesh: Mesh, at: [number, number, number]): Mesh {@@ -49,13 +46,13 @@ function fixed(name: string, mesh: Mesh, at: [number, number, number]): Mesh {return mesh;}-export default defineGame<State>({- state: { clicks: 0, ray: null, reports: 0 },+export default defineGame({+ state: {},keys: { R: "report" },setup: () => {// (Setup may run again in one runtime, the playground's Stop: the boxes of the scene before are not this one's.)boxes.length = 0;- [seen, reported, kicks] = [0, 0, 0];+ [clicks, kicks] = [0, 0];const scene = new Scene();const sun = new DirectionalLight(0xffffff, 90000);sun.setSunAngles(50, 215);@@ -76,16 +73,12 @@ export default defineGame<State>({scene.add(ground, wall, ramp, rock);return { scene, camera, options: { name: "physics-hello", width: CAMERA.width, height: CAMERA.height, preset: "cinematic" as const } };},- frame(f) {- if (f.snap) {- // (The state was set, not changed: nothing to act on.)- seen = f.state.clicks;- reported = f.state.reports;- }- if (f.state.clicks !== seen && f.state.ray) {- seen = f.state.clicks;- const origin = new Vector3(...f.state.ray.origin), direction = new Vector3(...f.state.ray.direction);- raycaster.set(origin, direction);+ on: {+ click(world, ev: Click) {+ if (!ev.ray) return;+ const click = ++clicks;+ const direction = new Vector3(...ev.ray.direction);+ raycaster.set(new Vector3(...ev.ray.origin), direction);const hit = raycaster.intersectPhysics()[0];if (hit && hit.object.physics?.type === "fixed" && hit.normal) {// Something that stands still: a new box off its surface. In the scene, it has its body.@@ -93,31 +86,20 @@ export default defineGame<State>({box.name = `box${boxes.length}`;box.position.copy(hit.point).addScaledVector(hit.normal, OFF);box.physics = { type: "dynamic", density: DENSITY };- f.scene.add(box);+ world.scene.add(box);boxes.push(box);- console.log(`hello ${JSON.stringify({ click: seen, add: box.name, on: hit.object.name, at: box.position.toArray() })}`);+ console.log(`hello ${JSON.stringify({ click, add: box.name, on: hit.object.name, at: box.position.toArray() })}`);} else if (hit) {// A box: kicked along the ground, away from the camera.const push = new Vector3(direction.x, 0, direction.z).normalize().multiplyScalar(KICK * DENSITY * BOX ** 3);hit.object.applyImpulse(push);kicks++;- console.log(`hello ${JSON.stringify({ click: seen, kick: hit.object.name, from: hit.object.position.toArray(), impulse: push.toArray() })}`);- } else console.log(`hello ${JSON.stringify({ click: seen, miss: true })}`);- }- if (f.state.reports !== reported) {- reported = f.state.reports;+ console.log(`hello ${JSON.stringify({ click, kick: hit.object.name, from: hit.object.position.toArray(), impulse: push.toArray() })}`);+ } else console.log(`hello ${JSON.stringify({ click, miss: true })}`);+ },+ report() {const row = (o: Object3D) => ({ name: o.name, at: o.position.toArray().map((v) => Math.round(v * 1e4) / 1e4), speed: Math.round(o.getLinearVelocity().length() * 1e3) / 1e3, asleep: o.sleeping });console.log(`report ${JSON.stringify({ boxes: boxes.map(row), kicks })}`);- }- },- handlers: {- click(tx, ev: { ray?: State["ray"] }) {- tx.decide(!!ev.ray, "a click without its view ray");- tx.state.ray = ev.ray!;- tx.state.clicks++;- },- report(tx) {- tx.state.reports++;},},});diff --git a/packages/gameplay/src/frame.ts b/packages/gameplay/src/frame.tsindex 0c3c5a1..1c8ee7b 100644--- a/packages/gameplay/src/frame.ts+++ b/packages/gameplay/src/frame.ts@@ -73,21 +73,31 @@ export class FrameRunner<S> {return this.ids.get(id);}+ /** Seconds since the scene started on this node (what `f.time` is in the frame script). */+ get clock(): number {+ return this.time;+ }++ /** The committed state as a read-only snapshot, made anew per commit or replaced state (scene code cannot corrupt+ * the store). */+ committed(): Readonly<S> {+ if (this.frozen?.seq !== this.store.seq || this.frozen.src !== this.store.state) {+ this.frozen = { seq: this.store.seq, src: this.store.state, state: deepFreeze(structuredClone(this.store.state)) as Readonly<S> };+ }+ return this.frozen.state;+ }+/** The frame script's clock set to `time` (s): a render of the game at that moment (`seek` in node-host.ts). */seek(time: number): void {this.time = Math.max(time, 0);}run(dt: number, now: number, snap = false): void {- if (!this.fn) return;+ // (The clock runs without a frame script too: world handlers read it.)dt = Math.min(Math.max(dt, 0), 0.1);this.time += dt;- // Read-only snapshot of the committed state, refreshed per commit or replaced state (frame code cannot corrupt- // the store).- if (this.frozen?.seq !== this.store.seq || this.frozen.src !== this.store.state) {- this.frozen = { seq: this.store.seq, src: this.store.state, state: deepFreeze(structuredClone(this.store.state)) as Readonly<S> };- }- this.fn({ time: this.time, dt, snap, now, state: this.frozen.state, scene: this.scene, camera: this.camera, object: (id) => this.object(id), random: this.random });+ if (!this.fn) return;+ this.fn({ time: this.time, dt, snap, now, state: this.committed(), scene: this.scene, camera: this.camera, object: (id) => this.object(id), random: this.random });}}diff --git a/packages/gameplay/src/game.ts b/packages/gameplay/src/game.tsindex 3379d3a..11f1946 100644--- a/packages/gameplay/src/game.ts+++ b/packages/gameplay/src/game.ts@@ -7,6 +7,7 @@ import { hashString, seededRandom, withDeterminism } from "./random.ts";import { applyCommitted, canonicalJson, createStore, worldHash, type JsonObject, type Write, type World } from "./store.ts";import type { FrameFn } from "./frame.ts";import { isFailure, Transaction, type EmittedEvent, type GameEvent, type RenderRequest, type Snapshot } from "./tx.ts";+import type { WorldHandler } from "./world.ts";export interface SetupContext {roomId: string;@@ -41,29 +42,44 @@ export interface GameDefinition<S = JsonObject> {* matches the state. Never committed or replayed (see frame.ts).*/frame?: FrameFn<S>;- /** Keyboard shortcuts of the native viewer and the playground: key ("R", "Space") -> handler. */+ /**+ * World handlers, by event type (world.ts): run on the node that owns the scene and the physics world as the event+ * arrives, so they can change the scene at once (`world.scene.add(mesh)`, a ray, an impulse). An event may have a+ * handler, a world handler, or both (the world handler first).+ */+ on?: Record<string, WorldHandler<S>>;+ /** Keyboard shortcuts of the native viewer and the playground: key ("R", "Space") -> handler or world handler. */keys?: Record<string, string>;}+/** What `defineGame` takes: a game, whose `handlers` may be left out when it has world handlers (`on`) only. */+export type GameInput<S = JsonObject> = Omit<GameDefinition<S>, "handlers"> & Partial<Pick<GameDefinition<S>, "handlers">>;+/** `keys`, defaulting to the conventional L / R / V shortcuts for handlers with those names. */export function gameKeys(game: GameDefinition<unknown>): Record<string, string> {if (game.keys) return { ...game.keys };const conventional: Record<string, string> = { L: "lights", R: "rain", V: "viewpoint" };- return Object.fromEntries(Object.entries(conventional).filter(([, h]) => typeof game.handlers[h] === "function"));+ return Object.fromEntries(Object.entries(conventional).filter(([, h]) => typeof game.handlers[h] === "function" || typeof game.on?.[h] === "function"));}-export function defineGame<S>(game: GameDefinition<S>): GameDefinition<S> {- if (!game || typeof game.setup !== "function") throw new TypeError("defineGame: setup(ctx) is required");+export function defineGame<S>(input: GameInput<S>): GameDefinition<S> {+ if (!input || typeof input.setup !== "function") throw new TypeError("defineGame: setup(ctx) is required");+ if (input.on !== undefined && (!input.on || typeof input.on !== "object")) throw new TypeError("defineGame: on must be an object of world handlers");+ for (const [type, h] of Object.entries(input.on ?? {})) if (typeof h !== "function") throw new TypeError(`defineGame: world handler "${type}" is not a function`);+ // (A game of world handlers only needs no `handlers`: none are made for it here.)+ if (input.handlers === undefined && input.on) input.handlers = {};+ const game = input as GameDefinition<S>;if (!game.handlers || typeof game.handlers !== "object") throw new TypeError("defineGame: handlers are required");for (const [type, h] of Object.entries(game.handlers)) if (typeof h !== "function") throw new TypeError(`defineGame: handler "${type}" is not a function`);if (game.frame !== undefined && typeof game.frame !== "function") throw new TypeError("defineGame: frame must be a function");- for (const [key, h] of Object.entries(game.keys ?? {})) if (!game.handlers[h]) throw new TypeError(`defineGame: key "${key}" maps to unknown handler "${h}"`);+ for (const [key, h] of Object.entries(game.keys ?? {})) if (!game.handlers[h] && !game.on?.[h]) throw new TypeError(`defineGame: key "${key}" maps to unknown handler "${h}"`);if (canonicalJson(game.state) !== canonicalJson(JSON.parse(JSON.stringify(game.state ?? {})))) throw new TypeError("defineGame: state must be plain JSON");return game;}-export function describeGame(game: GameDefinition<unknown>): { handlers: string[]; tick: boolean; frame: boolean; keys: Record<string, string>; seed: number | null } {- return { handlers: Object.keys(game.handlers), tick: typeof game.tick === "function", frame: typeof game.frame === "function", keys: gameKeys(game), seed: game.seed ?? null };+/** What a game has: `handlers` are the state's (a room runs them), `on` the world's (the node that owns the scene). */+export function describeGame(game: GameDefinition<unknown>): { handlers: string[]; on: string[]; tick: boolean; frame: boolean; keys: Record<string, string>; seed: number | null } {+ return { handlers: Object.keys(game.handlers), on: Object.keys(game.on ?? {}), tick: typeof game.tick === "function", frame: typeof game.frame === "function", keys: gameKeys(game), seed: game.seed ?? null };}/** The room's seed: the game's, else derived from the room id. */@@ -102,7 +118,11 @@ export function executeEvent(game: GameDefinition<unknown>, snapshot: Snapshot,const handler: Handler<unknown> | undefined =game.handlers[event.type] ?? (event.type === "tick" && tick ? (t, p) => tick(t, Number(p?.dt) || 0) : undefined);const empty = { writes: [], emits: [], renders: [] };- if (!handler) return { status: "error", reads: {}, ...empty, failure: `no handler for event type "${event.type}"` };+ if (!handler) {+ // (A room runs handlers only: an event that has a world handler alone has nothing to run here.)+ const why = game.on?.[event.type] ? `"${event.type}" has a world handler (on) only: it runs on the node that owns the scene, not as a state transaction` : `no handler for event type "${event.type}"`;+ return { status: "error", reads: {}, ...empty, failure: why };+ }try {withDeterminism(event.ts, tx.random, () => {const r: unknown = handler(tx, structuredClone(event.payload));diff --git a/packages/gameplay/src/index.ts b/packages/gameplay/src/index.tsindex 3a7528b..d6b699c 100644--- a/packages/gameplay/src/index.ts+++ b/packages/gameplay/src/index.ts@@ -3,7 +3,9 @@ export { FrameRunner } from "./frame.ts";export type { FrameContext, FrameFn } from "./frame.ts";export { installNodeHost } from "./node-host.ts";export type { NodeHost } from "./node-host.ts";-export type { ExecResult, GameDefinition, Handler, LogEntry, SetupContext, SetupResult, VerifyReport } from "./game.ts";+export type { ExecResult, GameDefinition, GameInput, Handler, LogEntry, SetupContext, SetupResult, VerifyReport } from "./game.ts";+export { runWorldHandler } from "./world.ts";+export type { WorldContext, WorldHandler } from "./world.ts";export { Failure, isFailure, normalizeRenderRequest, Transaction } from "./tx.ts";export type { EmittedEvent, GameEvent, RenderRequest, Snapshot } from "./tx.ts";export {diff --git a/packages/gameplay/src/node-host.ts b/packages/gameplay/src/node-host.tsindex 131c2c6..19c3e85 100644--- a/packages/gameplay/src/node-host.ts+++ b/packages/gameplay/src/node-host.ts@@ -4,7 +4,8 @@// publishes the entry points the renderer calls as `globalThis.__threert`://// setup(roomId, seed?) build the scene (deterministic per seed), bind it, show the initial state-// event(type, payload, ts) this node is the authority (local play): run the handler + follow-ups, commit+// event(type, payload, ts) this node is the authority (local play): run the event's world handler (`on`,+// world.ts: it changes the scene at once), then its handler + follow-ups, commit// commit(writes, seq) the room is the authority: apply its committed state writes// setState(state, seq) replace the state (a render of a room's current state)// state() the committed state and its sequence number@@ -23,6 +24,7 @@ import {import { buildScene, describeGame, executeEvent, gameKeys, initialWorld, type GameDefinition } from "./game.ts";import { FrameRunner } from "./frame.ts";import { applyCommitted, commit, createStore, type Json, type JsonObject, type Store, type Write } from "./store.ts";+import { runWorldHandler } from "./world.ts";export interface NodeHost {describe(): string;@@ -76,13 +78,30 @@ export function installNodeHost(game: GameDefinition<unknown>, engine?: Engine):},event(type, payload, ts) {- const { store } = live();+ const { store, frames, binding } = live();const writes: Write[] = [];const log: string[] = [];- const queue: { type: string; payload: Json }[] = [{ type, payload: JSON.parse(payload) as Json }];+ const first = { type, payload: JSON.parse(payload) as Json, id: ++eventId };+ const queue: { type: string; payload: Json; id?: number }[] = [];+ // The event's world handler (world.ts), on the state as committed before the event; then its handler, if it has+ // one (an event with neither is the error it was), then the state events the world handler emitted.+ const on = game.on?.[type];+ const transacts = typeof game.handlers[type] === "function" || (type === "tick" && typeof game.tick === "function");+ if (!on || transacts) queue.push(first);+ if (on) {+ const r = runWorldHandler(on, frames, store.seed, { id: first.id, type, payload: first.payload, ts });+ log.push(r.error === undefined ? `✓ ${type} (world)` : `✗ ${type} (world): error ${r.error.split("\n")[0]}`);+ queue.push(...r.emits);+ }+ // An event of a world handler alone changed no state: the engine follows the scene as the handler left it (also+ // when it threw: the world does not stop), and the frame script has nothing new to show.+ if (!queue.length) {+ binding.sync();+ return JSON.stringify({ writes, log, seq: store.seq });+ }while (queue.length) {const ev = queue.shift()!;- const res = executeEvent(game, store, { id: ++eventId, type: ev.type, payload: ev.payload, ts });+ const res = executeEvent(game, store, { id: ev.id ?? ++eventId, type: ev.type, payload: ev.payload, ts });if (res.status === "error") {log.push(`✗ ${ev.type}: error ${res.failure?.split("\n")[0]}`);continue;diff --git a/packages/gameplay/src/world.ts b/packages/gameplay/src/world.tsnew file mode 100644index 0000000..1b0ff3f--- /dev/null+++ b/packages/gameplay/src/world.ts@@ -0,0 +1,101 @@+// World handlers: `on[type](world, ev)`. An event's handler that runs on the node that owns the scene and the physics+// world (node-host.ts), not in a room, so it can change the scene at once: cast a ray, `world.scene.add(mesh)`, kick a+// body. It is the node's counterpart of `handlers` (a transaction on the game state, which a room may run) and of+// `frame` (the scene as a function of the state, every frame):+//+// on: {+// click(world, ev) {+// raycaster.set(ev.ray.origin, ev.ray.direction);+// const hit = raycaster.intersectPhysics()[0];+// if (!hit) return;+// const box = new Mesh(geometry, wood);+// box.position.copy(hit.point).addScaledVector(hit.normal, 1.5);+// box.physics = "dynamic";+// world.scene.add(box);+// world.emit("placed", { by: ev.player }); // a state transaction: handlers.placed+// },+// },+//+// - When: as the event arrives, synchronously, before the engine's next physics tick. What it changed in the scene+// goes to the engine through the scene binding when it returns (the one way out for every change of the scene: the+// frame script's and the editor's go the same way), without a commit and without running `frame` again.+// - With `handlers[type]` too: the world handler runs first, on the state as committed before the event; then the+// handler's transaction, and after it the events the world handler emitted, in order. A room that is the authority+// runs `handlers` on its own, so neither may depend on the other having run.+// - `world.emit(type, payload)` starts a state transaction (`handlers[type]`, as `tx.emit` does from a handler): on+// this node when it is the authority, as it is wherever world handlers run today.+// - Synchronous, as handlers are: no await. `Math.random` and `Date` are the event's (`world.random`, `world.now`).+// - A world handler that throws does not stop the world: what it had changed is synced, the event's handler and the+// engine's next tick run all the same, and the error is in the event's log.+// - Where they do not run: in a room. A node that follows a room gets committed state (`commit`, `setState`), not+// events, so its world handlers never run; an event with only a world handler sent to a room is an error there+// (game.ts `executeEvent`). Who owns the physics when a room is the authority is not decided.+// - What they add is not in the game state: a state restored on another node (`setState`, a render of a room's state)+// does not have it. Their changes all pass through the scene binding, which is where they will be logged and+// replayed from (ROADMAP § 6 step 9).++import type { Object3D, PerspectiveCamera, Scene } from "@threert/scene";+import type { FrameRunner } from "./frame.ts";+import { seededRandom, withDeterminism } from "./random.ts";+import type { GameEvent } from "./tx.ts";+import type { Json } from "./store.ts";++export interface WorldContext<S> {+ /** The scene `setup` built, and its camera. Change it: the engine follows when the handler returns. */+ readonly scene: Scene;+ readonly camera: PerspectiveCamera;+ /** Last committed game state (read-only): as it was before this event's own handler, if it has one. */+ readonly state: Readonly<S>;+ /** Seconds since the scene started on this node (the frame script's clock). */+ readonly time: number;+ /** The event's time, ms since the epoch (`Date.now()` in the handler is this too). */+ readonly now: number;+ /** Object by id (or name) as setup assigned it. */+ object(id: string): Object3D | undefined;+ /** Random stream of this event (seeded from the room seed and the event; `Math.random` in the handler is this). */+ random(): number;+ /** Starts a state transaction: `handlers[type]` runs with `payload` after this handler and the event's own. */+ emit(type: string, payload?: unknown): void;+}++/** A world handler: receives a copy of the event payload. Must be synchronous. */+// eslint-disable-next-line @typescript-eslint/no-explicit-any+export type WorldHandler<S> = (world: WorldContext<S>, ev: any) => void;++/** The random stream of a world handler's event (the transaction of the same event has stream `event.id`). */+const WORLD_STREAM = 0x40000000;++/**+ * Runs `on[event.type]` on this node. Returns the state events it emitted and its error, if it threw (what it had+ * emitted before is dropped with it, as a failed transaction's emits are).+ */+export function runWorldHandler<S>(handler: WorldHandler<S>, frames: FrameRunner<S>, seed: number, event: GameEvent): { emits: { type: string; payload: Json }[]; error?: string } {+ const emits: { type: string; payload: Json }[] = [];+ const random = seededRandom(seed, (event.id + WORLD_STREAM) >>> 0);+ const world: WorldContext<S> = {+ scene: frames.scene,+ camera: frames.camera,+ state: frames.committed(),+ time: frames.clock,+ now: event.ts,+ object: (id) => frames.object(id),+ random,+ emit(type, payload = {}) {+ if (typeof type !== "string" || !type) throw new TypeError("emit: event type must be a non-empty string");+ const text = JSON.stringify(payload) as string | undefined;+ if (text === undefined) throw new TypeError(`emit(${type}): the payload must be plain JSON`);+ emits.push({ type, payload: JSON.parse(text) as Json });+ },+ };+ try {+ withDeterminism(event.ts, random, () => {+ const r: unknown = handler(world, structuredClone(event.payload));+ if (typeof (r as PromiseLike<unknown> | undefined)?.then === "function") {+ throw new Error("world handlers must be synchronous: the engine's next tick does not wait for an await");+ }+ });+ return { emits };+ } catch (e) {+ return { emits: [], error: e instanceof Error ? (e.stack ?? e.message) : String(e) };+ }+}diff --git a/packages/gameplay/test/world.test.ts b/packages/gameplay/test/world.test.tsnew file mode 100644index 0000000..d3702dd--- /dev/null+++ b/packages/gameplay/test/world.test.ts@@ -0,0 +1,267 @@+// World handlers (`on`, src/world.ts): an event's handler that runs on the node that owns the scene, so it changes the+// scene at once. What it sends to the engine and when, how it lives with `handlers` and `frame`, its context, what a+// throw does, and where it does not run.+import { test } from "node:test";+import assert from "node:assert/strict";+import { BoxGeometry, Mesh, MeshStandardMaterial, PerspectiveCamera, Raycaster, RecordingEngine, Scene, Vector3, type ObjectDesc } from "@threert/scene";+import { createStore, defineGame, executeEvent, initialWorld, type GameDefinition, type WorldContext } from "../src/index.ts";+import * as gameplay from "../src/index.ts";++// (The package's entry points take a game of any state: `GameDefinition<unknown>`.)+type AnyGame = GameDefinition<unknown>;+const installNodeHost = <S>(g: GameDefinition<S>, engine?: RecordingEngine) => gameplay.installNodeHost(g as AnyGame, engine);+const describeGame = <S>(g: GameDefinition<S>) => gameplay.describeGame(g as AnyGame);+const gameKeys = <S>(g: GameDefinition<S>) => gameplay.gameKeys(g as AnyGame);++const kinds = (calls: [string, ...unknown[]][]) => calls.map((c) => c[0]);+const box = new BoxGeometry(0.5, 0.5, 0.5);+const wood = new MeshStandardMaterial({ name: "wood", color: 0x8a6a4a });++function scene() {+ const scene = new Scene(), camera = new PerspectiveCamera(50, 16 / 9);+ camera.position.set(0, 1, 5);+ const ground = new Mesh(new BoxGeometry(10, 0.1, 10), wood);+ ground.id = "ground";+ scene.add(camera, ground);+ return { scene, camera };+}++interface S { score: number; placed: string[]; seenByFrame: number }++/** A click adds a box (and emits "placed"); "score" is a handler; "both" has a world handler and a handler. */+function game(over: Partial<Parameters<typeof defineGame<S>>[0]> = {}) {+ const trace: string[] = [];+ let boxes = 0;+ const g = defineGame<S>({+ seed: 7,+ state: { score: 0, placed: [], seenByFrame: 0 },+ setup: scene,+ on: {+ click(world, ev: { at?: [number, number, number]; emit?: boolean }) {+ const b = new Mesh(box, wood);+ b.id = `box_${boxes++}`;+ b.position.set(...(ev.at ?? [0, 1, 0]));+ world.scene.add(b);+ trace.push(`on.click score ${world.state.score}`);+ if (ev.emit) world.emit("score", { points: 2 });+ },+ both(world) {+ trace.push(`on.both score ${world.state.score}`);+ (world.object("ground") as Mesh).power = 0.5;+ world.emit("score", { points: 10 });+ },+ },+ handlers: {+ score(tx, ev: { points: number }) {+ tx.state.score += ev.points;+ trace.push(`handlers.score ${tx.state.score}`);+ },+ both(tx) {+ tx.state.score += 1;+ trace.push(`handlers.both ${tx.state.score}`);+ },+ },+ ...over,+ });+ return { g, trace };+}++test("a world handler changes the scene as the event arrives: no commit, no frame script run for it", () => {+ let frames = 0;+ const { g, trace } = game({ frame: () => void frames++ });+ assert.deepEqual(describeGame(g).on, ["click", "both"]);+ assert.deepEqual(describeGame(g).handlers, ["score", "both"], "handlers are the state's, as before");+ const engine = new RecordingEngine();+ const host = installNodeHost(g, engine);+ assert.deepEqual(JSON.parse(host.describe()).on, ["click", "both"], "the renderer's input path sees them");+ host.setup("node");+ engine.take();+ const ran = frames;+ const r = JSON.parse(host.event("click", JSON.stringify({ at: [1, 2, 3] }), 1000));+ // The box is in the engine when the event returns: its geometry (the first of its kind), the object and its place;+ // no state write, no new sequence number.+ const calls = engine.take();+ assert.deepEqual(kinds(calls), ["geometry", "object", "transform"]);+ assert.equal((calls[1][2] as ObjectDesc).name, "box_0");+ assert.deepEqual((calls[2][2] as number[]).slice(0, 3), [1, 2, 3]);+ assert.deepEqual([r.writes, r.seq, r.log], [[], 0, ["✓ click (world)"]]);+ assert.equal(frames, ran, "the state did not change: the frame script is not run again");+ assert.deepEqual(trace, ["on.click score 0"]);+ // It may start a state transaction: the handler runs after it, commits, and the frame script shows the new state.+ const e = JSON.parse(host.event("click", JSON.stringify({ emit: true }), 1000));+ assert.deepEqual([e.writes.map((w: { path: string }) => w.path), e.seq], [["state/score"], 1]);+ assert.equal(JSON.parse(host.state()).state.score, 2);+ assert.equal(frames, ran + 1);+ assert.deepEqual(trace.slice(1), ["on.click score 0", "handlers.score 2"]);+ assert.deepEqual(kinds(engine.take()), ["object", "transform"]);+});++test("an event with a world handler and a handler: the world handler first, on the state before; then the handler, then what it emitted", () => {+ const { g, trace } = game();+ const engine = new RecordingEngine();+ const host = installNodeHost(g, engine);+ host.setup("node");+ engine.take();+ const r = JSON.parse(host.event("both", "{}", 0));+ assert.deepEqual(trace, ["on.both score 0", "handlers.both 1", "handlers.score 11"]);+ assert.equal(r.seq, 2, "two transactions: the event's own and the emitted one");+ assert.equal(r.log[0], "✓ both (world)");+ assert.deepEqual(kinds(engine.take()), ["power"], "what the world handler changed in the scene, sent once");+ // The state it reads is read-only, and is the committed one.+ const g2 = defineGame<S>({ state: { score: 5, placed: [], seenByFrame: 0 }, setup: scene, on: { poke(world) { (world.state as S).score = 99; } } });+ const h2 = installNodeHost(g2, new RecordingEngine());+ h2.setup("node");+ assert.match(JSON.parse(h2.event("poke", "{}", 0)).log[0], /✗ poke \(world\): error .*read only|✗ poke \(world\): error/);+ assert.equal(JSON.parse(h2.state()).state.score, 5);+});++test("a game of world handlers only: no handlers to write, keys map to them, an unknown event is still an error", () => {+ const g = defineGame<Record<string, never>>({ state: {}, setup: scene, on: { click() {}, lights() {} }, keys: { Space: "click" } });+ assert.deepEqual(g.handlers, {});+ assert.deepEqual(gameKeys(g), { Space: "click" });+ assert.deepEqual(gameKeys(defineGame({ state: {}, setup: scene, on: { lights() {} } })), { L: "lights" }, "the conventional shortcuts find world handlers too");+ assert.throws(() => defineGame({ state: {}, setup: scene, on: { click() {} }, keys: { K: "kick" } }), /unknown handler "kick"/);+ assert.throws(() => defineGame({ state: {}, setup: scene, on: { click: 1 as never } }), /world handler "click" is not a function/);+ assert.throws(() => defineGame({ state: {}, setup: scene } as never), /handlers are required/, "a game without either is still refused");+ const host = installNodeHost(g, new RecordingEngine());+ host.setup("node");+ assert.match(JSON.parse(host.event("nope", "{}", 0)).log[0], /✗ nope: error no handler for event type "nope"/);+});++test("the world handler's context: the scene, the frame clock, the event's time and its own random stream", () => {+ const seen: { time: number; now: number; date: number; random: number[]; math: number; ground: boolean; camera: boolean }[] = [];+ const g = defineGame<Record<string, never>>({+ seed: 11,+ state: {},+ setup: scene,+ on: {+ look(world: WorldContext<Record<string, never>>) {+ seen.push({ time: world.time, now: world.now, date: Date.now(), random: [world.random(), world.random()], math: Math.random(), ground: world.object("ground") === world.scene.children[1], camera: world.camera === world.scene.children[0] });+ },+ },+ });+ const run = () => {+ seen.length = 0;+ const host = installNodeHost(g, new RecordingEngine());+ host.setup("node");+ host.event("look", "{}", 5000);+ // (The clock runs without a frame script: the renderer calls `frame` for a game with world handlers.)+ for (let k = 0; k < 30; k++) host.frame(1 / 60, 0);+ host.event("look", "{}", 6000);+ return structuredClone(seen);+ };+ const a = run(), b = run();+ assert.deepEqual(a, b, "the same events on the same seed draw the same numbers");+ assert.deepEqual([a[0].time, a[0].now, a[0].date], [0, 5000, 5000]);+ assert.ok(Math.abs(a[1].time - 0.5) < 1e-9 && a[1].now === 6000, `${a[1].time}`);+ assert.ok(a[0].ground && a[0].camera);+ assert.notDeepEqual(a[0].random, a[1].random, "each event has its own stream");+ assert.ok(a[0].random.every((x) => x >= 0 && x < 1) && a[0].math >= 0 && a[0].math < 1 && !a[0].random.includes(a[0].math), "Math.random is the stream too");+});++test("a world handler that throws does not stop the world: its changes are synced, the event's handler runs, the error is in the log", () => {+ const trace: string[] = [];+ const g = defineGame<{ n: number }>({+ state: { n: 0 },+ setup: scene,+ on: {+ spawn(world, ev: { fail?: boolean }) {+ const b = new Mesh(box, wood);+ b.id = `box_${trace.length}`;+ world.scene.add(b);+ world.emit("count", {});+ trace.push("on.spawn");+ if (ev.fail) throw new Error("spawn failed");+ },+ later: (async () => {}) as never,+ },+ handlers: {+ spawn(tx) {+ tx.state.n += 1;+ },+ count(tx) {+ tx.state.n += 100;+ },+ },+ });+ const engine = new RecordingEngine();+ const host = installNodeHost(g, engine);+ host.setup("node");+ engine.take();+ const r = JSON.parse(host.event("spawn", JSON.stringify({ fail: true }), 0));+ assert.equal(r.log[0], "✗ spawn (world): error Error: spawn failed");+ // The box it added before it threw is in the engine; the event's own handler ran (a room would have run it too);+ // what it emitted went with it.+ assert.deepEqual(kinds(engine.take()), ["geometry", "object", "transform"]);+ assert.equal(JSON.parse(host.state()).state.n, 1);+ // The next event is as any other.+ const ok = JSON.parse(host.event("spawn", "{}", 0));+ assert.equal(ok.log[0], "✓ spawn (world)");+ assert.equal(JSON.parse(host.state()).state.n, 102);+ assert.deepEqual(kinds(engine.take()), ["object", "transform"]);+ assert.match(JSON.parse(host.event("later", "{}", 0)).log[0], /✗ later \(world\): error Error: world handlers must be synchronous/);+});++test("world handlers do not run in a room: an event with only one is an error there, and committed state runs none", () => {+ const { g, trace } = game();+ // What a room does with an event: a transaction.+ const r = executeEvent(g as AnyGame, createStore(initialWorld(g as AnyGame), 7), { id: 1, type: "click", payload: {}, ts: 0 });+ assert.equal(r.status, "error");+ assert.match(r.failure!, /"click" has a world handler \(on\) only: it runs on the node that owns the scene/);+ assert.equal(executeEvent(g as AnyGame, createStore(initialWorld(g as AnyGame), 7), { id: 1, type: "both", payload: {}, ts: 0 }).status, "ok", "an event with both: the room runs its handler");+ assert.deepEqual(trace.splice(0), ["handlers.both 1"], "and not its world handler");+ // A node that follows a room: it gets the room's writes and states, not events.+ const engine = new RecordingEngine();+ const host = installNodeHost(g, engine);+ host.setup("node");+ engine.take();+ host.commit(JSON.stringify([{ path: "state/score", value: 3 }]), 1);+ host.setState(JSON.stringify({ score: 9, placed: [], seenByFrame: 0 }), 2);+ assert.deepEqual(trace, []);+ assert.deepEqual(engine.take(), []);+});++/** The recording engine with a physics world's calls recorded (and a ray answered from a table). */+class PhysicsEngine extends RecordingEngine {+ answer: unknown = null;+ override physics(op: string, args: object): string {+ this.calls.push(["physics", op, args]);+ return JSON.stringify(op === "ray" ? this.answer : null);+ }+ physicsPoses(): Float32Array {+ return new Float32Array(0);+ }+}++test("queries and the scene's queue: a handler's changes reach the engine when it returns, so the next event's query sees them and its own does not", () => {+ const raycaster = new Raycaster();+ const g = defineGame<Record<string, never>>({+ state: {},+ setup() {+ const s = scene();+ (s.scene.children[1] as Mesh).physics = "fixed";+ return s;+ },+ on: {+ click(world) {+ const b = new Mesh(box, wood);+ b.physics = "dynamic";+ world.scene.add(b);+ // Asked in the same handler: the box is in the scene, not yet in the engine.+ raycaster.set(world.camera.position, new Vector3(0, -1, 0));+ raycaster.intersectPhysics();+ },+ },+ });+ const engine = new PhysicsEngine();+ const host = installNodeHost(g, engine);+ host.setup("node");+ engine.take();+ const ops = () => (engine.take().filter((c) => c[0] === "physics") as [string, string][]).map((c) => c[1]);+ assert.deepEqual(JSON.parse(host.event("click", "{}", 0)).log, ["✓ click (world)"]);+ assert.deepEqual(ops(), ["ray", "body", "collider"], "the handler's own query comes before its box has a body");+ // The next event, with no frame (no tick) between: its query is asked of an engine that has the first box, which+ // the engine's queries see without a tick (physics-core: queries_see_what_the_calls_left_without_a_tick).+ host.event("click", "{}", 0);+ assert.deepEqual(ops(), ["ray", "body", "collider"]);+});diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.tsindex ee03a65..3ad24e4 100644--- a/packages/scene/src/core.ts+++ b/packages/scene/src/core.ts@@ -173,7 +173,8 @@ function physicsCommand(c: PhysicsCommand): void {physicsQueue.push(c);}-/** @internal A query answered now, against the world as of its last tick; null where there is no engine. */+/** @internal A query answered now, against the world as the engine has it (what was synced, with or without a tick+ * since); null where there is no engine. */export function physicsQuery(op: "state" | "ray" | "overlap" | "sweep" | "contacts" | "hash", args: Record<string, unknown> = {}): unknown {return physicsEngine ? JSON.parse(physicsEngine.physics(op, args)) : null;}diff --git a/packages/scene/src/raycaster.ts b/packages/scene/src/raycaster.tsindex f84fa72..549ce13 100644--- a/packages/scene/src/raycaster.ts+++ b/packages/scene/src/raycaster.ts@@ -6,7 +6,9 @@//// The physics world answers too (ROADMAP § 6 step 7): `Raycaster.intersectPhysics` is the ray against the colliders of// the objects with `physics`, in the engine (its tree of them, not a walk over triangles here), and `Shapecaster` asks-// what a shape overlaps or meets when moved. Both see the world as of its last tick.+// 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 { Box3, Matrix4, Quaternion, Ray, Vector2, Vector3 } from "./math.ts";import type { BufferGeometry } from "./geometry.ts";diff --git a/renderer/physics-core/src/bridge.rs b/renderer/physics-core/src/bridge.rsindex c8d4d40..b47c696 100644--- a/renderer/physics-core/src/bridge.rs+++ b/renderer/physics-core/src/bridge.rs@@ -408,7 +408,8 @@ impl Bridge {_ => Value::Null,}}- // Queries, against the world as of the last tick. {origin, direction, max?, skip?, all?}: the first hit (or+ // Queries, against the world as the calls left it (`Physics::fresh`: with or without a tick since).+ // {origin, direction, max?, skip?, all?}: the first hit (or// null), or with `all` every hit, nearest first."ray" => {let (o, d, max, skip) = (vec3(a, "origin", [0.0; 3])?, vec3(a, "direction", [0.0; 3])?, num(a, "max", 1e4)?, self.skip(a)?);@@ -804,9 +805,8 @@ mod tests {assert!(s.at[&2].0[2] > 1.05, "pushed: {:?}", s.at[&2].0);}- /// Queries report the caller's ids and the scene objects (the world as of the last tick: a collider is seen from- /// the tick after it was added); a force acts through one frame's ticks only; contacts come in the order they- /// happened with their bodies.+ /// Queries report the caller's ids and the scene objects (a collider is seen as soon as it is added, before any+ /// tick); a force acts through one frame's ticks only; contacts come in the order they happened with their bodies.#[test]fn queries_forces_and_contacts() {let (mut b, mut s) = (Bridge::default(), scene());@@ -814,9 +814,11 @@ mod tests {// (Weightless, so it stays where the queries expect it.)b.call(&mut s, "body", &json!({ "id": 7, "object": 2, "gravityScale": 0 })).unwrap();b.call(&mut s, "collider", &json!({ "id": 70, "body": 7, "shape": { "type": "box", "halfExtents": [0.25, 0.25, 0.25] }, "events": true })).unwrap();- assert!(b.call(&mut s, "ray", &json!({ "origin": [0, 10, 0], "direction": [0, -1, 0] })).unwrap().is_null(), "before a tick");+ // (A query sees what the calls made, before any tick, and the same after one.)+ let before = b.call(&mut s, "ray", &json!({ "origin": [0, 10, 0], "direction": [0, -1, 0] })).unwrap();run(&mut b, &mut s, 1);let h = b.call(&mut s, "ray", &json!({ "origin": [0, 10, 0], "direction": [0, -1, 0] })).unwrap();+ assert_eq!((before["collider"].as_u64(), before["distance"].as_f64().map(|d| (d * 1e4).round())), (Some(70), Some(77500.0)), "before a tick: {before}");assert_eq!((h["collider"].as_u64(), h["body"].as_u64(), h["object"].as_u64()), (Some(70), Some(7), Some(2)));assert!((h["distance"].as_f64().unwrap() - 7.75).abs() < 1e-4 && h["normal"][1] == 1.0);let all = b.call(&mut s, "ray", &json!({ "origin": [0, 10, 0], "direction": [0, -1, 0], "all": true })).unwrap();diff --git a/renderer/physics-core/src/check.rs b/renderer/physics-core/src/check.rsindex 49b5490..6878502 100644--- a/renderer/physics-core/src/check.rs+++ b/renderer/physics-core/src/check.rs@@ -75,10 +75,18 @@ 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); 3] = [("convex hulls", 400), ("bodies of several colliders", 400), ("joints with limits and motors", 200)];+pub const KINDS: [(&str, u32); 4] = [+ ("convex hulls", 400),+ ("bodies of several colliders", 400),+ ("joints with limits and motors", 200),+ // The rest of what a game's calls reach (docs/ROADMAP.md § 6 step 9 has the upstream list of platform math calls+ // 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),+];/// The hash of all the cases (`cases()`) with `enhanced-determinism`, natively and in wasm32 alike.-pub const EXPECTED_CASES: u64 = 0x9e16_a677_1fa8_f317;+pub const EXPECTED_CASES: u64 = 0x6fd1_eba4_551b_8d39;/// A generator of integers only: a float made from one is exact arithmetic, the same bits on every platform.struct Rng(u64);@@ -116,6 +124,8 @@ pub fn case(kind: u32, seed: u32) -> u64 {p.add_collider(None, &ColliderDesc { position: [0.0, -0.5, 0.0], ..ColliderDesc::new(Shape::Box([50.0, 0.5, 50.0])) }).unwrap();let body = |p: &mut Physics, r: &mut Rng, at: [f32; 3]| p.add_body(&BodyDesc { position: at, rotation: r.quat(), linvel: r.v3(2.0), angvel: r.v3(10.0), ..Default::default() }).unwrap();let hull = |r: &mut Rng| Shape::ConvexHull((0..8).map(|_| r.v3(0.5)).collect());+ // (Kind 3's kinematic body: where it is driven, and how it is turned.)+ let mut pusher: Option<(BodyId, [f32; 3], [f32; 4])> = None;match kind {// Two tumbling hulls of 8 random points that meet over the ground.0 => {@@ -137,7 +147,7 @@ pub fn case(kind: u32, seed: u32) -> u64 {p.add_collider(Some(b), &ColliderDesc { position: r.v3(0.5), density: r.range(200.0, 3000.0), ..ColliderDesc::new(Shape::Sphere(r.range(0.1, 0.4))) }).unwrap();}// A box hinged to a post (limits, a motor) and a hull on a slider and a rope, all turned at random.- _ => {+ 2 => {let post = p.add_body(&BodyDesc { kind: BodyKind::Fixed, position: [0.0, 3.0, 0.0], rotation: r.quat(), ..Default::default() }).unwrap();let a = body(&mut p, &mut r, [1.0, 3.0, 0.0]);p.add_collider(Some(a), &ColliderDesc::new(Shape::Box([r.range(0.2, 0.6), r.range(0.1, 0.3), r.range(0.2, 0.6)]))).unwrap();@@ -149,12 +159,67 @@ 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();}+ // 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.+ _ => {+ let n = 9u32;+ let vertices: Vec<[f32; 3]> = (0..n * n).map(|k| [(k % n) as f32 - 4.0, 0.3 + 0.15 * r.unit(), (k / n) as f32 - 4.0]).collect();+ let indices: Vec<[u32; 3]> = (0..(n - 1) * (n - 1)).flat_map(|k| { let a = k / (n - 1) * n + k % (n - 1); [[a, a + n, a + 1], [a + 1, a + n, a + n + 1]] }).collect();+ p.add_collider(None, &ColliderDesc::new(Shape::Trimesh { vertices, indices })).unwrap();+ for k in 0..3 {+ let b = p.add_body(&BodyDesc { position: [k as f32 - 1.0 + 0.3 * r.unit(), 4.0 + k as f32, 0.3 * r.unit()], linvel: [r.unit() * 5.0, r.range(-60.0, -30.0), r.unit() * 5.0], angvel: r.v3(10.0), ccd: true, ..Default::default() }).unwrap();+ let shape = if k == 1 { Shape::Box([r.range(0.05, 0.15), r.range(0.05, 0.15), r.range(0.05, 0.15)]) } else { Shape::Sphere(r.range(0.05, 0.15)) };+ p.add_collider(Some(b), &ColliderDesc { restitution: r.range(0.0, 0.8), ..ColliderDesc::new(shape) }).unwrap();+ }+ pusher = Some((p.add_body(&BodyDesc { kind: BodyKind::Kinematic, position: [-3.0, 0.8, 0.0], ..Default::default() }).unwrap(), [r.range(1.0, 3.0), 0.0, r.unit()], r.quat()));+ p.add_collider(pusher.map(|x| x.0), &ColliderDesc::new(Shape::Box([0.3, 0.3, 0.6]))).unwrap();+ let a = body(&mut p, &mut r, [0.0, 2.0, 2.0]);+ p.add_collider(Some(a), &ColliderDesc::new(Shape::Box([0.3, 0.2, 0.3]))).unwrap();+ let b = body(&mut p, &mut r, [0.7, 2.0, 2.0]);+ p.add_collider(Some(b), &ColliderDesc::new(Shape::Box([0.2, 0.3, 0.2]))).unwrap();+ p.add_joint(a, b, &JointDesc::Fixed { anchor1: r.v3(0.4), anchor2: r.v3(0.4) }).unwrap();+ let post = p.add_body(&BodyDesc { kind: BodyKind::Fixed, position: [2.0, 3.0, -2.0], ..Default::default() }).unwrap();+ let c = body(&mut p, &mut r, [2.0, 2.4, -2.0]);+ p.add_collider(Some(c), &ColliderDesc::new(Shape::Capsule { half_height: r.range(0.1, 0.4), radius: r.range(0.1, 0.2) })).unwrap();+ p.add_joint(post, c, &JointDesc::Spherical { anchor1: r.v3(0.2), anchor2: [0.0, 0.5, 0.0] }).unwrap();+ }}let mut h = 0u64;- for t in 0..90 {+ let mut fold = |x: u64| h = (h ^ x).wrapping_mul(0x0000_0100_0000_01b3);+ for t in 0..90u32 {+ if let Some((b, v, q)) = pusher {+ let s = (t + 1) as f32 * crate::TICK;+ p.set_kinematic_target(b, [-3.0 + v[0] * s, 0.8, v[2] * s], q).unwrap();+ }p.step();if t % 10 == 9 {- h = (h ^ p.hash()).wrapping_mul(0x0000_0100_0000_01b3);+ fold(p.hash());+ 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`).+ let at = [r.unit() * 3.0, 6.0, r.unit() * 3.0];+ for pass in 0..2 {+ for hit in [p.cast_ray(at, [r.unit() * 0.3, -1.0, r.unit() * 0.3], 20.0, None).unwrap(), p.sweep(&Shape::Sphere(0.2), at, [0.0, 0.0, 0.0, 1.0], [0.0, -1.0, 0.0], 20.0, None).unwrap()] {+ match hit {+ 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),+ }+ }+ for c in p.overlap(&Shape::Box([1.0, 0.5, 1.0]), [at[0], 0.6, at[2]], r.quat(), None).unwrap() {+ fold(c as u64);+ }+ if pass == 0 {+ if let Some((b, _, q)) = pusher {+ p.set_pose(b, [at[0], 1.0, at[2]], q).unwrap();+ }+ }+ }+ }}}h@@ -204,4 +269,15 @@ mod tests {let ((s, c), (ls, lc)) = (degree.sin_cos(), libm::sincosf(degree));assert_eq!((s.to_bits(), c.to_bits()), (ls.to_bits(), lc.to_bits()));}++ /// 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]+ fn a_trimesh_has_no_pseudo_normals() {+ use rapier3d::prelude::{SharedShape, TriMeshFlags, Vector};+ let s = SharedShape::trimesh(vec![Vector::new(0.0, 0.0, 0.0), Vector::new(1.0, 0.0, 0.0), Vector::new(0.0, 0.0, 1.0)], vec![[0, 2, 1]]).unwrap();+ let mesh = s.as_trimesh().unwrap();+ assert!(mesh.flags().is_empty() && mesh.pseudo_normals().is_none(), "{:?}", mesh.flags());+ assert!(!mesh.flags().intersects(TriMeshFlags::ORIENTED | TriMeshFlags::FIX_INTERNAL_EDGES));+ }}diff --git a/renderer/physics-core/src/robustness.rs b/renderer/physics-core/src/robustness.rsindex 93c2ec7..2d19401 100644--- a/renderer/physics-core/src/robustness.rs+++ b/renderer/physics-core/src/robustness.rs@@ -370,6 +370,57 @@ fn the_hash_takes_one_nan() {assert_eq!(hash_bits(-0.0), (-0.0f32).to_bits(), "only NaNs are made one");}+/// A query sees the world as the calls left it, with or without a tick since. (The broad phase is the last step's: it+/// had no collider added since, and had a body moved by "pose" where it was, so a ray met it there and missed it+/// where it is. Two events that arrive with no tick between them are the case: the second one's query must see what+/// the first one added.)+#[test]+fn queries_see_what_the_calls_left_without_a_tick() {+ let (mut b, mut s) = world();+ ok(&mut b, &mut s, "collider", json!({ "id": 1000, "position": [0, -0.5, 0], "shape": { "type": "box", "halfExtents": [50, 0.5, 50] } }));+ let ray = |x: f64| json!({ "origin": [x, 9, 0], "direction": [0, -1, 0], "all": true });+ let ball = |x: f64| json!({ "shape": sphere(0.4), "position": [x, 9, 0], "direction": [0, -1, 0] });+ // What the queries answer: the colliders a ray down at x passes through with their distances, the first one's+ // normal, what a 0.4 m ball overlaps at (x, 2, 0), and what a ball lowered from 9 m meets, where and how far.+ let seen = |b: &mut Bridge, s: &mut Objects, x: f64| -> Value {+ let r = ok(b, s, "ray", ray(x));+ let first = ok(b, s, "ray", json!({ "origin": [x, 9, 0], "direction": [0, -1, 0] }));+ let o = ok(b, s, "overlap", json!({ "shape": sphere(0.4), "position": [x, 2, 0] }));+ let w = ok(b, s, "sweep", ball(x));+ let round = |v: &Value| (v.as_f64().unwrap() * 1e3).round() / 1e3;+ json!({+ "ray": r.as_array().unwrap().iter().map(|h| json!([h["collider"], round(&h["distance"])])).collect::<Vec<_>>(),+ "first": [first["collider"], first["body"], round(&first["normal"][1])],+ "overlap": o.as_array().unwrap().iter().map(|h| h["collider"].clone()).collect::<Vec<_>>(),+ "sweep": [w["collider"], round(&w["distance"]), round(&w["point"][1]), round(&w["normal"][1])],+ })+ };+ // A static collider, then a body with a box and a ball on top of it: seen at once, and the same after a tick.+ let ground = json!({ "ray": [[1000, 9.0]], "first": [1000, null, 1.0], "overlap": [], "sweep": [1000, 8.6, 0.0, 1.0] });+ assert_eq!(seen(&mut b, &mut s, 0.0), ground);+ ok(&mut b, &mut s, "body", json!({ "id": 1, "position": [0, 2, 0], "gravityScale": 0 }));+ ok(&mut b, &mut s, "collider", json!({ "id": 1, "body": 1, "shape": { "type": "box", "halfExtents": [0.5, 0.5, 0.5] } }));+ ok(&mut b, &mut s, "collider", json!({ "id": 2, "body": 1, "position": [0, 0.75, 0], "shape": sphere(0.25) }));+ let there = json!({ "ray": [[2, 6.0], [1, 6.5], [1000, 9.0]], "first": [2, 1, 1.0], "overlap": [1], "sweep": [2, 5.6, 3.0, 1.0] });+ assert_eq!(seen(&mut b, &mut s, 0.0), there);+ assert_eq!(ok(&mut b, &mut s, "ray", json!({ "origin": [0, 9, 0], "direction": [0, -1, 0], "skip": 1 }))["collider"], 1000, "its own ray passes through it");+ run(&mut b, &mut s, 1);+ assert_eq!(seen(&mut b, &mut s, 0.0), there);+ // Moved by a call (turned upside down too: the ball is under the box now): it is where it was put, not where it was.+ ok(&mut b, &mut s, "pose", json!({ "body": 1, "position": [5, 2, 0], "rotation": [1, 0, 0, 0] }));+ let moved = json!({ "ray": [[1, 6.5], [2, 7.5], [1000, 9.0]], "first": [1, 1, 1.0], "overlap": [1], "sweep": [1, 6.1, 2.5, 1.0] });+ assert_eq!(seen(&mut b, &mut s, 0.0), ground);+ assert_eq!(seen(&mut b, &mut s, 5.0), moved);+ run(&mut b, &mut s, 1);+ assert_eq!(seen(&mut b, &mut s, 0.0), ground);+ assert_eq!(seen(&mut b, &mut s, 5.0), moved);+ // Removed: gone at once (as it was before).+ ok(&mut b, &mut s, "remove", json!({ "collider": 2 }));+ ok(&mut b, &mut s, "pose", json!({ "body": 1, "position": [5, 2, 0] }));+ ok(&mut b, &mut s, "remove", json!({ "body": 1 }));+ assert_eq!(seen(&mut b, &mut s, 5.0), ground);+}+/// A small generator of integers (the fuzz below is the same on every machine).struct Rng(u64);diff --git a/renderer/physics-core/src/world.rs b/renderer/physics-core/src/world.rsindex 8bed8dc..14d3b48 100644--- a/renderer/physics-core/src/world.rs+++ b/renderer/physics-core/src/world.rs@@ -345,6 +345,11 @@ pub struct Physics {contacts_dropped: u64,/// What was taken out of the world after a tick, and why (`take_faults`).faults: Vec<Fault>,+ /// Colliders the broad phase does not have right until the next step: those added since the last one (it does not+ /// have them at all) and those of bodies moved by `set_pose` (it has them where they were). Queries leave them+ /// out of the broad phase's answer and test them one by one where they are, so a query sees the world as the+ /// calls left it, with or without a tick since.+ fresh: std::collections::BTreeSet<ColliderId>,}impl Default for Physics {@@ -371,6 +376,7 @@ impl Physics {contacts: Default::default(),contacts_dropped: 0,faults: vec![],+ fresh: Default::default(),}}@@ -434,6 +440,7 @@ impl Physics {let jointed = self.world.impulse_joints.attached_joints(h).next().is_some();self.world.remove_body_with_colliders(h, true);for c in &gone {+ self.fresh.remove(c);if let Some((_, data)) = self.colliders.remove(c) {self.shape_data -= data;}@@ -479,6 +486,7 @@ impl Physics {let h = self.world.insert_collider(c.user_data(id as u128), parent);self.colliders.insert(id, (h, data));self.shape_data += data;+ self.fresh.insert(id);Ok(id)}@@ -486,6 +494,7 @@ impl Physics {if let Some((h, data)) = self.colliders.remove(&id) {self.world.remove_collider(h);self.shape_data -= data;+ self.fresh.remove(&id);}}@@ -606,6 +615,8 @@ impl Physics {pub fn step(&mut self) {self.world.step_with_events(&(), &self.events);self.ticks += 1;+ // (The broad phase has every collider where it is now.)+ self.fresh.clear();for e in self.events.0.lock().unwrap().drain(..) {// (A removed collider's contact ends without it: its id is no longer known.)let id = |h: ColliderHandle| self.world.colliders.get(h).map(|c| c.user_data as u32);@@ -717,9 +728,12 @@ impl Physics {pub fn set_pose(&mut self, id: BodyId, position: [f32; 3], rotation: [f32; 4]) -> Result<(), String> {within(&position, MAX_COORD, "a body's position")?;let p = pose(position, rotation)?;- if let Some(b) = self.body_mut(id) {- b.set_position(p, true);- }+ let Some(&h) = self.bodies.get(&id) else { return Ok(()) };+ let b = &mut self.world.bodies[h];+ b.set_position(p, true);+ // (Until the next step the broad phase has its colliders where they were: `fresh`.)+ let moved: Vec<ColliderId> = b.colliders().iter().filter_map(|&c| self.world.colliders.get(c)).map(|c| c.user_data as u32).collect();+ self.fresh.extend(moved);Ok(())}@@ -802,18 +816,30 @@ impl Physics {Some(Hit { collider, body, distance, point: point.to_array(), normal: normal.to_array() })}- /// The first collider a ray meets within `max` metres (the world as of the last step). `skip`: a body whose- /// colliders the ray passes through (the one that casts it).+ /// The first collider a ray meets within `max` metres, in the world as the calls left it (`fresh`). `skip`: a body+ /// whose colliders the ray passes through (the one that casts it).pub fn cast_ray(&self, origin: [f32; 3], direction: [f32; 3], max: f32, skip: Option<BodyId>) -> Result<Option<Hit>, String> {let Some((ray, max)) = Self::ray(origin, direction, max)? else { return Ok(None) };- let Some((h, i)) = self.world.cast_ray_and_get_normal(&ray, max, true, self.filter(skip)) else { return Ok(None) };- Ok(self.hit(h, i.time_of_impact, ray.point_at(i.time_of_impact), i.normal))+ let settled = |_: ColliderHandle, c: &Collider| !self.fresh.contains(&(c.user_data as u32));+ 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));+ }+ }+ Ok(best)}/// Every collider a ray passes through within `max` metres, nearest first, at most `limit` of them.pub fn cast_ray_all(&self, origin: [f32; 3], direction: [f32; 3], max: f32, skip: Option<BodyId>, limit: usize) -> Result<Vec<Hit>, String> {let Some((ray, max)) = Self::ray(origin, direction, max)? else { return Ok(vec![]) };- let mut hits: Vec<Hit> = self.world.intersect_ray(ray, max, true, self.filter(skip)).filter_map(|(h, _, i)| self.hit(h, i.time_of_impact, ray.point_at(i.time_of_impact), i.normal)).collect();+ let settled = |_: ColliderHandle, c: &Collider| !self.fresh.contains(&(c.user_data as u32));+ 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));+ }+ }// (Equal distances in collider order: the same answer on every machine.)hits.sort_by(|a, b| a.distance.total_cmp(&b.distance).then(a.collider.cmp(&b.collider)));hits.truncate(limit);@@ -839,10 +865,44 @@ impl Physics {shape.shared()}- fn filter(&self, skip: Option<BodyId>) -> QueryFilter<'_> {- match skip.and_then(|b| self.bodies.get(&b)) {+ /// A query's filter over the broad phase: without `skip`'s colliders, and without the fresh ones (`settled`), which+ /// the query tests itself.+ fn filter<'a>(&self, skip: Option<BodyId>, settled: &'a impl Fn(ColliderHandle, &Collider) -> bool) -> QueryFilter<'a> {+ let f = match skip.and_then(|b| self.bodies.get(&b)) {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() {+ f+ } else {+ f.predicate(settled)+ }+ }++ /// The fresh colliders a query tests itself (not `skip`'s), each where it is now: on a body, at the body's pose+ /// (its own world pose is the last step's until the next).+ fn fresh(&self, skip: Option<BodyId>) -> impl Iterator<Item = (ColliderHandle, &Collider, Pose)> {+ let skip = skip.and_then(|b| self.bodies.get(&b)).copied();+ self.fresh.iter().filter_map(move |id| {+ let h = self.colliders.get(id)?.0;+ let c = self.world.colliders.get(h)?;+ if !c.is_enabled() || (skip.is_some() && c.parent() == skip) {+ return None;+ }+ let at = match (c.parent().and_then(|p| self.world.bodies.get(p)), c.position_wrt_parent()) {+ (Some(b), Some(local)) => *b.position() * *local,+ _ => *c.position(),+ };+ Some((h, c, at))+ })+ }++ /// The nearer of two hits (equal distances: the lower collider id).+ fn nearer(a: Option<Hit>, b: Option<Hit>) -> Option<Hit> {+ match (a, b) {+ (Some(a), Some(b)) => Some(if b.distance.total_cmp(&a.distance).then(b.collider.cmp(&a.collider)).is_lt() { b } else { a }),+ (a, b) => a.or(b),}}@@ -850,7 +910,14 @@ impl Physics {pub fn overlap(&self, shape: &Shape, position: [f32; 3], rotation: [f32; 4], skip: Option<BodyId>) -> Result<Vec<ColliderId>, String> {let s = Self::query_shape(shape)?;within(&position, MAX_COORD, "a query's position")?;- let mut out: Vec<ColliderId> = self.world.intersect_shape(pose(position, rotation)?, &*s.0, self.filter(skip)).map(|(_, c)| c.user_data as u32).collect();+ let p = pose(position, rotation)?;+ let settled = |_: ColliderHandle, c: &Collider| !self.fresh.contains(&(c.user_data as u32));+ let mut out: Vec<ColliderId> = self.world.intersect_shape(p, &*s.0, self.filter(skip, &settled)).map(|(_, c)| c.user_data as u32).collect();+ for (_, c, at) in self.fresh(skip) {+ if rapier3d::parry::query::intersection_test(&p, &*s.0, &at, c.shape()).is_ok_and(|i| i.intersecting) {+ out.push(c.user_data as u32);+ }+ }out.sort_unstable();Ok(out)}@@ -861,8 +928,16 @@ impl Physics {let p = pose(position, rotation)?;let Some((ray, max)) = Self::ray(position, direction, max)? else { return Ok(None) };let options = ShapeCastOptions { max_time_of_impact: max, target_distance: 0.0, stop_at_penetration: true, compute_impact_geometry_on_penetration: true };- let Some((h, hit)) = self.world.cast_shape(&p, ray.dir, &*s.0, options, self.filter(skip)) else { return Ok(None) };- Ok(self.hit(h, hit.time_of_impact, hit.witness1, hit.normal1))+ let settled = |_: ColliderHandle, c: &Collider| !self.fresh.contains(&(c.user_data as u32));+ let mut best = self.world.cast_shape(&p, ray.dir, &*s.0, options, self.filter(skip, &settled)).and_then(|(h, hit)| self.hit(h, hit.time_of_impact, hit.witness1, hit.normal1));+ for (h, c, at) in self.fresh(skip) {+ // (As the broad phase's answer: the collider is the first shape, and what is its own is moved to the world.)+ if let Ok(Some(hit)) = rapier3d::parry::query::cast_shapes(&at, Vector::ZERO, c.shape(), &p, ray.dir, &*s.0, options) {+ let hit = hit.transform1_by(&at);+ best = Self::nearer(best, self.hit(h, hit.time_of_impact, hit.witness1, hit.normal1));+ }+ }+ Ok(best)}/// Tests only: the body's velocity made infinite behind the world's checks (as only Rapier itself could), so thatdiff --git a/renderer/src/main.rs b/renderer/src/main.rsindex e219743..328b9c2 100644--- a/renderer/src/main.rs+++ b/renderer/src/main.rs@@ -392,11 +392,12 @@ fn render_live(slot: &mut Option<gpu::Gpu>, job: &Job, presets: &Path, frames: ufor _ in 0..frames.max(1) {core.advance_time(1.0 / 60.0);let swayed = host.world.borrow_mut().apply_sway(core.scene_time());- if host.has_frame() {+ // (`frames`: also a game of world handlers, and a scene with bodies: its listeners get their events.)+ if host.frames() {host.frame(1.0 / 60.0)?;}let physics = host.advance_physics(1.0 / 60.0);- if host.has_frame() || swayed || physics {+ if host.frames() || swayed || physics {core.commit(&mut host.world.borrow_mut())?;}core.render(1, |_, _| {});diff --git a/renderer/src/physics.rs b/renderer/src/physics.rsindex 0ee1d8a..ebc2c3a 100644--- a/renderer/src/physics.rs+++ b/renderer/src/physics.rs@@ -190,6 +190,28 @@ mod tests {assert_eq!(format!("{:016x}", check::cases()), format!("{:016x}", check::EXPECTED_CASES));}+ /// Two events with no tick between them: the body the first one's script added is in the engine once that script+ /// returned (the binding's sync), and the second one's ray meets it, though the world has not stepped since.+ #[test]+ fn a_query_sees_a_body_added_since_the_last_tick() {+ let mut w = world();+ w.set_object(1, "box".into(), None, Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();+ w.set_transform(1, Vec3::new(0.0, 2.0, 0.0), Quat::IDENTITY, Vec3::ONE).unwrap();+ let mut p = PhysicsWorld::default();+ let ray = json!({ "origin": [0, 9, 0], "direction": [0, -1, 0] });+ p.call(&mut w, "gravity", &json!({ "gravity": [0, -9.81, 0] })).unwrap();+ p.advance(&mut w, 1.0 / 60.0);+ assert!(p.call(&mut w, "ray", &ray).unwrap().is_null());+ // The first event's sync.+ p.call(&mut w, "body", &json!({ "id": 1, "object": 1, "slot": 0 })).unwrap();+ p.call(&mut w, "collider", &json!({ "id": 1, "body": 1, "shape": { "type": "box", "halfExtents": [0.5, 0.5, 0.5] } })).unwrap();+ // The second event's query, no `advance` between.+ let hit = p.call(&mut w, "ray", &ray).unwrap();+ assert_eq!((hit["object"].as_u64(), hit["body"].as_u64()), (Some(1), Some(1)), "{hit}");+ assert!((hit["distance"].as_f64().unwrap() - 6.5).abs() < 1e-4, "{hit}");+ assert_eq!(p.take_stats().ticks, 1);+ }+/// A force applied before a live run (in setup) acts in its first frame's tick: settling at time 0 makes no tick/// and does not end it (a frame without a tick does).#[test]diff --git a/renderer/src/script.rs b/renderer/src/script.rsindex 41efd95..ed266d3 100644--- a/renderer/src/script.rs+++ b/renderer/src/script.rs@@ -469,8 +469,18 @@ impl ScriptHost {self.info["keys"][key].as_str().map(String::from)}+ /// The game handles events of this type: with a handler (a transaction on the state) or a world handler (`on`:+ /// it changes the scene on this node; packages/gameplay/src/world.ts).pub fn has_handler(&self, name: &str) -> bool {- self.info["handlers"].as_array().is_some_and(|h| h.iter().any(|x| x == name))+ ["handlers", "on"].iter().any(|k| self.info[k].as_array().is_some_and(|h| h.iter().any(|x| x == name)))+ }++ /// The node host runs every frame (`frame`): the game has a frame script, or world handlers (they read the+ /// frame clock), or the scene has a physics world (its contacts and the bodies that left the world are delivered+ /// to their listeners once a frame, whoever registered them: a frame script, a world handler or setup). A scene+ /// with none of them pays nothing.+ pub fn frames(&self) -> bool {+ self.has_frame() || self.info["on"].as_array().is_some_and(|h| !h.is_empty()) || self.physics.borrow().is_some()}/// Builds and binds the scene (deterministic for a room id / seed); returns the time it took, ms.@@ -710,7 +720,7 @@ impl GameSession {/// sync) that throws does not stop the world: the frame's physics ticks are made and what changed is committed all/// the same, then the error is returned (the window and `live` print it and go on).pub fn frame(&mut self, core: &mut crate::live::LiveCore, dt: f32) -> Result<bool> {- if !self.host.has_frame() {+ if !self.host.frames() {// Wind sway and the physics follow the scene time with or without a frame script.let swayed = self.host.world.borrow_mut().apply_sway(core.scene_time());if self.host.advance_physics(dt) || swayed {@@ -719,7 +729,10 @@ impl GameSession {return Ok(false);}let t = Instant::now();- core.set_time(self.clock.tick(dt));+ // (A frame script's clock is the game's; a game without one keeps the view's own time, as before.)+ if self.host.has_frame() {+ core.set_time(self.clock.tick(dt));+ }self.host.world.borrow_mut().apply_sway(core.scene_time());let scripted = self.host.frame(dt);self.js_ms = t.elapsed().as_secs_f32() * 1000.0;@@ -854,6 +867,57 @@ mod tests {assert!((z(&s) - 0.3).abs() < 1e-4, "{}", z(&s));}+ /// The input path knows a game's world handlers (`on`) as it knows its handlers, and the node host runs every+ /// frame for a game that has them, or whose scene has a physics world, though it has no frame script.+ #[test]+ fn world_handlers_and_the_frames_of_a_game_without_a_frame_script() {+ let plain = GAME.replace("handlers: [\"click\"], frame: true", "handlers: [\"hit\"], frame: false");+ assert!(plain.contains("frame: false"));+ let h = ScriptHost::new(&plain).unwrap();+ assert!(h.has_handler("hit") && !h.has_handler("click") && !h.has_frame() && !h.frames(), "a scene with no script to run a frame for");+ let on = plain.replace("handlers: [\"hit\"],", "handlers: [\"hit\"], on: [\"click\"],");+ let h = ScriptHost::new(&on).unwrap();+ assert!(h.has_handler("click") && h.has_handler("hit") && !h.has_handler("drag"));+ assert!(!h.has_frame() && h.frames(), "world handlers read the frame clock");+ // A physics world (made by the scene's first physics call): its events go to their listeners once a frame.+ let bodies = plain.replace("return \"{}\";", "__engine.physics('gravity', { gravity: [0, -9.81, 0] }); return \"{}\";");+ let h = ScriptHost::new(&bodies).unwrap();+ assert!(!h.frames());+ h.setup("room", None).unwrap();+ assert!(h.frames());+ }++ /// A game without a frame script whose scene has bodies: the node host's `frame` runs every frame all the same+ /// (it delivers the contacts and the bodies that left the world to their listeners), after which the physics+ /// ticks; a scene with neither has no script run for it. (Skipped without a GPU.)+ #[test]+ fn a_scene_with_bodies_gets_its_frames_without_a_frame_script() {+ for (physics, expected) in [(true, 3), (false, 0)] {+ let g = match crate::gpu::Gpu::new() {+ Ok(g) => g,+ Err(e) => return eprintln!("skipped: {e}"),+ };+ let mut game = GAME.replace("handlers: [\"click\"], frame: true", "handlers: [\"click\"], frame: false").replace(", map: 2 }", " }");+ if physics {+ game = game.replace("return \"{}\";", "__engine.physics('body', { id: 1, object: 4, gravityScale: 0, linvel: [0, 0, 6] }); __engine.physics('collider', { id: 1, body: 1, shape: { type: 'sphere', radius: 0.5 } }); return \"{}\";");+ }+ let bundle = std::env::temp_dir().join(format!("threert-no-frame-script-{}-{physics}.js", std::process::id()));+ std::fs::write(&bundle, game).unwrap();+ let started = GameSession::start(&bundle, "room", std::path::Path::new("."), g, &crate::default_presets_dir(), 64, 36);+ std::fs::remove_file(&bundle).ok();+ let (mut s, mut core) = started.unwrap();+ for _ in 0..3 {+ s.frame(&mut core, 1.0 / 60.0).unwrap();+ }+ let frames: i32 = s.host.call(100, |ctx| ctx.eval("frames")).unwrap();+ assert_eq!(frames, expected, "physics {physics}");+ if physics {+ let z = s.host.world.borrow().objects[&4].position.z;+ assert!((z - 0.3).abs() < 1e-4, "three ticks at 6 m/s: {z}");+ }+ }+ }+#[test]fn budgets_and_errors() {let h = ScriptHost::new(GAME).unwrap();diff --git a/renderer/third_party/glamx/PATCH.md b/renderer/third_party/glamx/PATCH.mdindex 00cd553..ecd00a8 100644--- a/renderer/third_party/glamx/PATCH.md+++ b/renderer/third_party/glamx/PATCH.md@@ -24,6 +24,21 @@ in other bits (`physics_core::check::cases`).- `src/lib.rs` allows unused imports (as a path dependency the crate's warnings show).+## Upstream++The same finding and the same kind of change are open upstream, not merged or released when this copy was made+(2026-11-10):++- dimforge/glamx issue #9, "SymmetricEigen3::eigenvalues calls platform acos/cos in std builds, breaking+ enhanced-determinism": https://github.com/dimforge/glamx/issues/9+- dimforge/glamx pull request #10, "Route eigenvalue trigonometry through ComplexField under std":+ https://github.com/dimforge/glamx/pull/10+- dimforge/rapier issue #1054 lists about twenty more platform math calls in Rapier and parry 0.36.1 / 0.31.1; which+ of them our worlds reach, and what is done about each, is in docs/ROADMAP.md § 6 step 9.++**Delete this copy and both `[patch.crates-io]` tables once a glamx release has the fix and Rapier uses it**; the+recorded hashes (`physics_core::check`) and `tools/physics-determinism.ts` say whether the release behaves the same.+## Every crate that is built must name the patch`[patch.crates-io]` only takes effect in the manifest of the crate (or workspace root) that cargo is building: a