Skip to content

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

In-place edits under software traversal: units, a top tree after the still scene's (ROADMAP § 6 step 7b) (#21)

Yujiadc370812544c
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 6359c45..c2063bb 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -3904,7 +3904,8 @@ benchmark level. The order follows the dependencies; a step that meets a further
bytes need not. Fixed in `bvh.rs` (a leaf of the empty vertex buffer's zero triangle), with a test that walks
the kernel's loop on the CPU. **Not confirmed as what hung**: the same sequence on a build without the fix,
with the guard, passed (both scenes alone, with the fix and the guard, give their tests' answers). And a **loop guard** (`merged::guard`): every loop of the kernel bounded and
- what it stops counted and read back; always on in a browser, `THREERT_LOOP_GUARD` natively.
+ what it stops counted and read back; always on in a browser, `THREERT_LOOP_GUARD` natively (since step 7b
+ a native kernel with units has it with nothing set).
- `tools/web-engine.ts` (CI): the module in Node with the page's `__engine` and the native bundle runs the
physics hello world's script to the native test's numbers.
- **In Chrome 157 on the machine's GPU** (`tools/web-hello.ts`, Playwright; docs/RUNTIME.md "Measured in a
@@ -3915,13 +3916,105 @@ benchmark level. The order follows the dependencies; a step that meets a further
1.13 s, 1.08 s of it the sky's bake on one thread; a kernel the browser has not compiled takes 1.4 s before
the first frame, 26 ms after that. Engine calls cost 40 ns (a scalar) to about a microsecond (a descriptor),
10,000 poses 0.3 ms. The module is 7.3 MiB (1.5 MiB with brotli).
- - Open, first: **a frame in which a body moves costs the page 16.7 ms, 16.4–16.6 of it the rebuild** (9.0
- natively under software traversal, nothing under hardware traversal): in-place edits under software
- traversal, the two-level tree, the next step. Then: the browser's image is not bit-identical to the native
- one (the guard changes the kernel's last bits; natively it is off and the catalog is byte-identical to main);
- 1.4 s for a kernel's first compile and 1.09 s of sky bake on the page's thread before the first frame; a
- scene larger than hello world in a browser, and the merged layout's cost on one natively; what hung on
+ - Open, first: **a frame in which a body moves costs the page 16.7 ms, 16.4–16.6 of it the rebuild** (9.0 natively
+ under software traversal, nothing under hardware traversal): in-place edits under software traversal, the
+ two-level tree, the next step (step 7b: 0.84 ms now, no rebuild). Then: the browser's image is not bit-identical
+ to the native one (the guard changes the kernel's last bits; natively it is off and the catalog is byte-identical
+ to main); 1.4 s for a kernel's first compile and 1.09 s of sky bake on the page's thread before the first frame;
+ a scene larger than hello world in a browser, and the merged layout's cost on one natively; what hung on
2026-11-11 is not confirmed; other browsers.
+7b. **[ThreeRT] In-place edits under software traversal (a two-level tree).** Decided by the user on 2026-11-11, before
+ step 8: a browser has no ray queries, and under software traversal every added object and every frame in which
+ a body moves rebuilds the scene (hello world in Chrome: 16.5 ms of the page's 16.7 a frame; the voxel level: 7 s an
+ explosion; its triangle data 2.1 GiB because instances are written out). Design: docs/RUNTIME.md "Software
+ traversal with units".
+ - The still scene stays one flat tree; what can move or be added (an instance of a mesh: a body's box, a voxel
+ chunk) is a unit with a tree of its own in model space, found through a top tree walked after the still one. A
+ scene without units gets the kernel it has today, byte for byte.
+ - Acceptance: the two walks transcribed to the CPU and run against brute force over random scenes and random
+ add / move / remove sequences (no read outside a range, always an end, the same closest hit), before any GPU
+ run; scenes without units unchanged (the sources handed to wgpu, the catalog's bytes); hello world's two checks
+ that fail under software traversal pass, and in Chrome a frame in which a body moves no longer rebuilds; the
+ voxel level under software traversal: triangle data, load, an explosion, a still frame; overlap measured on a
+ pile of debris.
+ - Every GPU run of the new walk has the loop guard, natively too (what hung on 2026-11-11 is not confirmed, so
+ another path that does not end may exist); whether software traversal has it by default natively is decided
+ with its measured cost.
+ - **Decided 2026-11-11, after the first GPU runs** (docs/RUNTIME.md "Software traversal with units"):
+ - **Units are a live session's and a browser's. An offline render under software traversal flattens every
+ instance by default**, its kernel and bytes main's; `THREERT_UNITS=1` gives it units, `THREERT_UNITS=0`
+ flattens a session. Why: the offline render under software traversal is the reference render and what the
+ catalog's byte gate compares, with no variable set; memory, load and edits in place are what a session and a
+ browser need; no catalog scene with models but Kabukichō has been rendered with units.
+ - **A native kernel with units has the loop guard with nothing set** (65,536; `THREERT_LOOP_GUARD=0` takes it
+ out). A native kernel without units has none by default, as before: no existing byte changes. What a stop
+ does is unchanged (an offline render fails, a session logs it, `test-render` fails the run). Whether all of
+ native software traversal has it by default is not part of this step.
+ - **Status: runs natively and in Chrome on the machine's GPU** (branch `sw-two-level`, 2026-11-11; every run with
+ the loop guard, which stopped nothing). The figures and their tables: docs/RUNTIME.md "Software traversal with
+ units", "Measured".
+ - Done: `renderer/src/units.rs` (mesh trees, the top tree, where they go in the node buffer, the checks made
+ where a tree is written), `shaders/trace_units.wgsl` (spliced into software traversal by a source feature,
+ `F_UNITS`; `pathtrace.wgsl` not edited), `prepare_live` keeping a session's instances as units (`prepare`,
+ an offline render's, flattens unless `THREERT_UNITS=1`), and the edits in place through `gpu::Top` (the TLAS
+ or the units), so `move_instances`, `update_instanced` and `edit_geometry` are one path under both
+ traversals. `THREERT_UNITS=0` flattens, as before. The guard's default for a kernel with units
+ (`gpu::loop_guard_of`).
+ - The acceptance:
+ - The CPU tests pass (the walks transcribed from the shaders and compared with their lines; random scenes
+ under random edits against brute force; a prepared scene with units against the same scene flattened;
+ broken and stale trees refused), before the first GPU run.
+ - Scenes without units: the sources handed to wgpu are main's (`the_default_sources_are_untouched`, hardware
+ traversal's among them); **offline with nothing said about units the catalog's 23 bundles are
+ byte-identical to main under software traversal** (both builds with the guard at 65,536, as every GPU run
+ here); under hardware traversal 18 are, and the other five (Bistro's three, Zero Day's two) differ from
+ main as two runs of main differ from each other ("Known issues": hardware traversal's ties).
+ - Hello world: `tools/physics-hello.ts` passes under software traversal with nothing else set (units and
+ the guard by default; it stopped nothing), the two checks that failed among them. In Chrome a frame in which a body moves costs the page **0.84 ms (was 16.7)** and none rebuilds the
+ scene (295 did); a click that adds a box commits in 0.6–0.8 ms (18–24) after the first.
+ - The voxel level under software traversal: triangle data **310.9 MiB (2,098)**, first frame after 5.2 s
+ (11.6), an explosion **2.5–4.5 ms in place (6.9–7.9 s)**; a still frame's trace **7.85 ms (4.58): 71 %
+ longer**.
+ - Kabukichō (352 units): triangle data 55 MiB (634), first frame 1.55 s (3.3); the trace 13.9 ms (12.0):
+ **16 % longer**, and with it the view misses 60 Hz on this machine (17.2 ms a frame).
+ - The guard on Kabukichō, main's kernel: +1.23 ms of trace (11 %); the merged layout +0.13 ms.
+ - The atomic tests under software traversal, as written and merged: 147 of 170 pass; the 23 that fail fail
+ on main's build too, with the same values: 13 `particles/*`, the 5 `gpu-particles/*`, `translucent/depth`,
+ `translucent/order`, `volume/lighting`, `volume/lighting-offline` (all particles, which software traversal
+ does not draw) and `surface/windows` (not explained). The names: docs/RUNTIME.md; "Known issues".
+ - Two faults the GPU runs found, fixed, each with a CPU test since: a scene of units alone drew a mesh's first
+ triangle at the origin (the still tree's leaf named triangle 0); a mesh written again in place kept its
+ units' old boxes (`voxel/cut-falls-live`: a falling part cut off).
+ - **Not run**, one by one (none was among the GPU runs agreed for this step; each is asked for before it is
+ made):
+ - a kernel with units without the loop guard (every run of one had it);
+ - a catalog scene with units, offline (`THREERT_UNITS=1`) or live, but Kabukichō;
+ - explosions on the voxel level until the edit room is full (V4): how many fit before a rebuild;
+ - a pile of debris (V5): overlap where it is worst;
+ - anything but hello world in a browser.
+ - Open:
+ - **First, what the next item is for: a still frame costs more with units** (software traversal, live,
+ 1280 × 720 traced at half, the guard on in both columns):
+
+ | scene | the trace, units / flat | frame GPU, units / flat | 60 Hz |
+ | --- | --- | --- | --- |
+ | hello world (natively) | 1.40–1.42 / 1.01–1.04 ms, **+37 %** | Chrome: 6.59 / 6.60 ms | held by both |
+ | the voxel level | 7.85 / 4.58 ms, **+71 %** | 11.2 / 7.9 ms | held by both |
+ | Kabukichō | 13.88 / 12.01 ms, **+16 %** | 17.18 / 15.35 ms | **missed with units** (a frame every 17.2–17.5 ms; flat 16.65) |
+
+ Against main's session on Kabukichō under software traversal (flat, no guard: 14.11 ms of GPU a frame) the
+ default now is 3.1 ms more, 1.2 of it the guard. Nothing was tuned: the top tree is built by median splits,
+ every unit's ray is transformed, and every ray enters the top tree. An SAH top tree and a path for units
+ whose transform is the identity are the first things to try; until then a session that only stands still
+ is cheaper flattened (`THREERT_UNITS=0`), at its memory and load time.
+ - The edit room and the tree ranges do not grow under software traversal: an edit that finds them full
+ rebuilds the scene (seen: 1,100 instances added to a room of 1,024 records). How many explosions that is
+ on the level is not measured.
+ - Procedural edits, posed models and rigid groups' poses still rebuild under software traversal; a scene
+ with more than 2^18 instances is flattened, as before.
+ - Whether all of native software traversal has the loop guard by default (not this step's; it costs 11 % of
+ Kabukichō's trace, and what hung on 2026-11-11 is still not confirmed).
+ - The 23 atomic tests that fail under software traversal on main ("Known issues"): the other line's.
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.
@@ -3979,6 +4072,24 @@ benchmark level. The order follows the dependencies; a step that meets a further
## Known issues
+- Under software traversal 23 of the 170 atomic tests fail (found 2026-11-11 in § 6 step 7b, the first whole run of
+ the suite under software traversal; main `a707e1c`'s build and the step's, as written and in the merged layout,
+ the same ids and values; not fixed: the rendering line's). Hardware traversal passes all 170.
+ - 20 are particles, which software traversal does not draw (they stay collapsed at the pivot,
+ docs/MATERIAL_FUNCTIONS.md): 13 `particles/*`, the 5 `gpu-particles/*`, `translucent/depth`, `translucent/order`.
+ - `volume/lighting` and `volume/lighting-offline` read 6 for 1. Basis: both measure one translucent particle in a
+ closed cube with one 6-nit wall behind it (their features are `particles`, `translucency`); without the particle
+ the region is the wall. The same missing particles, in a family whose name does not say so.
+ - `surface/windows` reads 0.3934 for 0.4234 (−7 %, tolerance 3 %); `surface/windows-mirror` beside it passes.
+ Basis: the scene is one plane with the library's facade windows and no instance, so nothing of step 7b is in
+ its kernel (the source is main's byte for byte), and main's build reads the same 0.3934 in both layouts. The
+ cause was not looked for.
+- Offline renders of `bistro`, `bistro-slice`, `bistro-district`, `zero-day` and `zero-day-animated` are not the same
+ bytes twice under hardware traversal (measured 2026-11-11 in § 6 step 7b's merge gate; the last entry here has
+ Bistro's ties between coincident surfaces at 2–4 %). Main `a707e1c` against itself, 320 × 180, 4 spp: 1,782 /
+ 1,095 / 125 / 7,988 / 10,426 of 57,600 pixels differ; the catalog's other 18 bundles repeat exactly, and software
+ traversal repeats all 23. So hardware traversal's byte identity on these five says nothing; software traversal's
+ is the gate.
- Emissive quads under masked decals of the same shape went black with hardware ray tracing (found 2026-11-08 by the
unbiasedness check, `tools/unbiased-check.ts`; fixed the same day, branch `coplanar-flatten`).
- Zero Day against the software BVH (16384 spp, 320 × 180, raw HDR): one 4 × 4 region 0.966, another 0.978, at every
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 30ea183..9dbdf1e 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -370,9 +370,10 @@ tree (ROADMAP § 6).
not bit-identical to the kernel's without the guard: the compiler arranges the arithmetic of the functions it is in
differently (hello world, one sample: 354 of 43,200 numbers differ, by at most 2 × 10⁻⁷ of their value). What it
stops it counts: the count is read back without waiting (`LiveCore::guard_trips`, the page's `guardTrips()`, the frame log), an offline
- render in which it moved is an error, and anything but 0 means wrong pixels. Natively it is off unless
- `THREERT_LOOP_GUARD=<limit>`. The live passes need none: their loops are counted loops over constants and clamped
- parameters.
+ render in which it moved is an error, and anything but 0 means wrong pixels. Natively `THREERT_LOOP_GUARD=<limit>`
+ sets it; with nothing set a kernel with units has it (65,536; `THREERT_LOOP_GUARD=0` takes it out) and every other
+ kernel has none, as before ("Software traversal with units"). The live passes need none: their loops are counted
+ loops over constants and clamped parameters.
- **A tree over nothing** (`bvh.rs`). A node with `count: 0` is an interior node to the kernel, and the one-node tree
of a scene without triangles had itself and the bytes after its buffer for children. It is now a leaf of triangle
0, which an empty vertex buffer's zeros make a triangle without area; a procedural object without boxes is left out
@@ -380,10 +381,11 @@ tree (ROADMAP § 6).
**that it is what kept the two dispatches from returning is not confirmed**: the sequence that hung, run again on
a build without the fix and with the guard, passed (the bytes after the buffer ended the walk that time; a hang
needs them to be a box the ray meets and a count or child indices that do not end).
-- **What a browser does not have.** Hardware ray queries, so software traversal: no particles of either kind, no
- translucency pass, and no in-place edits (every added object and every frame a body moves rebuilds the scene; the
- two-level tree is the step after this one). The denoiser (OIDN, offline only), the offline render, snapshots and
- the profile's readbacks. The dynamic sky's bake thread (a sky whose sun moves keeps the sky it was built with).
+- **What a browser does not have.** Hardware ray queries, so software traversal: no particles of either kind and no
+ translucency pass. Edits in place it has had since the step after this one, for model instances ("Software
+ traversal with units" below; before it every added object and every frame a body moved rebuilt the scene). The
+ denoiser (OIDN, offline only), the offline render, snapshots and the profile's readbacks. The dynamic sky's bake
+ thread (a sky whose sun moves keeps the sky it was built with).
Checked without a GPU:
- `tools/web-engine.ts` (CI): the module in Node (V8), `__engine` made by the page's code, the game bundle, the
@@ -393,10 +395,13 @@ Checked without a GPU:
### Measured in a browser (2026-11-11)
+This section is the build before units (every instance flattened). With units a frame in which a body moves costs
+the page 0.84 ms and none rebuilds the scene: "Software traversal with units", "Measured", below.
+
Three things first:
-- **A frame in which a rigid body moves costs the page 16.7 ms, 16.4–16.6 of it rebuilding the scene** (p50; natively
- under software traversal 9.0 ms, under hardware traversal nothing). The CPU side alone fills a 60 fps frame. It is
- what the next step, in-place edits under software traversal, is for.
+- **A frame in which a rigid body moves cost the page 16.7 ms, 16.4–16.6 of it rebuilding the scene** (p50; natively
+ under software traversal 9.0 ms, under hardware traversal nothing). The CPU side alone filled a 60 fps frame. It
+ is what the next step, in-place edits under software traversal, was for.
- **The browser's image is not bit-identical to the native one.** A browser's kernel has the loop guard, and the
kernel with the guard differs from the kernel without it in the last bits (rounding: 354 of 43,200 numbers of a
one-sample hello world, by at most 2 × 10⁻⁷ of their value). Natively the guard is off by default, so native
@@ -484,10 +489,253 @@ run-to-run spread (GPU ms a frame p50, each twice: as written 8.0, 6.9; merged 6
**Size:** the module 7.34 MiB (gzip 2.28 MiB, brotli 1.51 MiB; no `wasm-opt`), wasm-bindgen's JavaScript and the
page's 105 KiB (brotli 17 KiB), hello world's bundle 230 KiB (brotli 53 KiB).
-**Not measured:** any scene but hello world in a browser; the merged layout's and the guard's cost on a scene whose
-trace is the frame (Kabukichō); the atomic tests in the merged layout as a suite (two of them alone: the scenes
-without a triangle, both layouts, the tests' answers); Safari and Firefox (nothing Chrome-only was written: WebGPU
-through wgpu, default limits except buffer sizes, timestamp queries only if the adapter has them).
+**Not measured:** any scene but hello world in a browser; Safari and Firefox (nothing Chrome-only was written:
+WebGPU through wgpu, default limits except buffer sizes, timestamp queries only if the adapter has them). Measured
+since, natively (below, "Software traversal with units"): the merged layout's and the guard's cost on a scene whose
+trace is the frame (Kabukichō), and the atomic tests under software traversal as a suite, in both layouts.
+
+## Software traversal with units (in-place edits without ray queries)
+
+ROADMAP § 6 step 7b. **Status: runs natively and in Chrome on this machine's GPU** (2026-11-11; every run with the
+loop guard, which stopped nothing). Edits and memory are what the step was for; a still frame pays for them.
+
+**Where units are used.** In a live session and in a browser (the wasm build), by default. **An offline render
+(`threert-render render`) under software traversal flattens every instance, as before this step: its kernel and its
+bytes are main's with nothing set.** `THREERT_UNITS=1` gives an offline render units; `THREERT_UNITS=0` flattens a
+live session too (the A/B). Why the line is there (decided 2026-11-11):
+- an offline render under software traversal is the reference render, and what the catalog's byte gate compares; the
+ gate runs with no variable set, and stays a comparison with main's bytes;
+- what units give (the triangle data of each mesh held once, a faster load, edits in place) is what a session that
+ edits and a browser need; an offline render builds its scene once and edits nothing;
+- no catalog scene with models but Kabukichō has been rendered with units on the GPU.
+
+**What a still frame costs** (software traversal, live, 1280 × 720 traced at half, this machine, guard on in both
+columns; the tables and the rest are under "Measured" at the end of this section):
+
+| scene | the trace, units / flat | frame GPU, units / flat | 60 Hz (16.7 ms) |
+| --- | --- | --- | --- |
+| hello world (natively) | 1.40–1.42 / 1.01–1.04 ms: **+37 %** | in Chrome 6.59 / 6.60 ms (its trace 2.55 / 2.08) | held by both |
+| the voxel level (10,459 units) | 7.85 / 4.58 ms: **+71 %** | 11.2 / 7.9 ms | held by both |
+| Kabukichō (352 units) | 13.88 / 12.01 ms: **+16 %** | 17.18 / 15.35 ms | **missed with units** (a frame every 17.2–17.5 ms; flat 16.65) |
+
+Against what main's live session ran on Kabukichō under software traversal with nothing set (flat, no guard: 14.11 ms
+of GPU a frame, 10.78 of trace), the session's default now (units, the guard) is 3.1 ms a frame more, 1.2 of it the
+guard as measured on the flat kernel. Nothing of the unit walk was tuned; that is the next thing to do (ROADMAP § 6
+step 7b, "Open").
+
+**Not run** (each needs a GPU run outside the ones agreed for this step): a kernel with units without the guard; a
+catalog scene with units, offline or live, but Kabukichō; explosions on the voxel level until the edit room is full;
+a pile of debris, where units' boxes overlap most.
+
+**What there was.** Software traversal (a browser's only one) walked one flat tree over every triangle in world
+space. Instances were written out into it (`flatten_instances`), so adding or moving anything rebuilt the scene, and a
+level of placed meshes held every placement's triangles. The kernel already shades a hit on an instance (`Hit.inst`
+names a record with the instance's rows; hardware traversal fills it), and already walks a second level for
+procedural objects (`trace_procs`: the ray into the object's space, a tree of its own).
+
+**What there is now.** Under software traversal an instance stays an instance: a **unit**.
+- **The still scene is the flat tree it was**, walked first, exactly as before. (A scene whose triangles are all
+ units' has for it a leaf of one triangle without area, put after the meshes' triangles: the tree over nothing's
+ leaf names triangle 0, which with units is a mesh's first, in model space.)
+- **A mesh's tree** is built once over its triangles in model space, where they already are (the pool hardware
+ traversal builds its BLASes from; under software traversal the mesh's triangles are put in its tree's order, a
+ cutout triangle carrying its flag). Its nodes sit in the node buffer after the still tree's; a tree is relocatable
+ (child indices count from its root, leaf triangles from its mesh's first).
+- **A unit** is the instance's kernel record (160 B), as under hardware traversal, with two of its unused words
+ filled: its mesh tree's root, and whether it casts shadows.
+- **The top tree** is over the units' world boxes, one unit a leaf. A unit's box is its mesh's tree's bounds under the
+ unit's transform, read when the top tree is built (so a mesh written again where it was moves its units' boxes with
+ it). It is rebuilt whole on the CPU whenever a unit is added, moved or removed (as the TLAS is under hardware
+ traversal) and written into its own range of the node buffer. Its root and the number of units reach the kernel in two
+ words of the frame's parameters (`Params.motion.z`, `.w`, as bits; no binding, no buffer more).
+- **The kernel** walks the top tree after the still one, with the ray already cut to the still scene's hit; at a
+ unit it takes the ray into the unit's space (as `trace_procs` does) and walks the mesh's tree. The hit it returns
+ is the hit hardware traversal returns (the triangle, the record), so nothing after the traversal differs.
+- **`pathtrace.wgsl` is not edited.** The unit walk is `shaders/trace_units.wgsl`, spliced in by `kernel_source`
+ for scenes that have units under software traversal (`F_UNITS`, a source feature, as vertex colours are). A scene
+ without units is handed the source it was handed before, byte for byte; hardware traversal's source never
+ contains it.
+- Still flattened, as before: meshes that deform (a pose shared by a crowd), every instance of a scene with more
+ of them than a top tree holds (2^18), and every instance of an offline render (`prepare`; a live session's scene
+ goes through `prepare_live`), unless `THREERT_UNITS=1`. `THREERT_UNITS=0` flattens everything, as before this
+ step (the A/B).
+
+**Edits in place.** The edits that hardware traversal makes in place go through one type (`gpu::Top`: the TLAS and
+its BLASes, or the units), so the engine's path is the same under both traversals (`live.rs` `move_instances`,
+`update_instanced`, `edit_geometry`):
+
+| edit | under software traversal with units |
+| --- | --- |
+| a unit moves (a rigid body's box, a piece of debris) | its record and the top tree |
+| an instance of a mesh the scene has is added or removed | a record in the edit room, the top tree |
+| a mesh of its own is added (a new chunk, a new box) | its triangles and attributes into the edit room in its tree's order, its tree into the mesh range, a record, the top tree |
+| a mesh of its own changes (a voxel edit: the chunks it touched) | those meshes' trees made again (the old tree's nodes given back and filled), their records; no other unit is read |
+| a mesh is removed | its record cleared, its tree given back and filled, the top tree |
+
+The scene is rebuilt, as before this step, by: the first instanced mesh of a scene that has none (its kernel has no
+unit walk: one rebuild, as hardware traversal's first instance is); an edit of a procedural object; a posed model or
+a rigid group's pose (their triangles are in the still tree); an instance of a mesh that deforms; **room that is
+full** (the edit room and the tree ranges are sized at the build, a quarter of the scene and at least 65,536
+triangles and 1,024 records, and do not grow under software traversal: under hardware traversal they do; what an
+edit replaces stays behind until the next rebuild, under both; a scene with units and no geometry of its own to
+edit gets the records and object entries alone, so an instance of a mesh it has is added in place and a mesh it
+has not rebuilds it); a top tree that is refused (below). The edit log names the reason (`rebuild (edit room:
+records (software traversal's does not grow))`).
+
+**Why the loops end.** A walk follows indices it reads, so the trees are checked on the CPU where they are written
+(`units.rs`): every child index is greater than its parent's and inside its tree's range, a leaf's triangles inside
+its mesh's and at most 16, a top leaf's record a unit's. A tree that fails is not uploaded: the scene is rebuilt.
+A unit's record names its mesh's tree by its root, so a top tree is refused while a shown unit's record names a root
+that is not its mesh's tree now (freed, or placed again elsewhere), or a unit sits past the kernel's records. Room
+not yet used, and a tree given back, hold leaves that end (`units::FILL`), not zeros (zeros are an interior node
+whose children are nodes 0 and 1). With no unit shown the count is 0 and the kernel does not enter the top range.
+
+**The stack.** Both levels share one stack of 64 entries, the unit walk's own (the still walk keeps its 48, in
+`pathtrace.wgsl`, untouched); a walk's stack is never deeper than its tree, and a unit's walk pushes above what the
+top walk has pending. The top tree is built by median splits, each halving: 18 levels hold 2^18 units, the most a
+top tree is given (a scene with more instances is flattened, as before). That leaves 46 for a mesh tree. Binned SAH
+is not balanced: measured on the CPU, its trees over the catalog's models are 17 deep for 37 k triangles, 20 for
+502 k, 22 for a 31 k-triangle building of Kabukichō, and 42 for the 5.86 M triangles of `zero-day` (a balanced tree
+there is 21), which as part of a flattened scene fitted the still walk's 48. A mesh tree deeper than 46 is built
+again by median splits, whose depth is log2(triangles / 4): a worse tree to walk, never a wrong one. A push past the
+stack is dropped (geometry missed, never a hang), and the builders' bounds mean it is not reached;
+`the_builders_keep_their_depths` holds them to it.
+
+**Checked on the CPU** (`units.rs`, `lib.rs` `units_tests`; no GPU):
+- the kernel's two walks transcribed line for line (a test compares the transcription's source lines with the
+ shaders'), with every buffer read through an accessor that refuses an index outside its buffer and every loop
+ iteration counted;
+- random scenes and random sequences of adding a mesh, adding, moving and removing units, removing a mesh: after each
+ step, for closest, shadow and any-hit rays, no read outside a buffer, an end within the nodes there are, and the
+ closest hit brute force over every triangle finds;
+- a scene prepared with units (`prepare_live`, what a session uploads) against the same scene flattened, ray for ray:
+ a hit where there was one, at the same distance to 2 × 10⁻⁴ (a unit's triangles are met in its own space), and
+ the same shadow rays blocked;
+- broken trees (a child at or before its parent, a cycle, a range outside, a leaf over 16, a record that is no unit)
+ refused; a record naming a tree that is gone refused;
+- the sources handed to wgpu for every scene without units: the hashes main has
+ (`the_default_sources_are_untouched`); the guarded, merged kernel with units is valid WGSL in 8 storage buffers;
+- an offline render of a scene with instances: no unit, no `F_UNITS`, and the triangle and node bytes the flattened
+ scene has, unless `THREERT_UNITS=1` (`an_offline_render_has_no_units_unless_told`);
+- the guard's default: a kernel with units has it at 65,536 with nothing set and none at `THREERT_LOOP_GUARD=0`, a
+ kernel without units is the source it was (`a_kernel_with_units_has_the_loop_guard`; naga validates the guarded
+ kernel with units as written).
+
+**The loop guard.** A browser's kernel always has it (`merged::guard`). **Natively a kernel with units has it with
+nothing set** (65,536 iterations an invocation; `THREERT_LOOP_GUARD=0` takes it out, `=<limit>` sets another): what
+hung on 2026-11-11 is not confirmed, the unit walk is new, and no kernel with units has run without it. A native
+kernel without units has none unless `THREERT_LOOP_GUARD` says so, as before (its source and every existing byte
+unchanged); whether all of native software traversal gets it is not decided here. Every GPU run of a kernel with
+units so far had it (8,192 or 65,536), and it stopped nothing in any of them. On Kabukichō it costs the flattened
+kernel 1.2 ms of trace a frame (11 %; below). What it does when it stops something is unchanged: an offline render
+is an error, a live session counts it in the frame log (`guard`; `null` while the scene's kernel has none, as
+before a scene's first unit), and `tools/test-render.ts` fails a run in which it stopped a live test's frames.
+Under software traversal as written the guard's count has its binding and buffer whether or not the scene's kernel
+names it (not at `THREERT_LOOP_GUARD=0`), so a scene's first unit brings the guard without another layout.
+
+### Measured (2026-11-11)
+
+Apple M5 Pro; natively `THREERT_HWRT=0` with `THREERT_LOOP_GUARD` 65,536 unless said; "flat" is the same build with
+`THREERT_UNITS=0` (every instance flattened: main's kernel, and main's bytes on the catalog); live views 1280 × 720
+traced at half. These runs were made while an offline render had units by default too; the offline figures with units
+below are what `THREERT_UNITS=1` gives now. Run again with the defaults as they are (nothing set but
+`THREERT_HWRT=0`): the last paragraph of this section. The runs, their order and their limits are in
+`out/web-probe/gpu-runs-b.md` (kept beside the checkout). Other applications held part of the GPU throughout; figures
+are p50, two launches where a spread is given.
+
+**Hello world in Chrome** (`tools/web-hello.ts --frames`; Chrome 157, the page's guard), ms p50 / p95:
+
+| | units | flat (the section above) |
+| --- | --- | --- |
+| a frame in which a body moves: the page's time | **0.84 / 1.07** | 16.73 / 17.99 |
+| of it the commit | 0.08 / 0.10 | 16.49 / 17.68 (the rebuild) |
+| frames that rebuilt the scene | 0 of 1,173 | 295 of about 1,180 |
+| a click that adds a box: commit | the first 31.6 (one rebuild, into the kernel with units), then **0.79, 0.73, 0.64** | 18.5–24.1 |
+| the trace, still / a body moves | 2.55 / 2.66 | 2.08 / 1.72 |
+| frame GPU, still / a body moves | 6.59 / 6.73 | 6.60 / 6.15 |
+
+The scripted test passes (640 × 360 and 1280 × 720), its report and clicks the native run's number for number; it
+now checks that no frame rebuilds the scene and that only the first box's click does.
+
+**Hello world natively** (`tools/physics-hello.ts`, merged layout): every check passes, the two that software
+traversal failed among them (the commits `rebuild, in place × 4`; one rebuild). A frame in which a body moves:
+commit 0.02 ms (flat 8.65), frame CPU 4.6 ms (8.9); a click's commit 0.25–0.35 ms in place (9.1–9.6). The trace is
+1.40–1.42 ms where flat's is 1.01–1.04 (**+0.38 ms, 37 %**, the same with one box as with four: every ray reads the
+top tree where the still scene is a ground and a wall).
+
+**The voxel level** (10,459 units of 6,410 meshes; flattened, 13.2 M triangles):
+
+| | units | flat |
+| --- | --- | --- |
+| triangle data (vertices, attributes, nodes) | **310.9 MiB** | 2,098.2 MiB |
+| trees built at load (`bvh_ms`) | 333 ms | 5,378 ms |
+| first frame after | 5.2 s | 11.6 s |
+| an explosion (0.5–4 m; 4–20 chunk meshes placed) | **2.5–4.5 ms, in place** (1.8–2.0 of it the trees) | 6.9–7.9 s (the scene rebuilt) |
+| still frame: the trace | **7.85 ms** | 4.58 ms |
+| still frame: GPU | 11.2 ms | 7.9 ms |
+
+The still frame is where units cost: **+71 % trace**. The level is 10,459 placed chunks side by side and stacked,
+whose boxes touch and overlap, under a top tree built by median splits; flattened they are one SAH tree. Not done:
+a better top tree (SAH), a unit whose transform is the identity walked without transforming the ray. Not measured:
+a pile of debris (boxes that overlap deeply), explosions until the room is full.
+
+**Kabukichō** (352 units of 19 building meshes):
+
+| | units | flat |
+| --- | --- | --- |
+| offline, 320 × 180, 64 spp: the trace (units: `THREERT_UNITS=1`) | 394.8 ms | 336.2 ms (units +17 %) |
+| trees built (`bvh_ms`) | 89 ms | 1,635 ms |
+| triangle data | 55.0 MiB | 634.1 MiB |
+| live, guard on: frame GPU / the trace | 17.18 / 13.88 ms | 15.35 / 12.01 ms (units **+1.87 ms, 16 %**) |
+| the same in the merged layout | 17.44 / 14.10 ms | 15.66 / 12.28 ms |
+| first frame, second launch | 1.55 s | 3.3 s |
+
+With units the view misses 60 Hz on this machine (frame interval 17.2–17.5 ms; flat 16.65). The images are not the
+same bytes as flat's (a unit's ray is intersected in model space, and the emitter table follows the triangles'
+order): at 64 spp the means are 0.69371 and 0.69395, 20-pixel blocks 0.5 % apart (p50), unbiased; hardware
+traversal's image of the same render is as far from both.
+
+**The guard and the merged layout on a scene whose trace is the frame** (Kabukichō flat, main's kernel, live; frame
+GPU / the trace, ms): as written 14.11 / 10.78; merged 14.29 / 10.91; as written with the guard 15.35 / 12.01;
+merged with the guard 15.66 / 12.28. **The guard: +1.23 ms of trace (11 %). The merged layout: +0.13 ms, with the
+guard +0.27.** (On hello world both were inside the spread.) A kernel with units was not run without the guard.
+
+**The atomic tests under software traversal** (170, a family a command, guard on; the first whole run of the suite
+under software traversal on this machine; made while offline tests had units too): 147 pass and 23 fail, as written
+and in the merged layout alike, **and the same 23 fail on main's build, with the same values**:
+- particles, which software traversal does not draw (docs/MATERIAL_FUNCTIONS.md: they need ray queries):
+ `particles/count-zero`, `emissive-spark`, `emissive-spark-nominal`, `emissive-unsampled`, `follow-emitter`,
+ `hidden-in-place-live`, `instance-data`, `lit-normal`, `lit-orientation`, `motion-repose`, `node-custom`,
+ `quad-placement`, `shown-in-place-live` (13; `particles/burst-not-yet` expects nothing drawn and passes);
+ `gpu-particles/beside-particles`, `plane`, `voxels`, `voxels-live`, `voxels-side` (5); `translucent/depth`,
+ `translucent/order` (translucent particles);
+- `volume/lighting`, `volume/lighting-offline` (6 for 1): their subject is one translucent particle in front of a
+ 6-nit wall, so these two are the same missing particles: the region reads the wall;
+- `surface/windows` (0.3934 for 0.4234): not explained. Its scene is one plane with the library's facade windows
+ and no instance, so its kernel on this branch is main's source byte for byte.
+The last three are in ROADMAP "Known issues"; they are the other line's to fix. The suite found one fault of units:
+`voxel/cut-falls-live` drew a falling part cut off at the box it had before it fell (a unit kept the bounds its
+mesh had when added; now the box is the tree's, above). Before that the first GPU run found another: a scene of
+units alone drew a mesh's first triangle at the origin (the still leaf, above). Both have CPU tests now.
+
+**How each kind of edit went** (the atomic edit tests one by one, the edit log): instances added, moved and removed,
+a model's second copy, a new mesh, vertex colours, emitters added and removed: in place. A rebuild, with its reason
+in the log: 1,100 specks added to a scene with room for 1,024 records; a procedural object edited or moved.
+
+**With the defaults as they are now** (units live and in a browser, flat offline, the guard with units; run after
+the rule above was built in):
+- Hello world natively with nothing set but `THREERT_HWRT=0` (`tools/physics-hello.ts`): every check; the commits
+ `rebuild, in place × 4`; 812 of 823 frames' kernel has the guard (the eleven before the first box have a kernel
+ without units, and the log's `guard` is `null`), and it stopped nothing.
+- The catalog offline under software traversal, `THREERT_UNITS` not set: **23 of 23 bundles byte-identical to main**
+ (HDR and PNG, 320 × 180, 4 spp). Both builds ran with `THREERT_LOOP_GUARD=65536`, as every GPU run of this step;
+ that the kernel without the guard is main's too is the source hashes' test.
+- `cargo test --release` whole (78 pass), the atomic tests under hardware traversal (170 pass), and the scripted
+ test in Chrome (every check, the guard 0 in 826 frames, no frame rebuilt, the report the native run's): as before.
+- Not run again: the perf smoke and the catalog under hardware traversal (18 of 23 identical; `bistro`,
+ `bistro-slice`, `bistro-district`, `zero-day`, `zero-day-animated` differ from main in 1,884 / 133 / 80 / 9,507 /
+ 8,850 of 57,600 pixels, and main from main in 1,782 / 1,095 / 125 / 7,988 / 10,426: ROADMAP "Known issues",
+ hardware traversal's ties). Hardware traversal's sources, layouts and buffers are not touched by the rule.
## Correctness
diff --git a/docs/VOXEL.md b/docs/VOXEL.md
index 596a9f0..1d6e92a 100644
--- a/docs/VOXEL.md
+++ b/docs/VOXEL.md
@@ -431,9 +431,17 @@ Where it runs (the user, 2026-11-10):
- 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.
+ commands, poses, events and queries are the four channels between them. In a real browser so far: the physics
+ hello world (Chrome, 2026-11-11; docs/RUNTIME.md "The engine in a browser"). The voxel level has not run in one.
- 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.
+ threads optional), and the browser has no ray queries (WebGPU): it renders with the engine's own kernel under
+ software traversal. There a chunk's mesh and a piece of debris are units (a tree of their own under a top tree;
+ docs/RUNTIME.md "Software traversal with units", ROADMAP § 6 step 7b), so that an edit rewrites the chunks it
+ touched and not the scene (in a session and in a browser; an offline render under software traversal flattens
+ them, as before, and is byte for byte the reference render it was). Measured natively under software traversal
+ (2026-11-11), live: the level's triangle data 310.9 MiB (flattened: 2,098), an explosion 2.5–4.5 ms in place
+ (6.9–7.9 s), and a still frame's trace 7.85 ms where the flattened level's is 4.58 (the chunks' boxes overlap; the
+ top tree is not tuned yet).
- The triangle route's output renders in `web/` as it is: standard meshes or glTF with palette materials, each voxel's
colour as vertex colours, nothing that needs WGSL. Procedural boxes (a geometry function in WGSL) are native only.
diff --git a/renderer/shaders/trace_units.wgsl b/renderer/shaders/trace_units.wgsl
new file mode 100644
index 0000000..a400675
--- /dev/null
+++ b/renderer/shaders/trace_units.wgsl
@@ -0,0 +1,114 @@
+// Units: software traversal's second level (gpu.rs F_UNITS, renderer/src/units.rs; docs/RUNTIME.md "Software traversal
+// with units"). Spliced into pathtrace.wgsl's software traversal by `kernel_source` for scenes that have units; a scene
+// without them, and hardware traversal, never see this file.
+//
+// A unit is a model instance (`instances`, as hardware traversal's): its mesh's triangles in model space in
+// `tri_verts`, from the record's first triangle; its mesh's tree in `nodes`, from the root in the record's `n0.w`
+// (child indices count from that root, a leaf's triangles from the mesh's first). `n1.w`: the unit casts shadows.
+// The top tree, over the units' world boxes, starts at node `P.motion.z` (bits; child indices count from it); each of
+// its leaves is one unit, `left_or_first` its record. `P.motion.w` (bits): how many units there are. (`P.motion.y`
+// is `render --signals`'.)
+//
+// `trace` walks the still scene first and calls this with its hit: the ray is already cut to it. Both levels share one
+// stack, this function's own: a unit's walk pushes above what the top walk has pending and stops when it is back down
+// to it. 64 entries: 18 for the top tree, 46 for a mesh's (units.rs `STACK`). Every index read here was checked on the
+// CPU when it was written (units.rs `check_mesh`, `check_top`), the depths with them.
+fn trace_units(o: vec3<f32>, d: vec3<f32>, hit_in: Hit, mode: u32) -> Hit {
+ var hit = hit_in;
+ if (bitcast<u32>(P.motion.w) == 0u) { return hit; }
+ let top = bitcast<u32>(P.motion.z);
+ let inv_d = 1.0 / select(d, vec3<f32>(1e-20), abs(d) < vec3<f32>(1e-20));
+ var stack: array<u32, 64>;
+ var sp = 0u;
+ var node = top;
+ loop {
+ let n = nodes[node];
+ if (n.count > 0u) {
+ // A top leaf: one unit.
+ let rec = n.left_or_first;
+ let r = instances[rec];
+ if (mode != TRACE_SHADOW || bitcast<u32>(r.n1.w) != 0u) {
+ // The ray in the unit's space (its direction not renormalised: t is the world's).
+ let lo = proc_point(r, o);
+ let ld = proc_dir(r, d);
+ let linv = 1.0 / select(ld, vec3<f32>(1e-20), abs(ld) < vec3<f32>(1e-20));
+ let root = bitcast<u32>(r.n0.w);
+ let first = r.info.x;
+ let base = sp;
+ var m = root;
+ loop {
+ let q = nodes[m];
+ if (q.count > 0u) {
+ for (var k = 0u; k < q.count; k++) {
+ let ti = first + q.left_or_first + k;
+ let x = intersect_tri(lo, ld, ti, hit.t);
+ if (x.x < hit.t) {
+ let flags = bitcast<u32>(tri_verts[ti * 3u].w);
+ if (has(F_MASKED) && (flags & TRI_MASKED) != 0u && !cutouts_opaque() && mode != TRACE_ANY_OPAQUE && !alpha_pass(ti, rec, x.y, x.z, x.x)) { continue; }
+ hit = Hit(x.x, ti, x.y, x.z, rec);
+ if (mode != TRACE_CLOSEST) { return hit; }
+ }
+ }
+ if (sp == base) { break; }
+ sp--;
+ m = stack[sp];
+ continue;
+ }
+ let ml = root + q.left_or_first;
+ let mr = ml + 1u;
+ let ql = nodes[ml];
+ let qr = nodes[mr];
+ var ul = ray_aabb(lo, linv, ql.bmin, ql.bmax, hit.t);
+ var ur = ray_aabb(lo, linv, qr.bmin, qr.bmax, hit.t);
+ if (ul == INF && ur == INF) {
+ if (sp == base) { break; }
+ sp--;
+ m = stack[sp];
+ continue;
+ }
+ var mnear = ml;
+ var mfar = mr;
+ if (ur < ul) {
+ mnear = mr;
+ mfar = ml;
+ let tmp = ul; ul = ur; ur = tmp;
+ }
+ m = mnear;
+ if (ur != INF && sp < 64u) {
+ stack[sp] = mfar;
+ sp++;
+ }
+ }
+ }
+ if (sp == 0u) { break; }
+ sp--;
+ node = stack[sp];
+ continue;
+ }
+ let l = top + n.left_or_first;
+ let r = l + 1u;
+ let nl = nodes[l];
+ let nr = nodes[r];
+ var tl = ray_aabb(o, inv_d, nl.bmin, nl.bmax, hit.t);
+ var tr = ray_aabb(o, inv_d, nr.bmin, nr.bmax, hit.t);
+ if (tl == INF && tr == INF) {
+ if (sp == 0u) { break; }
+ sp--;
+ node = stack[sp];
+ continue;
+ }
+ var near = l;
+ var far = r;
+ if (tr < tl) {
+ near = r;
+ far = l;
+ let tmp = tl; tl = tr; tr = tmp;
+ }
+ node = near;
+ if (tr != INF && sp < 64u) {
+ stack[sp] = far;
+ sp++;
+ }
+ }
+ return hit;
+}
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index da74ed8..1c49726 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -134,18 +134,26 @@ impl EditRoom {
std::env::var("THREERT_EDIT_RESERVE").ok().and_then(|v| v.parse().ok()).unwrap_or(1.0)
}
- /// Whether the scene gets room (`for_scene`): editable geometry under hardware RT.
+ /// Whether the scene gets room (`for_scene`): editable geometry under hardware RT, or under software traversal
+ /// with units (`hwrt` true for them too: `lib.rs prepare`).
pub fn editable(scene: &Scene, hwrt: bool) -> bool {
hwrt && Self::reserve() > 0.0 && (!scene.procs.is_empty() || !scene.retained.own_instance.is_empty())
}
- fn for_scene(scene: &Scene, tris: usize, records: usize, hwrt: bool) -> EditRoom {
+ /// `units`: software traversal with units, whose room does not grow (hardware traversal's does, from nothing): a
+ /// scene of theirs without editable geometry still gets records and object entries, for instances of the meshes
+ /// it has (a mesh it has not rebuilds the scene: no triangles).
+ pub(crate) fn for_scene(scene: &Scene, tris: usize, records: usize, hwrt: bool, units: bool) -> EditRoom {
let k = Self::reserve();
let (procs, meshes) = (!scene.procs.is_empty(), !scene.retained.own_instance.is_empty());
- if !Self::editable(scene, hwrt) {
- return EditRoom::default();
- }
let part = |n: usize, min: usize| ((n as f64 * 0.25 * k) as usize).max((min as f64 * k) as usize);
+ if !Self::editable(scene, hwrt || units) {
+ return if units && k > 0.0 {
+ EditRoom { records: part(records, 1024), objects: part(scene.objects.len() / scene.object_stride(), 1024), ..EditRoom::default() }
+ } else {
+ EditRoom::default()
+ };
+ }
let blob_words = scene.proc_layout.as_ref().map_or(0, |l| l.head.len() + l.blob_words);
EditRoom {
tris: if meshes { part(tris, 1 << 16) } else { 0 },
@@ -210,6 +218,9 @@ pub struct Uploaded {
pub prev_verts: wgpu::Buffer,
pub dynamic_first: usize,
pub accel: Option<Accel>,
+ /// Software traversal's units (units.rs), when the scene has any: what `accel` is to hardware traversal. Their
+ /// trees are in the node buffer (`bg_parts.nodes`).
+ pub units: Option<crate::units::Units>,
/// The particle pass, when the scene has particle systems (hardware RT).
pub particles: Option<ParticleGpu>,
pub gpu_particles: Option<GpuParticlesGpu>,
@@ -541,6 +552,103 @@ pub struct Accel {
pub proc_base: usize,
}
+/// What is above the triangles for an edit in place: hardware traversal's TLAS and BLASes, or software traversal's
+/// units (units.rs). An instance's slot is its TLAS index; its kernel record is the slot less `inst_base` (0 for
+/// units: a unit's slot is its record).
+pub enum Top<'a> {
+ Hw(&'a mut Accel),
+ Sw(&'a mut crate::units::Units),
+}
+
+impl<'a> Top<'a> {
+ /// The scene's, or None under software traversal without units (edits rebuild then).
+ pub fn of(accel: &'a mut Option<Accel>, units: &'a mut Option<crate::units::Units>) -> Option<Top<'a>> {
+ match (accel.as_mut(), units.as_mut()) {
+ (Some(a), _) => Some(Top::Hw(a)),
+ (None, Some(u)) => Some(Top::Sw(u)),
+ _ => None,
+ }
+ }
+
+ pub fn inst_base(&self) -> usize {
+ match self {
+ Top::Hw(a) => a.inst_base,
+ Top::Sw(_) => 0,
+ }
+ }
+
+ /// The slot of the first procedural object (`proc_first`: its record).
+ pub fn proc_base(&self, proc_first: usize) -> usize {
+ match self {
+ Top::Hw(a) => a.proc_base,
+ Top::Sw(_) => proc_first,
+ }
+ }
+
+ pub fn sw(&self) -> bool {
+ matches!(self, Top::Sw(_))
+ }
+
+ /// No instance at `slot`.
+ pub fn clear(&mut self, slot: usize) {
+ match self {
+ Top::Hw(a) => a.tlas[slot] = None,
+ Top::Sw(u) => u.set(slot, None),
+ }
+ }
+
+ /// An instance of instanced mesh `k` at `slot`, placed by `world`. (Its bounds are the mesh's BLAS's, or its
+ /// tree's: units.rs `Unit`.)
+ pub fn place(&mut self, slot: usize, k: u32, world: glam::Mat4, custom: u32, cast_shadow: bool, hidden: bool) {
+ match self {
+ Top::Hw(a) => a.tlas[slot] = Some(wgpu::TlasInstance::new(&a.meshes[k as usize], tlas_rows(world), custom, instance_mask(cast_shadow, hidden))),
+ Top::Sw(u) => u.set(slot, u.unit(k, world, hidden)),
+ }
+ }
+
+ /// A procedural object's instance at `slot` (its AABB BLAS). Hardware traversal only: software traversal finds
+ /// procedural objects by their records (`trace_procs`), and its edits of them rebuild the scene.
+ pub fn place_blas(&mut self, slot: usize, blas: &wgpu::Blas, world: glam::Mat4, custom: u32, mask: u8) {
+ if let Top::Hw(a) = self {
+ a.tlas[slot] = Some(wgpu::TlasInstance::new(blas, tlas_rows(world), custom, mask));
+ }
+ }
+
+ /// Whether instanced mesh `k` can be placed: always under hardware traversal (its BLAS); under software traversal
+ /// if it has a tree (a mesh that deforms has none: its instances are flattened).
+ pub fn has_mesh(&self, k: u32) -> bool {
+ match self {
+ Top::Hw(_) => true,
+ Top::Sw(u) => u.root(k).is_some(),
+ }
+ }
+
+ /// The instance at `slot`, if there is one, placed by `world` now; with `shown`, its mask too (hidden or not,
+ /// casting shadows or not).
+ pub fn moved(&mut self, slot: usize, world: glam::Mat4, shown: Option<(bool, bool)>) {
+ match self {
+ Top::Hw(a) => {
+ if let Some(t) = a.tlas[slot].as_mut() {
+ t.transform = tlas_rows(world);
+ if let Some((cast_shadow, hidden)) = shown {
+ t.mask = instance_mask(cast_shadow, hidden);
+ }
+ }
+ }
+ Top::Sw(u) => u.moved(slot, world, shown.map(|(_, hidden)| hidden)),
+ }
+ }
+
+ /// An instance's kernel record as this traversal reads it: a unit's carries its mesh's tree's root and whether it
+ /// casts shadows (hardware traversal has them in the TLAS).
+ pub fn record(&self, r: crate::scene::GpuInstance, k: u32, cast_shadow: bool) -> crate::scene::GpuInstance {
+ match self {
+ Top::Hw(_) => r,
+ Top::Sw(u) => crate::units::unit_record(r, u.root(k).unwrap_or(0), cast_shadow),
+ }
+ }
+}
+
/// A TLAS instance transform: the world matrix's first three rows.
/// TLAS mask of an instance: 1 casts shadows, 2 does not, 0 a hidden instance of an instanced object (no ray sees it).
pub fn instance_mask(cast_shadow: bool, hidden: bool) -> u8 {
@@ -619,6 +727,14 @@ pub fn kernel_source(src: &str, features: u32) -> String {
" s.emissive = emission(m, uv, lod) * obj_power(a);\n // three.js MeshBasicMaterial: its colour to camera rays and mirror-like paths, lit by nothing, lighting nothing.\n if (m.tex1.z == MAT_UNLIT) {\n s.emissive = select(vec3<f32>(0.0), base, cur_depth == 0u || mirror_path);\n base = vec3<f32>(0.0);\n spec = 0.0;\n metal = 0.0;\n }\n",
);
}
+ if features & F_UNITS != 0 {
+ // The still scene's walk ends by handing its hit to the units' (then to the procedural objects', as before).
+ patch(
+ " if (has(F_PROC)) { return trace_procs(o, d, hit, mode); }\n return hit;\n}\n",
+ " hit = trace_units(o, d, hit, mode);\n if (has(F_PROC)) { return trace_procs(o, d, hit, mode); }\n return hit;\n}\n",
+ );
+ patch("\n// @trace-end\n", &format!("\n{}\n// @trace-end\n", include_str!("../shaders/trace_units.wgsl")));
+ }
if features & F_BACKGROUND != 0 {
patch(" aerial: vec4<f32>, // the sky's aerial perspective (F_AERIAL): density multiple, Rayleigh scale, Mie scale, -\n};\n", " aerial: vec4<f32>, // the sky's aerial perspective (F_AERIAL): density multiple, Rayleigh scale, Mie scale, -\n background: vec4<f32>, // three.js scene.background (radiance), 1\n};\n");
patch("fn sky_mis(d: vec3<f32>, pdf: f32) -> vec3<f32> {\n", "fn sky_mis(d: vec3<f32>, pdf: f32) -> vec3<f32> {\n // three.js scene.background: what camera rays (and paths bent straight through glass) see where nothing is.\n if (pdf <= 0.0) { return P.background.rgb; }\n");
@@ -626,18 +742,30 @@ pub fn kernel_source(src: &str, features: u32) -> String {
s
}
-/// The loop guard's limit, if the kernel is to have one (merged.rs `guard`: every loop of it bounded, so a dispatch
-/// ends whatever the data): THREERT_LOOP_GUARD=<iterations an invocation> natively, where the kernel is otherwise as
-/// written; always in a browser, where a dispatch that does not end is the player's whole GPU.
+/// The loop guard's limit for every kernel, if one is set (merged.rs `guard`: every loop of a kernel bounded, so a
+/// dispatch ends whatever the data): THREERT_LOOP_GUARD=<iterations an invocation> natively, where a kernel is
+/// otherwise as written; always in a browser, where a dispatch that does not end is the player's whole GPU.
pub fn loop_guard() -> Option<u32> {
- match LOOP_GUARD.load(std::sync::atomic::Ordering::Relaxed) {
- 0 => {}
- n => return Some(n),
- }
- match std::env::var("THREERT_LOOP_GUARD").ok().and_then(|v| v.parse::<u32>().ok()) {
- Some(0) => None,
- Some(n) => Some(n),
- None => cfg!(target_arch = "wasm32").then_some(1 << 16),
+ loop_guard_of(false)
+}
+
+/// The loop guard's limit for a kernel with units or without (`F_UNITS`). A kernel with units has the guard natively
+/// too, at the browser's limit, unless THREERT_LOOP_GUARD=0: its second level is the traversal that has run least,
+/// and what it walks is rewritten by edits while it runs. A kernel without units is as `loop_guard` says: natively,
+/// with nothing set, the source as written.
+pub fn loop_guard_of(units: bool) -> Option<u32> {
+ let page = LOOP_GUARD.load(std::sync::atomic::Ordering::Relaxed);
+ let var = std::env::var("THREERT_LOOP_GUARD").ok().and_then(|v| v.parse::<u32>().ok());
+ guard_limit(page, var, units, cfg!(target_arch = "wasm32"))
+}
+
+/// `loop_guard_of`, of what was set: by a page (0: nothing), by the environment (Some(0): off), and where.
+fn guard_limit(page: u32, var: Option<u32>, units: bool, browser: bool) -> Option<u32> {
+ match (page, var) {
+ (n, _) if n > 0 => Some(n),
+ (_, Some(0)) => None,
+ (_, Some(n)) => Some(n),
+ (_, None) => (units || browser).then_some(1 << 16),
}
}
@@ -652,6 +780,13 @@ pub fn set_loop_guard(limit: u32) {
}
}
+/// Whether a device's layout as written has the guard's count (group 1, `merged::GUARD_BINDING`; `KernelBufs::guard`):
+/// when a kernel of it may have the guard. Under software traversal that is unless THREERT_LOOP_GUARD=0, a scene's
+/// first unit bringing the guard with it; under hardware traversal, when a limit is set.
+fn guard_room(hwrt: bool) -> bool {
+ loop_guard_of(!hwrt).is_some()
+}
+
/// The kernel's source for a traversal: pathtrace.wgsl as it is (software), or with the hardware traversal in the
/// software one's place and the translucency pass after it.
pub fn kernel_base(hwrt: bool) -> String {
@@ -665,10 +800,11 @@ pub fn kernel_base(hwrt: bool) -> String {
}
}
-/// A kernel source as it is compiled: with the loop guard if there is one, its count in `MergedLive` (the merged
-/// layout) or in a buffer of its own (group 1, `merged::GUARD_BINDING`).
-fn guarded(src: &str, merged: bool) -> String {
- match loop_guard() {
+/// A kernel source as it is compiled: with the loop guard if it has one (`loop_guard_of`: `units`, whether the source
+/// has the unit walk), its count in `MergedLive` (the merged layout) or in a buffer of its own (group 1,
+/// `merged::GUARD_BINDING`).
+fn guarded(src: &str, merged: bool, units: bool) -> String {
+ match loop_guard_of(units) {
None => src.to_string(),
Some(n) if merged => crate::merged::guard(src, n, "ML.loop_guard_trips"),
Some(n) => crate::merged::guard(&format!("{src}\n{}", crate::merged::guard_decl()), n, crate::merged::GUARD_TRIPS.name),
@@ -758,10 +894,11 @@ pub struct KernelBufs {
impl KernelBufs {
/// For a cache of `entries`, reservoirs for `pixels` and the live passes' three of these bytes.
- pub fn new(d: &wgpu::Device, merged: bool, entries: u64, pixels: u64, refl: u64, motion: u64, direct: u64) -> KernelBufs {
+ /// `guard`: the layout as written has the guard's count (`Gpu::guard_room`).
+ pub fn new(d: &wgpu::Device, merged: bool, guard: bool, entries: u64, pixels: u64, refl: u64, motion: u64, direct: u64) -> KernelBufs {
if !merged {
let sb = |label: &str, size: u64| Buf::whole(d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }));
- let guard = loop_guard().map(|_| sb("loop guard", crate::merged::GUARD_WORDS as u64 * 4));
+ let guard = guard.then(|| sb("loop guard", crate::merged::GUARD_WORDS as u64 * 4));
return KernelBufs { cache: CacheBuffers::new(d, entries), resv: Buf::whole(reservoirs(d, pixels)), refl: sb("refl", refl), motion: sb("motion", motion), direct: sb("direct", direct), guard, merged: None };
}
let bytes = [entries * 4, entries * 32, entries * 32, pixels * 64, refl, motion, direct, crate::merged::GUARD_WORDS as u64 * 4];
@@ -962,7 +1099,10 @@ pub const F_VCOLOR: u32 = 1 << 22;
/// Density grids (`scene::GridBuild`): the grid atlas (binding 19) and `vgrid` for volume functions (F_SOURCE). (Bit
/// 24 is F_AERIAL's.)
pub const F_GRID: u32 = 1 << 25;
-pub const F_SOURCE: u32 = F_TINT | F_UNLIT | F_BACKGROUND | F_VCOLOR | F_GRID;
+pub const F_SOURCE: u32 = F_TINT | F_UNLIT | F_BACKGROUND | F_VCOLOR | F_GRID | F_UNITS;
+/// Software traversal's units (units.rs; shaders/trace_units.wgsl): the second level's walk, spliced into the
+/// software traversal after the still scene's (F_SOURCE). Never with hardware traversal.
+pub const F_UNITS: u32 = 1 << 26;
/// The sky's aerial perspective (SkyAtmosphere `aerialPerspective`; pathtrace.wgsl `aerial_tr`) on every path segment
/// that ends on a surface: compiled out where no scene has it. (Bit 23 is left to INSTANCE_BIT below.)
pub const F_AERIAL: u32 = 1 << 24;
@@ -997,7 +1137,7 @@ pub fn instance_features(scene: &Scene) -> u32 {
if scene.gpu_instances.is_empty() {
return media | particles;
}
- media | particles | F_INST | if scene.meshes.iter().any(|m| m.opaque < m.count) { F_MASKED } else { 0 }
+ media | particles | F_INST | if scene.meshes.iter().any(|m| m.opaque < m.count) { F_MASKED } else { 0 } | if scene.units.is_some() { F_UNITS } else { 0 }
}
/// `features` from the parts parameter edits change (materials, fog), and the instanced meshes' (`instance_features`).
@@ -1138,7 +1278,7 @@ impl Gpu {
// Bounds checks are not needed: all indices come from our own BVH / scene builder.
let module = (!merged).then(|| unsafe {
device.create_shader_module_trusted(
- wgpu::ShaderModuleDescriptor { label: Some("pathtrace"), source: wgpu::ShaderSource::Wgsl(guarded(&src, false).into()) },
+ wgpu::ShaderModuleDescriptor { label: Some("pathtrace"), source: wgpu::ShaderSource::Wgsl(guarded(&src, false, false).into()) },
wgpu::ShaderRuntimeChecks::unchecked(),
)
});
@@ -1215,10 +1355,11 @@ impl Gpu {
storage(7, false),
];
// The merged layout: group 1's seven buffers are one (merged.rs `KERNEL_LIVE`), the loop guard's count in it.
- // As written, a kernel with the guard has the count in a buffer of its own.
+ // As written, a kernel with the guard has the count in a buffer of its own: the binding is there whenever a
+ // kernel of this device may have the guard (`guard_room`; a kernel without it does not name the binding).
if merged {
vis_entries.truncate(2);
- } else if loop_guard().is_some() {
+ } else if guard_room(hwrt) {
vis_entries.push(storage(crate::merged::GUARD_BINDING, false));
}
let vis_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("vis"), entries: &vis_entries });
@@ -1246,7 +1387,7 @@ impl Gpu {
storage(6, true),
],
});
- let no_vis_bufs = KernelBufs::new(&device, merged, 1, 1, 64, 64, 64);
+ let no_vis_bufs = KernelBufs::new(&device, merged, guard_room(hwrt), 1, 1, 64, 64, 64);
let no_vis = vis_bind_group(&device, &vis_layout, &no_vis_view, &no_vis_bufs);
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout), Some(&vis_layout)], immediate_size: 0 });
let (tl_layout, tl_pipeline_layout) = if hwrt {
@@ -1270,6 +1411,11 @@ impl Gpu {
Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, hwrt, pages: Default::default(), tl_layout, tl_pipeline_layout, tl_pipelines: Default::default(), media_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })
}
+ /// Whether this device's kernel buffers have the loop guard's count (`guard_room`; always in the merged layout).
+ pub fn guard_room(&self) -> bool {
+ guard_room(self.hwrt)
+ }
+
/// The path-tracing kernel specialised for a scene (feature mask + material functions), compiled on first use.
pub fn pipeline(&self, k: &Kernel, live: bool) -> wgpu::ComputePipeline {
let mut cache = self.pipelines.lock().unwrap();
@@ -1314,7 +1460,7 @@ impl Gpu {
let src = k.caps.as_ref().map_or(src.clone(), |c| crate::merged::kernel(&src, c));
unsafe {
self.device.create_shader_module_trusted(
- wgpu::ShaderModuleDescriptor { label: Some("pathtrace+functions"), source: wgpu::ShaderSource::Wgsl(guarded(&src, self.merged).into()) },
+ wgpu::ShaderModuleDescriptor { label: Some("pathtrace+functions"), source: wgpu::ShaderSource::Wgsl(guarded(&src, self.merged, patches & F_UNITS != 0).into()) },
wgpu::ShaderRuntimeChecks::unchecked(),
)
}
@@ -1463,7 +1609,9 @@ impl Gpu {
b
};
let records: Vec<crate::scene::GpuInstance> = scene.gpu_instances.iter().chain(&scene.proc_records).copied().collect();
- let room = EditRoom::for_scene(scene, tri_verts.len() / 3, records.len(), self.hwrt);
+ // (Software traversal's units have room as hardware traversal's instances do: `prepare` sized their trees'
+ // by the same figures.)
+ let room = EditRoom::for_scene(scene, tri_verts.len() / 3, records.len(), self.hwrt, scene.units.is_some());
let st = wgpu::BufferUsages::STORAGE;
// (COPY_SRC: the live view's in-place edits grow these past their room by a copy, live.rs `edit_geometry`.)
let edit = st | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC;
@@ -1483,7 +1631,8 @@ impl Gpu {
// The vertex colours' bytes on the GPU (the edit room's included).
timings.push(("vcolor_mb".into(), if scene.gpu_vcolors.is_empty() { 0.0 } else { (scene.gpu_vcolors.len() * 4 + room.tris * 12) as f64 / (1 << 20) as f64 }));
let b_attrs = buf_room("attrs", bytemuck::cast_slice(&scene.attrs), room.tris * std::mem::size_of::<crate::scene::GpuTriAttr>(), edit);
- let b_nodes = buf("nodes", nodes, st);
+ // (With units, edits write trees into it: units.rs.)
+ let b_nodes = buf("nodes", nodes, if scene.units.is_some() { st | wgpu::BufferUsages::COPY_DST } else { st });
// What the triangles hold on the GPU besides their BLASes: vertices (a, e1, e2), attributes, the software BVH's nodes
// (ROADMAP § 6 step 2's table: a meshed representation against voxel data).
timings.push(("tri_data_mb".into(), (std::mem::size_of_val(tri_verts) + std::mem::size_of_val(&scene.attrs[..]) + nodes.len()) as f64 / (1 << 20) as f64));
@@ -1920,7 +2069,7 @@ impl Gpu {
self.device.poll(wgpu::PollType::wait_indefinitely())?;
timings.push(("upload_ms".into(), t0.elapsed().as_secs_f64() * 1000.0));
let bg_parts = BindParts { nodes: b_nodes, energy: b_energy, texinfo: b_texinfo, tex_view, env_view, sampler, grid_view };
- Ok(Uploaded { bg, bg_parts, tables, accum: b_accum, params: b_params, width: w, height: h, kernel, materials: b_mats, lights: b_lights, objects: b_objects, emitters: b_emit, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, particles, gpu_particles, grids, translucent, media: b_media, vcolor_base: (!scene.gpu_vcolors.is_empty()).then_some(scene.vcolor_base as u64 * 16), media_nodes: scene.media_nodes.clone(), instances: b_instances, room, cdf: b_cdf, cdf_words: env_cdf.len(), region_words, env_tex })
+ Ok(Uploaded { bg, bg_parts, tables, accum: b_accum, params: b_params, width: w, height: h, kernel, materials: b_mats, lights: b_lights, objects: b_objects, emitters: b_emit, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, units: scene.units.clone(), particles, gpu_particles, grids, translucent, media: b_media, vcolor_base: (!scene.gpu_vcolors.is_empty()).then_some(scene.vcolor_base as u64 * 16), media_nodes: scene.media_nodes.clone(), instances: b_instances, room, cdf: b_cdf, cdf_words: env_cdf.len(), region_words, env_tex })
}
/// Bytes Metal allocates for an AABB BLAS over `count` boxes in `boxes` (its own size query through wgpu-hal; None
@@ -2486,11 +2635,11 @@ impl Gpu {
up.tables = tables;
}
- /// The loop guard's count as the GPU has it now (None: no guard): the invocations it stopped since the buffers
- /// were made. Waits for the GPU.
+ /// The loop guard's count as the GPU has it now (None: `kernel` has no guard): the invocations it stopped since
+ /// the buffers were made. Waits for the GPU.
#[cfg(not(target_arch = "wasm32"))]
- pub fn guard_trips(&self, bufs: &KernelBufs) -> Result<Option<u32>> {
- let Some(g) = bufs.guard.as_ref().filter(|_| loop_guard().is_some()) else { return Ok(None) };
+ pub fn guard_trips(&self, bufs: &KernelBufs, kernel: &Kernel) -> Result<Option<u32>> {
+ let Some(g) = bufs.guard.as_ref().filter(|_| loop_guard_of(kernel.features & F_UNITS != 0).is_some()) else { return Ok(None) };
let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("loop guard read"), size: 4, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let mut e = self.device.create_command_encoder(&Default::default());
e.copy_buffer_to_buffer(&g.buffer, g.offset, &read, 0, 4);
@@ -2521,6 +2670,29 @@ impl Gpu {
}
}
+ /// Software traversal's top tree again, over the units as they are now, written to its range of the node buffer
+ /// (what `rebuild_tlas` is to hardware traversal). Err: no tree can be made (more units than its range holds, a
+ /// unit that is nowhere); nothing was written, and the caller rebuilds the scene.
+ pub fn retop(&self, units: &mut crate::units::Units, nodes: &wgpu::Buffer) -> std::result::Result<(), String> {
+ let top = units.top()?;
+ if !top.is_empty() {
+ self.queue.write_buffer(nodes, units.layout.top_first as u64 * 32, bytemuck::cast_slice(&top));
+ }
+ Ok(())
+ }
+
+ /// A mesh tree's nodes into the node buffer at its root (`Units::add_tree` placed it).
+ pub fn write_tree(&self, nodes: &wgpu::Buffer, root: u32, tree: &crate::units::MeshTree) {
+ self.queue.write_buffer(nodes, root as u64 * 32, bytemuck::cast_slice(&tree.nodes));
+ }
+
+ /// A freed mesh tree's nodes (`Units::drop_tree`: its root and length) are room again: leaves that end a walk
+ /// (`units::FILL`), as the room was laid out. (No unit names them: `Units::top` holds that. This is so that the
+ /// room never holds a part of an old tree beside a part of a new one.)
+ pub fn fill_tree(&self, nodes: &wgpu::Buffer, (root, len): (u32, u32)) {
+ self.queue.write_buffer(nodes, root as u64 * 32, bytemuck::cast_slice(&vec![crate::units::FILL; len as usize]));
+ }
+
pub fn rebuild_tlas(&self, accel: &Accel, e: &mut wgpu::CommandEncoder) {
e.build_acceleration_structures(std::iter::empty::<&wgpu::BlasBuildEntry>(), [&accel.tlas]);
}
@@ -2684,7 +2856,7 @@ impl Gpu {
}
let (b_accum, b_params, bg) = (&up.accum, &up.params, &up.bg);
let accum_size = b_accum.size();
- let stopped_before = self.guard_trips(&self.no_vis_bufs)?;
+ let stopped_before = self.guard_trips(&self.no_vis_bufs, &up.kernel)?;
let t1 = Instant::now();
@@ -2715,9 +2887,9 @@ impl Gpu {
}
timings.push(("trace_ms".into(), t1.elapsed().as_secs_f64() * 1000.0));
// The loop guard, if the kernel has it: a render in which it stopped a loop has wrong pixels, and is an error.
- if let (Some(before), Some(now)) = (stopped_before, self.guard_trips(&self.no_vis_bufs)?) {
+ if let (Some(before), Some(now)) = (stopped_before, self.guard_trips(&self.no_vis_bufs, &up.kernel)?) {
if now != before {
- return Err(anyhow!("the loop guard stopped {} of the kernel's invocations at {} iterations (THREERT_LOOP_GUARD): a traversal that does not end on this scene's data, or a limit too low for it", now.wrapping_sub(before), loop_guard().unwrap_or(0)));
+ return Err(anyhow!("the loop guard stopped {} of the kernel's invocations at {} iterations (THREERT_LOOP_GUARD): a traversal that does not end on this scene's data, or a limit too low for it", now.wrapping_sub(before), loop_guard_of(up.kernel.features & F_UNITS != 0).unwrap_or(0)));
}
}
let t_tl = Instant::now();
@@ -2814,21 +2986,74 @@ mod tests {
println!("source live {}", sha(&crate::live::live_source(false)));
for hwrt in [false, true] {
let base = kernel_base(hwrt);
- assert_eq!(guarded(&base, false), base);
- println!("source kernel hwrt={hwrt} {}", sha(&guarded(&base, false)));
+ assert_eq!(guarded(&base, false, false), base);
+ println!("source kernel hwrt={hwrt} {}", sha(&guarded(&base, false, false)));
// Every combination of the features that patch the source (`kernel_source`), each as compiled.
let bits = [F_TINT, F_UNLIT, F_BACKGROUND, F_VCOLOR, F_GRID];
let mut all = Sha256::new();
for m in 0..32u32 {
let f = bits.iter().enumerate().filter(|(k, _)| m >> k & 1 == 1).fold(0, |a, (_, b)| a | b);
let src = kernel_source(&base, f);
- assert_eq!(guarded(&src, false), src);
- all.update(guarded(&src, false).as_bytes());
+ assert_eq!(guarded(&src, false, false), src);
+ all.update(guarded(&src, false, false).as_bytes());
}
println!("source kernel hwrt={hwrt} x32 features {}", all.finalize().iter().map(|b| format!("{b:02x}")).collect::<String>());
}
}
+ /// A kernel with units has the loop guard natively with nothing set, at the browser's limit; THREERT_LOOP_GUARD=0
+ /// takes it out, a limit set is the limit, a page's limit comes first. A kernel without units has it only where
+ /// one is set, or in a browser.
+ #[test]
+ fn a_kernel_with_units_has_the_loop_guard() {
+ assert_eq!(guard_limit(0, None, true, false), Some(65536));
+ assert_eq!(guard_limit(0, None, false, false), None);
+ assert_eq!(guard_limit(0, Some(0), true, false), None);
+ assert_eq!(guard_limit(0, Some(0), true, true), None);
+ assert_eq!(guard_limit(0, Some(16), true, false), Some(16));
+ assert_eq!(guard_limit(0, Some(16), false, false), Some(16));
+ assert_eq!(guard_limit(0, None, false, true), Some(65536));
+ assert_eq!(guard_limit(8192, Some(0), false, false), Some(8192));
+ if std::env::var("THREERT_LOOP_GUARD").is_ok() {
+ return;
+ }
+ // As compiled: the source with units has every loop bounded and the count's buffer; hardware traversal, which
+ // never has units, has room for the count only when a limit is set.
+ let src = kernel_source(&kernel_base(false), F_UNITS);
+ let g = guarded(&src, false, true);
+ assert!(g.contains("return LOOP_GUARD_N > 65536u;") && g.contains(&crate::merged::guard_decl()), "the guard and its count");
+ // (That it bounds every loop: merged.rs `the_guard_bounds_every_loop`. The unit walk's are among them.)
+ let stops = |s: &str| s.matches("if (loop_guard()) { break; }").count();
+ let flat = crate::merged::guard(&format!("{}\n{}", kernel_base(false), crate::merged::guard_decl()), 65536, crate::merged::GUARD_TRIPS.name);
+ assert!(stops(&g) > stops(&flat) && stops(&flat) > 40);
+ assert_eq!(guarded(&src, false, false), src, "units told to have no guard: the source as written");
+ // What a native session with units compiles with nothing set, to naga (wgpu's front end).
+ let m = naga::front::wgsl::parse_str(&g).unwrap_or_else(|e| panic!("{}", e.emit_to_string(&g)));
+ naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all()).validate(&m).unwrap_or_else(|e| panic!("{}", e.emit_to_string(&g)));
+ assert!(guard_room(false) && !guard_room(true));
+ }
+
+ /// Software traversal's units are in a kernel only when the scene has them (F_UNITS): the source without the
+ /// feature is the file; with it, the still scene's walk hands its hit to `trace_units`, whose text is there once,
+ /// inside the software traversal (the part hardware traversal's source replaces, which therefore cannot have it).
+ #[test]
+ fn units_are_spliced_into_software_traversal_only() {
+ let base = kernel_base(false);
+ assert!(!base.contains("trace_units"));
+ let u = kernel_source(&base, F_UNITS);
+ assert_eq!(u.matches("fn trace_units(").count(), 1);
+ assert_eq!(u.matches("hit = trace_units(o, d, hit, mode);").count(), 1);
+ let (begin, end, at) = (u.find("// @trace-begin").unwrap(), u.find("// @trace-end").unwrap(), u.find("fn trace_units(").unwrap());
+ assert!(begin < at && at < end);
+ // Taking the units out again gives the file back: nothing else was touched.
+ let call = " hit = trace_units(o, d, hit, mode);\n";
+ let body = format!("\n{}\n// @trace-end\n", include_str!("../shaders/trace_units.wgsl"));
+ assert_eq!(u.replacen(call, "", 1).replacen(&body, "\n// @trace-end\n", 1), base);
+ // Hardware traversal's source has neither anchor.
+ let hw = kernel_base(true);
+ assert!(!hw.contains("// @trace-end") && !hw.contains("return trace_procs(o, d, hit, mode);"));
+ }
+
#[test]
fn kernel_source_finds_its_anchors() {
let base = include_str!("../shaders/pathtrace.wgsl");
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 8104bff..cd290c0 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -21,6 +21,7 @@ pub mod script;
pub mod skin;
pub mod sky;
pub mod tables;
+pub mod units;
pub mod texpack;
#[cfg(not(target_arch = "wasm32"))]
pub mod view;
@@ -350,19 +351,62 @@ pub fn fog_params(fog: Option<&desc::Fog>) -> [[f32; 4]; 4] {
]
}
+/// `prepare` for an offline render: under software traversal every instance flattened unless THREERT_UNITS=1.
pub fn prepare(g: &gpu::Gpu, sc: &mut scene::Scene, timings: &mut Vec<(String, f64)>) -> Prepared {
+ prepare_as(g.hwrt, units_on(false), sc, timings)
+}
+
+/// `prepare` for a live session: under software traversal the instances are units unless THREERT_UNITS=0.
+pub fn prepare_live(g: &gpu::Gpu, sc: &mut scene::Scene, timings: &mut Vec<(String, f64)>) -> Prepared {
+ prepare_as(g.hwrt, units_on(true), sc, timings)
+}
+
+/// Whether software traversal keeps a scene's instances as units (units.rs). A live session and a browser do: units
+/// are what they edit in place, and what a browser's memory and load time need. An offline render does not: it
+/// edits nothing, it is the reference the catalog's bytes are compared by, and its kernel and bytes stay what they
+/// were before units. THREERT_UNITS=1 has an offline render use them (the A/B against a live frame's units);
+/// THREERT_UNITS=0 flattens everywhere (the A/B against units).
+pub(crate) fn units_on(live: bool) -> bool {
+ units_said(std::env::var("THREERT_UNITS").ok().as_deref(), live)
+}
+
+fn units_said(var: Option<&str>, live: bool) -> bool {
+ match var {
+ Some("0") => false,
+ Some("1") => true,
+ _ => live || cfg!(target_arch = "wasm32"),
+ }
+}
+
+/// Whether `prepare_live` will keep the scene's instances as units (software traversal, and it has instances), asked
+/// before it runs (live.rs `load_scene`: the light tree's part for emitters edits add).
+pub fn units_wanted(hwrt: bool, sc: &scene::Scene) -> bool {
+ !hwrt && units_on(true) && !sc.instances.is_empty() && sc.instances.len() <= units::MAX_UNITS
+}
+
+/// `prepare` for a traversal: hardware ray queries, or software traversal with units (units.rs) or without.
+pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut Vec<(String, f64)>) -> Prepared {
let t = Instant::now();
- // Software traversal has no instancing: the instances become ordinary world-space triangles.
- if !g.hwrt && !sc.instances.is_empty() {
- flatten_instances(sc);
+ // Software traversal: the instances stay instances, units of a second level (units.rs; docs/RUNTIME.md "Software
+ // traversal with units"), each mesh with a tree of its own over its model-space triangles, which are put in the
+ // tree's order here, before anything counts them. Without units (THREERT_UNITS=0, the A/B; a mesh no tree can
+ // be made of; more instances than a top tree holds) the instances become ordinary world-space triangles, as
+ // they all did before.
+ let mut trees = None;
+ if !hwrt && !sc.instances.is_empty() {
+ trees = if units && sc.instances.len() <= units::MAX_UNITS { unit_trees(sc) } else { None };
+ match &trees {
+ Some(_) => flatten_deforming(sc),
+ None => flatten_instances(sc),
+ }
}
// Software traversal walks each procedural object's boxes through a tree of its own, and the tree over no box is
// not one the kernel can walk (bvh.rs `EMPTY`): an object without boxes has nothing to meet, and is left out.
- if !g.hwrt {
+ if !hwrt {
sc.procs.retain(|p| !p.blob.boxes.is_empty());
}
// Hardware RT only needs triangles grouped by shadow casting; software traversal needs our BVH.
- let bvh = if g.hwrt {
+ let bvh = if hwrt {
let mut order: Vec<u32> = (0..sc.tris.len() as u32).collect();
order.sort_by_key(|&i| group_of(sc.tri_flags[i as usize]));
bvh::Bvh { nodes: vec![bvh::GpuNode { bmin: [0.0; 3], left_or_first: 0, bmax: [0.0; 3], count: 0 }], order }
@@ -390,19 +434,64 @@ pub fn prepare(g: &gpu::Gpu, sc: &mut scene::Scene, timings: &mut Vec<(String, f
for (k, (t, a)) in sc.pool_tris.iter().zip(&sc.pool_attrs).enumerate() {
let [a0, b, c] = *t;
let (e1, e2): (Vec3A, Vec3A) = (b - a0, c - a0);
- tri_verts.push([a0.x, a0.y, a0.z, f32::from_bits(if k < deforming { scene::TRI_DYNAMIC } else { 0 })]);
+ // (A unit's triangles are in its tree's order, cutouts among the rest: each carries its own flag, as the still
+ // scene's do. Hardware traversal has them apart, in a geometry of their own.)
+ let cutout = trees.is_some() && sc.materials.get(a.uv[3].to_bits() as usize).is_some_and(|m| m.uv2[3] > 0.0);
+ tri_verts.push([a0.x, a0.y, a0.z, f32::from_bits(if k < deforming { scene::TRI_DYNAMIC } else { 0 } | if cutout { scene::TRI_MASKED } else { 0 })]);
tri_verts.push([e1.x, e1.y, e1.z, 0.0]);
tri_verts.push([e2.x, e2.y, e2.z, 0.0]);
attrs.push(*a);
}
sc.gpu_instances = sc.instances.iter().map(|i| { let m = sc.meshes[i.mesh as usize]; i.gpu(pool_first as u32 + m.first, m.opaque) }).collect();
+ // A scene whose triangles are all units': the still tree is then the leaf of one triangle, triangle 0 (bvh.rs
+ // `EMPTY`), which no ray meets while triangle 0 is the zeros of an empty buffer. Here triangle 0 is the pool's
+ // first, a mesh's in its model space, and the still walk would meet it standing in the world. The leaf gets a
+ // triangle of its own after the pool, without area.
+ let no_still = trees.is_some() && pool_first == 0;
+ let nothing = tri_verts.len() / 3;
+ if no_still {
+ tri_verts.extend([[0.0; 4]; 3]);
+ attrs.push(bytemuck::Zeroable::zeroed());
+ }
+ // The units: the mesh trees after the still tree's nodes, room for the trees and units edits add (the edit room's
+ // triangles and records, gpu.rs `EditRoom`), the top tree; each unit's record gets its tree's root.
+ let mut nodes = bvh.nodes;
+ if no_still {
+ nodes[0].left_or_first = nothing as u32;
+ }
+ sc.units = None;
+ if let Some(trees) = trees {
+ let room = gpu::EditRoom::for_scene(sc, tri_verts.len() / 3, sc.instances.len() + sc.procs.len(), false, true);
+ let used: usize = trees.iter().flatten().map(|t| t.nodes.len()).sum();
+ let mut u = units::Units { layout: units::Layout::new(nodes.len(), used + room.tris, sc.instances.len() + room.records), trees: vec![None; trees.len()], slots: vec![None; sc.instances.len()], count: 0, records: sc.instances.len() + sc.procs.len() + room.records };
+ let still = nodes.len();
+ nodes.resize(still + u.layout.nodes(), units::FILL);
+ for (k, t) in trees.iter().enumerate() {
+ if let Some(t) = t {
+ let root = u.add_tree(k as u32, t).expect("the mesh range holds the build's trees") as usize;
+ nodes[root..root + t.nodes.len()].copy_from_slice(&t.nodes);
+ }
+ }
+ for (r, i) in sc.instances.iter().enumerate() {
+ if let Some(unit) = u.unit(i.mesh, i.world, i.hidden) {
+ sc.gpu_instances[r] = units::unit_record(sc.gpu_instances[r], unit.root, i.cast_shadow);
+ u.slots[r] = Some(unit);
+ }
+ }
+ // (A scene whose units the top tree cannot hold, or with one that is nowhere: none is drawn, and it says so.)
+ match u.top() {
+ Ok(top) => nodes[u.layout.top_first as usize..u.layout.top_first as usize + top.len()].copy_from_slice(&top),
+ Err(e) => eprintln!("units: no top tree ({e}): the scene's instances are not drawn"),
+ }
+ sc.units = Some(u);
+ }
// Procedural geometry: its records after the model instances', its boxes / materials / data in `proc_data`.
- let layout = scene::proc_layout(&sc.procs, !g.hwrt);
+ let layout = scene::proc_layout(&sc.procs, !hwrt);
sc.proc_records = sc.procs.iter().zip(&layout.headers).map(|(p, &h)| p.gpu(h)).collect();
sc.proc_layout = (!sc.procs.is_empty()).then_some(layout);
// Translucent particles (hardware RT): after the pool, in no group (only the translucency pass traces them).
sc.trans_first = (tri_verts.len() / 3) as u32;
- if g.hwrt {
+ if hwrt {
for (t, a) in sc.trans_tris.iter().zip(&sc.trans_attrs) {
let [a0, b, c] = *t;
let (e1, e2): (Vec3A, Vec3A) = (b - a0, c - a0);
@@ -426,7 +515,7 @@ pub fn prepare(g: &gpu::Gpu, sc: &mut scene::Scene, timings: &mut Vec<(String, f
v
};
// Posed models: where each of their triangles landed (they are re-skinned in place, hardware RT only).
- if g.hwrt && (!sc.retained.dynamic.is_empty() || !sc.retained.rigid.is_empty() || !sc.particles.is_empty() || !sc.gpu_particles.is_empty()) {
+ if hwrt && (!sc.retained.dynamic.is_empty() || !sc.retained.rigid.is_empty() || !sc.particles.is_empty() || !sc.gpu_particles.is_empty()) {
let first_dynamic: usize = groups[..4].iter().sum();
let finals: std::collections::HashMap<u32, u32> = bvh.order[first_dynamic..].iter().enumerate().map(|(k, &i)| (i, (first_dynamic + k) as u32)).collect();
for d in sc.retained.dynamic.values_mut().chain(sc.retained.rigid.values_mut().map(|r| &mut r.rest)) {
@@ -614,7 +703,9 @@ pub fn prepare(g: &gpu::Gpu, sc: &mut scene::Scene, timings: &mut Vec<(String, f
vol2: fog[3],
raster: [0.0; 4],
cache: [0.0; 4],
- motion: [0.0; 4],
+ // (z, w: software traversal's units: the top tree's root and their count, as bits; trace_units.wgsl. y is
+ // `render --signals`'.)
+ motion: sc.units.as_ref().map_or([0.0; 4], |u| [0.0, 0.0, f32::from_bits(u.layout.top_first), f32::from_bits(u.count)]),
prev_pos: [0.0; 4],
prev_fwd: [0.0; 4],
prev_right: [0.0; 4],
@@ -636,10 +727,72 @@ pub fn prepare(g: &gpu::Gpu, sc: &mut scene::Scene, timings: &mut Vec<(String, f
first += u32::try_from(count).expect("more than 2^32 triangles");
}
let energy = energy_lut();
- Prepared { tri_verts, groups, nodes: bvh.nodes, emitters, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, mat_runs, fixed_mats, tri_order }
+ Prepared { tri_verts, groups, nodes, emitters, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, mat_runs, fixed_mats, tri_order }
}
/// Instances as world-space triangles (software traversal), appended to the flattened ones with their objects.
+/// Software traversal's units (units.rs): a tree for each instanced mesh that keeps its shape, its triangles (and
+/// what goes with them: attributes, vertex colours) put in the tree's order. None: no units (a mesh no tree can be
+/// made of: a vertex that is not a number); the caller flattens every instance then.
+fn unit_trees(sc: &mut scene::Scene) -> Option<Vec<Option<units::MeshTree>>> {
+ let mut trees = Vec::with_capacity(sc.meshes.len());
+ for m in &sc.meshes {
+ if m.deforms || m.count == 0 {
+ trees.push(None);
+ continue;
+ }
+ match units::mesh_tree(&sc.pool_tris[m.first as usize..(m.first + m.count) as usize]) {
+ Ok(t) => trees.push(Some(t)),
+ Err(e) => {
+ eprintln!("units: {e}: the scene's instances are flattened");
+ return None;
+ }
+ }
+ }
+ if !sc.pool_vcolors.is_empty() {
+ sc.pool_vcolors.resize(sc.pool_tris.len(), scene::WHITE);
+ }
+ for (m, t) in sc.meshes.iter().zip(&trees) {
+ let Some(t) = t else { continue };
+ let r = m.first as usize..(m.first + m.count) as usize;
+ let tris: Vec<_> = t.order.iter().map(|&i| sc.pool_tris[r.start + i as usize]).collect();
+ sc.pool_tris[r.clone()].copy_from_slice(&tris);
+ let attrs: Vec<_> = t.order.iter().map(|&i| sc.pool_attrs[r.start + i as usize]).collect();
+ sc.pool_attrs[r.clone()].copy_from_slice(&attrs);
+ if !sc.pool_vcolors.is_empty() {
+ let colors: Vec<_> = t.order.iter().map(|&i| sc.pool_vcolors[r.start + i as usize]).collect();
+ sc.pool_vcolors[r].copy_from_slice(&colors);
+ }
+ }
+ Some(trees)
+}
+
+/// With units: the instances of meshes that deform (a pose a crowd shares) are still written out as world-space
+/// triangles, as every instance was. They keep their place among the instances (edits name instances by index) and
+/// are no unit.
+fn flatten_deforming(sc: &mut scene::Scene) {
+ for k in 0..sc.instances.len() {
+ let inst = sc.instances[k].clone();
+ let m = sc.meshes[inst.mesh as usize];
+ if inst.hidden || !m.deforms {
+ continue;
+ }
+ let first = sc.tris.len() as u32;
+ for k in m.first..m.first + m.count {
+ if let Some(&c) = sc.pool_vcolors.get(k as usize) {
+ scene::put_colors(&mut sc.vcolors, sc.tris.len(), Some(vec![c]));
+ }
+ sc.tris.push(inst.tri(&sc.pool_tris[k as usize]));
+ sc.tri_flags.push(scene::instance_tri_flags(&inst, &sc.pool_attrs[k as usize], &sc.materials));
+ sc.attrs.push(scene::instance_attr(&sc.pool_attrs[k as usize], inst.world, inst.object));
+ }
+ sc.tri_nodes.push((inst.name.clone(), first, sc.tris.len() as u32));
+ if let Some(i) = inst.sub {
+ sc.tri_instances.push((first, sc.tris.len() as u32, i));
+ }
+ }
+}
+
fn flatten_instances(sc: &mut scene::Scene) {
for inst in std::mem::take(&mut sc.instances) {
if inst.hidden {
@@ -883,3 +1036,170 @@ mod light_lod_tests {
assert!(mean(&table) < 0.5 * mean(&unsorted), "groups are compact: {} vs {}", mean(&table), mean(&unsorted));
}
}
+
+#[cfg(test)]
+mod units_tests {
+ use super::*;
+ use crate::units::cpu::{Kernel, INF, TRACE_CLOSEST, TRACE_SHADOW};
+ use crate::world::{Geometry, Kind, World};
+ use glam::{Mat4, Quat};
+
+ /// A world with a flattened ground, meshes of their own (`own_blas`: units under software traversal) turned and
+ /// scaled, one that casts no shadow, one hidden, and an instanced mesh of five instances of which four are drawn.
+ fn world(ground: bool) -> World {
+ let mut w = World::default();
+ w.set_material(1, serde_json::from_value(serde_json::json!({ "name": "m", "color": [0.5, 0.5, 0.5], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true })).unwrap());
+ let quad = |s: f32| Geometry { positions: vec![-s, -s, 0.0, s, -s, 0.0, s, s, 0.0, -s, s, 0.0], normals: [0.0, 0.0, 1.0].repeat(4), uvs: vec![0.0; 8], indices: vec![0, 1, 2, 0, 2, 3], groups: vec![], colors: vec![] };
+ // A closed shape of 80 triangles (a strip of quads around an axis), for a tree with interior nodes.
+ let ring = {
+ let (mut p, mut n, mut idx) = (vec![], vec![], vec![]);
+ for k in 0..=40u32 {
+ let a = k as f32 / 40.0 * std::f32::consts::TAU;
+ for y in [-0.5f32, 0.5] {
+ p.extend([a.cos() * (0.6 + 0.2 * y), y, a.sin() * 0.6]);
+ n.extend([a.cos(), 0.0, a.sin()]);
+ }
+ }
+ for k in 0..40u32 {
+ idx.extend([2 * k, 2 * k + 1, 2 * k + 2, 2 * k + 1, 2 * k + 3, 2 * k + 2]);
+ }
+ Geometry { uvs: vec![0.0; p.len() / 3 * 2], positions: p, normals: n, indices: idx, groups: vec![], colors: vec![] }
+ };
+ w.set_geometry(2, quad(6.0)).unwrap();
+ w.set_geometry(3, quad(0.5)).unwrap();
+ w.set_geometry(5, ring).unwrap();
+ let mesh = |geometry, own_blas| Kind::Mesh { geometry, material: 1, own_blas, materials: vec![] };
+ if ground {
+ w.set_object(10, "ground".into(), None, mesh(2, false), true, false).unwrap();
+ w.set_transform(10, Vec3::new(0.0, -1.0, 0.0), Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2), Vec3::ONE).unwrap();
+ }
+ let place = |w: &mut World, id: u32, geometry: u32, at: [f32; 3], turn: f32, scale: [f32; 3], shadow: bool| {
+ w.set_object(id, format!("o{id}"), None, mesh(geometry, true), shadow, false).unwrap();
+ w.set_transform(id, Vec3::from(at), Quat::from_euler(glam::EulerRot::XYZ, turn, turn * 0.7, 0.3), Vec3::from(scale)).unwrap();
+ };
+ place(&mut w, 11, 5, [0.0, 0.0, 0.0], 0.4, [1.0, 1.0, 1.0], true);
+ place(&mut w, 12, 5, [2.0, 0.5, -1.0], 1.9, [0.5, 2.0, 0.7], true);
+ place(&mut w, 13, 3, [-2.0, 0.2, 0.5], 0.9, [3.0, 1.0, 1.0], false);
+ place(&mut w, 14, 5, [0.3, 0.1, 0.2], 2.5, [1.2, 0.4, 1.2], true);
+ place(&mut w, 15, 3, [0.0, 3.0, 0.0], 0.0, [1.0, 1.0, 1.0], true);
+ w.set_visible(15, false).unwrap();
+ w.set_object(20, "many".into(), None, Kind::Instanced { geometry: 5, procedural: false, materials: vec![1], capacity: 5 }, true, false).unwrap();
+ let m: Vec<f32> = (0..5).flat_map(|k| Mat4::from_scale_rotation_translation(Vec3::splat(0.6), Quat::from_rotation_y(k as f32), Vec3::new(-4.0 + 2.0 * k as f32, 1.5, -3.0)).to_cols_array()).collect();
+ w.set_instances(20, 4, Some(m), None, None).unwrap();
+ let cam = serde_json::from_value(serde_json::json!({ "fov": 50, "near": 0.1, "far": 100, "exposure": { "mode": "manual", "ev100": 0 } })).unwrap();
+ w.set_object(4, "camera".into(), None, Kind::Camera(cam), true, false).unwrap();
+ w.set_transform(4, Vec3::new(0.0, 1.0, 9.0), Quat::IDENTITY, Vec3::ONE).unwrap();
+ w.set_settings(crate::world::Settings { camera: Some(4), ..Default::default() });
+ w
+ }
+
+ /// `prepare` under software traversal with units lays out what the kernel walks (the still tree, the meshes'
+ /// trees and their triangles in tree order, the records with their roots, the top tree, the parameters): the
+ /// kernel's walk over it, on the CPU with every read checked, meets what it meets in the same scene with every
+ /// instance flattened into world-space triangles (the software traversal there was), ray for ray: the same
+ /// distance (to the rounding of testing a triangle in its own space instead of the world's), and shadow rays
+ /// blocked alike (a unit that casts none lets them through). No GPU.
+ #[test]
+ fn a_scene_with_units_is_the_flattened_scene_to_every_ray() {
+ agree(&world(true), (3000, 400, 2000));
+ }
+
+ /// The same with no still triangle at all: the still tree is then the leaf of one triangle (bvh.rs `EMPTY`), and
+ /// that triangle must be one no ray meets, not the first of the units' (a mesh's, in its model space). First seen
+ /// on a GPU: `geometry/instanced`, two planes, darker towards a triangle standing at the origin.
+ #[test]
+ fn a_scene_of_units_alone_is_the_flattened_scene_to_every_ray() {
+ agree(&world(false), (1000, 1000, 400));
+ }
+
+ /// Units are a live session's and a browser's: an offline render flattens a scene's instances as it did before
+ /// units, unless told (THREERT_UNITS=1), and its kernel is then the one without the unit walk. THREERT_UNITS=0
+ /// flattens everywhere.
+ #[test]
+ fn an_offline_render_has_no_units_unless_told() {
+ let browser = cfg!(target_arch = "wasm32");
+ assert_eq!((units_said(None, false), units_said(None, true)), (browser, true));
+ assert_eq!((units_said(Some("1"), false), units_said(Some("1"), true)), (true, true));
+ assert_eq!((units_said(Some("0"), false), units_said(Some("0"), true)), (false, false));
+ assert_eq!(units_said(Some(""), false), browser);
+ if std::env::var("THREERT_UNITS").is_ok() {
+ return;
+ }
+ // What `prepare` hands an offline render of a scene with instances, and `prepare_live` a live session.
+ let build = |live: bool| {
+ let mut sc = scene::build(&world(true), std::path::Path::new("."), &default_presets_dir(), None).unwrap();
+ let p = prepare_as(false, units_on(live), &mut sc, &mut vec![]);
+ (sc, p)
+ };
+ let (off, po) = build(false);
+ let (flat, pf) = {
+ let mut sc = scene::build(&world(true), std::path::Path::new("."), &default_presets_dir(), None).unwrap();
+ let p = prepare_as(false, false, &mut sc, &mut vec![]);
+ (sc, p)
+ };
+ assert!(off.units.is_none() && off.instances.is_empty(), "offline: flattened");
+ assert_eq!(gpu::instance_features(&off) & gpu::F_UNITS, 0, "offline: the kernel without the unit walk");
+ assert_eq!(gpu::instance_features(&off), gpu::instance_features(&flat));
+ assert!(bytemuck::cast_slice::<_, u8>(&po.tri_verts) == bytemuck::cast_slice::<_, u8>(&pf.tri_verts) && bytemuck::cast_slice::<_, u8>(&po.nodes) == bytemuck::cast_slice::<_, u8>(&pf.nodes), "offline: the flattened scene's bytes");
+ let (live, _) = build(true);
+ assert!(live.units.is_some() && gpu::instance_features(&live) & gpu::F_UNITS != 0, "live: units");
+ assert!(units_wanted(false, &scene::build(&world(true), std::path::Path::new("."), &default_presets_dir(), None).unwrap()) && !units_wanted(true, &off));
+ }
+
+ fn agree(w: &World, least: (usize, usize, usize)) {
+ let build = |units: bool| {
+ let mut sc = scene::build(&w, std::path::Path::new("."), &default_presets_dir(), None).unwrap();
+ let p = prepare_as(false, units, &mut sc, &mut vec![]);
+ (sc, p)
+ };
+ let (su, pu) = build(true);
+ let (sf, pf) = build(false);
+ assert_eq!(su.tris.is_empty(), w.objects.get(&10).is_none(), "still triangles: the ground's only");
+ let u = su.units.as_ref().expect("the scene has units");
+ assert!(sf.units.is_none() && sf.instances.is_empty(), "flattened: no instance is left");
+ // Nine instances: four own meshes shown, one hidden (no instance at all), five of the instanced mesh of which
+ // one is hidden: eight units in the top tree.
+ assert_eq!((su.instances.len(), u.count), (9, 8), "{:?}", su.instances.iter().map(|i| (i.name.clone(), i.hidden)).collect::<Vec<_>>());
+ assert!(gpu::instance_features(&su) & gpu::F_UNITS != 0 && gpu::instance_features(&sf) & gpu::F_UNITS == 0);
+ assert_eq!((pu.params.motion[2].to_bits(), pu.params.motion[3].to_bits()), (u.layout.top_first, 8));
+ // The flattened scene holds every instance's triangles; the scene with units holds each mesh's once.
+ assert!(pf.tri_verts.len() > pu.tri_verts.len());
+ assert_eq!(pu.nodes.len(), u.layout.top_first as usize + u.layout.top_cap as usize);
+ let kernel = |p: &Prepared, sc: &scene::Scene| {
+ let (top, units) = (p.params.motion[2].to_bits(), p.params.motion[3].to_bits());
+ (p.nodes.clone(), p.tri_verts.clone(), sc.gpu_instances.clone(), top, units)
+ };
+ let (ku, kf) = (kernel(&pu, &su), kernel(&pf, &sf));
+ let walk = |k: &(Vec<bvh::GpuNode>, Vec<[f32; 4]>, Vec<scene::GpuInstance>, u32, u32), o: Vec3A, d: Vec3A, mode: u32| {
+ let instances = if k.2.is_empty() { vec![scene::GpuInstance::default()] } else { k.2.clone() };
+ let kernel = Kernel { nodes: &k.0, tri_verts: &k.1, instances: &instances, top: k.3, units: k.4, steps: Default::default(), budget: 1 << 20, deepest: Default::default() };
+ kernel.trace(o, d, INF, mode).unwrap_or_else(|e| panic!("ray {o} {d}, mode {mode}: the kernel {e}"))
+ };
+ let mut s = 12345u64;
+ let mut rnd = || {
+ s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ ((s >> 40) as f32) / (1u64 << 24) as f32
+ };
+ let (mut hits, mut on_units, mut shadowed) = (0, 0, 0);
+ for k in 0..9000 {
+ // From around the camera into the scene, through the space around the origin (where a mesh's model-space
+ // triangles would stand if anything took them for the world's), and from above straight down.
+ let (o, d) = if k % 3 == 0 {
+ (Vec3A::new(8.0 * rnd() - 4.0, 4.0 * rnd(), 9.0), Vec3A::new(3.0 * rnd() - 1.5, 3.0 * rnd() - 2.0, -4.0).normalize())
+ } else if k % 3 == 1 {
+ (Vec3A::new(2.0 * rnd() - 1.0, 2.0 * rnd() - 1.0, 4.0), Vec3A::new(0.1 * rnd() - 0.05, 0.1 * rnd() - 0.05, -1.0).normalize())
+ } else {
+ (Vec3A::new(12.0 * rnd() - 6.0, 6.0, 8.0 * rnd() - 5.0), Vec3A::new(0.2 * rnd() - 0.1, -1.0, 0.2 * rnd() - 0.1).normalize())
+ };
+ let (a, b) = (walk(&ku, o, d, TRACE_CLOSEST), walk(&kf, o, d, TRACE_CLOSEST));
+ assert!((a.t - b.t).abs() <= 2e-4 * (1.0 + b.t.min(1e4)) || (a.t == INF) == (b.t == INF) && a.t == INF, "ray {o} {d}: with units {a:?}, flattened {b:?}");
+ assert_eq!(a.t == INF, b.t == INF, "ray {o} {d}: with units {a:?}, flattened {b:?}");
+ hits += (a.t < INF) as usize;
+ on_units += (a.inst != units::cpu::NO_INST) as usize;
+ let (sa, sb) = (walk(&ku, o, d, TRACE_SHADOW), walk(&kf, o, d, TRACE_SHADOW));
+ assert_eq!(sa.t == INF, sb.t == INF, "shadow ray {o} {d}: with units {sa:?}, flattened {sb:?}");
+ shadowed += (sa.t < INF) as usize;
+ }
+ assert!(hits > least.0 && on_units > least.1 && shadowed > least.2, "{hits} hits, {on_units} on units, {shadowed} shadow rays blocked");
+ }
+}
diff --git a/renderer/src/live.rs b/renderer/src/live.rs
index 4d9b473..1de5f1d 100644
--- a/renderer/src/live.rs
+++ b/renderer/src/live.rs
@@ -23,7 +23,7 @@
use crate::gpu::Buf;
use crate::world::World;
-use crate::{gpu, post, prepare, scene, tables};
+use crate::{gpu, post, scene, tables};
// (The headless runner below, native only, is what uses all of it.)
#[cfg_attr(target_arch = "wasm32", allow(unused_imports))]
use anyhow::{anyhow, Result};
@@ -381,7 +381,7 @@ impl Targets {
ae_state: b(),
lumq: b(),
lumb: b(),
- kernel: gpu::KernelBufs::new(d, g.merged, cache, resv, n * 32, n * 16, n * 16),
+ kernel: gpu::KernelBufs::new(d, g.merged, g.guard_room(), cache, resv, n * 32, n * 16, n * 16),
slabs,
lut_view: lut_tex.create_view(&Default::default()),
lut_tex,
@@ -838,6 +838,12 @@ enum Picked {
Proc(scene::ProcObject),
}
+/// What an edit places at an object's slot: a procedural object's BLAS (hardware traversal), or instanced mesh `k`.
+enum Placed {
+ Proc(wgpu::Blas),
+ Mesh(u32),
+}
+
/// One object fewer draws instanced mesh `k`: a mesh edits manage that none draws any more is freed (its triangles a
/// hole the next new mesh can take, its slot reused, its BLAS dropped with it).
fn drop_mesh_user(k: u32, edit: &mut EditState, tables: &mut tables::Tables, meshes: &[scene::InstMesh]) {
@@ -955,9 +961,10 @@ fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Path, w: u32
sc.height = h;
// Emitters its edits add get a light-tree subtree of their own (ROADMAP § 6 step 4; THREERT_LT_DYNAMIC=0: by power
// share, the A/B).
- sc.emitter_slot = gpu::EditRoom::editable(&sc, g.hwrt) && std::env::var("THREERT_LT_DYNAMIC").map_or(true, |v| v != "0");
+ // (Software traversal with units edits in place as hardware traversal does: `units_wanted`.)
+ sc.emitter_slot = gpu::EditRoom::editable(&sc, g.hwrt || crate::units_wanted(g.hwrt, &sc)) && std::env::var("THREERT_LT_DYNAMIC").map_or(true, |v| v != "0");
let mut timings = vec![("build_ms".to_string(), t0.elapsed().as_secs_f64() * 1000.0)];
- let mut prep = prepare(g, &mut sc, &mut timings);
+ let mut prep = crate::prepare_live(g, &mut sc, &mut timings);
let mut tables = tables::Tables::new(&sc, std::mem::take(&mut prep.emitter_tris), prep.light_tree.take());
// (THREERT_EDIT_REBUILD=1: every edit rebuilds, a material that starts emitting too: the A/B.)
tables.emit_in_place = std::env::var("THREERT_EDIT_REBUILD").map_or(true, |v| v != "1");
@@ -1208,9 +1215,9 @@ pub struct LiveCore {
pub cpu_wait_ms: f32,
/// The cloud cover the sky and the sun light were made with (`move_sun`).
sky_cover: f32,
- /// The loop guard (merged.rs `guard`), if the kernel has it: the invocations it has stopped at its limit since the
- /// view was made, as last read back (a frame or two behind, without waiting). Above zero: frames with wrong
- /// pixels, a traversal that did not end on the scene's data. None without the guard.
+ /// The loop guard (merged.rs `guard`), if a kernel of this session may have it: the invocations it has stopped at
+ /// its limit since the view was made, as last read back (a frame or two behind, without waiting). Above zero:
+ /// frames with wrong pixels, a traversal that did not end on the scene's data. None without the guard.
pub guard_trips: Option<u32>,
/// Its readback: the buffer and its state (0 free, 1 mapping, 2 mapped), as the frame timer's.
guard_read: Option<(wgpu::Buffer, Arc<AtomicU32>)>,
@@ -1590,7 +1597,9 @@ impl LiveCore {
let raster = std::env::var("THREERT_RASTER").is_ok_and(|v| v == "1").then(|| Raster::new(&g, w, h));
let cache = cache_on.then(|| RadianceCache { bufs: targets.kernel.cache.clone(), resolve: g.cache_resolve_pipeline(&targets.kernel) });
let kernel_bg = gpu::vis_bind_group(&g.device, &g.vis_layout, raster.as_ref().map_or(&g.no_vis_view, |r| &r.vis), &targets.kernel);
- let guard_read = (gpu::loop_guard().is_some() && targets.kernel.guard.is_some())
+ // (Read whenever a kernel of this session may have the guard: under software traversal a scene's first unit
+ // brings it, `gpu::loop_guard_of`.)
+ let guard_read = (gpu::loop_guard_of(!g.hwrt).is_some() && targets.kernel.guard.is_some())
.then(|| (g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("loop guard read"), size: 4, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }), Arc::new(AtomicU32::new(0))));
let mut core = LiveCore { particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, cap_next: None, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), still: 0, inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, motion_blur_off: false, ghost_fix_off: false, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, over_budget: (0, 0), profile, timer, raster, cache, restir, restir_prev: None, kernel_bg, prev_span: None, reposed: false, emitters_moved: false, cold_frames: 0, pose_span: None, pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), lit_changed: 0, spark_lights: false, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, sky_cover: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);
@@ -1958,12 +1967,14 @@ impl LiveCore {
self.sc.exposure_settings.ae2 = [e, 0.0, 0.0, 0.0];
}
- /// Moves movable instances (hardware RT): their kernel records (the old transform kept as the previous frame's, for
- /// motion vectors), their object entries' pivots and their TLAS transforms; with `build_tlas` it rebuilds the TLAS
- /// (otherwise the dynamic rebuild that follows does). No triangles change. False without hardware RT (the caller
- /// rebuilds: software traversal flattens instances).
+ /// Moves movable instances: their kernel records (the old transform kept as the previous frame's, for motion
+ /// vectors), their object entries' pivots and their TLAS transforms (hardware traversal; with `build_tlas` it
+ /// rebuilds the TLAS, otherwise the dynamic rebuild that follows does) or their units and the top tree over them
+ /// (software traversal, units.rs). No triangles change. False when it cannot (software traversal without units,
+ /// or an instance that is no unit; a top tree that cannot be made): the caller rebuilds.
fn move_instances(&mut self, world: &World, placed: &[(u32, u32)], build_tlas: bool) -> bool {
- let Some(accel) = self.sc.up.accel.as_mut() else { return false };
+ // (Hardware traversal's TLAS instances, or software traversal's units; neither: the caller rebuilds.)
+ let Some(mut top) = gpu::Top::of(&mut self.sc.up.accel, &mut self.sc.up.units) else { return false };
let size = std::mem::size_of::<scene::GpuInstance>() as u64;
let q = &self.g.queue;
// (Many records, a rigid body world's thousands a frame, are written as the one range that holds them: the
@@ -1979,9 +1990,14 @@ impl LiveCore {
Some(Picked::Mesh(inst)) => inst,
_ => &mut self.sc.instances[i as usize],
};
+ // (Software traversal: an instance of a mesh that deforms is no unit; its triangles are among the still
+ // scene's, in the world, and a rebuild moves them.)
+ if !top.has_mesh(inst.mesh) {
+ return false;
+ }
let old = self.sc.gpu_instances[i as usize];
inst.world = w;
- let mut r = inst.gpu(old.info[0], old.info[3]);
+ let mut r = top.record(inst.gpu(old.info[0], old.info[3]), inst.mesh, inst.cast_shadow);
r.p = old.m;
self.sc.gpu_instances[i as usize] = r;
if merged {
@@ -1997,23 +2013,28 @@ impl LiveCore {
if !motion_vectors() {
self.sc.tables.objects[inst.object as usize * st + 1][3] = shader_time(self.time);
}
- let row = |k: usize| [w.x_axis[k], w.y_axis[k], w.z_axis[k], w.w_axis[k]];
- if let Some(t) = accel.tlas[accel.inst_base + i as usize].as_mut() {
- t.transform = [row(0), row(1), row(2)].concat().try_into().unwrap();
- }
+ let slot = top.inst_base() + i as usize;
+ top.moved(slot, w, None);
self.inst_moving.push(i);
}
if merged {
q.write_buffer(&self.sc.up.instances, lo as u64 * size, bytemuck::cast_slice(&self.sc.gpu_instances[lo..=hi]));
}
q.write_buffer(&self.sc.up.objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
- if build_tlas {
- let mut e = self.g.device.create_command_encoder(&Default::default());
- self.g.rebuild_tlas(accel, &mut e);
- q.submit([e.finish()]);
- }
self.inst_moved = true;
- true
+ match top {
+ gpu::Top::Hw(accel) => {
+ if build_tlas {
+ let mut e = self.g.device.create_command_encoder(&Default::default());
+ self.g.rebuild_tlas(accel, &mut e);
+ q.submit([e.finish()]);
+ }
+ true
+ }
+ // (The top tree is built here whoever else changes units this commit: it is CPU work and one write, and a
+ // tree that cannot be made must send the caller to a rebuild now.)
+ gpu::Top::Sw(units) => self.g.retop(units, &self.sc.up.bg_parts.nodes).map_err(|e| eprintln!("units: {e}: rebuilding the scene")).is_ok(),
+ }
}
/// The material table to the GPU: written in place, or, with more materials than its buffer holds (materials added
@@ -2152,7 +2173,9 @@ impl LiveCore {
let nodes: &[[f32; 4]] = e.light_tree.as_ref().map_or(&[], |t| &t.nodes);
let need = ((em.len() + nodes.len()) * 16) as u64;
if need > up.emitters.size() {
- up.emitters = g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("emitters"), size: need + need / 2, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
+ // (The usage it was made with: the merged layout copies the tables each frame, `Gpu::sync_tables`.)
+ let usage = up.emitters.usage();
+ up.emitters = g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("emitters"), size: need + need / 2, usage, mapped_at_creation: false });
g.rebind_scene(up);
}
if !em.is_empty() {
@@ -2277,7 +2300,7 @@ impl LiveCore {
let (now, mv) = (shader_time(self.time), motion_vectors());
let empty = crate::world::InstanceTable::default();
let sc = &mut self.sc;
- let Some(accel) = sc.up.accel.as_mut() else { return Err("software traversal".into()) };
+ let Some(mut top) = gpu::Top::of(&mut sc.up.accel, &mut sc.up.units) else { return Err("software traversal".into()) };
let mut done = 0;
for &id in ids {
// (Removed or hidden: nothing is drawn; a structural change rebuilds.)
@@ -2291,7 +2314,12 @@ impl LiveCore {
let m = world.world_matrix(id);
// Past both the old and the new count every instance is hidden and stays so: left as it is.
let (first, cap) = (place.first as usize, place.drawn.max(t.count).min(capacity) as usize);
- let (rec0, slot0) = if procedural { (sc.proc_first + first, accel.proc_base + first) } else { (first, accel.inst_base + first) };
+ // (A procedural one's hidden instances are out of hardware traversal by their TLAS masks; software
+ // traversal walks every record there is: the build leaves them out.)
+ if procedural && top.sw() {
+ return Err("a procedural instanced mesh (software traversal)".into());
+ }
+ let (rec0, slot0) = if procedural { (sc.proc_first + first, top.proc_base(sc.proc_first) + first) } else { (first, top.inst_base() + first) };
for i in 0..cap {
let (wm, hidden) = scene::instance_world(m, t, i);
if !procedural && !hidden && wm.determinant() < 0.0 {
@@ -2304,9 +2332,12 @@ impl LiveCore {
(p.gpu(old.info[0]), p.entry(n.power, t.custom(i, n.custom), t.color(i)))
} else {
let inst = &mut sc.instances[first + i];
+ if !top.has_mesh(inst.mesh) {
+ return Err("an instanced mesh that is no unit (software traversal)".into());
+ }
(inst.world, inst.hidden) = (wm, hidden);
let (lo, hi) = sc.meshes[inst.mesh as usize].placed_bounds(wm);
- (inst.gpu(old.info[0], old.info[3]), scene::object_row(wm.transform_point3(glam::Vec3::ZERO), n.power, hi - lo, t.custom(i, n.custom), t.color(i)))
+ (top.record(inst.gpu(old.info[0], old.info[3]), inst.mesh, n.cast_shadow), scene::object_row(wm.transform_point3(glam::Vec3::ZERO), n.power, hi - lo, t.custom(i, n.custom), t.color(i)))
};
rec.p = old.m;
sc.gpu_instances[rec0 + i] = rec;
@@ -2318,10 +2349,7 @@ impl LiveCore {
let edited = if !mv || e[0][3] != entry[0][3] { now } else { e[1][3] };
e.copy_from_slice(&entry[..st]);
e[1][3] = edited;
- if let Some(ti) = accel.tlas[slot0 + i].as_mut() {
- ti.transform = gpu::tlas_rows(wm);
- ti.mask = gpu::instance_mask(n.cast_shadow, hidden);
- }
+ top.moved(slot0 + i, wm, Some((n.cast_shadow, hidden)));
}
let q = &self.g.queue;
q.write_buffer(&sc.up.instances, (rec0 * size) as u64, bytemuck::cast_slice(&sc.gpu_instances[rec0..rec0 + cap]));
@@ -2334,10 +2362,15 @@ impl LiveCore {
}
if done > 0 {
self.inst_moved = true;
- if build_tlas {
- let mut e = self.g.device.create_command_encoder(&Default::default());
- self.g.rebuild_tlas(accel, &mut e);
- self.g.queue.submit([e.finish()]);
+ match top {
+ gpu::Top::Hw(accel) => {
+ if build_tlas {
+ let mut e = self.g.device.create_command_encoder(&Default::default());
+ self.g.rebuild_tlas(accel, &mut e);
+ self.g.queue.submit([e.finish()]);
+ }
+ }
+ gpu::Top::Sw(units) => self.g.retop(units, &sc.up.bg_parts.nodes)?,
}
}
Ok(done)
@@ -2631,6 +2664,12 @@ impl LiveCore {
Ok(true)
}
+ /// `guard_trips` for the frame log: None while the scene's kernel has no guard. Natively with nothing set that is
+ /// a scene without units (`gpu::loop_guard_of`): under software traversal the first unit brings the guard.
+ pub fn guard_count(&self) -> Option<u32> {
+ self.guard_trips.filter(|_| gpu::loop_guard_of(self.sc.up.kernel.features & gpu::F_UNITS != 0).is_some())
+ }
+
/// The edit room as the frame log reports it (`room`): triangles, records and object entries in use and held (GPU
/// order counts, holes not in use), its growths, and the GPU bytes of the buffers edits write and of the triangle
/// BLASes the live meshes need (estimated from the build's bytes per triangle), MB.
@@ -2809,7 +2848,13 @@ impl LiveCore {
let (g, assets) = (&self.g, &self.assets);
let features = up.kernel.features;
let grow = Grow { g: &self.g, ok: up.particles.is_none() && up.gpu_particles.is_none() };
- let Some(accel) = up.accel.as_mut() else { return Err("software traversal".into()) };
+ // (Hardware traversal's TLAS and BLASes, or software traversal's units: `gpu::Top`.)
+ let Some(mut top) = gpu::Top::of(&mut up.accel, &mut up.units) else {
+ // Software traversal without units. With units on, that is a scene without an instance yet: the first
+ // one brings the unit walk into the kernel (F_UNITS), as hardware traversal's first brings F_INST.
+ let first = crate::units_on(true) && ch.added.iter().any(|id| matches!(world.objects.get(id).map(|o| &o.kind), Some(Kind::Mesh { own_blas: true, .. } | Kind::Instanced { procedural: false, .. })));
+ return Err(if first { "the scene's first instanced mesh (kernel feature)" } else { "software traversal" }.into());
+ };
// The objects to place again: those added, and those whose geometry was replaced.
let mut todo: std::collections::BTreeSet<u32> = ch.added.clone();
if !ch.geometries.is_empty() {
@@ -2825,7 +2870,7 @@ impl LiveCore {
}
}
}
- let (inst_base, proc_base, proc_first) = (accel.inst_base, accel.proc_base, *proc_first);
+ let (inst_base, proc_base, proc_first) = (top.inst_base(), top.proc_base(*proc_first), *proc_first);
let slot_of = |id: u32, edit: &EditState, tables: &tables::Tables, proc_of: &std::collections::HashMap<u32, usize>| -> Option<(usize, usize)> {
if let Some(&v) = edit.placed.get(&id) {
Some(v)
@@ -2853,7 +2898,7 @@ impl LiveCore {
// An instanced mesh an edit added: its instances, records and entries.
if let Some((r0, cap, o0)) = edit.instanced.remove(id) {
for r in r0..r0 + cap {
- accel.tlas[inst_base + r] = None;
+ top.clear(inst_base + r);
if let Some(i) = instances.get_mut(r) {
i.hidden = true;
}
@@ -2870,7 +2915,7 @@ impl LiveCore {
// An instanced mesh the build placed: its instances out (records and entries stay until the next rebuild).
if let Some(place) = tables.retained.instanced.get(id).filter(|p| !p.procedural) {
for r in place.first as usize..(place.first + place.capacity) as usize {
- accel.tlas[inst_base + r] = None;
+ top.clear(inst_base + r);
if let Some(i) = instances.get_mut(r) {
i.hidden = true;
}
@@ -2886,7 +2931,7 @@ impl LiveCore {
return Err("an object the build placed otherwise (a model, a procedural instanced mesh) removed".into());
}
if let Some((slot, _)) = at {
- accel.tlas[slot] = None;
+ top.clear(slot);
}
unpick(*id, edit, tables, instances, procs, proc_of);
// What it held goes back to the room (the build's records and entries stay until the next rebuild).
@@ -2920,7 +2965,7 @@ impl LiveCore {
emitters_changed |= release(id, tables, meshes, edit.pool_first);
if !world.shown(id) {
if let Some((slot, _)) = at {
- accel.tlas[slot] = None;
+ top.clear(slot);
}
if edit.instanced.contains_key(&id) {
return Err("an instanced mesh added in place hidden".into());
@@ -2952,12 +2997,17 @@ impl LiveCore {
let mut placement = m;
let (record, gpu, blas, entry) = match &o.kind {
Kind::Procedural { .. } => {
+ // (Software traversal walks procedural objects by their count and their own trees in the region:
+ // the build lays those out.)
+ if top.sw() {
+ return Err("a procedural object (software traversal)".into());
+ }
if features & gpu::F_PROC == 0 {
return Err("the scene's first procedural object (kernel feature)".into());
}
let Some(p) = scene::proc_object(world, id, m, object as u32, &tables.retained.materials, assets).map_err(|e| format!("{e:#}"))? else {
if let Some((slot, _)) = at {
- accel.tlas[slot] = None;
+ top.clear(slot);
}
unpick(id, edit, tables, instances, procs, proc_of);
continue;
@@ -3007,7 +3057,7 @@ impl LiveCore {
edit.added.insert(id, Picked::Proc(p));
}
}
- (record, gpu, blas, entry)
+ (record, gpu, Placed::Proc(blas), entry)
}
Kind::Mesh { materials, .. } if materials.len() > 1 => return Err("a mesh with several materials".into()),
Kind::Model { uri, nodes, animation, functions } => {
@@ -3024,16 +3074,19 @@ impl LiveCore {
}
let mesh = *tables.retained.model_mesh.get(&(uri.clone(), nodes.clone())).ok_or("a model not in the scene (its materials and textures load with a rebuild)")?;
let im = meshes[mesh as usize];
+ if !top.has_mesh(mesh) {
+ return Err("a model whose mesh is no unit (it deforms; software traversal flattens it)".into());
+ }
*edit.users.entry(mesh).or_default() += 1;
if let Some(k) = edit.mesh_of.insert(id, mesh) {
drop_mesh_user(k, edit, tables, meshes);
}
let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: o.cast_shadow, name: o.name.clone(), sub: None, hidden: false };
- let gpu = inst.gpu((edit.pool_first as u32) + im.first, im.opaque);
+ let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.opaque), mesh, o.cast_shadow);
let (lo, hi) = im.placed_bounds(m);
let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, o.custom, [1.0; 3]);
edit.added.insert(id, Picked::Mesh(inst));
- (at.map(|(_, r)| r), gpu, gpu::Gpu::mesh_blas(accel, mesh).clone(), entry)
+ (at.map(|(_, r)| r), gpu, Placed::Mesh(mesh), entry)
}
Kind::Mesh { own_blas: true, .. } | Kind::Instanced { procedural: false, .. } => {
// An own-BLAS mesh, or (added in place) an instanced mesh: their mesh made alike.
@@ -3077,16 +3130,29 @@ impl LiveCore {
None => {
let geo = world.geometries.get(geometry).ok_or("unknown geometry")?;
let t0 = Instant::now();
- let (t, a) = if emits { scene::emitter_mesh_tris(geo, m, mat, object as u32) } else { scene::own_mesh_tris(geo, mat) };
+ let (mut t, mut a) = if emits { scene::emitter_mesh_tris(geo, m, mat, object as u32) } else { scene::own_mesh_tris(geo, mat) };
if t.is_empty() {
if let Some((slot, _)) = at {
- accel.tlas[slot] = None;
+ top.clear(slot);
}
unpick(id, edit, tables, instances, procs, proc_of);
continue;
}
+ // Software traversal: the mesh's tree, and its triangles (their attributes, further down their
+ // colours) in the tree's order, as `prepare` lays a unit's mesh out.
+ let tree = match &top {
+ gpu::Top::Hw(_) => None,
+ gpu::Top::Sw(_) => {
+ let tree = crate::units::mesh_tree(&t)?;
+ t = tree.order.iter().map(|&i| t[i as usize]).collect();
+ a = tree.order.iter().map(|&i| a[i as usize]).collect();
+ Some(tree)
+ }
+ };
+ // (A unit's cutout triangles carry their flag; hardware traversal has them in a geometry apart.)
+ let flags = f32::from_bits(if tree.is_some() && class == 1 { scene::TRI_MASKED } else { 0 });
// As `prepare` lays the pool out: (a, flags), e1, e2; attributes; the BLAS's vertices.
- let verts: Vec<[f32; 4]> = t.iter().flat_map(|&[a, b, c]| [[a.x, a.y, a.z, 0.0], [b.x - a.x, b.y - a.y, b.z - a.z, 0.0], [c.x - a.x, c.y - a.y, c.z - a.z, 0.0]]).collect();
+ let verts: Vec<[f32; 4]> = t.iter().flat_map(|&[a, b, c]| [[a.x, a.y, a.z, flags], [b.x - a.x, b.y - a.y, b.z - a.z, 0.0], [c.x - a.x, c.y - a.y, c.z - a.z, 0.0]]).collect();
let blas_verts: Vec<[f32; 3]> = t.iter().flat_map(|&[a, b, c]| [[a.x, a.y, a.z], [b.x, b.y, b.z], [c.x, c.y, c.z]]).collect();
split.tris += t0.elapsed().as_secs_f64() * 1e3;
// The same triangle count as the mesh it replaces: rewritten where it is, its BLAS rebuilt (no
@@ -3097,36 +3163,63 @@ impl LiveCore {
Some(k) => {
let im = meshes[k as usize];
split.deformed += 1;
+ // (Its tree again: the records of the objects that draw it, all placed again by
+ // this edit, take the root it has now.)
+ if let (gpu::Top::Sw(units), Some(tree)) = (&mut top, &tree) {
+ if let Some(old) = units.drop_tree(k) {
+ g.fill_tree(&up.bg_parts.nodes, old);
+ }
+ let root = units.add_tree(k, tree).ok_or("edit room: tree nodes")?;
+ g.write_tree(&up.bg_parts.nodes, root, tree);
+ }
(k, edit.pool_first + im.first as usize, im)
}
None => {
// A hole that fits, else the room's end (grown if it lacks room).
let first = match edit.tris.take(t.len()) {
Some(f) => f,
- None if grow.tris(&mut edit.tris, t.len(), &mut up.verts, &mut up.attrs, &mut up.prev_verts, vcolor_base, accel) => {
+ // (Software traversal's room does not grow: the rebuild makes a larger one.)
+ None if match &mut top { gpu::Top::Hw(accel) => grow.tris(&mut edit.tris, t.len(), &mut up.verts, &mut up.attrs, &mut up.prev_verts, vcolor_base, accel), gpu::Top::Sw(_) => false } => {
edit.grows += 1;
edit.rebind = true;
edit.tris.take(t.len()).ok_or("edit room: triangles")?
}
- None => return Err("edit room: triangles (particles, or the device's limits)".into()),
+ None => return Err(if matches!(top, gpu::Top::Sw(_)) { "edit room: triangles (software traversal's does not grow)" } else { "edit room: triangles (particles, or the device's limits)" }.into()),
};
let mut im = scene::own_inst_mesh(&t, (first - edit.pool_first) as u32, class);
im.emits = emits;
let t1 = Instant::now();
// A freed mesh's slot, else a new one.
- let k = match edit.dead_meshes.pop() {
- Some(k) => {
- g.set_mesh(accel, k, first, im.count, im.opaque);
- meshes[k as usize] = im;
- k
- }
- None => {
- let k = g.add_mesh(accel, first, im.count, im.opaque);
- debug_assert_eq!(k as usize, meshes.len());
- meshes.push(im);
+ let dead = edit.dead_meshes.pop();
+ let k = match &mut top {
+ gpu::Top::Hw(accel) => match dead {
+ Some(k) => {
+ g.set_mesh(accel, k, first, im.count, im.opaque);
+ k
+ }
+ None => g.add_mesh(accel, first, im.count, im.opaque),
+ },
+ // Its tree into the mesh trees' room (a freed mesh's slot gives its tree back first).
+ gpu::Top::Sw(units) => {
+ let k = dead.unwrap_or(meshes.len() as u32);
+ let tree = tree.as_ref().expect("software traversal made the tree");
+ if let Some(old) = units.drop_tree(k) {
+ g.fill_tree(&up.bg_parts.nodes, old);
+ }
+ let Some(root) = units.add_tree(k, tree) else {
+ edit.dead_meshes.extend(dead);
+ edit.tris.give(first, t.len());
+ return Err("edit room: tree nodes".into());
+ };
+ g.write_tree(&up.bg_parts.nodes, root, tree);
k
}
};
+ if k as usize == meshes.len() {
+ meshes.push(im);
+ } else {
+ meshes[k as usize] = im;
+ }
edit.managed.insert(k);
split.blas += t1.elapsed().as_secs_f64() * 1e3;
split.added += 1;
@@ -3136,10 +3229,15 @@ impl LiveCore {
let t2 = Instant::now();
w_verts.put((first * 48) as u64, bytemuck::cast_slice(&verts));
w_attrs.put((first * std::mem::size_of::<scene::GpuTriAttr>()) as u64, bytemuck::cast_slice(&a));
- w_blas.put((first * 36) as u64, bytemuck::cast_slice(&blas_verts));
+ if !top.sw() {
+ w_blas.put((first * 36) as u64, bytemuck::cast_slice(&blas_verts));
+ }
if let Some(base) = vcolor_base {
// White where it has none: the room's slots may hold an earlier mesh's.
- let c = if colored { scene::tri_colors(geo, false, None) } else { vec![scene::WHITE; t.len()] };
+ let mut c = if colored { scene::tri_colors(geo, false, None) } else { vec![scene::WHITE; t.len()] };
+ if let (Some(tree), true) = (&tree, colored) {
+ c = tree.order.iter().map(|&i| c[i as usize]).collect();
+ }
w_colors.put(base + (first * 12) as u64, bytemuck::cast_slice(&c));
}
split.upload += t2.elapsed().as_secs_f64() * 1e3;
@@ -3200,12 +3298,12 @@ impl LiveCore {
}
let r0 = match edit.records.take(cap) {
Some(r) => r,
- None if grow.records(&mut edit.records, cap, &mut up.instances, accel) => {
+ None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, cap, &mut up.instances, accel), gpu::Top::Sw(_) => false } => {
edit.grows += 1;
edit.rebind = true;
edit.records.take(cap).ok_or("edit room: records")?
}
- None => return Err("edit room: records (particles, or the device's limits)".into()),
+ None => return Err(if matches!(top, gpu::Top::Sw(_)) { "edit room: records (software traversal's does not grow)" } else { "edit room: records (particles, or the device's limits)" }.into()),
};
let o0 = match edit.objects.take(cap) {
Some(k) => k,
@@ -3217,7 +3315,6 @@ impl LiveCore {
None => return Err("edit room: objects (particles, or the device's limits)".into()),
};
let (st, size) = (tables.stride, std::mem::size_of::<scene::GpuInstance>());
- let blas = gpu::Gpu::mesh_blas(accel, mesh).clone();
if instances.len() < r0 + cap {
let filler = scene::Instance { mesh, world: glam::Mat4::IDENTITY, object: 0, cast_shadow: false, name: String::new(), sub: None, hidden: true };
instances.resize(r0 + cap, filler);
@@ -3230,10 +3327,10 @@ impl LiveCore {
}
for (i, &(wm, hidden)) in placed.iter().enumerate() {
let inst = scene::Instance { mesh, world: wm, object: (o0 + i) as u32, cast_shadow: o.cast_shadow, name: o.name.clone(), sub: Some(i as u32), hidden };
- let rec = inst.gpu((edit.pool_first as u32) + im.first, im.opaque);
+ let rec = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.opaque), mesh, o.cast_shadow);
w_records.put(((r0 + i) * size) as u64, bytemuck::bytes_of(&rec));
gpu_instances[r0 + i] = rec;
- accel.tlas[inst_base + r0 + i] = Some(wgpu::TlasInstance::new(&blas, gpu::tlas_rows(wm), gpu::INSTANCE_BIT | (r0 + i) as u32, gpu::instance_mask(o.cast_shadow, hidden)));
+ top.place(inst_base + r0 + i, mesh, wm, gpu::INSTANCE_BIT | (r0 + i) as u32, o.cast_shadow, hidden);
let (lo, hi) = im.placed_bounds(wm);
let entry = scene::object_row(wm.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, t.custom(i, o.custom), t.color(i));
w_objects.put(((o0 + i) * st * 16) as u64, bytemuck::cast_slice(&entry[..st]));
@@ -3249,7 +3346,7 @@ impl LiveCore {
placement = glam::Mat4::IDENTITY;
}
let inst = scene::Instance { mesh, world: placement, object: object as u32, cast_shadow: o.cast_shadow, name: o.name.clone(), sub: None, hidden: false };
- let gpu = inst.gpu((edit.pool_first as u32) + im.first, im.opaque);
+ let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.opaque), mesh, o.cast_shadow);
let (lo, hi) = im.placed_bounds(placement);
let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, o.custom, [1.0; 3]);
let record = at.map(|(_, r)| r);
@@ -3259,7 +3356,7 @@ impl LiveCore {
edit.added.insert(id, Picked::Mesh(inst));
}
}
- (record, gpu, gpu::Gpu::mesh_blas(accel, mesh).clone(), entry)
+ (record, gpu, Placed::Mesh(mesh), entry)
}
_ => return Err("not an object with its own BLAS".into()),
};
@@ -3269,12 +3366,12 @@ impl LiveCore {
_ => {
let r = match edit.records.take(1) {
Some(r) => r,
- None if grow.records(&mut edit.records, 1, &mut up.instances, accel) => {
+ None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, 1, &mut up.instances, accel), gpu::Top::Sw(_) => false } => {
edit.grows += 1;
edit.rebind = true;
edit.records.take(1).ok_or("edit room: records")?
}
- None => return Err("edit room: records (particles, or the device's limits)".into()),
+ None => return Err(if matches!(top, gpu::Top::Sw(_)) { "edit room: records (software traversal's does not grow)" } else { "edit room: records (particles, or the device's limits)" }.into()),
};
let v = (inst_base + r, r);
edit.placed.insert(id, v);
@@ -3287,7 +3384,10 @@ impl LiveCore {
}
gpu_instances[record] = gpu;
let custom = if matches!(o.kind, Kind::Procedural { .. }) { record as u32 } else { gpu::INSTANCE_BIT | record as u32 };
- accel.tlas[slot] = Some(wgpu::TlasInstance::new(&blas, gpu::tlas_rows(placement), custom, mask(o.cast_shadow)));
+ match blas {
+ Placed::Proc(blas) => top.place_blas(slot, &blas, placement, custom, mask(o.cast_shadow)),
+ Placed::Mesh(k) => top.place(slot, k, placement, custom, o.cast_shadow, false),
+ }
let st = tables.stride;
w_objects.put((object * st * 16) as u64, bytemuck::cast_slice(&entry[..st]));
let at = object * st;
@@ -3302,7 +3402,9 @@ impl LiveCore {
w_cdf.flush(q, &up.cdf);
w_verts.flush(q, &up.verts);
w_attrs.flush(q, &up.attrs);
- w_blas.flush(q, &accel.verts);
+ if let gpu::Top::Hw(accel) = &top {
+ w_blas.flush(q, &accel.verts);
+ }
w_colors.flush(q, &up.prev_verts);
w_records.flush(q, &up.instances);
w_objects.flush(q, &up.objects);
@@ -3311,7 +3413,19 @@ impl LiveCore {
new_meshes.sort_unstable();
new_meshes.dedup();
// The new meshes' and procedural BLASes and the TLAS in one build (`Gpu::build_meshes`).
- g.build_edit(accel, &new_meshes, &pending_procs, &mut e, true);
+ match &mut top {
+ gpu::Top::Hw(accel) => g.build_edit(accel, &new_meshes, &pending_procs, &mut e, true),
+ // The trees are written; the meshes this edit freed give theirs back; the top tree over the units as they
+ // are now (one that cannot be made: the scene is rebuilt).
+ gpu::Top::Sw(units) => {
+ for &k in &edit.dead_meshes {
+ if let Some(old) = units.drop_tree(k) {
+ g.fill_tree(&up.bg_parts.nodes, old);
+ }
+ }
+ g.retop(units, &up.bg_parts.nodes)?;
+ }
+ }
split.blas += t3.elapsed().as_secs_f64() * 1e3;
// THREERT_PROFILE_BLAS=1: the BLAS / TLAS builds' GPU time (the queue drained before and after; frame log
// `blas`), as for the dynamic rebuilds.
@@ -3609,6 +3723,10 @@ impl LiveCore {
let jitter = (halton(self.frame % 16 + 1, 2), halton(self.frame % 16 + 1, 3));
for k in 0..spp.max(1) {
let mut p = self.sc.base;
+ // Software traversal's units as edits left them: the top tree's root and how many it holds (trace_units.wgsl).
+ if let Some(u) = &self.sc.up.units {
+ (p.motion[2], p.motion[3]) = (f32::from_bits(u.layout.top_first), f32::from_bits(u.count));
+ }
if self.raster.is_some() && !self.sc.instanced {
p.raster = [1.0, jitter.0, jitter.1, 0.0];
}
@@ -3626,7 +3744,7 @@ impl LiveCore {
}
if (!self.sc.dynamic.1.is_empty() || !self.sc.tables.retained.instance_of.is_empty() || !self.sc.tables.retained.rigid.is_empty()) && motion_vectors() {
// The kernel finds the first dynamic triangle in Params::group_first (group 4), a u32.
- p.motion = [1.0, 0.0, 0.0, 0.0];
+ p.motion[0] = 1.0;
}
if self.cache.is_some() {
// Light-sampled particles (sparks: Particles emitterArea) move their light every frame: the cache and
@@ -4296,7 +4414,7 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {
use std::io::Write;
let line = serde_json::json!({
"t": start.elapsed().as_secs_f64() * 1e3, "interval": last_frame.elapsed().as_secs_f64() * 1e3, "start": t_frame.duration_since(prev_start).as_secs_f64() * 1e3,
- "cpu": t_frame.elapsed().as_secs_f64() * 1e3, "script": game.frame_ms, "js": game.js_ms, "commit": game.commit_ms, "skin": core.cpu_skin_ms, "upload": core.cpu_upload_ms, "blas": core.gpu_blas_ms, "wait": core.cpu_wait_ms, "gpu": core.gpu_ms, "trace": core.gpu_trace_ms, "edit": core.edit_ms, "instanced": core.instanced_ms, "edit_split": [core.edit_split.tris, core.edit_split.upload, core.edit_split.blas, core.edit_split.added, core.edit_split.deformed, core.edit_split.objects], "rebuild": core.rebuild_ms, "fallback": core.fallback, "fallbacks": core.fallbacks, "room": core.room_stats(), "voxel": std::mem::take(&mut game.host.voxels.borrow_mut().ticks), "physics": game.host.physics.borrow_mut().as_mut().map(|p| { let s = p.take_stats(); serde_json::json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved }) }), "scale": core.render_scale, "history": core.history_len, "guard": core.guard_trips,
+ "cpu": t_frame.elapsed().as_secs_f64() * 1e3, "script": game.frame_ms, "js": game.js_ms, "commit": game.commit_ms, "skin": core.cpu_skin_ms, "upload": core.cpu_upload_ms, "blas": core.gpu_blas_ms, "wait": core.cpu_wait_ms, "gpu": core.gpu_ms, "trace": core.gpu_trace_ms, "edit": core.edit_ms, "instanced": core.instanced_ms, "edit_split": [core.edit_split.tris, core.edit_split.upload, core.edit_split.blas, core.edit_split.added, core.edit_split.deformed, core.edit_split.objects], "rebuild": core.rebuild_ms, "fallback": core.fallback, "fallbacks": core.fallbacks, "room": core.room_stats(), "voxel": std::mem::take(&mut game.host.voxels.borrow_mut().ticks), "physics": game.host.physics.borrow_mut().as_mut().map(|p| { let s = p.take_stats(); serde_json::json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved }) }), "scale": core.render_scale, "history": core.history_len, "guard": core.guard_count(),
});
writeln!(l, "{line}")?;
}
diff --git a/renderer/src/merged.rs b/renderer/src/merged.rs
index 3b39757..29935d9 100644
--- a/renderer/src/merged.rs
+++ b/renderer/src/merged.rs
@@ -426,7 +426,8 @@ pub fn live(src: &str) -> String {
/// frame. No formula changes, but the image is not bit-identical to the kernel's without the guard: the compiler
/// arranges the arithmetic of the functions it is in differently (hello world, one sample a pixel: 354 of 43,200
/// numbers differ, by at most 2 x 10^-7 of their value). Between the two layouts, guard or not, the bytes are equal.
-/// `THREERT_LOOP_GUARD=<limit>` natively (`gpu::loop_guard`); a browser's kernel always has it.
+/// `THREERT_LOOP_GUARD=<limit>` natively (`gpu::loop_guard_of`: a kernel with units has it with nothing set); a
+/// browser's kernel always has it.
///
/// A stopped loop is counted, not hidden: the invocation that reaches the limit adds one to the first word of `trips`
/// (an `array<atomic<u32>, 4>` the source can name: `ML.loop_guard_trips` in the merged layout, the buffer `guard_decl`
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 9698c47..35d378c 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -498,6 +498,9 @@ pub struct Scene {
/// environment's CDF in the `env_cdf` binding (`Params::procs`), the records the model instances' in `instances`.
pub proc_layout: Option<ProcLayout>,
pub proc_records: Vec<GpuInstance>,
+ /// Software traversal's units (`prepare`: the instances it keeps as instances; units.rs), None under hardware
+ /// traversal and for a scene without any.
+ pub units: Option<crate::units::Units>,
/// Translucent particles' triangles (`transparent` material): in the kernel's triangle tables after everything
/// else (`trans_first`, set by `prepare`), in no traversal group: only the translucency pass sees them.
pub trans_tris: Vec<[Vec3A; 3]>,
@@ -1837,6 +1840,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
geometry_fns,
proc_layout: None,
proc_records: vec![],
+ units: None,
trans_tris,
trans_attrs,
trans_first: 0,
diff --git a/renderer/src/units.rs b/renderer/src/units.rs
new file mode 100644
index 0000000..55e2f77
--- /dev/null
+++ b/renderer/src/units.rs
@@ -0,0 +1,1270 @@
+//! Units: what software traversal can add, move and remove without rebuilding the scene (docs/RUNTIME.md "Software
+//! traversal with units"; ROADMAP § 6 step 7b). A unit is a model instance, as under hardware traversal: its mesh's
+//! triangles once, in model space; a tree over them (a mesh tree, the software BLAS); its kernel record with the
+//! tree's root in it; and a leaf of the top tree (the software TLAS), which is over the units' world boxes. The
+//! kernel's walk is shaders/trace_units.wgsl. This module builds the trees, says where they go in the node buffer,
+//! and checks every tree before it is written: the kernel follows the indices it reads, and ends only if they are a
+//! tree's.
+//!
+//! The node buffer: the still scene's tree (as before), then the mesh trees' range (trees side by side, room after
+//! them), then the top tree's range. A mesh tree is relocatable: child indices count from its root, a leaf's
+//! triangles from its mesh's first triangle. The top tree's child indices count from its root, and each of its leaves
+//! is one unit: `left_or_first` the unit's record, `count` 1. It is rebuilt whole whenever a unit changes.
+//!
+//! Depths: both levels share the unit walk's stack of `STACK` entries (a push past it is dropped: geometry missed,
+//! never a hang). A walk's stack is never deeper than its tree, so the top tree is held to `TOP_DEPTH` and a mesh tree
+//! to `MESH_DEPTH` (a tree deeper than that is built again by median splits, which halve), and the two fit. Binned
+//! SAH is not balanced: its tree over 5.86 M triangles (the catalog's largest model) is 42 deep, twice a balanced
+//! one's 21, and over 30 k to 500 k triangles 17 to 22. The still scene's walk has 48 entries for its one tree.
+
+use crate::bvh::{self, GpuNode};
+use crate::scene::GpuInstance;
+use glam::{Mat4, Vec3A};
+
+/// The unit walk's stack (trace_units.wgsl; its own, not the still walk's): entries shared by both levels.
+pub const STACK: usize = 64;
+/// The still walk's stack (pathtrace.wgsl `trace`), as it was before there were units.
+pub const STILL_STACK: usize = 48;
+/// The deepest top tree (levels below the root): 2^18 units by median splits.
+pub const TOP_DEPTH: usize = 18;
+/// The deepest mesh tree (46): what the stack has left. SAH trees deeper than this are rebuilt by median splits.
+pub const MESH_DEPTH: usize = STACK - TOP_DEPTH;
+/// The most units a top tree holds.
+pub const MAX_UNITS: usize = 1 << TOP_DEPTH;
+/// A leaf's most triangles (bvh.rs builds leaves of up to 16).
+pub const MAX_LEAF: u32 = 16;
+
+/// What unused room in the node buffer holds: a leaf of one item, which ends a walk that lands on it (zeros would be
+/// an interior node whose children are node 0 and node 1).
+pub const FILL: GpuNode = bvh::EMPTY;
+
+/// A mesh's tree: its nodes (relocatable), the order it puts the mesh's triangles in (`order[i]`: the triangle now at
+/// position i), its depth, the bounds of the triangles it was built over (model space).
+pub struct MeshTree {
+ pub nodes: Vec<GpuNode>,
+ pub order: Vec<u32>,
+ pub depth: usize,
+ pub lo: Vec3A,
+ pub hi: Vec3A,
+}
+
+fn finite(n: &GpuNode) -> bool {
+ n.bmin.iter().chain(&n.bmax).all(|v| v.is_finite()) && (0..3).all(|k| n.bmin[k] <= n.bmax[k])
+}
+
+/// Checks that `nodes` is a tree the kernel's walk ends on, from node 0: every interior node's children are the two
+/// nodes at `left` and `left + 1`, `left` greater than the node's own index (so nothing is entered twice) and inside
+/// the tree; every node is reached exactly once; every box is finite; every leaf passes `leaf(first, count)`; nothing
+/// is deeper than `max_depth`. Returns the depth (levels below the root).
+fn check_tree(nodes: &[GpuNode], max_depth: usize, leaf: impl Fn(u32, u32) -> Result<(), String>) -> Result<usize, String> {
+ if nodes.is_empty() {
+ return Err("a tree without nodes".into());
+ }
+ let mut seen = vec![false; nodes.len()];
+ let mut stack = vec![(0usize, 0usize)];
+ let (mut deepest, mut reached) = (0, 0);
+ while let Some((i, depth)) = stack.pop() {
+ if std::mem::replace(&mut seen[i], true) {
+ return Err(format!("node {i} is reached twice"));
+ }
+ reached += 1;
+ deepest = deepest.max(depth);
+ let n = &nodes[i];
+ if n.count > 0 {
+ leaf(n.left_or_first, n.count).map_err(|e| format!("leaf {i}: {e}"))?;
+ continue;
+ }
+ if !finite(n) {
+ return Err(format!("node {i}'s box is not finite"));
+ }
+ let l = n.left_or_first as usize;
+ if l <= i || l + 1 >= nodes.len() {
+ return Err(format!("node {i}'s children {l}, {} are not after it and inside the tree's {} nodes", l + 1, nodes.len()));
+ }
+ if depth + 1 > max_depth {
+ return Err(format!("deeper than {max_depth}"));
+ }
+ stack.push((l, depth + 1));
+ stack.push((l + 1, depth + 1));
+ }
+ if reached != nodes.len() {
+ return Err(format!("{} of {} nodes are not reached", nodes.len() - reached, nodes.len()));
+ }
+ Ok(deepest)
+}
+
+/// A mesh tree over `tris` triangles, as the kernel may walk it: `check_tree`, leaves of 1 to `MAX_LEAF` triangles
+/// inside the mesh, no deeper than `MESH_DEPTH`. Its depth.
+pub fn check_mesh(nodes: &[GpuNode], tris: usize) -> Result<usize, String> {
+ check_tree(nodes, MESH_DEPTH, |first, count| {
+ if count > MAX_LEAF || first as usize + count as usize > tris {
+ return Err(format!("triangles {first}..{} of {tris}", first as u64 + count as u64));
+ }
+ Ok(())
+ })
+}
+
+/// A top tree whose leaves are among the records `is_unit` holds true for, each of them at most once, no deeper than
+/// `TOP_DEPTH`.
+pub fn check_top(nodes: &[GpuNode], is_unit: impl Fn(u32) -> bool) -> Result<usize, String> {
+ let seen = std::cell::RefCell::new(std::collections::HashSet::new());
+ check_tree(nodes, TOP_DEPTH, |rec, count| {
+ if count != 1 || !is_unit(rec) {
+ return Err(format!("record {rec} (count {count}) is not one unit"));
+ }
+ if !seen.borrow_mut().insert(rec) {
+ return Err(format!("record {rec} twice"));
+ }
+ Ok(())
+ })
+}
+
+/// A tree by median splits over boxes (min, max): leaves of up to `max_leaf` boxes, each split halving along the
+/// widest axis of the boxes' centres, so its depth is ceil(log2(boxes / max_leaf)). Returns the nodes (a leaf's
+/// `left_or_first`: its first position in the order) and the order.
+fn build_median(boxes: &[(Vec3A, Vec3A)], max_leaf: usize) -> (Vec<GpuNode>, Vec<u32>) {
+ let mut order: Vec<u32> = (0..boxes.len() as u32).collect();
+ let mut nodes = vec![FILL];
+ if boxes.is_empty() {
+ return (nodes, order);
+ }
+ let centre = |k: u32| (boxes[k as usize].0 + boxes[k as usize].1) * 0.5;
+ let mut stack = vec![(0usize, 0usize, boxes.len())];
+ while let Some((ni, start, end)) = stack.pop() {
+ let (mut lo, mut hi) = (Vec3A::splat(f32::INFINITY), Vec3A::splat(f32::NEG_INFINITY));
+ let (mut clo, mut chi) = (lo, hi);
+ for &k in &order[start..end] {
+ lo = lo.min(boxes[k as usize].0);
+ hi = hi.max(boxes[k as usize].1);
+ clo = clo.min(centre(k));
+ chi = chi.max(centre(k));
+ }
+ let count = end - start;
+ if count <= max_leaf {
+ nodes[ni] = GpuNode { bmin: lo.into(), left_or_first: start as u32, bmax: hi.into(), count: count as u32 };
+ continue;
+ }
+ let ext = chi - clo;
+ let axis = if ext.x >= ext.y && ext.x >= ext.z { 0 } else if ext.y >= ext.z { 1 } else { 2 };
+ let mid = count / 2;
+ order[start..end].select_nth_unstable_by(mid, |&a, &b| centre(a)[axis].total_cmp(&centre(b)[axis]).then(a.cmp(&b)));
+ let left = nodes.len();
+ nodes.push(FILL);
+ nodes.push(FILL);
+ nodes[ni] = GpuNode { bmin: lo.into(), left_or_first: left as u32, bmax: hi.into(), count: 0 };
+ stack.push((left + 1, start + mid, end));
+ stack.push((left, start, start + mid));
+ }
+ (nodes, order)
+}
+
+fn tri_boxes(tris: &[[Vec3A; 3]]) -> Vec<(Vec3A, Vec3A)> {
+ tris.iter().map(|t| (t[0].min(t[1]).min(t[2]), t[0].max(t[1]).max(t[2]))).collect()
+}
+
+/// The tree of a mesh's model-space triangles: binned SAH as the still scene's (bvh.rs), or by median splits when
+/// that came out deeper than `MESH_DEPTH`. Checked. A mesh without triangles has no tree, and is no unit.
+pub fn mesh_tree(tris: &[[Vec3A; 3]]) -> Result<MeshTree, String> {
+ if tris.is_empty() {
+ return Err("a mesh without triangles has no tree".into());
+ }
+ if tris.iter().flatten().any(|v| !v.is_finite()) {
+ return Err("a mesh's vertex is not finite".into());
+ }
+ let b = bvh::build(tris);
+ let (nodes, order) = match check_mesh(&b.nodes, tris.len()) {
+ Ok(_) => (b.nodes, b.order),
+ Err(_) => build_median(&tri_boxes(tris), 4),
+ };
+ let depth = check_mesh(&nodes, tris.len())?;
+ let (lo, hi) = tris.iter().flatten().fold((Vec3A::splat(f32::INFINITY), Vec3A::splat(f32::NEG_INFINITY)), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
+ Ok(MeshTree { nodes, order, depth, lo, hi })
+}
+
+/// A unit for the top tree: its record, and its mesh's model-space bounds under its world transform.
+pub struct UnitBox {
+ pub record: u32,
+ pub lo: Vec3A,
+ pub hi: Vec3A,
+}
+
+impl UnitBox {
+ /// The world box of model bounds `lo..hi` under `world`: the box of its eight corners, a little larger than
+ /// computed (the kernel tests the triangles in the unit's own space, to its own rounding: a hit there must not
+ /// be lost to this box's).
+ pub fn new(record: u32, world: Mat4, lo: Vec3A, hi: Vec3A) -> UnitBox {
+ let (mut a, mut b) = (Vec3A::splat(f32::INFINITY), Vec3A::splat(f32::NEG_INFINITY));
+ for c in 0..8 {
+ let p = world.transform_point3a(Vec3A::new(if c & 1 == 0 { lo.x } else { hi.x }, if c & 2 == 0 { lo.y } else { hi.y }, if c & 4 == 0 { lo.z } else { hi.z }));
+ a = a.min(p);
+ b = b.max(p);
+ }
+ let pad = Vec3A::splat((b - a).max_element() * 1e-4 + a.abs().max(b.abs()).max_element() * 1e-5 + 1e-6);
+ UnitBox { record, lo: a - pad, hi: b + pad }
+ }
+}
+
+/// The top tree over `units` (at least one): median splits down to one unit a leaf, each leaf's `left_or_first` its
+/// unit's record. Checked against the units it was given.
+pub fn top_tree(units: &[UnitBox]) -> Result<Vec<GpuNode>, String> {
+ if units.is_empty() {
+ return Err("a top tree needs a unit".into());
+ }
+ if units.len() > MAX_UNITS {
+ return Err(format!("{} units: more than a top tree holds ({MAX_UNITS})", units.len()));
+ }
+ if units.iter().any(|u| !(u.lo.is_finite() && u.hi.is_finite())) {
+ return Err("a unit's box is not finite".into());
+ }
+ let boxes: Vec<(Vec3A, Vec3A)> = units.iter().map(|u| (u.lo, u.hi)).collect();
+ let (mut nodes, order) = build_median(&boxes, 1);
+ for n in nodes.iter_mut().filter(|n| n.count > 0) {
+ n.left_or_first = units[order[n.left_or_first as usize] as usize].record;
+ }
+ let records: std::collections::HashSet<u32> = units.iter().map(|u| u.record).collect();
+ check_top(&nodes, |r| records.contains(&r))?;
+ Ok(nodes)
+}
+
+/// A unit's record: the instance's (`scene::Instance::gpu`), with its mesh tree's root and whether it casts shadows in
+/// the two words the normal rows leave unused (trace_units.wgsl reads them as bits).
+pub fn unit_record(mut r: GpuInstance, root: u32, cast_shadow: bool) -> GpuInstance {
+ r.n[0][3] = f32::from_bits(root);
+ r.n[1][3] = f32::from_bits(cast_shadow as u32);
+ r
+}
+
+/// Where the units' trees are in the node buffer, and which of the mesh trees' range is free. Nodes are counted, not
+/// bytes.
+#[derive(Clone, Debug)]
+pub struct Layout {
+ /// The mesh trees' range: its first node and its length.
+ pub mesh_first: u32,
+ pub mesh_cap: u32,
+ /// The top tree's range (its root is its first node) and the most units it has room for.
+ pub top_first: u32,
+ pub top_cap: u32,
+ /// Free runs of the mesh range (first node, length), in order, never adjacent.
+ free: Vec<(u32, u32)>,
+}
+
+impl Layout {
+ /// After a still tree of `still` nodes: room for `mesh_nodes` nodes of mesh trees and a top tree of `units` units.
+ pub fn new(still: usize, mesh_nodes: usize, units: usize) -> Layout {
+ let (mesh_first, mesh_cap) = (still as u32, mesh_nodes as u32);
+ let top_cap = (2 * units.clamp(1, MAX_UNITS) - 1) as u32;
+ Layout { mesh_first, mesh_cap, top_first: mesh_first + mesh_cap, top_cap, free: if mesh_cap > 0 { vec![(mesh_first, mesh_cap)] } else { vec![] } }
+ }
+
+ /// Every node of the buffer after the still tree's: all room (`FILL`).
+ pub fn nodes(&self) -> usize {
+ (self.mesh_cap + self.top_cap) as usize
+ }
+
+ /// The most units the top tree's range holds.
+ pub fn max_units(&self) -> usize {
+ (self.top_cap as usize + 1) / 2
+ }
+
+ /// A place for a mesh tree of `len` nodes: its root (first fit), or None when no free run is long enough.
+ pub fn place(&mut self, len: usize) -> Option<u32> {
+ let len = len as u32;
+ let k = self.free.iter().position(|f| f.1 >= len)?;
+ let at = self.free[k].0;
+ if self.free[k].1 == len {
+ self.free.remove(k);
+ } else {
+ self.free[k] = (at + len, self.free[k].1 - len);
+ }
+ Some(at)
+ }
+
+ /// Gives a mesh tree's nodes back (its root and length, as `place` gave them).
+ pub fn release(&mut self, root: u32, len: usize) {
+ let len = len as u32;
+ debug_assert!(root >= self.mesh_first && root + len <= self.mesh_first + self.mesh_cap);
+ let k = self.free.partition_point(|f| f.0 < root);
+ debug_assert!(k == 0 || self.free[k - 1].0 + self.free[k - 1].1 <= root, "released twice");
+ debug_assert!(k == self.free.len() || root + len <= self.free[k].0, "released twice");
+ self.free.insert(k, (root, len));
+ if k + 1 < self.free.len() && self.free[k].0 + self.free[k].1 == self.free[k + 1].0 {
+ self.free[k].1 += self.free[k + 1].1;
+ self.free.remove(k + 1);
+ }
+ if k > 0 && self.free[k - 1].0 + self.free[k - 1].1 == self.free[k].0 {
+ self.free[k - 1].1 += self.free[k].1;
+ self.free.remove(k);
+ }
+ }
+
+ /// The free nodes of the mesh range.
+ pub fn free_nodes(&self) -> usize {
+ self.free.iter().map(|f| f.1 as usize).sum()
+ }
+}
+
+/// A unit as the top tree sees it: where it places its mesh, and the tree its record names (its mesh, and the root
+/// the record was last written with: `Units::top` refuses a unit whose record names a tree that is no longer there).
+/// Its box in the top tree is its tree's bounds under `world`, taken when the top tree is built: a mesh written
+/// again where it was (a geometry that moves every frame) has a new tree, and its units the new bounds with it.
+/// Hidden: it keeps its place (an instanced object's instance that is not drawn now) and is in no top tree.
+#[derive(Clone, Copy, Debug)]
+pub struct Unit {
+ pub world: Mat4,
+ pub hidden: bool,
+ pub mesh: u32,
+ pub root: u32,
+}
+
+/// A mesh's tree in the node buffer: its root, its node count, the bounds of its triangles (model space).
+#[derive(Clone, Copy, Debug)]
+pub struct Tree {
+ pub root: u32,
+ pub len: u32,
+ pub lo: Vec3A,
+ pub hi: Vec3A,
+}
+
+/// Software traversal's units of a scene (what the TLAS and the mesh BLASes are to hardware traversal): where the
+/// trees are, each instanced mesh's tree, and the unit at each kernel record.
+#[derive(Clone, Debug)]
+pub struct Units {
+ pub layout: Layout,
+ /// By instanced mesh (the scene's `meshes` index): its tree. None: no tree (a mesh that deforms or has no
+ /// triangle, or one an edit freed).
+ pub trees: Vec<Option<Tree>>,
+ /// By kernel record: the unit there, if the record is one's.
+ pub slots: Vec<Option<Unit>>,
+ /// The units in the top tree as last built (`top`): the kernel's `P.motion.w`.
+ pub count: u32,
+ /// The records the kernel's instance table holds (the scene's and its room's): no unit is past them.
+ pub records: usize,
+}
+
+impl Units {
+ /// Mesh `k`'s tree's root.
+ pub fn root(&self, k: u32) -> Option<u32> {
+ self.trees.get(k as usize).copied().flatten().map(|t| t.root)
+ }
+
+ /// A unit of mesh `k` placed by `world`, whose record names the tree mesh `k` has now. None: the mesh has no
+ /// tree (it is no unit's).
+ pub fn unit(&self, k: u32, world: Mat4, hidden: bool) -> Option<Unit> {
+ self.root(k).map(|root| Unit { world, hidden, mesh: k, root })
+ }
+
+ /// The unit at `record` moved to `world` (with `hidden`: shown or not), its record written again: it names its
+ /// mesh's tree as it is now.
+ pub fn moved(&mut self, record: usize, world: Mat4, hidden: Option<bool>) {
+ let Some(mut u) = self.slots.get(record).copied().flatten() else { return };
+ u.world = world;
+ u.hidden = hidden.unwrap_or(u.hidden);
+ u.root = self.root(u.mesh).unwrap_or(u.root);
+ self.slots[record] = Some(u);
+ }
+
+ /// The unit at `record` (None: none there now). Records past the slots there are make them.
+ pub fn set(&mut self, record: usize, unit: Option<Unit>) {
+ if record >= self.slots.len() {
+ if unit.is_none() {
+ return;
+ }
+ self.slots.resize(record + 1, None);
+ }
+ self.slots[record] = unit;
+ }
+
+ /// A place for mesh `k`'s tree (the tree it had, if any, given back first): its root, or None when the mesh
+ /// range has no run that long. The caller writes the tree's nodes there.
+ pub fn add_tree(&mut self, k: u32, tree: &MeshTree) -> Option<u32> {
+ self.drop_tree(k);
+ let root = self.layout.place(tree.nodes.len())?;
+ if self.trees.len() <= k as usize {
+ self.trees.resize(k as usize + 1, None);
+ }
+ self.trees[k as usize] = Some(Tree { root, len: tree.nodes.len() as u32, lo: tree.lo, hi: tree.hi });
+ Some(root)
+ }
+
+ /// Mesh `k`'s tree given back: its root and length (the caller fills them with `FILL`), if it had one.
+ pub fn drop_tree(&mut self, k: u32) -> Option<(u32, u32)> {
+ let t = self.trees.get_mut(k as usize)?.take()?;
+ self.layout.release(t.root, t.len as usize);
+ Some((t.root, t.len))
+ }
+
+ /// The top tree over the units that are shown, for the top range's start, and their count kept (`count`). No
+ /// unit: no nodes (the kernel does not walk a top tree then). Err: more units than the range holds, a unit whose
+ /// box is not finite, one past the kernel's records, or one whose record names a tree that is not its mesh's now
+ /// (freed, or placed elsewhere since the record was written: the kernel would walk whatever is there); nothing
+ /// is changed then.
+ pub fn top(&mut self) -> Result<Vec<GpuNode>, String> {
+ let mut boxes: Vec<UnitBox> = vec![];
+ for (r, u) in self.slots.iter().enumerate() {
+ let Some(u) = u.as_ref().filter(|u| !u.hidden) else { continue };
+ if r >= self.records {
+ return Err(format!("the unit at record {r} is past the kernel's {} records", self.records));
+ }
+ match self.trees.get(u.mesh as usize).copied().flatten() {
+ Some(t) if t.root == u.root => boxes.push(UnitBox::new(r as u32, u.world, t.lo, t.hi)),
+ _ => return Err(format!("the unit at record {r} names a tree at node {} that is not mesh {}'s now", u.root, u.mesh)),
+ }
+ }
+ if boxes.len() > self.layout.max_units() {
+ return Err(format!("{} units: more than the top tree's range holds ({})", boxes.len(), self.layout.max_units()));
+ }
+ let nodes = if boxes.is_empty() { vec![] } else { top_tree(&boxes)? };
+ self.count = boxes.len() as u32;
+ Ok(nodes)
+ }
+}
+
+/// The kernel's traversal on the CPU, for tests (here and lib.rs): what the kernel binds, read through accessors that
+/// refuse an index outside their buffer, every loop iteration counted.
+#[cfg(test)]
+pub(crate) mod cpu {
+ use super::*;
+
+ pub(crate) const INF: f32 = 3.0e38;
+ pub(crate) const NO_INST: u32 = 0xffff_ffff;
+ pub(crate) const TRACE_CLOSEST: u32 = 0;
+ pub(crate) const TRACE_SHADOW: u32 = 1;
+ pub(crate) const TRACE_ANY: u32 = 2;
+
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ pub(crate) struct Hit {
+ pub(crate) t: f32,
+ pub(crate) tri: u32,
+ pub(crate) inst: u32,
+ }
+
+ /// What the kernel binds, on the CPU: every read through `node`, `vert`, `record`, which refuse an index outside
+ /// their buffer; every loop iteration counted against `budget` (the loop guard's role: the walk must end).
+ pub(crate) struct Kernel<'a> {
+ pub(crate) nodes: &'a [GpuNode],
+ pub(crate) tri_verts: &'a [[f32; 4]],
+ pub(crate) instances: &'a [GpuInstance],
+ /// `P.motion.z`, `P.motion.w`.
+ pub(crate) top: u32,
+ pub(crate) units: u32,
+ pub(crate) steps: std::cell::Cell<u64>,
+ pub(crate) budget: u64,
+ /// The deepest the shared stack got.
+ pub(crate) deepest: std::cell::Cell<usize>,
+ }
+
+ pub(crate) type Walk<T> = Result<T, String>;
+
+ impl Kernel<'_> {
+ pub(crate) fn node(&self, i: u32) -> Walk<GpuNode> {
+ self.nodes.get(i as usize).copied().ok_or(format!("reads node {i} of {}", self.nodes.len()))
+ }
+ pub(crate) fn vert(&self, i: u32) -> Walk<Vec3A> {
+ self.tri_verts.get(i as usize).map(|v| Vec3A::new(v[0], v[1], v[2])).ok_or(format!("reads vertex {i} of {}", self.tri_verts.len()))
+ }
+ pub(crate) fn record(&self, i: u32) -> Walk<GpuInstance> {
+ self.instances.get(i as usize).copied().ok_or(format!("reads record {i} of {}", self.instances.len()))
+ }
+ pub(crate) fn step(&self) -> Walk<()> {
+ self.steps.set(self.steps.get() + 1);
+ if self.steps.get() > self.budget {
+ return Err("does not stop".into());
+ }
+ Ok(())
+ }
+
+ /// pathtrace.wgsl `ray_aabb`.
+ pub(crate) fn ray_aabb(o: Vec3A, inv_d: Vec3A, bmin: [f32; 3], bmax: [f32; 3], tmax: f32) -> f32 {
+ let t0 = (Vec3A::from(bmin) - o) * inv_d;
+ let t1 = (Vec3A::from(bmax) - o) * inv_d;
+ let (tmin_v, tmax_v) = (t0.min(t1), t0.max(t1));
+ let tn = tmin_v.x.max(tmin_v.y).max(tmin_v.z.max(0.0));
+ let tf = tmax_v.x.min(tmax_v.y).min(tmax_v.z.min(tmax));
+ if tn <= tf {
+ tn
+ } else {
+ INF
+ }
+ }
+
+ /// pathtrace.wgsl `intersect_tri`: (t, u, v), t = INF for a miss.
+ pub(crate) fn intersect_tri(&self, o: Vec3A, d: Vec3A, i: u32, tmax: f32) -> Walk<f32> {
+ let (v0, e1, e2) = (self.vert(i * 3)?, self.vert(i * 3 + 1)?, self.vert(i * 3 + 2)?);
+ let pv = d.cross(e2);
+ let det = e1.dot(pv);
+ if det.abs() < 1e-12 {
+ return Ok(INF);
+ }
+ let inv = 1.0 / det;
+ let tv = o - v0;
+ let u = tv.dot(pv) * inv;
+ if !(0.0..=1.0).contains(&u) {
+ return Ok(INF);
+ }
+ let qv = tv.cross(e1);
+ let v = d.dot(qv) * inv;
+ if v < 0.0 || u + v > 1.0 {
+ return Ok(INF);
+ }
+ let t = e2.dot(qv) * inv;
+ if t <= 0.0 || t >= tmax {
+ return Ok(INF);
+ }
+ Ok(t)
+ }
+
+ pub(crate) fn inv(d: Vec3A) -> Vec3A {
+ Vec3A::ONE / Vec3A::select(d.abs().cmplt(Vec3A::splat(1e-20)), Vec3A::splat(1e-20), d)
+ }
+
+ /// pathtrace.wgsl `proc_dir`, `proc_point`.
+ pub(crate) fn proc_dir(r: &GpuInstance, d: Vec3A) -> Vec3A {
+ let n = |k: usize| Vec3A::new(r.n[k][0], r.n[k][1], r.n[k][2]);
+ n(0) * d.x + n(1) * d.y + n(2) * d.z
+ }
+ pub(crate) fn proc_point(r: &GpuInstance, p: Vec3A) -> Vec3A {
+ Self::proc_dir(r, p - Vec3A::new(r.m[0][3], r.m[1][3], r.m[2][3]))
+ }
+
+ /// pathtrace.wgsl `trace`, the still scene's tree (no cutouts: the scenes here have none), then the units as
+ /// `kernel_source` splices them in.
+ pub(crate) fn trace(&self, o: Vec3A, d: Vec3A, tmax_in: f32, mode: u32) -> Walk<Hit> {
+ let mut hit = Hit { t: tmax_in, tri: 0xffff_ffff, inst: NO_INST };
+ let inv_d = Self::inv(d);
+ let (mut stack, mut sp, mut node) = ([0u32; STILL_STACK], 0usize, 0u32);
+ loop {
+ self.step()?;
+ let n = self.node(node)?;
+ if n.count > 0 {
+ for k in 0..n.count {
+ self.step()?;
+ let ti = n.left_or_first + k;
+ let flags = self.tri_verts.get(ti as usize * 3).ok_or(format!("reads triangle {ti}"))?[3].to_bits();
+ if mode == TRACE_SHADOW && flags & crate::scene::TRI_NO_SHADOW != 0 {
+ continue;
+ }
+ let t = self.intersect_tri(o, d, ti, hit.t)?;
+ if t < hit.t {
+ hit = Hit { t, tri: ti, inst: NO_INST };
+ if mode != TRACE_CLOSEST {
+ return Ok(hit);
+ }
+ }
+ }
+ if sp == 0 {
+ break;
+ }
+ sp -= 1;
+ node = stack[sp];
+ continue;
+ }
+ let l = n.left_or_first;
+ let r = l + 1;
+ let (nl, nr) = (self.node(l)?, self.node(r)?);
+ let mut tl = Self::ray_aabb(o, inv_d, nl.bmin, nl.bmax, hit.t);
+ let mut tr = Self::ray_aabb(o, inv_d, nr.bmin, nr.bmax, hit.t);
+ if tl == INF && tr == INF {
+ if sp == 0 {
+ break;
+ }
+ sp -= 1;
+ node = stack[sp];
+ continue;
+ }
+ let (mut near, mut far) = (l, r);
+ if tr < tl {
+ (near, far) = (r, l);
+ std::mem::swap(&mut tl, &mut tr);
+ }
+ node = near;
+ if tr != INF && sp < STILL_STACK {
+ stack[sp] = far;
+ sp += 1;
+ }
+ }
+ self.trace_units(o, d, hit, mode)
+ }
+
+ /// shaders/trace_units.wgsl `trace_units`, statement for statement.
+ pub(crate) fn trace_units(&self, o: Vec3A, d: Vec3A, hit_in: Hit, mode: u32) -> Walk<Hit> {
+ let mut hit = hit_in;
+ if self.units == 0 {
+ return Ok(hit);
+ }
+ let top = self.top;
+ let inv_d = Self::inv(d);
+ let (mut stack, mut sp, mut node) = ([0u32; STACK], 0usize, top);
+ loop {
+ self.step()?;
+ let n = self.node(node)?;
+ if n.count > 0 {
+ let rec = n.left_or_first;
+ let r = self.record(rec)?;
+ if mode != TRACE_SHADOW || r.n[1][3].to_bits() != 0 {
+ let lo = Self::proc_point(&r, o);
+ let ld = Self::proc_dir(&r, d);
+ let linv = Self::inv(ld);
+ let root = r.n[0][3].to_bits();
+ let first = r.info[0];
+ let base = sp;
+ let mut m = root;
+ loop {
+ self.step()?;
+ let q = self.node(m)?;
+ if q.count > 0 {
+ for k in 0..q.count {
+ self.step()?;
+ let ti = first + q.left_or_first + k;
+ let x = self.intersect_tri(lo, ld, ti, hit.t)?;
+ if x < hit.t {
+ hit = Hit { t: x, tri: ti, inst: rec };
+ if mode != TRACE_CLOSEST {
+ return Ok(hit);
+ }
+ }
+ }
+ if sp == base {
+ break;
+ }
+ sp -= 1;
+ m = stack[sp];
+ continue;
+ }
+ let ml = root + q.left_or_first;
+ let mr = ml + 1;
+ let (ql, qr) = (self.node(ml)?, self.node(mr)?);
+ let mut ul = Self::ray_aabb(lo, linv, ql.bmin, ql.bmax, hit.t);
+ let mut ur = Self::ray_aabb(lo, linv, qr.bmin, qr.bmax, hit.t);
+ if ul == INF && ur == INF {
+ if sp == base {
+ break;
+ }
+ sp -= 1;
+ m = stack[sp];
+ continue;
+ }
+ let (mut mnear, mut mfar) = (ml, mr);
+ if ur < ul {
+ (mnear, mfar) = (mr, ml);
+ std::mem::swap(&mut ul, &mut ur);
+ }
+ m = mnear;
+ if ur != INF && sp < STACK {
+ stack[sp] = mfar;
+ sp += 1;
+ self.deepest.set(self.deepest.get().max(sp));
+ }
+ }
+ }
+ if sp == 0 {
+ break;
+ }
+ sp -= 1;
+ node = stack[sp];
+ continue;
+ }
+ let l = top + n.left_or_first;
+ let r = l + 1;
+ let (nl, nr) = (self.node(l)?, self.node(r)?);
+ let mut tl = Self::ray_aabb(o, inv_d, nl.bmin, nl.bmax, hit.t);
+ let mut tr = Self::ray_aabb(o, inv_d, nr.bmin, nr.bmax, hit.t);
+ if tl == INF && tr == INF {
+ if sp == 0 {
+ break;
+ }
+ sp -= 1;
+ node = stack[sp];
+ continue;
+ }
+ let (mut near, mut far) = (l, r);
+ if tr < tl {
+ (near, far) = (r, l);
+ std::mem::swap(&mut tl, &mut tr);
+ }
+ node = near;
+ if tr != INF && sp < STACK {
+ stack[sp] = far;
+ sp += 1;
+ self.deepest.set(self.deepest.get().max(sp));
+ }
+ }
+ Ok(hit)
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::cpu::*;
+ use super::*;
+ use glam::{Quat, Vec3};
+
+ /// The transcriptions above are the shaders': the statements they follow are still there, in this order. A change
+ /// to either walk fails here, and the transcription is to follow it.
+ #[test]
+ fn the_cpu_kernel_is_the_shaders() {
+ let ordered = |body: &str, what: &str, lines: &[&str]| {
+ let mut at = 0;
+ for l in lines {
+ at += body[at..].find(l).unwrap_or_else(|| panic!("{what} no longer has `{l}` where the CPU kernel expects it")) + l.len();
+ }
+ };
+ let units = include_str!("../shaders/trace_units.wgsl");
+ ordered(
+ units,
+ "trace_units.wgsl",
+ &[
+ "fn trace_units(o: vec3<f32>, d: vec3<f32>, hit_in: Hit, mode: u32) -> Hit {",
+ "if (bitcast<u32>(P.motion.w) == 0u) { return hit; }",
+ "let top = bitcast<u32>(P.motion.z);",
+ "var stack: array<u32, 64>;",
+ "var node = top;",
+ "let n = nodes[node];",
+ "if (n.count > 0u) {",
+ "let rec = n.left_or_first;",
+ "let r = instances[rec];",
+ "if (mode != TRACE_SHADOW || bitcast<u32>(r.n1.w) != 0u) {",
+ "let lo = proc_point(r, o);",
+ "let ld = proc_dir(r, d);",
+ "let linv = 1.0 / select(ld, vec3<f32>(1e-20), abs(ld) < vec3<f32>(1e-20));",
+ "let root = bitcast<u32>(r.n0.w);",
+ "let first = r.info.x;",
+ "let base = sp;",
+ "var m = root;",
+ "let q = nodes[m];",
+ "if (q.count > 0u) {",
+ "for (var k = 0u; k < q.count; k++) {",
+ "let ti = first + q.left_or_first + k;",
+ "let x = intersect_tri(lo, ld, ti, hit.t);",
+ "if (x.x < hit.t) {",
+ "hit = Hit(x.x, ti, x.y, x.z, rec);",
+ "if (mode != TRACE_CLOSEST) { return hit; }",
+ "if (sp == base) { break; }",
+ "m = stack[sp];",
+ "let ml = root + q.left_or_first;",
+ "let mr = ml + 1u;",
+ "var ul = ray_aabb(lo, linv, ql.bmin, ql.bmax, hit.t);",
+ "var ur = ray_aabb(lo, linv, qr.bmin, qr.bmax, hit.t);",
+ "if (ul == INF && ur == INF) {",
+ "if (sp == base) { break; }",
+ "if (ur < ul) {",
+ "m = mnear;",
+ "if (ur != INF && sp < 64u) {",
+ "stack[sp] = mfar;",
+ "if (sp == 0u) { break; }",
+ "node = stack[sp];",
+ "let l = top + n.left_or_first;",
+ "let r = l + 1u;",
+ "var tl = ray_aabb(o, inv_d, nl.bmin, nl.bmax, hit.t);",
+ "var tr = ray_aabb(o, inv_d, nr.bmin, nr.bmax, hit.t);",
+ "if (tl == INF && tr == INF) {",
+ "if (sp == 0u) { break; }",
+ "if (tr < tl) {",
+ "node = near;",
+ "if (tr != INF && sp < 64u) {",
+ "stack[sp] = far;",
+ "return hit;",
+ ],
+ );
+ assert_eq!(units.matches("loop {").count(), 2, "two walks");
+ let kernel = include_str!("../shaders/pathtrace.wgsl");
+ ordered(
+ kernel,
+ "pathtrace.wgsl",
+ &[
+ "fn proc_dir(r: Instance, d: vec3<f32>) -> vec3<f32> { return r.n0.xyz * d.x + r.n1.xyz * d.y + r.n2.xyz * d.z; }",
+ "fn proc_point(r: Instance, p: vec3<f32>) -> vec3<f32> { return proc_dir(r, p - vec3<f32>(r.m0.w, r.m1.w, r.m2.w)); }",
+ "fn intersect_tri(o: vec3<f32>, d: vec3<f32>, i: u32, tmax: f32) -> vec3<f32> {",
+ "let v0 = tri_verts[i * 3u].xyz;",
+ "let e1 = tri_verts[i * 3u + 1u].xyz;",
+ "let e2 = tri_verts[i * 3u + 2u].xyz;",
+ "let pv = cross(d, e2);",
+ "let det = dot(e1, pv);",
+ "if (abs(det) < 1e-12) { return vec3<f32>(INF, 0.0, 0.0); }",
+ "let u = dot(tv, pv) * inv;",
+ "if (u < 0.0 || u > 1.0) { return vec3<f32>(INF, 0.0, 0.0); }",
+ "let qv = cross(tv, e1);",
+ "let v = dot(d, qv) * inv;",
+ "if (v < 0.0 || u + v > 1.0) { return vec3<f32>(INF, 0.0, 0.0); }",
+ "let t = dot(e2, qv) * inv;",
+ "if (t <= 0.0 || t >= tmax) { return vec3<f32>(INF, 0.0, 0.0); }",
+ "fn trace(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mode: u32) -> Hit {",
+ "var stack: array<u32, 48>;",
+ "if (mode == TRACE_SHADOW && (flags & TRI_NO_SHADOW) != 0u) { continue; }",
+ "let r = intersect_tri(o, d, ti, hit.t);",
+ "hit = Hit(r.x, ti, r.y, r.z, NO_INST);",
+ "if (mode != TRACE_CLOSEST) { return hit; }",
+ "if (tr != INF && sp < 48u) {",
+ "if (has(F_PROC)) { return trace_procs(o, d, hit, mode); }",
+ ],
+ );
+ // What the stack and the record's words are here is what they are there.
+ assert_eq!((STACK, STILL_STACK), (64, 48));
+ assert!(TOP_DEPTH + MESH_DEPTH <= STACK);
+ }
+
+ /// A deterministic stream of numbers in [0, 1).
+ struct Rng(u64);
+ impl Rng {
+ fn f(&mut self) -> f32 {
+ self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ ((self.0 >> 40) as f32) / (1u64 << 24) as f32
+ }
+ fn below(&mut self, n: usize) -> usize {
+ ((self.f() * n as f32) as usize).min(n.saturating_sub(1))
+ }
+ fn v(&mut self, s: f32) -> Vec3A {
+ Vec3A::new(self.f() - 0.5, self.f() - 0.5, self.f() - 0.5) * s
+ }
+ fn tris(&mut self, n: usize, spread: f32, size: f32) -> Vec<[Vec3A; 3]> {
+ (0..n)
+ .map(|_| {
+ let c = self.v(spread);
+ [c + self.v(size), c + self.v(size), c + self.v(size)]
+ })
+ .collect()
+ }
+ }
+
+ /// A scene as the renderer keeps one under software traversal with units, small: the buffers the kernel reads and
+ /// the bookkeeping that writes them. Its operations are what an edit does (live.rs): a mesh's triangles and tree
+ /// into room, a record, the top tree again.
+ struct Scene {
+ nodes: Vec<GpuNode>,
+ tri_verts: Vec<[f32; 4]>,
+ instances: Vec<GpuInstance>,
+ layout: Layout,
+ still_tris: usize,
+ /// Meshes: first triangle, triangle count, root, node count, model bounds. None: removed.
+ meshes: Vec<Option<(u32, u32, u32, usize, Vec3A, Vec3A)>>,
+ /// Units by record: mesh, world, casts shadows. None: a free record.
+ units: Vec<Option<(usize, Mat4, bool)>>,
+ top: u32,
+ count: u32,
+ }
+
+ fn put_tris(out: &mut Vec<[f32; 4]>, tris: &[[Vec3A; 3]]) {
+ for [a, b, c] in tris {
+ let (e1, e2) = (*b - *a, *c - *a);
+ out.extend([[a.x, a.y, a.z, 0.0], [e1.x, e1.y, e1.z, 0.0], [e2.x, e2.y, e2.z, 0.0]]);
+ }
+ }
+
+ impl Scene {
+ fn new(still: &[[Vec3A; 3]], mesh_room: usize, units: usize) -> Scene {
+ let b = bvh::build(still);
+ let mut tri_verts = vec![];
+ put_tris(&mut tri_verts, &b.order.iter().map(|&i| still[i as usize]).collect::<Vec<_>>());
+ // (An empty still scene: the tree over nothing is a leaf of triangle 0, here three zero triangles; the meshes'
+ // triangles follow whole triangles.)
+ if still.is_empty() {
+ tri_verts.resize(9, [0.0; 4]);
+ }
+ let layout = Layout::new(b.nodes.len(), mesh_room, units);
+ let mut nodes = b.nodes;
+ nodes.resize(nodes.len() + layout.nodes(), FILL);
+ Scene { nodes, tri_verts, instances: vec![GpuInstance::default()], top: layout.top_first, layout, still_tris: still.len(), meshes: vec![], units: vec![], count: 0 }
+ }
+
+ /// A new mesh: its tree placed and written, its triangles appended in the tree's order.
+ fn add_mesh(&mut self, tris: &[[Vec3A; 3]]) -> Result<usize, String> {
+ let t = mesh_tree(tris)?;
+ let root = self.layout.place(t.nodes.len()).ok_or("no room for the tree")?;
+ self.nodes[root as usize..root as usize + t.nodes.len()].copy_from_slice(&t.nodes);
+ let first = (self.tri_verts.len() / 3) as u32;
+ put_tris(&mut self.tri_verts, &t.order.iter().map(|&i| tris[i as usize]).collect::<Vec<_>>());
+ let (lo, hi) = tri_boxes(tris).into_iter().fold((Vec3A::splat(f32::INFINITY), Vec3A::splat(f32::NEG_INFINITY)), |a, b| (a.0.min(b.0), a.1.max(b.1)));
+ self.meshes.push(Some((first, tris.len() as u32, root, t.nodes.len(), lo, hi)));
+ Ok(self.meshes.len() - 1)
+ }
+
+ /// The mesh gone: its tree's nodes room again (`FILL`: a stale root must end a walk).
+ fn remove_mesh(&mut self, k: usize) {
+ let (_, _, root, len, ..) = self.meshes[k].take().unwrap();
+ self.nodes[root as usize..root as usize + len].fill(FILL);
+ self.layout.release(root, len);
+ }
+
+ fn record(&self, mesh: usize, world: Mat4, cast: bool) -> GpuInstance {
+ let (first, _, root, ..) = self.meshes[mesh].unwrap();
+ let inst = crate::scene::Instance { mesh: mesh as u32, world, object: 0, cast_shadow: cast, name: String::new(), sub: None, hidden: false };
+ unit_record(inst.gpu(first, 0), root, cast)
+ }
+
+ fn add_unit(&mut self, mesh: usize, world: Mat4, cast: bool) -> usize {
+ let k = self.units.iter().position(|u| u.is_none()).unwrap_or_else(|| {
+ self.units.push(None);
+ self.units.len() - 1
+ });
+ self.units[k] = Some((mesh, world, cast));
+ if self.instances.len() <= k {
+ self.instances.resize(k + 1, GpuInstance::default());
+ }
+ self.instances[k] = self.record(mesh, world, cast);
+ k
+ }
+
+ /// The top tree again, over the units there are now, into its range.
+ fn retop(&mut self) -> Result<(), String> {
+ let boxes: Vec<UnitBox> = self.units.iter().enumerate().filter_map(|(k, u)| u.map(|(m, w, _)| (k, m, w))).map(|(k, m, w)| { let (.., lo, hi) = self.meshes[m].unwrap(); UnitBox::new(k as u32, w, lo, hi) }).collect();
+ self.count = boxes.len() as u32;
+ if boxes.is_empty() {
+ return Ok(());
+ }
+ if boxes.len() > self.layout.max_units() {
+ return Err("no room for the top tree".into());
+ }
+ let t = top_tree(&boxes)?;
+ let at = self.layout.top_first as usize;
+ self.nodes[at..at + t.len()].copy_from_slice(&t);
+ Ok(())
+ }
+
+ fn kernel(&self) -> Kernel<'_> {
+ let budget = 64 * (self.nodes.len() as u64 + self.tri_verts.len() as u64) + 1024;
+ Kernel { nodes: &self.nodes, tri_verts: &self.tri_verts, instances: &self.instances, top: self.top, units: self.count, steps: Default::default(), budget, deepest: Default::default() }
+ }
+
+ /// Every triangle a ray could meet, tested one by one with the kernel's own triangle test (the still scene's in
+ /// the world, a unit's in the unit's space, as the kernel does): the closest hit.
+ fn brute(&self, o: Vec3A, d: Vec3A, mode: u32) -> Hit {
+ let k = self.kernel();
+ let mut best = Hit { t: INF, tri: 0xffff_ffff, inst: NO_INST };
+ for ti in 0..self.still_tris as u32 {
+ let t = k.intersect_tri(o, d, ti, best.t).unwrap();
+ if t < best.t {
+ best = Hit { t, tri: ti, inst: NO_INST };
+ }
+ }
+ for (rec, u) in self.units.iter().enumerate() {
+ let Some((mesh, _, cast)) = u else { continue };
+ if mode == TRACE_SHADOW && !cast {
+ continue;
+ }
+ let r = &self.instances[rec];
+ let (lo, ld) = (Kernel::proc_point(r, o), Kernel::proc_dir(r, d));
+ let (first, count, ..) = self.meshes[*mesh].unwrap();
+ for ti in first..first + count {
+ let t = k.intersect_tri(lo, ld, ti, best.t).unwrap();
+ if t < best.t {
+ best = Hit { t, tri: ti, inst: rec as u32 };
+ }
+ }
+ }
+ best
+ }
+
+ /// Rays against the scene: the kernel's walk reads nothing outside its buffers, stops, and finds brute force's
+ /// closest hit (the same distance to the bit; the same triangle unless two are at that distance); an any-hit
+ /// walk finds something exactly when there is something. Returns how many rays hit a unit.
+ fn check(&self, rng: &mut Rng, rays: usize, what: &str) -> usize {
+ let mut on_units = 0;
+ let targets: Vec<Vec3A> = self.units.iter().flatten().map(|(m, w, _)| { let (.., lo, hi) = self.meshes[*m].unwrap(); w.transform_point3a((lo + hi) * 0.5) }).collect();
+ for k in 0..rays {
+ let o = rng.v(60.0);
+ // Half of the rays at a unit (random ones mostly miss small things), half anywhere.
+ let d = if k % 2 == 0 && !targets.is_empty() { (targets[rng.below(targets.len())] + rng.v(1.0) - o).normalize_or(Vec3A::X) } else { rng.v(2.0).normalize_or(Vec3A::X) };
+ for mode in [TRACE_CLOSEST, TRACE_SHADOW, TRACE_ANY] {
+ let kernel = self.kernel();
+ let got = kernel.trace(o, d, INF, mode).unwrap_or_else(|e| panic!("{what}: ray {o} {d}, mode {mode}: the kernel {e}"));
+ let want = self.brute(o, d, mode);
+ if mode == TRACE_CLOSEST {
+ assert_eq!(got.t.to_bits(), want.t.to_bits(), "{what}: ray {o} {d}: the walk's hit {got:?}, brute force's {want:?}");
+ if got.tri != want.tri || got.inst != want.inst {
+ // Two triangles at one distance: both are closest.
+ let again = Kernel { budget: u64::MAX, ..self.kernel() };
+ let t = if got.inst == NO_INST { again.intersect_tri(o, d, got.tri, INF).unwrap() } else { let r = &self.instances[got.inst as usize]; again.intersect_tri(Kernel::proc_point(r, o), Kernel::proc_dir(r, d), got.tri, INF).unwrap() };
+ assert_eq!(t.to_bits(), want.t.to_bits(), "{what}: ray {o} {d}: {got:?} is not at brute force's distance {want:?}");
+ }
+ on_units += (got.inst != NO_INST) as usize;
+ } else {
+ assert_eq!(got.tri != 0xffff_ffff, want.tri != 0xffff_ffff, "{what}: ray {o} {d}, mode {mode}: {got:?} against {want:?}");
+ }
+ assert!(kernel.deepest.get() <= STACK);
+ }
+ }
+ on_units
+ }
+ }
+
+ fn pose(rng: &mut Rng) -> Mat4 {
+ let s = Vec3::new(0.3 + 2.0 * rng.f(), 0.3 + 2.0 * rng.f(), 0.3 + 2.0 * rng.f());
+ let q = Quat::from_euler(glam::EulerRot::XYZ, rng.f() * 6.0, rng.f() * 6.0, rng.f() * 6.0);
+ Mat4::from_scale_rotation_translation(s, q, Vec3::from(rng.v(30.0)))
+ }
+
+ /// Random scenes under random edits: meshes added and removed, units added, moved and removed, the top tree built
+ /// again after each, as an edit does. After every edit the kernel's two walks, on the CPU with every read checked,
+ /// agree with brute force. Scenes with and without a still part; units that overlap; a scene emptied of units.
+ #[test]
+ fn the_walks_agree_with_brute_force_under_random_edits() {
+ let (mut edits, mut unit_hits, mut rays) = (0, 0, 0);
+ for seed in 0..12u64 {
+ let mut rng = Rng(seed * 7919 + 1);
+ let n = 50 + rng.below(400);
+ let still = if seed % 3 == 0 { vec![] } else { rng.tris(n, 40.0, 3.0) };
+ let mut sc = Scene::new(&still, 6000, 64);
+ sc.check(&mut rng, 40, "no unit yet");
+ for step in 0..60 {
+ let live_meshes: Vec<usize> = (0..sc.meshes.len()).filter(|&k| sc.meshes[k].is_some()).collect();
+ let live_units: Vec<usize> = (0..sc.units.len()).filter(|&k| sc.units[k].is_some()).collect();
+ let what;
+ match rng.below(10) {
+ 0 | 1 => {
+ // A mesh: a few triangles, or a few hundred; some flat (a quad's two triangles in one plane).
+ let n = [1, 2, 12, 80, 300][rng.below(5)];
+ let tris = if rng.f() < 0.2 { vec![[Vec3A::ZERO, Vec3A::X, Vec3A::Y], [Vec3A::X, Vec3A::new(1.0, 1.0, 0.0), Vec3A::Y]] } else { rng.tris(n, 4.0, 1.5) };
+ match sc.add_mesh(&tris) {
+ Ok(m) => {
+ sc.add_unit(m, pose(&mut rng), rng.f() < 0.8);
+ what = "a mesh and a unit of it";
+ }
+ Err(e) => {
+ assert_eq!(e, "no room for the tree");
+ continue;
+ }
+ }
+ }
+ 2 | 3 | 4 if !live_meshes.is_empty() && live_units.len() < sc.layout.max_units() => {
+ // Another unit of a mesh there is; sometimes right on top of a unit there is (overlap).
+ let world = if !live_units.is_empty() && rng.f() < 0.3 { sc.units[live_units[rng.below(live_units.len())]].unwrap().1 * Mat4::from_translation(Vec3::from(rng.v(0.5))) } else { pose(&mut rng) };
+ sc.add_unit(live_meshes[rng.below(live_meshes.len())], world, rng.f() < 0.8);
+ what = "a unit";
+ }
+ 5 | 6 | 7 if !live_units.is_empty() => {
+ let k = live_units[rng.below(live_units.len())];
+ let (m, _, cast) = sc.units[k].unwrap();
+ let world = pose(&mut rng);
+ sc.units[k] = Some((m, world, cast));
+ sc.instances[k] = sc.record(m, world, cast);
+ what = "a unit moved";
+ }
+ 8 if !live_units.is_empty() => {
+ let k = live_units[rng.below(live_units.len())];
+ let (m, ..) = sc.units[k].take().unwrap();
+ // (The record stays as it was: nothing names it once the top tree is built again.)
+ if !sc.units.iter().flatten().any(|u| u.0 == m) {
+ sc.remove_mesh(m);
+ }
+ what = "a unit removed";
+ }
+ 9 if seed % 4 == 1 && step > 30 => {
+ // Every unit and every mesh gone: a scene that has units' room and none.
+ for k in live_units {
+ sc.units[k] = None;
+ }
+ for m in live_meshes {
+ sc.remove_mesh(m);
+ }
+ what = "every unit removed";
+ }
+ _ => continue,
+ }
+ sc.retop().unwrap();
+ edits += 1;
+ unit_hits += sc.check(&mut rng, 30, what);
+ rays += 30;
+ }
+ // The mesh range's free runs add up to what the removed trees gave back.
+ let used: usize = sc.meshes.iter().flatten().map(|m| m.3).sum();
+ assert_eq!(sc.layout.free_nodes() + used, sc.layout.mesh_cap as usize);
+ }
+ assert!(edits > 300 && unit_hits * 8 > rays, "{edits} edits, {unit_hits} of {rays} closest hits on units");
+ }
+
+ /// The trees the builders make are the trees the checks accept, at their depth bounds: a top tree of a thousand
+ /// units, a mesh of triangles all in one place (no split by position: median splits), a long strip.
+ #[test]
+ fn the_builders_keep_their_depths() {
+ let mut rng = Rng(5);
+ let units: Vec<UnitBox> = (0..1000).map(|k| UnitBox::new(k, Mat4::from_translation(Vec3::from(rng.v(100.0))), Vec3A::splat(-0.25), Vec3A::splat(0.25))).collect();
+ let top = top_tree(&units).unwrap();
+ assert_eq!(top.len(), 1999);
+ assert_eq!(check_top(&top, |r| r < 1000).unwrap(), 10, "1000 units: ceil(log2)");
+ assert!(top_tree(&[]).is_err());
+ let one = top_tree(&units[..1]).unwrap();
+ assert_eq!((one.len(), one[0].count, one[0].left_or_first), (1, 1, 0));
+ // 5,000 copies of one triangle: no position splits them.
+ let same = vec![[Vec3A::ZERO, Vec3A::X, Vec3A::Y]; 5000];
+ let t = mesh_tree(&same).unwrap();
+ assert!(t.depth <= MESH_DEPTH && check_mesh(&t.nodes, 5000).is_ok(), "depth {}", t.depth);
+ let mut seen = t.order.clone();
+ seen.sort_unstable();
+ assert_eq!(seen, (0..5000).collect::<Vec<u32>>());
+ // A strip along x, each triangle a little longer than the last.
+ let strip: Vec<[Vec3A; 3]> = (0..4000).map(|k| { let x = (k as f32).powf(1.5); [Vec3A::new(x, 0.0, 0.0), Vec3A::new(x + 1.0, 0.0, 0.0), Vec3A::new(x, 1.0, 0.0)] }).collect();
+ assert!(mesh_tree(&strip).unwrap().depth <= MESH_DEPTH);
+ assert!(mesh_tree(&[]).is_err());
+ assert!(mesh_tree(&[[Vec3A::ZERO, Vec3A::X, Vec3A::splat(f32::NAN)]]).is_err());
+ }
+
+ /// The checks refuse what the kernel's walk would not end on, or would read outside its buffers on: a child that
+ /// points back or at itself, a child outside the tree, a node with two parents, a leaf past its mesh, a leaf of
+ /// too many triangles, a box that is not a number, a top leaf that names no unit or one twice, a tree too deep.
+ #[test]
+ fn the_checks_refuse_broken_trees() {
+ let mut rng = Rng(9);
+ let tris = rng.tris(200, 5.0, 1.0);
+ let good = mesh_tree(&tris).unwrap().nodes;
+ assert!(check_mesh(&good, 200).is_ok());
+ let interior = good.iter().position(|n| n.count == 0).unwrap();
+ let leaf = good.iter().position(|n| n.count > 0).unwrap();
+ let broken = |f: &dyn Fn(&mut Vec<GpuNode>)| {
+ let mut n = good.clone();
+ f(&mut n);
+ check_mesh(&n, 200).err().unwrap_or_else(|| "(accepted)".into())
+ };
+ assert!(broken(&|n| n[interior].left_or_first = interior as u32).contains("not after it"), "a child that is itself");
+ let deeper = (1..good.len()).find(|&k| good[k].count == 0).unwrap();
+ assert!(broken(&|n| n[deeper].left_or_first = 0).contains("not after it"), "a child that points back");
+ assert!(broken(&|n| n[interior].left_or_first = n.len() as u32 - 1).contains("inside the tree"), "a right child outside");
+ assert!(broken(&|n| { let l = n[0].left_or_first; let k = (l as usize..n.len()).find(|&k| n[k].count == 0 && n[k].left_or_first > l + 1).unwrap(); n[k].left_or_first = n[0].left_or_first + 2; }).len() > 0, "a node with two parents, or nodes not reached");
+ assert!(broken(&|n| n[leaf].left_or_first = 200).contains("triangles"), "a leaf past its mesh");
+ assert!(broken(&|n| n[leaf].count = 17).contains("triangles"), "a leaf of 17");
+ assert!(broken(&|n| n[leaf].count = 0x3f80_0000).contains("triangles"), "a count that is a float's bits");
+ assert!(broken(&|n| n[interior].bmin[1] = f32::NAN).contains("not finite"));
+ assert!(broken(&|n| n.truncate(n.len() - 1)).len() > 0, "a tree cut short");
+ assert!(check_mesh(&[], 1).is_err());
+ // Zeros (room that was never filled): an interior node whose children are nodes 0 and 1.
+ assert!(check_mesh(&[GpuNode { bmin: [0.0; 3], left_or_first: 0, bmax: [0.0; 3], count: 0 }; 3], 1).is_err());
+ // A top tree.
+ let units: Vec<UnitBox> = (0..9).map(|k| UnitBox::new(k * 2, Mat4::from_translation(Vec3::new(k as f32, 0.0, 0.0)), Vec3A::ZERO, Vec3A::ONE)).collect();
+ let top = top_tree(&units).unwrap();
+ assert!(check_top(&top, |r| r % 2 == 0 && r < 18).is_ok());
+ assert!(check_top(&top, |r| r < 8).unwrap_err().contains("is not one unit"));
+ let mut twice = top.clone();
+ let leaves: Vec<usize> = (0..twice.len()).filter(|&k| twice[k].count > 0).collect();
+ twice[leaves[0]].left_or_first = twice[leaves[1]].left_or_first;
+ assert!(check_top(&twice, |r| r % 2 == 0 && r < 18).unwrap_err().contains("twice"));
+ // A chain deeper than a top tree may be.
+ let mut chain = vec![];
+ for k in 0..(TOP_DEPTH as u32 + 2) {
+ chain.push(GpuNode { bmin: [0.0; 3], left_or_first: 2 * k + 1, bmax: [1.0; 3], count: 0 });
+ chain.push(GpuNode { bmin: [0.0; 3], left_or_first: 0, bmax: [1.0; 3], count: 1 });
+ }
+ // (Node 2k is interior with children 2k + 1 (a leaf) and 2k + 2 (the next interior); the last pair are leaves.)
+ chain.pop();
+ let last = chain.len() - 1;
+ chain[last] = GpuNode { bmin: [0.0; 3], left_or_first: 0, bmax: [1.0; 3], count: 1 };
+ assert!(check_tree(&chain, 64, |_, _| Ok(())).is_ok());
+ assert!(check_tree(&chain, TOP_DEPTH, |_, _| Ok(())).unwrap_err().contains("deeper"));
+ }
+
+ /// Room and the place of trees: first fit, runs joined again when trees go, nothing lost.
+ #[test]
+ fn the_layout_places_and_takes_back() {
+ let mut l = Layout::new(100, 50, 8);
+ assert_eq!((l.mesh_first, l.top_first, l.top_cap, l.nodes(), l.max_units()), (100, 150, 15, 65, 8));
+ let (a, b, c) = (l.place(10).unwrap(), l.place(20).unwrap(), l.place(20).unwrap());
+ assert_eq!((a, b, c), (100, 110, 130));
+ assert!(l.place(1).is_none());
+ l.release(b, 20);
+ assert_eq!(l.place(5), Some(110));
+ l.release(a, 10);
+ l.release(110, 5);
+ assert_eq!(l.free_nodes(), 30);
+ assert_eq!(l.place(30), Some(100), "the runs are one again");
+ l.release(c, 20);
+ l.release(100, 30);
+ assert_eq!((l.free_nodes(), l.place(50)), (50, Some(100)));
+ // No unit at all: a top range of one node, no mesh range.
+ let none = Layout::new(7, 0, 0);
+ assert_eq!((none.nodes(), none.max_units()), (1, 1));
+ }
+
+ /// `Units` (what live.rs's edits keep): a unit names the tree its mesh has when its record is written; a top tree
+ /// is refused, and nothing changed, while a shown unit names a tree that was freed or placed again elsewhere, or
+ /// sits past the kernel's records; writing the record again (`moved`), hiding it or clearing it mends that.
+ #[test]
+ fn the_units_refuse_a_record_that_names_a_tree_that_is_gone() {
+ let mut rng = Rng(11);
+ let (small, large) = (mesh_tree(&rng.tris(40, 2.0, 0.3)).unwrap(), mesh_tree(&rng.tris(400, 2.0, 0.3)).unwrap());
+ let (ns, nl) = (small.nodes.len(), large.nodes.len());
+ assert!(nl > ns);
+ let mut u = Units { layout: Layout::new(10, ns + nl, 4), trees: vec![], slots: vec![], count: 0, records: 4 };
+ // A mesh without a tree is no unit's.
+ assert!(u.unit(0, Mat4::IDENTITY, false).is_none());
+ assert_eq!(u.add_tree(0, &small), Some(10));
+ assert_eq!(u.add_tree(1, &large), Some(10 + ns as u32));
+ assert_eq!(u.layout.free_nodes(), 0);
+ let (a, b) = (u.unit(0, Mat4::IDENTITY, false).unwrap(), u.unit(1, Mat4::from_translation(glam::Vec3::X * 5.0), false).unwrap());
+ assert_eq!((a.root, b.root), (10, 10 + ns as u32));
+ u.set(0, Some(a));
+ u.set(2, Some(b));
+ // (Clearing a record past the slots makes none.)
+ u.set(9, None);
+ assert_eq!(u.slots.len(), 3);
+ let top = u.top().unwrap();
+ assert_eq!((top.len(), u.count), (3, 2));
+ check_top(&top, |r| u.slots.get(r as usize).is_some_and(|s| s.is_some())).unwrap();
+
+ // Mesh 0's tree is freed: its unit's record still names node 10.
+ assert_eq!(u.drop_tree(0), Some((10, ns as u32)));
+ assert_eq!(u.drop_tree(0), None);
+ let e = u.top().unwrap_err();
+ assert!(e.contains("record 0") && e.contains("mesh 0"), "{e}");
+ assert_eq!(u.count, 2, "a refused top tree changes nothing");
+ // Hidden, it is in no top tree and nothing reads its record's root.
+ u.moved(0, Mat4::IDENTITY, Some(true));
+ assert_eq!((u.top().unwrap().len(), u.count), (1, 1));
+ u.moved(0, Mat4::IDENTITY, Some(false));
+ assert!(u.top().is_err());
+
+ // Mesh 1's tree is made again: its own nodes are given back first, one run with mesh 0's, and the new tree
+ // starts where that run does. Its unit's record names the old root until it is written again.
+ u.set(0, None);
+ assert_eq!(u.add_tree(1, &large), Some(10));
+ assert_eq!(u.layout.free_nodes(), ns);
+ assert!(u.top().is_err());
+ assert_eq!(u.add_tree(1, &small), Some(10));
+ let e = u.top().unwrap_err();
+ assert!(e.contains("record 2") && e.contains("mesh 1"), "{e}");
+ u.moved(2, Mat4::from_translation(glam::Vec3::Y), None);
+ assert_eq!(u.slots[2].unwrap().root, 10);
+ assert_eq!((u.top().unwrap().len(), u.count), (1, 1));
+ assert_eq!(u.layout.free_nodes(), nl);
+
+ // A unit past the kernel's records is refused; hidden or cleared, it is not there.
+ u.set(4, u.unit(1, Mat4::IDENTITY, false));
+ let e = u.top().unwrap_err();
+ assert!(e.contains("record 4") && e.contains("4 records"), "{e}");
+ u.set(4, None);
+ // More units than the top tree's range holds.
+ u.records = 16;
+ for r in 3..8 {
+ u.set(r, u.unit(1, Mat4::from_translation(glam::Vec3::Z * r as f32), false));
+ }
+ assert!(u.top().unwrap_err().contains("more than the top tree's range holds"));
+ assert_eq!(u.count, 1);
+ // No unit shown: no nodes, a count of 0 (the kernel walks no top tree).
+ for r in 0..8 {
+ u.set(r, None);
+ }
+ assert_eq!((u.top().unwrap().len(), u.count), (0, 0));
+ }
+
+ /// A mesh written again where it was (a geometry that moves every frame: live.rs writes a mesh of the same
+ /// triangle count over the one it replaces) has a new tree, and its unit's box in the top tree is the new tree's:
+ /// the walk must reach triangles that left the old bounds. (Seen on the GPU, voxel/cut-falls-live: a part that
+ /// fell 0.2 m was cut off at the box it had before.)
+ #[test]
+ fn a_unit_of_a_mesh_written_again_has_its_new_bounds() {
+ let tri = |y: f32| [[Vec3A::new(0.0, y, 0.0), Vec3A::new(1.0, y, 0.0), Vec3A::new(0.0, y + 1.0, 0.0)]];
+ let (first, fallen) = (mesh_tree(&tri(2.0)).unwrap(), mesh_tree(&tri(-3.0)).unwrap());
+ assert_eq!((first.lo.y, first.hi.y, fallen.lo.y, fallen.hi.y), (2.0, 3.0, -3.0, -2.0));
+ let mut u = Units { layout: Layout::new(1, 8, 2), trees: vec![], slots: vec![], count: 0, records: 2 };
+ u.add_tree(0, &first).unwrap();
+ u.set(0, u.unit(0, Mat4::IDENTITY, false));
+ let top = u.top().unwrap();
+ assert!(top[0].bmin[1] <= 2.0 && top[0].bmax[1] >= 3.0, "{:?}", top[0]);
+ // The same mesh, other triangles; its unit placed again, as the edit places it, and then only moved.
+ u.add_tree(0, &fallen).unwrap();
+ u.set(0, u.unit(0, Mat4::IDENTITY, false));
+ let top = u.top().unwrap();
+ assert!(top[0].bmin[1] <= -3.0 && top[0].bmax[1] >= -2.0 && top[0].bmax[1] < 0.0, "{:?}", top[0]);
+ u.add_tree(0, &first).unwrap();
+ u.moved(0, Mat4::from_translation(glam::Vec3::Y * 10.0), None);
+ let top = u.top().unwrap();
+ assert!(top[0].bmin[1] <= 12.0 && top[0].bmin[1] > 11.0 && top[0].bmax[1] >= 13.0, "{:?}", top[0]);
+ }
+}
diff --git a/tools/bench-layout.ts b/tools/bench-layout.ts
index 099b8c0..8da9ed5 100644
--- a/tools/bench-layout.ts
+++ b/tools/bench-layout.ts
@@ -4,7 +4,7 @@
// floor: GPU ms a frame and its trace pass (timestamp queries), the frame interval, and the guard's count (0, or the
// numbers mean nothing). A still view, so nothing rebuilds. The GPU lock is held.
//
-// node tools/bench-layout.ts [hello | kabukicho] [--seconds 8] [--json out.json]
+// node tools/bench-layout.ts [hello | kabukicho] [--seconds 8] [--variants a,b] [--json out.json]
//
// Every variant but the first runs the kernel in a form this machine may not have run before. After 2026-11-11 (a
// dispatch that did not end took the display down): the first frame of each variant is waited for with a timeout,
@@ -28,7 +28,9 @@ const variants: Record<string, Record<string, string>> = {
"merged+guard": { THREERT_MERGED: "1", THREERT_LOOP_GUARD: GUARD },
};
// Guarded variants first: a kernel that would not end is found by its count, not by the display.
-const order = ["written+guard", "merged+guard", "written", "merged", "merged", "written", "merged+guard", "written+guard"];
+// (`--variants written+guard,merged+guard`: only those, in the same order.)
+const only = opt("--variants", "").split(",").filter(Boolean);
+const order = ["written+guard", "merged+guard", "written", "merged", "merged", "written", "merged+guard", "written+guard"].filter((v) => !only.length || only.includes(v));
const holder = acquireGpuLock("bench-layout");
if (holder) { console.log(`not measured: GPU lock held by ${holder.tool} (pid ${holder.pid})`); process.exit(2); }
diff --git a/tools/test-render.ts b/tools/test-render.ts
index 5efd6ae..b1fb1d9 100644
--- a/tools/test-render.ts
+++ b/tools/test-render.ts
@@ -35,7 +35,13 @@ const proc = spawn(rendererBin, ["serve"], { stdio: ["pipe", "pipe", "pipe"] });
const lines = createInterface({ input: proc.stdout! })[Symbol.asyncIterator]();
await lines.next(); // ready
let stderr = "";
-proc.stderr!.on("data", (d) => (stderr = (stderr + d).slice(-4000)));
+// (The loop guard, THREERT_LOOP_GUARD: an offline render it stopped is an error; a live test's frames it stopped are
+// only said here. Wrong pixels either way: the run fails.)
+let guardStops = "";
+proc.stderr!.on("data", (d) => {
+ stderr = (stderr + d).slice(-4000);
+ guardStops = /live: the loop guard has stopped[^\n]*/.exec(String(d))?.[0] ?? guardStops;
+});
/** Mean radiance (RGB) of a region of a raw f32 RGB image. */
function region(px: Float32Array, w: number, h: number, [u0, v0, u1, v1]: Region): [number, number, number] {
@@ -127,4 +133,5 @@ console.log(`\n${passed} pass, ${failed} fail, ${results.length - passed - faile
summary("test-render A: pass rate", passed / Math.max(results.length, 1), { lowerIsBetter: false, digits: 3 });
summary("test-render A: wall time", total / 1000, { unit: " s", digits: 1 });
if (stderr && failed) console.error(stderr.split("\n").filter((l) => /error|panic/i.test(l)).slice(-5).join("\n"));
-process.exitCode = failed ? 1 : 0;
+if (guardStops) console.log(`test-render: ${guardStops}`);
+process.exitCode = failed || guardStops ? 1 : 0;
diff --git a/tools/web-hello.ts b/tools/web-hello.ts
index 6e88dd5..577f136 100644
--- a/tools/web-hello.ts
+++ b/tools/web-hello.ts
@@ -234,8 +234,11 @@ try {
check(boxes.every((b) => b.asleep && b.speed === 0), "every box is at rest, asleep");
}
check(state.trips === 0, `the loop guard stopped nothing in ${state.frames} frames (${state.trips})`);
- // Software traversal: every added box and every frame a body moves rebuilds the scene (hardware: once, then in place).
- console.log(`web hello: ${state.frames} frames, ${state.rebuilt} of them rebuilt the scene (software traversal: each box added, each frame a body moved: ${state.moved})`);
+ // Software traversal with units (docs/RUNTIME.md): the first box rebuilds the scene (a model's first instance: the
+ // kernel gets the unit walk), at its click's commit; every later box and every frame a body moves is in place.
+ // (Flattened, as before units: each box added and each of those frames rebuilt it.)
+ const commits = (state.clicks as ({ rebuilt: boolean } | null)[]).map((c) => (c ? (c.rebuilt ? "rebuild" : "in place") : "none"));
+ check(state.rebuilt === 0 && commits[0] === "rebuild" && commits.slice(1).every((c) => c === "in place"), `no frame rebuilt the scene (${state.rebuilt} of ${state.frames}; a body moved in ${state.moved}); the clicks' commits: ${commits.join(", ")}`);
// The native test's numbers, if given: the same ticks, so the same boxes to the report's four decimals.
const native = opt("--native");
if (native && existsSync(native)) {
@@ -262,7 +265,8 @@ try {
await page.close();
const F = data.frames;
// The first frames (pipelines compiled on first use, caches filling) apart; then still frames, frames in which a
- // body moved (each rebuilds the scene), frames a click's box rebuilt.
+ // body moved (in place: the units' top tree), frames that rebuilt the scene (none with units: the first box's
+ // rebuild is its click's commit).
const rows = (name: string, f: FrameRow[]) => ({
name,
frames: f.length,