The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Units: what a still frame costs (ROADMAP § 6 step 7c): one stack an invocation, one loop for both levels, a top tree by surface area (#23)
Yujia8052dc9e1bb3
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex c2063bb..c809e29 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -4015,6 +4015,39 @@ benchmark level. The order follows the dependencies; a step that meets a further- Whether all of native software traversal has the loop guard by default (not this step's; it costs 11 % ofKabukichō'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.+7c. **[ThreeRT] What a still frame costs with units.** Before step 8 (which adds units): step 7b's units made the+ trace 37 % / 71 % / 16 % longer on hello world, the voxel level and Kabukichō, and Kabukichō missed 60 Hz under+ software traversal, a browser's only path. Design and every figure: docs/RUNTIME.md "Software traversal with+ units" ("The stack", "How the top tree is made", "Measured: the still frame").+ - **Status: done on this machine** (branch `units-still-cost`, 2026-11-11; every GPU run with the loop guard, which+ stopped nothing). The trace, units as in 7b → now / flat, live, 1280 × 720 traced at half: hello world+ 1.42 → **0.73** / 0.99 ms; the voxel level 7.83 → **4.17** / 4.54; Kabukichō 13.98 → **11.8** / 12.2, its frame+ 15.2 ms of GPU: **60 Hz again**. No picture changed for it: the atomic tests with units pass, the catalog's+ models with units are their flattened pictures (ΔE 0.01–0.03 on the small ones), and the offline catalog with+ nothing set is main's bytes (24 of 24).+ - What it was, in the order of what it gave: arrays set to zero for every ray (a walk's own stack: now one for an+ invocation, the kernel module's); a unit's walk as a loop inside the top walk's, where a ray waited for its+ group (now one loop); a top tree by median splits (now by surface area, and kept: the settled units' tree+ with its boxes brought up to date, a small tree built for the units that come or travel).+ - Measured with it, as step 7b left open: the catalog's scenes with models live with units; explosions until the+ room is full (0.5–0.6 s for the rebuild, right after it); debris as units (8,192 in flight: +2–4 % of trace,+ 2.3 ms of CPU a frame), and from it and a CPU count of piles: **step 8 has room for a few thousand debris+ bodies; the CPU's instance update bounds it before the trace does.**+ - Open:+ - **A flattened scene still sets its walk's 48 words to zero for every ray**: with units hello world's trace is+ 0.73 ms and flattened 0.99, the voxel level 4.17 and 4.54. A kernel without units is `pathtrace.wgsl` as it+ is (its `trace` declares the stack; the file is shared and was not edited here). The same change there (the+ stack a private variable of the module; `trace_procs` has one too) should give every scene without+ units under software traversal what it gave these (0.36 / 1.1 / 1.5 ms on the three scenes), in a browser+ too. Not measured on a kernel without units; it changes that kernel's source, so the default sources'+ hashes and possibly the catalog's software-traversal bytes: its own step.+ - `zero-day` (+13 %) and `bistro` (+4 %) with units: one unit of millions of triangles whose transform is not a+ translation. Such a scene loses nothing flattened (it has one copy of the triangles either way); units for+ it only when it is edited.+ - The loop guard's 1.2 ms on Kabukichō (11 %): two other forms of the count gave nothing; not explained.+ - Bodies at rest on one another have no GPU number (no game makes a pile yet): step 8's first measurement.+ - Under software traversal a rigid group's pose still rebuilds the scene every frame (`zero-day-animated`:+ 2.6 s a frame), as before step 7b.8. **[engine] Voxel bodies.** The voxel collision shape and debris as bodies.- Acceptance: about a hundred debris bodies within the frame budget on the level, with the CPU split recorded.- Then the decision: keep Rapier or write our own.diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 9dbdf1e..883f554 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -496,36 +496,34 @@ trace is the frame (Kabukichō), and the atomic tests under software traversal a## 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.+ROADMAP § 6 steps 7b and 7c. **Status: runs natively and in Chrome on this machine's GPU** (2026-11-11; every run+with the loop guard, which stopped nothing). Step 7b brought the edits and the memory; a still frame then paid for+them (the trace 37 % / 71 % / 16 % longer on the three scenes below), and step 7c took that cost out.**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+(`threert-render render`) under software traversal flattens every instance, as before step 7b: its kernel and itsbytes are main's with nothing set.** `THREERT_UNITS=1` gives an offline render units; `THREERT_UNITS=0` flattens alive 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; thegate 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.+ edits and a browser need; an offline render builds its scene once and edits nothing.**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):+columns; "Measured: the still frame" at the end of this section has every step between the two):-| scene | the trace, units / flat | frame GPU, units / flat | 60 Hz (16.7 ms) |+| scene | the trace: units as in step 7b → **now** / flat | frame GPU: 7b → **now** / 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) |+| hello world (natively) | 1.42 → **0.73** / 0.99 ms | 4.60 → **3.92** / 4.33 ms | held |+| the voxel level (10,459 units) | 7.83 → **4.17** / 4.54 ms | 11.16 → **7.52** / 7.87 ms | held |+| Kabukichō (352 units) | 13.98 → **11.8** / 12.2 ms | 17.4 → **15.2** / 15.6–15.9 ms | **held again** (a frame every 16.64 ms; step 7b: 17.3) |-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").+With units the trace is now a little below the flattened scene's on these three, and on the catalog's small models;+on the two largest single models it is 4 % (`bistro`) and 13 % (`zero-day`) above. Most of what was taken out was+not traversal: it was arrays set to zero for every ray ("The stack", below).-**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.+**Not run**: a kernel with units without the guard; a pile of bodies at rest on one another on the GPU (no game+makes one yet; counted on the CPU, below); anything but hello world in a browser.**What there was.** Software traversal (a browser's only one) walked one flat tree over every triangle in worldspace. Instances were written out into it (`flatten_instances`), so adding or moving anything rebuilt the scene, and a@@ -541,20 +539,38 @@ procedural objects (`trace_procs`: the ray into the object's space, a tree of ittraversal builds its BLASes from; under software traversal the mesh's triangles are put in its tree's order, acutout 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.+- **A unit** is the instance's kernel record (160 B), as under hardware traversal, with three of its unused words+ filled: its mesh tree's root; whether it casts shadows; whether it is placed by a translation alone (the ray then+ keeps its direction and only its origin moves: 8,308 of the voxel level's 10,459 units).- **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).+ unit's transform, read when the top tree is made (so a mesh written again where it was moves its units' boxes with+ it). It is written whole into its own range of the node buffer whenever a unit is added, moved or removed (as the+ TLAS is built under hardware traversal). 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).+- **How the top tree is made** (`units::Kept`). By the surface-area heuristic (binned, one unit a leaf, its depth held+ to 18 whatever the boxes are): median splits by centres, what step 7b had, put a wall and the lamp beside it in+ halves that both span the wall, and a ray read 82 top nodes to enter 2 units on the voxel level (62 now). Such a+ build is 3.8 ms for 10,000 units, so it is seldom made over all of them. The units are two sets: the **settled**,+ which are where a build over all last had them (or less than their own size from there), whose tree is that+ build's, kept, its boxes brought up to date (0.45 ms for 10,000) and leaves taken out as units go; and the+ **loose**, which have come since or travelled (pieces thrown, bodies in flight), whose own small tree is built+ whenever one of them comes, goes or travels on. The top tree is a root over the two (one level more: 19). One+ tree is built over all when the settled tree's nodes have grown past 1.3 times their area at the build, when the+ loose at rest are an eighth of the units, or when the scene is small (64 units: a build is microseconds). Tried+ and left out: putting a new unit into the one tree leaf by leaf; after a few thousand pieces had flown, rays+ through the piles read several times what a built tree costs them.- **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.+ unit it takes the ray into the unit's space (as `trace_procs` does) and walks the mesh's tree. **The top tree and+ the units' trees are walked by one loop**, each turn a node of whichever tree the ray is in: a GPU runs a group of+ rays through a loop together, and with a unit's walk as a loop inside the top walk's, a ray that had left a unit+ waited at every unit for the slowest of its group (1.5 ms of the voxel level's 6.8). The top tree's root's box is+ tested first: a ray that meets no unit reads one node, and a scene of one unit has no tree to walk. 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`, put into the source by+ `kernel_source` for scenes that have units under software traversal (`F_UNITS`, a source feature, as vertex+ colours are): the file's text, a call at the end of the still walk, and the still walk's stack declaration taken+ out ("The stack"). 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 moreof them than a top tree holds (2^18), and every instance of an offline render (`prepare`; a live session's scenegoes through `prepare_live`), unless `THREERT_UNITS=1`. `THREERT_UNITS=0` flattens everything, as before this@@ -590,19 +606,25 @@ that is not its mesh's tree now (freed, or placed again elsewhere), or a unit sinot yet used, and a tree given back, hold leaves that end (`units::FILL`), not zeros (zeros are an interior nodewhose 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.+**The stack.** One stack of 64 entries for an invocation of a kernel with units: a private variable of the module,+which the still walk uses too (`kernel_source` takes its own declaration out of the source for such a kernel; the+file is not edited). Why not a walk's own: an array a function declares is set to zero each time the function is+entered, whatever the ray then meets, and a ray's walk is entered many times a pixel. The unit walk's own 64 words+cost hello world 0.3 ms a frame, Kabukichō 0.75 and the voxel level 0.55; the still walk's own 48 cost them 0.36,+1.1 and 1.5 more, **and cost every flattened scene the same** (a kernel without units is the file as it is, so it+still pays: "Open" in ROADMAP § 6 step 7c). A walk reads only what it pushed, so what an earlier ray left is never+read. The still walk uses 48 entries, as before, and leaves the stack empty; a unit's walk pushes above what the+top walk has pending. The top tree is at most 19 deep (a built tree 18, which holds 2^18 units, the most a scene is+given units for; a root over two of them). That leaves 45 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 45 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+- the kernel's walks transcribed line for line (a test compares the transcription's source lines with theshaders'), with every buffer read through an accessor that refuses an index outside its buffer and every loopiteration counted;- random scenes and random sequences of adding a mesh, adding, moving and removing units, removing a mesh: after each@@ -613,6 +635,12 @@ stack is dropped (geometry missed, never a hang), and the builders' bounds meanthe 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 top tree's rule: kept while units move a little, the loose units' tree built when units come, go or travel,+ one tree over all when the settled one costs too much or the loose have come to rest; whichever it is, a tree+ `check_top` accepts, within a quarter of a built tree's cost through 200 frames of thrown pieces+ (`a_top_tree_is_kept_while_units_only_move`); the random edits above run through the same rule;+- what a ray reads, counted (`units_cost.rs`, measurements, not tests: `units_cost` over a bundle's scene with units+ and flattened; `units_pile`, pieces of debris thrown onto a scene);- 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@@ -633,7 +661,10 @@ before a scene's first unit), and `tools/test-render.ts` fails a run in which itUnder software traversal as written the guard's count has its binding and buffer whether or not the scene's kernelnames it (not at `THREERT_LOOP_GUARD=0`), so a scene's first unit brings the guard without another layout.-### Measured (2026-11-11)+### Measured (step 7b, 2026-11-11)++(As step 7b left it: the top tree by median splits, a stack of the unit walk's own, two nested loops. What a still+frame costs now is in "Measured: the still frame" after this.)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@@ -737,6 +768,67 @@ the rule above was built in):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.+### Measured: the still frame (step 7c, 2026-11-11)++The same machine, settings and tools as above (software traversal, live, 1280 × 720 traced at half, guard 65,536;+p50; Kabukichō two launches of `tools/bench-layout.ts`). Each row is a build with one more change; "flat" is the+last build with `THREERT_UNITS=0`. The runs and their order: `out/web-probe/gpu-runs-c.md` (kept beside the+checkout).++| the trace, ms | hello world | the voxel level | Kabukichō |+| --- | --- | --- | --- |+| flat | 0.99 | 4.54 | 12.2 |+| step 7b | 1.42 | 7.83 | 13.98, 13.93 |+| the top tree by surface area | 1.43 | 6.90 | 14.25, 14.21 |+| + every top node's own box tested when the walk comes to it (taken out again) | 1.42 | 7.43 | 14.34, 14.24 |+| + a unit placed by a translation alone keeps the ray's direction | 1.41 | 7.39 | 13.94, 14.01 |+| + the unit walk uses the still walk's stack: one array zeroed a ray, not two | 1.13 | 6.84 | 13.24, 13.17 |+| + one loop for the top tree and the units' trees | 1.09 | 5.30 | 13.31, 13.02 |+| + the stack is the module's: none zeroed a ray | **0.73** | **4.17** | **11.83, 11.75** |++Tried and left out: the still tree in the same loop as the other two (the voxel level 5.47 for 5.30, Kabukichō 14.7+for 13.2); two other forms of the loop guard's count (at most 3 % of hello's trace, nothing on Kabukichō: the+guard's 1.2 ms there is not its form). In Chrome (`tools/web-hello.ts --frames`) hello's trace is 1.81 ms still and+1.75 with a body moving (step 7b: 2.55 and 2.66).++**The catalog's scenes with models, live with units** (the last frames of 120 in lockstep compared by+`threert-render compare`):++| scene (units) | the trace, units / flat | the picture against flat's |+| --- | --- | --- |+| `khronos-clearcoat` (1) | 1.84 / 2.11 ms | ΔE 0.01, SSIM 1.0000 |+| `khronos-metal-rough` (1) | 2.27 / 2.68 | ΔE 0.02, SSIM 1.0000 |+| `khronos-transmission` (1) | 5.28 / 5.37 | ΔE 0.03, SSIM 0.9999 |+| `instancing` (1,000, all moving) | 3.39 / 7.89; flat rebuilds the scene every frame (276 ms of CPU a frame; units 6.5) | offline at one instant, 64 spp: ΔE 0.37, SSIM 0.995 |+| `bistro` (1 unit of 2.83 M triangles) | 23.1 / 22.2 | ΔE 0.69, SSIM 0.990 |+| `zero-day` (1 unit of 5.87 M) | 14.5 / 12.8 | ΔE 1.20, SSIM 0.963: the scene's own spread, see below |+| `zero-day-animated` (3,991) | every frame rebuilds the scene (2.6 s), with units as flat: a rigid group's pose, as before step 7b | – |++`zero-day`'s picture: two runs of the flat kernel are ΔE 0.11 apart, so units' 1.20 is not noise of one kernel.+Offline at 1,024 spp the three traversals are as far from one another: units against flat ΔE 0.97, hardware+traversal against flat 0.87, hardware against units 0.91 (mean luminance within 0.3 %): speckle on the scene's+fine and coincident geometry (ROADMAP "Known issues"), nothing missing or misplaced.++**The voxel level under edits.** An explosion's commit (0.5–4 m, in place): 2.6–3.9 ms, of it the trees 0.7–1.4+(step 7b: 2.5–4.5 and 1.8–2.0). An explosion a frame for ten seconds (433 edits) does not fill the default room+(triangles 2.23 M of 2.36 M, records 10,516 of 13,073). With a fifth of the room it fills four times: each time+the scene is rebuilt in **0.48–0.64 s** (flattened, every explosion is 7 s), the room is laid out again around the+scene as it then is, and the edits after it are in place again; the last frame is the never-full run's, identical,+and against hardware traversal's of the same run ΔE 0.07, SSIM 0.9997.++**Debris as units.** Twenty explosions in a second throw 8,192 voxel cubes, each an instance for 4 s (the `debris`+game): with all of them in flight the trace is 4.19–4.30 ms against 4.11–4.13 without (**+2–4 %**); the CPU's+instance updates are 2.2–2.4 ms a frame, about 1.6 of it the top tree (the loose units' tree built each frame; one+build over all three times in 277 frames). Pieces at rest on one another cost a ray more than pieces in flight;+counted on the CPU (`units_pile`: lumps of 36 triangles in eight piles on the level): 1,000 pieces +15 % of the bytes+a pixel reads, 4,000 +43 %, 16,000 +76 %, a ray past a pile entering 2.2 / 2.8 / 4.0 units; the top tree in a frame+of flight 0.9 / 1.3 / 2.5 ms. **So step 8 has room for a few thousand debris bodies**, and what bounds it first is+the CPU's update of the instances, not the trace.++**The merge gate**: the catalog offline under software traversal with nothing set, 24 of 24 bundles byte-identical to+main; `cargo test --release` whole (79 pass); the atomic tests under hardware traversal (170 pass) and the 29 with+units under software traversal; hello world natively and in Chrome (every check, the guard 0, no frame rebuilt).+## Correctness* `threert-render edit-check` builds the GPU tables both ways for a list of events: edited in place, and built freshdiff --git a/renderer/shaders/trace_units.wgsl b/renderer/shaders/trace_units.wgslindex a400675..a82789b 100644--- a/renderer/shaders/trace_units.wgsl+++ b/renderer/shaders/trace_units.wgsl@@ -7,108 +7,114 @@// (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`'.)+// is `render --signals`'.) `n2.w` (bits): the unit is placed by a translation alone, its normal rows the identity's+// (units.rs `unit_record`): the ray keeps its direction and only its origin moves, which is what the rows would have+// made of it.//-// `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 {+// `trace` walks the still scene first and calls this with its hit: the ray is already cut to it.+//+// The stack is the module's, one for an invocation of the kernel, and in a kernel with units the still walk uses it+// too (gpu.rs `kernel_source` takes its own away). An array a function declares is set to zero each time the+// function is entered, whatever the ray then meets, and a ray's walk is entered many times a pixel: the unit walk's+// own 64 words cost hello 0.3 ms a frame and the city 0.75, and the still walk's 48 cost every scene as much again,+// flattened ones too. This one is set to zero once. A walk reads only what it has pushed: what an earlier ray left+// is never read. The still walk has left it empty; a unit's walk pushes above what the top walk has pending and is+// done when it is back down to it. 64 entries: 19 for the top tree, 45 for a mesh's (units.rs `STACK`); the still+// walk uses 48 of them, as before. Every index read here was checked on the CPU when it was written (units.rs+// `check_mesh`, `check_top`), the depths with them.+//+// One loop walks both levels: a GPU runs a group of rays through a loop together, and a ray that has left an inner+// loop waits for the others of its group to leave it; with the unit's walk as a loop inside the top walk's, every+// ray of a group waited at every unit for the group's slowest (the voxel level, 10,459 units: the trace pass 6.8 ms+// for as many iterations as the flattened scene's 4.5 ms). Here each turn of the loop is a node of whichever tree+// the ray is in: `rec` says which (NO_INST: the top tree), and with it the ray (`ro`, `rd`, `rinv`: the world's, or+// the unit's), what child indices count from (`off`) and the unit's first triangle. A top leaf sets these and goes+// to the unit's root; when the stack is back down to where the unit was entered (`base`), they are set back.+//+// The root's box is tested before the walk: a ray that meets no unit reads one node, and a scene of one unit is a+// root that is a leaf, whose record only the rays that meet its box read.+var<private> stack: array<u32, 64>;++fn trace_units(o: vec3<f32>, d: vec3<f32>, inv_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>;+ let whole = nodes[top];+ if (ray_aabb(o, inv_d, whole.bmin, whole.bmax, hit.t) == INF) { return hit; }var sp = 0u;var node = top;+ var rec = NO_INST;+ var ro = o;+ var rd = d;+ var rinv = inv_d;+ var off = top;+ var first = 0u;+ var base = 0u;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 (n.count == 0u) {+ let l = off + n.left_or_first;+ let r = l + 1u;+ let nl = nodes[l];+ let nr = nodes[r];+ var tl = ray_aabb(ro, rinv, nl.bmin, nl.bmax, hit.t);+ var tr = ray_aabb(ro, rinv, nr.bmin, nr.bmax, hit.t);+ if (tl != INF || tr != INF) {+ 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++;+ }+ continue;+ }+ } else if (rec == NO_INST) {+ // A top leaf: one unit. The ray in the unit's space (its direction not renormalised: t is the world's):+ // `proc_point`, `proc_dir`, or the origin moved alone.+ let u = instances[n.left_or_first];+ if (mode != TRACE_SHADOW || bitcast<u32>(u.n1.w) != 0u) {+ rec = n.left_or_first;+ ro = o - vec3<f32>(u.m0.w, u.m1.w, u.m2.w);+ if (bitcast<u32>(u.n2.w) == 0u) {+ ro = proc_dir(u, ro);+ rd = proc_dir(u, d);+ rinv = 1.0 / select(rd, vec3<f32>(1e-20), abs(rd) < vec3<f32>(1e-20));+ }+ off = bitcast<u32>(u.n0.w);+ first = u.info.x;+ base = sp;+ node = off;+ continue;+ }+ } else {+ for (var k = 0u; k < n.count; k++) {+ let ti = first + n.left_or_first + k;+ let x = intersect_tri(ro, rd, 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 == 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++;+ // Nothing more under this node. The unit's walk is done when the stack is back where it began: the top's again.+ if (rec != NO_INST && sp == base) {+ rec = NO_INST;+ ro = o;+ rd = d;+ rinv = inv_d;+ off = top;}+ if (sp == 0u) { break; }+ sp--;+ node = stack[sp];}return hit;}diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex 1c49726..920f21b 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -729,9 +729,12 @@ pub fn kernel_source(src: &str, features: u32) -> String {}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).+ // And it has no stack of its own here: the name is then the module's, which the units' file declares, set to+ // zero once an invocation and not once a ray (shaders/trace_units.wgsl says what that is worth).+ patch(STILL_STACK, STILL_STACK_GONE);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",+ " hit = trace_units(o, d, inv_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")));}@@ -749,6 +752,11 @@ pub fn loop_guard() -> Option<u32> {loop_guard_of(false)}+/// pathtrace.wgsl's `trace` declares its stack (software traversal); in a kernel with units it does not+/// (`kernel_source`).+const STILL_STACK: &str = "\n var stack: array<u32, 48>;\n var sp = 0u;\n var node = 0u;\n";+const STILL_STACK_GONE: &str = "\n var sp = 0u;\n var node = 0u;\n";+/// 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,@@ -3042,13 +3050,17 @@ mod tests {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);+ assert_eq!(u.matches("hit = trace_units(o, d, inv_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);+ // One stack an invocation, the module's: the still walk declares none (the procedural objects' walk keeps+ // its own), and the name it uses is the one the units' file declares.+ assert_eq!((base.matches(STILL_STACK).count(), u.matches(STILL_STACK).count()), (1, 0));+ assert_eq!((u.matches("var<private> stack: array<u32, 64>;").count(), u.matches("var stack: array<u32").count(), base.matches("var stack: array<u32").count()), (1, 1, 2));// Taking the units out again gives the file back: nothing else was touched.- let call = " hit = trace_units(o, d, hit, mode);\n";+ let call = " hit = trace_units(o, d, inv_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);+ assert_eq!(u.replacen(call, "", 1).replacen(&body, "\n// @trace-end\n", 1).replacen(STILL_STACK_GONE, STILL_STACK, 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);"));diff --git a/renderer/src/lib.rs b/renderer/src/lib.rsindex cd290c0..4688cf4 100644--- a/renderer/src/lib.rs+++ b/renderer/src/lib.rs@@ -22,6 +22,8 @@ pub mod skin;pub mod sky;pub mod tables;pub mod units;+#[cfg(test)]+mod units_cost;pub mod texpack;#[cfg(not(target_arch = "wasm32"))]pub mod view;@@ -463,7 +465,7 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mutif 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 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, kept: Default::default() };let still = nodes.len();nodes.resize(still + u.layout.nodes(), units::FILL);for (k, t) in trees.iter().enumerate() {@@ -1172,7 +1174,7 @@ mod units_tests {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() };+ 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(), reads: 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;diff --git a/renderer/src/live.rs b/renderer/src/live.rsindex 1de5f1d..e46f518 100644--- a/renderer/src/live.rs+++ b/renderer/src/live.rs@@ -2675,6 +2675,14 @@ impl LiveCore {/// BLASes the live meshes need (estimated from the build's bytes per triangle), MB.pub fn room_stats(&self) -> serde_json::Value {let (e, up) = (&self.sc.edit, &self.sc.up);+ // Software traversal's (it does not grow): the same counts, and of the node buffer the mesh trees' range (in+ // use, held) and the units the top tree has against the most its range holds.+ if let Some(u) = up.units.as_ref() {+ return serde_json::json!({+ "tris": [e.tris.used(), e.tris.cap], "records": [e.records.used(), e.records.cap], "objects": [e.objects.used(), e.objects.cap],+ "holes": e.tris.free.len(), "grows": e.grows, "nodes": [u.layout.mesh_cap as usize - u.layout.free_nodes(), u.layout.mesh_cap], "units": [u.count, u.layout.max_units()],+ });+ }let Some(a) = up.accel.as_ref() else { return serde_json::Value::Null };let buffers = [&up.verts, &up.attrs, &up.prev_verts, &up.instances, &up.objects, &up.cdf, &up.emitters, &a.verts].iter().map(|b| b.size()).sum::<u64>();let live: u64 = self.sc.meshes.iter().enumerate().filter(|(k, _)| e.users.get(&(*k as u32)).copied().unwrap_or(0) > 0).map(|(_, m)| m.count as u64).sum::<u64>() + e.pool_first as u64;@@ -2685,7 +2693,13 @@ impl LiveCore {})}- /// Moving emitters moved (`repose`, `repose_rigid`): the light tree's moving subtree refit around their triangles+ /// Software traversal's top tree so far (the frame log's `top`): how many times it was built, kept with leaves+ /// taken out and put in, and kept with its boxes brought up to date, and the ms all of that took. Null without+ /// units.+ pub fn top_stats(&self) -> serde_json::Value {+ self.sc.up.units.as_ref().map_or(serde_json::Value::Null, |u| serde_json::json!([u.kept.builds, u.kept.changes, u.kept.refits, (u.kept.ms * 1e3).round() / 1e3]))+ }+/// now (the CPU copy of the dynamic tail), its nodes and the root uploaded (`ltree::LightTree::refit_moving`).fn refit_moving_tree(&mut self) {let first = self.sc.dynamic.0;@@ -4414,7 +4428,7 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {use std::io::Write;let line = serde_json::json!({"t": start.elapsed().as_secs_f64() * 1e3, "interval": last_frame.elapsed().as_secs_f64() * 1e3, "start": t_frame.duration_since(prev_start).as_secs_f64() * 1e3,- "cpu": t_frame.elapsed().as_secs_f64() * 1e3, "script": game.frame_ms, "js": game.js_ms, "commit": game.commit_ms, "skin": core.cpu_skin_ms, "upload": core.cpu_upload_ms, "blas": core.gpu_blas_ms, "wait": core.cpu_wait_ms, "gpu": core.gpu_ms, "trace": core.gpu_trace_ms, "edit": core.edit_ms, "instanced": core.instanced_ms, "edit_split": [core.edit_split.tris, core.edit_split.upload, core.edit_split.blas, core.edit_split.added, core.edit_split.deformed, core.edit_split.objects], "rebuild": core.rebuild_ms, "fallback": core.fallback, "fallbacks": core.fallbacks, "room": core.room_stats(), "voxel": std::mem::take(&mut game.host.voxels.borrow_mut().ticks), "physics": game.host.physics.borrow_mut().as_mut().map(|p| { let s = p.take_stats(); serde_json::json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved }) }), "scale": core.render_scale, "history": core.history_len, "guard": core.guard_count(),+ "cpu": t_frame.elapsed().as_secs_f64() * 1e3, "script": game.frame_ms, "js": game.js_ms, "commit": game.commit_ms, "skin": core.cpu_skin_ms, "upload": core.cpu_upload_ms, "blas": core.gpu_blas_ms, "wait": core.cpu_wait_ms, "gpu": core.gpu_ms, "trace": core.gpu_trace_ms, "edit": core.edit_ms, "instanced": core.instanced_ms, "edit_split": [core.edit_split.tris, core.edit_split.upload, core.edit_split.blas, core.edit_split.added, core.edit_split.deformed, core.edit_split.objects], "rebuild": core.rebuild_ms, "fallback": core.fallback, "fallbacks": core.fallbacks, "room": core.room_stats(), "top": core.top_stats(), "voxel": std::mem::take(&mut game.host.voxels.borrow_mut().ticks), "physics": game.host.physics.borrow_mut().as_mut().map(|p| { let s = p.take_stats(); serde_json::json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved }) }), "scale": core.render_scale, "history": core.history_len, "guard": core.guard_count(),});writeln!(l, "{line}")?;}diff --git a/renderer/src/units.rs b/renderer/src/units.rsindex 55e2f77..e4a89ad 100644--- a/renderer/src/units.rs+++ b/renderer/src/units.rs@@ -9,28 +9,36 @@//! 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.+//! is one unit: `left_or_first` the unit's record, `count` 1. It is built by the surface-area heuristic (`build_sah`)+//! and written whole whenever a unit changes, but seldom built over all the units: it is kept with its boxes brought+//! up to date (`refit_top`) while units only move a little, and units that come, or travel, get a tree of their own+//! beside the others' (`Kept`: the settled and the loose), which is what is built when they move.//!-//! 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.+//! Depths: one stack of `STACK` entries, the kernel module's (trace_units.wgsl says why not a walk's own): the still+//! walk uses it, leaves it empty, and both levels of the unit walk share it (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` (its builder takes no split the levels left could not finish, and stops a level+//! short of it: the top tree may be a root over two built trees) 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 uses 48 entries for its one tree, as before.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.+/// The stack of a kernel with units (trace_units.wgsl `stack`, the module's): entries shared by the unit walk's two+/// levels, and used by the still walk before them.pub const STACK: usize = 64;-/// The still walk's stack (pathtrace.wgsl `trace`), as it was before there were units.+/// The still walk's stack in a kernel without units, and how much of the module's the still walk uses in one with.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.+/// The deepest top tree (levels below the root): a built tree is no deeper than 18, whatever its units' boxes+/// (`build_sah`), and the top tree is one, or a root over two (`Kept`).+pub const TOP_DEPTH: usize = 19;+/// The deepest mesh tree (45): 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;+/// The most units a top tree holds: 2^18, what a built tree's depth has room for.+pub const MAX_UNITS: usize = 1 << (TOP_DEPTH - 1);/// A leaf's most triangles (bvh.rs builds leaves of up to 16).pub const MAX_LEAF: u32 = 16;@@ -158,6 +166,111 @@ fn build_median(boxes: &[(Vec3A, Vec3A)], max_leaf: usize) -> (Vec<GpuNode>, Vec(nodes, order)}+/// The bins of a top tree's split along an axis.+const TOP_BINS: usize = 32;++fn area(lo: Vec3A, hi: Vec3A) -> f32 {+ let e = (hi - lo).max(Vec3A::ZERO);+ 2.0 * (e.x * e.y + e.y * e.z + e.z * e.x)+}++/// A tree over boxes (min, max) by the surface-area heuristic, one box a leaf, no deeper than `max_depth` whatever+/// the boxes are (there are at most 2^`max_depth` of them). Each split is the cheapest of the binned ones along the+/// three axes of the boxes' centres (cost: each side's area times its count, the chance a ray through the node meets+/// the side times what is in it), among those that leave both sides no more boxes than the levels below can still+/// halve down to one; where there is none (every centre in one place; a split the depth forbids), the median along+/// the widest axis, which halves. So a node at depth d holds at most 2^(`max_depth` - d) boxes, and a leaf is no+/// deeper than `max_depth`. Returns the nodes (a leaf's `left_or_first`: its position in the order) and the order.+///+/// Why not the median everywhere (what the top tree was at first): units are not of one size. A median split by+/// centres puts a wall and the lamp beside it in whichever halves their centres fall in, and both halves' boxes then+/// span the wall: a ray reads far more of the tree than it enters units (the voxel level: 82 top nodes read a ray+/// for 2.2 units entered; `units_cost.rs`).+fn build_sah(boxes: &[(Vec3A, Vec3A)], max_depth: 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);+ }+ debug_assert!(max_depth >= usize::BITS as usize || boxes.len() <= 1 << max_depth);+ let centres: Vec<Vec3A> = boxes.iter().map(|b| (b.0 + b.1) * 0.5).collect();+ let mut stack = vec![(0usize, 0usize, boxes.len(), 0usize)];+ while let Some((ni, start, end, depth)) = 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(centres[k as usize]);+ chi = chi.max(centres[k as usize]);+ }+ let count = end - start;+ if count == 1 {+ nodes[ni] = GpuNode { bmin: lo.into(), left_or_first: start as u32, bmax: hi.into(), count: 1 };+ continue;+ }+ // The most boxes a side may hold: what the levels under a child still halve down to one.+ let room = 1usize.checked_shl((max_depth - depth - 1) as u32).unwrap_or(usize::MAX);+ let ext = chi - clo;+ let bin = |k: u32, axis: usize| (((centres[k as usize][axis] - clo[axis]) * (TOP_BINS as f32 / ext[axis])) as usize).min(TOP_BINS - 1);+ let mut best = (f32::INFINITY, 0usize, 0usize);+ for axis in 0..3 {+ if !(ext[axis] > 0.0) {+ continue;+ }+ let mut bins = [(Vec3A::splat(f32::INFINITY), Vec3A::splat(f32::NEG_INFINITY), 0usize); TOP_BINS];+ for &k in &order[start..end] {+ let b = &mut bins[bin(k, axis)];+ *b = (b.0.min(boxes[k as usize].0), b.1.max(boxes[k as usize].1), b.2 + 1);+ }+ // The right sides' areas from the last bin back, then the left sides' forward.+ let mut right = [0.0f32; TOP_BINS];+ let mut acc = (Vec3A::splat(f32::INFINITY), Vec3A::splat(f32::NEG_INFINITY));+ for i in (1..TOP_BINS).rev() {+ acc = (acc.0.min(bins[i].0), acc.1.max(bins[i].1));+ right[i] = area(acc.0, acc.1);+ }+ let mut acc = (Vec3A::splat(f32::INFINITY), Vec3A::splat(f32::NEG_INFINITY));+ let mut nl = 0;+ for i in 1..TOP_BINS {+ acc = (acc.0.min(bins[i - 1].0), acc.1.max(bins[i - 1].1));+ nl += bins[i - 1].2;+ let nr = count - nl;+ if nl == 0 || nr == 0 || nl > room || nr > room {+ continue;+ }+ let cost = area(acc.0, acc.1) * nl as f32 + right[i] * nr as f32;+ if cost < best.0 {+ best = (cost, axis, i);+ }+ }+ }+ let mid = if best.0.is_finite() {+ let (_, axis, split) = best;+ let slice = &mut order[start..end];+ let mut i = 0;+ for j in 0..slice.len() {+ if bin(slice[j], axis) < split {+ slice.swap(i, j);+ i += 1;+ }+ }+ i+ } else {+ let axis = if ext.x >= ext.y && ext.x >= ext.z { 0 } else if ext.y >= ext.z { 1 } else { 2 };+ order[start..end].select_nth_unstable_by(count / 2, |&a, &b| centres[a as usize][axis].total_cmp(¢res[b as usize][axis]).then(a.cmp(&b)));+ count / 2+ };+ 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, depth + 1));+ stack.push((left, start, start + mid, depth + 1));+ }+ (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()}@@ -182,6 +295,7 @@ pub fn mesh_tree(tris: &[[Vec3A; 3]]) -> Result<MeshTree, String> {}/// A unit for the top tree: its record, and its mesh's model-space bounds under its world transform.+#[derive(Clone, Copy, Debug)]pub struct UnitBox {pub record: u32,pub lo: Vec3A,@@ -204,8 +318,9 @@ impl UnitBox {}}-/// 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.+/// The top tree over `units` (at least one): by the surface-area heuristic (`build_sah`) down to one unit a leaf, a+/// level less deep than `TOP_DEPTH` (so that two can be joined); 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());@@ -217,7 +332,7 @@ pub fn top_tree(units: &[UnitBox]) -> Result<Vec<GpuNode>, String> {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);+ let (mut nodes, order) = build_sah(&boxes, TOP_DEPTH - 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;}@@ -226,14 +341,207 @@ pub fn top_tree(units: &[UnitBox]) -> Result<Vec<GpuNode>, String> {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).+/// A unit's record: the instance's (`scene::Instance::gpu`), with, in the three words the normal rows leave unused+/// (trace_units.wgsl reads them as bits): its mesh tree's root; whether it casts shadows; whether it is placed by a+/// translation alone (or not moved at all). The last is read off the record's own normal rows, which are then the+/// identity's: the walk moves the ray's origin and leaves the rest of the ray as it is, which is what multiplying by+/// these rows comes to, to the bit (the sign of a zero aside, which no comparison in the walk sees).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.n[2][3] = f32::from_bits(translation_alone(&r) as u32);r}+/// Whether a record's normal rows are the identity's.+pub fn translation_alone(r: &GpuInstance) -> bool {+ (0..3).all(|k| (0..3).all(|c| r.n[k][c] == if k == c { 1.0 } else { 0.0 }))+}++/// How much more than at its build the settled units' tree may cost (`top_cost`) and still be kept with its boxes+/// brought up to date (`refit_top`); past it a tree is built over all the units. (The top tree is about half of what+/// a ray reads on a level of 10,000 units, so 30 % of it is about 15 % of a ray.)+pub const REFIT_SLACK: f64 = 1.3;++/// How far a unit may go from where it was placed in the top tree before it is no longer kept there: this many times+/// the longest side of the box it was placed with (`Kept::astray`).+pub const ASTRAY: f32 = 1.0;++/// A scene of no more units than this has its top tree built whenever a unit comes, goes or goes astray: a build is+/// then microseconds.+pub const SMALL: usize = 64;++/// The loose units that have come to rest are put back with the others (one tree built over all) once they are this+/// share of the units; at rest: not gone astray through `QUIET` builds of the loose tree in a row.+pub const FOLD: f64 = 1.0 / 8.0;+pub const QUIET: u8 = 8;++/// What a top tree costs a ray, by surface area: the sum of its interior nodes' box areas (a line through space meets+/// a box in proportion to its area; at each interior node it meets, the walk reads two nodes). Not divided by the+/// root's: a unit that flies off makes the root large, and the tree no better.+pub fn top_cost(nodes: &[GpuNode]) -> f64 {+ nodes.iter().filter(|n| n.count == 0).map(|n| area(Vec3A::from(n.bmin), Vec3A::from(n.bmax)) as f64).sum()+}++/// A top tree as it stands (`nodes`: one `top_tree` built, or this made of it) with its boxes again from `units`: a+/// leaf's is its unit's, an interior node's what holds its two children's. The tree's shape is not touched: units+/// that moved a little are where the tree has them, and a tree that is not rebuilt costs a pass over its nodes+/// instead of a build (0.2 ms against 3.7 ms for 10,000 units). None: the units are not the tree's leaves, one for+/// one (a unit added, removed, hidden or shown: build it again), or `nodes` is no tree. The caller checks the result+/// as it checks a built tree, and compares its cost.+pub fn refit_top(nodes: &[GpuNode], units: &[UnitBox]) -> Option<Vec<GpuNode>> {+ if units.is_empty() || nodes.len() != 2 * units.len() - 1 {+ return None;+ }+ let most = units.iter().map(|u| u.record).max()? as usize;+ let mut at = vec![u32::MAX; most + 1];+ for (k, u) in units.iter().enumerate() {+ if std::mem::replace(&mut at[u.record as usize], k as u32) != u32::MAX {+ return None;+ }+ }+ let mut out = nodes.to_vec();+ // Children are after their parents (`check_tree`): from the last node back, both are done before their parent.+ for i in (0..out.len()).rev() {+ let n = out[i];+ if n.count > 0 {+ let k = std::mem::replace(at.get_mut(n.left_or_first as usize)?, u32::MAX);+ let u = units.get(k as usize)?;+ out[i] = GpuNode { bmin: u.lo.into(), bmax: u.hi.into(), ..n };+ } else {+ let l = n.left_or_first as usize;+ if l <= i || l + 1 >= out.len() {+ return None;+ }+ let (a, b) = (out[l], out[l + 1]);+ out[i] = GpuNode { bmin: Vec3A::from(a.bmin).min(b.bmin.into()).into(), bmax: Vec3A::from(a.bmax).max(b.bmax.into()).into(), ..n };+ }+ }+ Some(out)+}++/// A top tree as it stands (`nodes`, as for `refit_top`) without the leaves whose units are not among `units` (a+/// leaf's sibling takes its parent's place), every box brought up to date. With it, what the tree cost (`top_cost`)+/// with its boxes up to date before any leaf was taken out, and after. Taking leaves out leaves a tree no deeper and+/// no worse for the units that stay. None: `nodes` is no tree, a record is there twice, a unit has no leaf, or no+/// leaf is left. The result is laid out as a build's (children side by side, after their parent); the caller checks+/// it as it checks a built tree.+pub fn thin_top(nodes: &[GpuNode], units: &[UnitBox]) -> Option<(Vec<GpuNode>, [f64; 2])> {+ const NONE: u32 = u32::MAX;+ let n = nodes.len();+ if units.is_empty() || n == 0 {+ return None;+ }+ let most = units.iter().map(|u| u.record).max()? as usize;+ let mut at = vec![NONE; most + 1];+ for (k, u) in units.iter().enumerate() {+ if std::mem::replace(&mut at[u.record as usize], k as u32) != NONE {+ return None;+ }+ }+ // The tree as nodes that name their parent and children. Every node but the root is some node's child once, and+ // children are after their parents: a tree from node 0, whose every walk below ends.+ let mut lo: Vec<Vec3A> = nodes.iter().map(|q| q.bmin.into()).collect();+ let mut hi: Vec<Vec3A> = nodes.iter().map(|q| q.bmax.into()).collect();+ let mut par = vec![NONE; n];+ let mut kid = vec![[NONE; 2]; n];+ let mut alive = vec![true; n];+ for (i, q) in nodes.iter().enumerate() {+ if q.count > 0 {+ continue;+ }+ let l = q.left_or_first as usize;+ if l <= i || l + 1 >= n || par[l] != NONE || par[l + 1] != NONE {+ return None;+ }+ (par[l], par[l + 1], kid[i]) = (i as u32, i as u32, [l as u32, l as u32 + 1]);+ }+ if par[1..].contains(&NONE) {+ return None;+ }+ // Interior nodes' boxes from their children's, the last node first (a node taken out leaves its sibling under+ // its grandparent: still after it), and the sum of their areas.+ let sweep = |lo: &mut [Vec3A], hi: &mut [Vec3A], kid: &[[u32; 2]], alive: &[bool]| {+ let mut cost = 0.0;+ for i in (0..n).rev() {+ if alive[i] && kid[i][0] != NONE {+ let (a, b) = (kid[i][0] as usize, kid[i][1] as usize);+ (lo[i], hi[i]) = (lo[a].min(lo[b]), hi[a].max(hi[b]));+ cost += area(lo[i], hi[i]) as f64;+ }+ }+ cost+ };+ // The leaves that stay get their units' boxes; the others go after the cost with them is taken.+ let (mut stay, mut gone) = (0, vec![]);+ for i in 0..n {+ if nodes[i].count == 0 {+ continue;+ }+ match at.get(nodes[i].left_or_first as usize).copied().filter(|&k| k != NONE) {+ Some(k) => {+ (lo[i], hi[i]) = (units[k as usize].lo, units[k as usize].hi);+ at[nodes[i].left_or_first as usize] = NONE;+ stay += 1;+ }+ None => gone.push(i),+ }+ }+ if stay != units.len() {+ return None;+ }+ let before = sweep(&mut lo, &mut hi, &kid, &alive);+ let mut root = 0usize;+ for &x in &gone {+ // (A leaf that stays is left, so `x` is never the root: it has a parent, and a sibling to take its place.)+ let p = par[x] as usize;+ (alive[x], alive[p]) = (false, false);+ let s = if kid[p][0] as usize == x { kid[p][1] } else { kid[p][0] };+ let g = par[p];+ par[s as usize] = g;+ if g == NONE {+ root = s as usize;+ } else {+ let slot = if kid[g as usize][0] as usize == p { 0 } else { 1 };+ kid[g as usize][slot] = s;+ }+ }+ let after = if gone.is_empty() { before } else { sweep(&mut lo, &mut hi, &kid, &alive) };+ let mut out = vec![FILL];+ let mut stack = vec![(root, 0usize)];+ while let Some((i, to)) = stack.pop() {+ if kid[i][0] == NONE {+ out[to] = GpuNode { bmin: lo[i].into(), left_or_first: nodes[i].left_or_first, bmax: hi[i].into(), count: 1 };+ continue;+ }+ let left = out.len();+ out.push(FILL);+ out.push(FILL);+ out[to] = GpuNode { bmin: lo[i].into(), left_or_first: left as u32, bmax: hi[i].into(), count: 0 };+ stack.push((kid[i][1] as usize, left + 1));+ stack.push((kid[i][0] as usize, left));+ }+ (out.len() == 2 * units.len() - 1).then_some((out, [before, after]))+}++/// One top tree of two: a root over `a`'s and `b`'s, then `a`'s other nodes, then `b`'s. A level deeper than the+/// deeper of the two.+pub fn join_tops(a: &[GpuNode], b: &[GpuNode]) -> Vec<GpuNode> {+ let hold = |x: &GpuNode, y: &GpuNode| (Vec3A::from(x.bmin).min(y.bmin.into()), Vec3A::from(x.bmax).max(y.bmax.into()));+ let (lo, hi) = hold(&a[0], &b[0]);+ let mut out = Vec::with_capacity(a.len() + b.len() + 1);+ out.push(GpuNode { bmin: lo.into(), left_or_first: 1, bmax: hi.into(), count: 0 });+ // Where a tree's nodes after its root go: `a`'s from 3, `b`'s after them. A child index counts from the top+ // tree's root, and moves by as much as the node it names.+ let moved = |q: &GpuNode, by: u32| if q.count > 0 { *q } else { GpuNode { left_or_first: q.left_or_first + by, ..*q } };+ let (by_a, by_b) = (2, a.len() as u32 + 1);+ out.push(moved(&a[0], by_a));+ out.push(moved(&b[0], by_b));+ out.extend(a[1..].iter().map(|q| moved(q, by_a)));+ out.extend(b[1..].iter().map(|q| moved(q, by_b)));+ out+}+/// 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)]@@ -339,6 +647,45 @@ pub struct Units {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,+ /// The top tree as `top` last made it, and how it came to be.+ pub kept: Kept,+}++/// The top tree `Units::top` last returned, and how it came to be. The units are in two sets. The settled, which are+/// where they were when a tree was last built over all the units (or have moved less than `ASTRAY` from there):+/// their tree is that build's, kept, its boxes brought up to date, leaves taken out as units go. And the loose: units+/// that have come since, or gone astray (pieces an explosion throws, bodies that travel): a tree of their own, built+/// again whenever one of them comes, goes or goes astray, which costs by their number and not by the scene's. With+/// loose units the top tree is a root over the two (`join_tops`); without, the settled tree alone.+///+/// Why not one tree with the new units put into it a leaf at a time: tried (greedy descent by least added area, the+/// depth held, equals balanced), and after a few thousand pieces had flown, the tree cost rays through the piles+/// several times a built tree's (`units_cost.rs` `units_pile`: 16,000 pieces, 204 k bytes a pixel against 22 k),+/// while by the area of its nodes it looked 10 % worse. Two trees that are each built are each good, and a ray that+/// passes both walks both: what it costs is measured there too.+#[derive(Clone, Debug, Default)]+pub struct Kept {+ /// The top tree as written.+ pub nodes: Vec<GpuNode>,+ /// With loose units: the settled units' tree by itself (`nodes` holds it from node 1). Without: empty, and+ /// `nodes` is it.+ settled: Vec<GpuNode>,+ /// By record: 0 not in the tree, 1 settled, 2 loose.+ part: Vec<u8>,+ loose: usize,+ /// By record: the box the unit had when it was placed (the build over all, or the loose tree's last build).+ placed: Vec<(Vec3A, Vec3A)>,+ /// By record, for a loose unit: how many builds of the loose tree in a row it has not gone astray since.+ calm: Vec<u8>,+ /// What the settled tree cost when it was built (`top_cost`), less the share of the leaves taken out since.+ pub built_cost: f64,+ /// How many times a tree was built over all the units; how many times the loose units' tree was built (the+ /// settled one kept); how many times the tree was kept as it was, its boxes brought up to date; the ms all of+ /// them took (the frame log's `top`).+ pub builds: u64,+ pub changes: u64,+ pub refits: u64,+ pub ms: f64,}impl Units {@@ -394,11 +741,14 @@ impl Units {}/// 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.+ /// unit: no nodes (the kernel does not walk a top tree then). The tree it made last is kept as far as it is+ /// still good (`Kept::top`): whole, its boxes brought up to date, while units only move a little; its settled+ /// part, with a tree built over the units that have come or travelled; else it is built again. 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 t = web_time::Instant::now();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 };@@ -413,12 +763,129 @@ impl Units {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)? };+ let slots = self.slots.len();+ let nodes = if boxes.is_empty() { vec![] } else { self.kept.top(&boxes, slots)? };self.count = boxes.len() as u32;+ self.kept.nodes = nodes.clone();+ self.kept.ms += t.elapsed().as_secs_f64() * 1e3;Ok(nodes)}}+impl Kept {+ /// The top tree over `boxes` (at least one; their records below `records`), by the least work that leaves it+ /// good: kept, its boxes brought up to date (no unit has come, gone or gone astray); the settled tree kept and+ /// the loose units' built; or one tree built over all (the first; a small scene's; a settled tree that costs+ /// more than `REFIT_SLACK` times what it may; loose units at rest that are many: `FOLD`). Whichever it is was+ /// checked (`check_top`) before anything here was changed for it.+ pub fn top(&mut self, boxes: &[UnitBox], records: usize) -> Result<Vec<GpuNode>, String> {+ if let Some(nodes) = self.keep(boxes, records) {+ return Ok(nodes);+ }+ let built = top_tree(boxes)?;+ self.built_cost = top_cost(&built);+ (self.settled, self.loose) = (vec![], 0);+ self.part.clear();+ self.place(boxes, 1);+ self.builds += 1;+ Ok(built)+ }++ fn place(&mut self, units: &[UnitBox], part: u8) {+ for u in units {+ let r = u.record as usize;+ if self.part.len() <= r {+ self.part.resize(r + 1, 0);+ self.placed.resize(r + 1, (Vec3A::ZERO, Vec3A::ZERO));+ self.calm.resize(r + 1, 0);+ }+ (self.part[r], self.placed[r]) = (part, (u.lo, u.hi));+ }+ }++ /// Whether a unit has gone from where the tree has it: its box is no longer within the box it was placed with,+ /// widened by that box's longest side (`ASTRAY`). A body that turns where it is, or has moved less than its own+ /// size, has not; one that flies has, every few frames. Left where it is in the tree, its leaf is among its old+ /// neighbours, and its box, brought up to date, stretches every node above it to where it is now: a tree that+ /// costs little more by the area of its nodes (what `REFIT_SLACK` sees) and many times more to the rays that+ /// pass the place (a thousand pieces thrown from one point, kept as they were built: 3.6 times the bytes a pixel).+ fn astray(&self, u: &UnitBox) -> bool {+ let (lo, hi) = self.placed[u.record as usize];+ let by = Vec3A::splat((hi - lo).max_element() * ASTRAY);+ u.lo.cmplt(lo - by).any() || u.hi.cmpgt(hi + by).any()+ }++ /// The kept tree made `boxes`', or None: build one over all (nothing is changed then).+ fn keep(&mut self, boxes: &[UnitBox], records: usize) -> Option<Vec<GpuNode>> {+ if self.nodes.is_empty() || !boxes.iter().all(|u| u.lo.is_finite() && u.hi.is_finite() && (u.record as usize) < records) {+ return None;+ }+ let mut is = vec![false; records];+ for u in boxes {+ is[u.record as usize] = true;+ }+ let checked = |t: Vec<GpuNode>| check_top(&t, |r| is.get(r as usize).copied().unwrap_or(false)).is_ok().then_some(t);+ // Each unit's part now: settled if it was and has not gone astray, else loose. (`stirred`: the loose tree is+ // no longer its units': one came, or went astray. `resting`: loose units that have long kept still.)+ let (mut settled, mut loose): (Vec<UnitBox>, Vec<UnitBox>) = (vec![], vec![]);+ let (mut stirred, mut resting) = (false, 0);+ let mut strayed = vec![];+ for u in boxes {+ match self.part.get(u.record as usize).copied().unwrap_or(0) {+ 1 if !self.astray(u) => settled.push(*u),+ 2 => {+ let astray = self.astray(u);+ stirred |= astray;+ resting += (!astray && self.calm[u.record as usize] >= QUIET) as usize;+ strayed.push(astray);+ loose.push(*u);+ }+ _ => {+ stirred = true;+ strayed.push(true);+ loose.push(*u);+ }+ }+ }+ let was_settled = if self.loose > 0 { self.settled.len() } else { self.nodes.len() }.div_ceil(2);+ if !stirred && settled.len() == was_settled && loose.len() == self.loose {+ // The tree as it is. (With loose units the settled tree's cost is its own nodes': node 1, and those from+ // 3 to where the loose tree's begin. The settled tree kept by itself gets its boxes when it is next used.)+ let nodes = checked(refit_top(&self.nodes, boxes)?)?;+ let cost = if self.loose > 0 { top_cost(&nodes[1..2]) + top_cost(&nodes[3..self.settled.len() + 2]) } else { top_cost(&nodes) };+ if cost > self.built_cost * REFIT_SLACK {+ return None;+ }+ self.refits += 1;+ return Some(nodes);+ }+ if boxes.len() <= SMALL || settled.is_empty() || resting as f64 > boxes.len() as f64 * FOLD {+ return None;+ }+ // The settled tree without the leaves that went, as good as it was; the loose units' tree, built.+ let (kept, [before, after]) = thin_top(if self.loose > 0 { &self.settled } else { &self.nodes }, &settled)?;+ if before > self.built_cost * REFIT_SLACK {+ return None;+ }+ let nodes = checked(if loose.is_empty() { kept.clone() } else { join_tops(&kept, &top_tree(&loose).ok()?) })?;+ for part in self.part.iter_mut() {+ *part = 0;+ }+ for u in &settled {+ self.part[u.record as usize] = 1;+ }+ self.place(&loose, 2);+ for (u, astray) in loose.iter().zip(strayed) {+ let calm = &mut self.calm[u.record as usize];+ *calm = if astray { 0 } else { calm.saturating_add(1) };+ }+ self.built_cost *= if before > 0.0 { after / before } else { 1.0 };+ (self.settled, self.loose) = (if loose.is_empty() { vec![] } else { kept }, loose.len());+ self.changes += 1;+ Some(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)]@@ -451,22 +918,53 @@ pub(crate) mod cpu {pub(crate) budget: u64,/// The deepest the shared stack got.pub(crate) deepest: std::cell::Cell<usize>,+ /// What the walks read, counted (units_cost.rs).+ pub(crate) reads: std::cell::Cell<Reads>,+ }++ /// A walk's reads by kind: nodes of the still tree, of the top tree and of mesh trees, vertices (three a triangle+ /// test) and unit records; `still_steps`: the loop iterations of the still scene's walk (the rest of `steps` are+ /// the unit walk's). `in_units`: the still walk is over.+ #[derive(Clone, Copy, Debug, Default, PartialEq)]+ pub(crate) struct Reads {+ pub(crate) still_nodes: u64,+ pub(crate) top_nodes: u64,+ pub(crate) mesh_nodes: u64,+ pub(crate) still_verts: u64,+ pub(crate) mesh_verts: u64,+ pub(crate) records: u64,+ pub(crate) still_steps: u64,+ pub(crate) in_units: bool,}pub(crate) type Walk<T> = Result<T, String>;impl Kernel<'_> {+ fn count(&self, f: impl Fn(&mut Reads)) {+ let mut r = self.reads.get();+ f(&mut r);+ self.reads.set(r);+ }+ /// The still walk is over. (The top tree's nodes are the buffer's last: a node at `top` or after is the top+ /// tree's, one before it a mesh tree's.)+ fn still_done(&self) {+ self.count(|r| r.in_units = true);+ }pub(crate) fn node(&self, i: u32) -> Walk<GpuNode> {+ self.count(|r| *(if !r.in_units { &mut r.still_nodes } else if i >= self.top { &mut r.top_nodes } else { &mut r.mesh_nodes }) += 1);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.count(|r| *(if r.in_units { &mut r.mesh_verts } else { &mut r.still_verts }) += 1);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.count(|r| r.records += 1);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);+ self.count(|r| r.still_steps += !r.in_units as u64);if self.steps.get() > self.budget {return Err("does not stop".into());}@@ -531,7 +1029,9 @@ pub(crate) mod cpu {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);+ // (The stack is the module's in a kernel with units, 64 long, the still walk's own bound kept; in one+ // without, the walk's own 48.)+ let (mut stack, mut sp, mut node) = ([0u32; STACK], 0usize, 0u32);loop {self.step()?;let n = self.node(node)?;@@ -582,111 +1082,89 @@ pub(crate) mod cpu {sp += 1;}}- self.trace_units(o, d, hit, mode)+ self.still_done();+ self.trace_units(o, d, inv_d, hit, mode, &mut stack)}/// 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> {+ pub(crate) fn trace_units(&self, o: Vec3A, d: Vec3A, inv_d: Vec3A, hit_in: Hit, mode: u32, stack: &mut [u32; STACK]) -> 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);+ let whole = self.node(top)?;+ if Self::ray_aabb(o, inv_d, whole.bmin, whole.bmax, hit.t) == INF {+ return Ok(hit);+ }+ let (mut sp, mut node) = (0usize, top);+ let mut rec = NO_INST;+ let (mut ro, mut rd, mut rinv) = (o, d, inv_d);+ let (mut off, mut first, mut base) = (top, 0u32, 0usize);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 n.count == 0 {+ let l = off + n.left_or_first;+ let r = l + 1;+ let (nl, nr) = (self.node(l)?, self.node(r)?);+ let mut tl = Self::ray_aabb(ro, rinv, nl.bmin, nl.bmax, hit.t);+ let mut tr = Self::ray_aabb(ro, rinv, nr.bmin, nr.bmax, hit.t);+ if tl != INF || tr != INF {+ 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));}+ continue;}- if sp == 0 {- break;+ } else if rec == NO_INST {+ let u = self.record(n.left_or_first)?;+ if mode != TRACE_SHADOW || u.n[1][3].to_bits() != 0 {+ rec = n.left_or_first;+ ro = o - Vec3A::new(u.m[0][3], u.m[1][3], u.m[2][3]);+ if u.n[2][3].to_bits() == 0 {+ ro = Self::proc_dir(&u, ro);+ rd = Self::proc_dir(&u, d);+ rinv = Self::inv(rd);+ }+ off = u.n[0][3].to_bits();+ first = u.info[0];+ base = sp;+ node = off;+ continue;}- 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;+ } else {+ for k in 0..n.count {+ self.step()?;+ let ti = first + n.left_or_first + k;+ let x = self.intersect_tri(ro, rd, ti, hit.t)?;+ if x < hit.t {+ hit = Hit { t: x, tri: ti, inst: rec };+ if mode != TRACE_CLOSEST {+ return Ok(hit);+ }+ }}- 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);+ if rec != NO_INST && sp == base {+ rec = NO_INST;+ ro = o;+ rd = d;+ rinv = inv_d;+ off = top;}- node = near;- if tr != INF && sp < STACK {- stack[sp] = far;- sp += 1;- self.deepest.set(self.deepest.get().max(sp));+ if sp == 0 {+ break;}+ sp -= 1;+ node = stack[sp];}Ok(hit)}@@ -714,59 +1192,66 @@ mod tests {units,"trace_units.wgsl",&[- "fn trace_units(o: vec3<f32>, d: vec3<f32>, hit_in: Hit, mode: u32) -> Hit {",+ "var<private> stack: array<u32, 64>;",+ "fn trace_units(o: vec3<f32>, d: vec3<f32>, inv_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>;",+ "let whole = nodes[top];",+ "if (ray_aabb(o, inv_d, whole.bmin, whole.bmax, hit.t) == INF) { return hit; }",+ "var sp = 0u;","var node = top;",+ "var rec = NO_INST;",+ "var ro = o;",+ "var rd = d;",+ "var rinv = inv_d;",+ "var off = top;",+ "var first = 0u;",+ "var base = 0u;","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;",+ "if (n.count == 0u) {",+ "let l = off + 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; }",+ "var tl = ray_aabb(ro, rinv, nl.bmin, nl.bmax, hit.t);",+ "var tr = ray_aabb(ro, rinv, nr.bmin, nr.bmax, hit.t);",+ "if (tl != INF || tr != INF) {","if (tr < tl) {","node = near;","if (tr != INF && sp < 64u) {","stack[sp] = far;",+ "continue;",+ "} else if (rec == NO_INST) {",+ "let u = instances[n.left_or_first];",+ "if (mode != TRACE_SHADOW || bitcast<u32>(u.n1.w) != 0u) {",+ "rec = n.left_or_first;",+ "ro = o - vec3<f32>(u.m0.w, u.m1.w, u.m2.w);",+ "if (bitcast<u32>(u.n2.w) == 0u) {",+ "ro = proc_dir(u, ro);",+ "rd = proc_dir(u, d);",+ "rinv = 1.0 / select(rd, vec3<f32>(1e-20), abs(rd) < vec3<f32>(1e-20));",+ "off = bitcast<u32>(u.n0.w);",+ "first = u.info.x;",+ "base = sp;",+ "node = off;",+ "continue;",+ "} else {",+ "for (var k = 0u; k < n.count; k++) {",+ "let ti = first + n.left_or_first + k;",+ "let x = intersect_tri(ro, rd, 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 (rec != NO_INST && sp == base) {",+ "rec = NO_INST;",+ "ro = o;",+ "rd = d;",+ "rinv = inv_d;",+ "off = top;",+ "if (sp == 0u) { break; }",+ "node = stack[sp];","return hit;",],);- assert_eq!(units.matches("loop {").count(), 2, "two walks");+ assert_eq!(units.matches("loop {").count(), 1, "one loop for both levels");let kernel = include_str!("../shaders/pathtrace.wgsl");ordered(kernel,@@ -800,7 +1285,7 @@ mod tests {);// 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);+ assert!(TOP_DEPTH + MESH_DEPTH <= STACK && STILL_STACK <= STACK, "one stack holds each walk");}/// A deterministic stream of numbers in [0, 1).@@ -841,6 +1326,8 @@ mod tests {units: Vec<Option<(usize, Mat4, bool)>>,top: u32,count: u32,+ /// The top tree as last written, and how it came to be (`Units::top`'s rule: `Kept::top`).+ kept: Kept,}fn put_tris(out: &mut Vec<[f32; 4]>, tris: &[[Vec3A; 3]]) {@@ -863,7 +1350,7 @@ mod tests {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 }+ Scene { nodes, tri_verts, instances: vec![GpuInstance::default()], top: layout.top_first, layout, still_tris: still.len(), meshes: vec![], units: vec![], count: 0, kept: Kept::default() }}/// A new mesh: its tree placed and written, its triangles appended in the tree's order.@@ -904,7 +1391,8 @@ mod tests {k}- /// The top tree again, over the units there are now, into its range.+ /// The top tree again, over the units there are now, into its range: kept, changed or built, by+ /// `Units::top`'s rule.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;@@ -914,15 +1402,17 @@ mod tests {if boxes.len() > self.layout.max_units() {return Err("no room for the top tree".into());}- let t = top_tree(&boxes)?;+ let t = self.kept.top(&boxes, self.units.len())?;+ check_top(&t, |r| self.units.get(r as usize).is_some_and(|u| u.is_some()))?;let at = self.layout.top_first as usize;self.nodes[at..at + t.len()].copy_from_slice(&t);+ self.kept.nodes = 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() }+ 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(), reads: Default::default() }}/// Every triangle a ray could meet, tested one by one with the kernel's own triangle test (the still scene's in@@ -987,24 +1477,41 @@ mod tests {}}+ /// A placement: a third of them a translation alone (the walk's short way), a few none at all.fn pose(rng: &mut Rng) -> Mat4 {+ let kind = rng.f();+ if kind < 0.05 {+ return Mat4::IDENTITY;+ }+ if kind < 0.35 {+ return Mat4::from_translation(Vec3::from(rng.v(30.0)));+ }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,+ /// Random scenes under random edits: meshes added and removed, units added, moved (far, or a little: the top tree+ /// is then kept and refitted) and removed, the top tree made 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);+ let (mut edits, mut unit_hits, mut rays, mut refits, mut changes, mut builds, mut short) = (0, 0, 0, 0, 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);+ // (Every other scene starts with more units than a small scene's: there the top tree is kept in parts.)+ let mut sc = Scene::new(&still, 6000, if seed % 2 == 0 { 64 } else { 400 });sc.check(&mut rng, 40, "no unit yet");+ if seed % 2 == 1 {+ let m = sc.add_mesh(&rng.tris(12, 3.0, 1.0)).unwrap();+ for _ in 0..150 {+ sc.add_unit(m, pose(&mut rng), true);+ }+ sc.retop().unwrap();+ sc.check(&mut rng, 40, "a scene of many units");+ }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();@@ -1033,8 +1540,13 @@ mod tests {}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);+ let (m, was, cast) = sc.units[k].unwrap();+ // Somewhere else, or (half of them) a step from where it was, turned a little or not.+ let world = match rng.below(4) {+ 0 => Mat4::from_translation(Vec3::from(rng.v(0.5))) * was,+ 1 => was * Mat4::from_rotation_y(rng.f() * 0.2),+ _ => pose(&mut rng),+ };sc.units[k] = Some((m, world, cast));sc.instances[k] = sc.record(m, world, cast);what = "a unit moved";@@ -1068,8 +1580,13 @@ mod tests {// 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);+ refits += sc.kept.refits;+ changes += sc.kept.changes;+ builds += sc.kept.builds;+ short += sc.units.iter().enumerate().filter(|(k, u)| u.is_some() && sc.instances[*k].n[2][3].to_bits() == 1).count();}assert!(edits > 300 && unit_hits * 8 > rays, "{edits} edits, {unit_hits} of {rays} closest hits on units");+ assert!(refits > 40 && changes > 100 && builds > 100 && short > 20, "{refits} top trees kept, {changes} with the loose units' built, {builds} built over all; {short} units placed by a translation alone at the end");}/// The trees the builders make are the trees the checks accept, at their depth bounds: a top tree of a thousand@@ -1080,7 +1597,54 @@ mod tests {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)");+ let depth = check_top(&top, |r| r < 1000).unwrap();+ assert!((10..=TOP_DEPTH).contains(&depth), "1000 units: {depth}");+ // By surface area, not by count: cheaper for a ray than the tree of median splits over the same units, of one+ // size or not (every tenth here a wall among lamps). (13 % and 15 % here; the voxel level's 10,459 units: 24 %,+ // units_cost.rs.)+ let boxes: Vec<(Vec3A, Vec3A)> = units.iter().map(|u| (u.lo, u.hi)).collect();+ let (sah, median) = (top_cost(&top), top_cost(&build_median(&boxes, 1).0));+ assert!(sah < 0.95 * median, "{sah} against {median}");+ let mixed: Vec<(Vec3A, Vec3A)> = boxes.iter().enumerate().map(|(k, b)| if k % 10 == 0 { (b.0 - Vec3A::new(12.0, 6.0, 0.0), b.1 + Vec3A::new(12.0, 6.0, 0.0)) } else { *b }).collect();+ let (sah, median) = (top_cost(&build_sah(&mixed, TOP_DEPTH).0), top_cost(&build_median(&mixed, 1).0));+ assert!(sah < 0.9 * median, "{sah} against {median}");+ // The depth holds whatever the boxes are: as many as the depth allows (every split must halve), one more level+ // than that, plenty; boxes all in one place, in a row each further than all before it together (the cheapest+ // split by area peels one off, a chain), in two clumps of unequal size, anywhere.+ for round in 0..400 {+ let n = 1 + rng.below(300);+ let least = (n as f32).log2().ceil() as usize;+ let max_depth = least + [0, 0, 1, 2, 40][round % 5];+ let boxes: Vec<(Vec3A, Vec3A)> = (0..n)+ .map(|k| {+ let c = match round % 4 {+ 0 => Vec3A::ZERO,+ 1 => Vec3A::new(1.5f32.powi(k as i32 % 60) * (1 + k / 60) as f32, 0.0, 0.0),+ 2 => rng.v(1.0) + if k % 7 == 0 { Vec3A::splat(500.0) } else { Vec3A::ZERO },+ _ => rng.v(50.0),+ };+ let h = Vec3A::splat(0.1 + rng.f() * if k % 9 == 0 { 20.0 } else { 1.0 });+ (c - h, c + h)+ })+ .collect();+ let (nodes, order) = build_sah(&boxes, max_depth);+ assert_eq!(nodes.len(), 2 * n - 1);+ let depth = check_tree(&nodes, max_depth, |_, count| if count == 1 { Ok(()) } else { Err("a leaf of several".into()) }).unwrap_or_else(|e| panic!("round {round}, {n} boxes, depth {max_depth}: {e}"));+ assert!(depth >= least);+ let mut seen = order.clone();+ seen.sort_unstable();+ assert_eq!(seen, (0..n as u32).collect::<Vec<_>>());+ // Every leaf's box is its box, every interior node's holds its children's.+ for (i, node) in nodes.iter().enumerate() {+ if node.count > 0 {+ let b = boxes[order[node.left_or_first as usize] as usize];+ assert_eq!((Vec3A::from(node.bmin), Vec3A::from(node.bmax)), b);+ } else {+ let (a, b) = (nodes[node.left_or_first as usize], nodes[node.left_or_first as usize + 1]);+ assert_eq!((Vec3A::from(node.bmin), Vec3A::from(node.bmax)), (Vec3A::from(a.bmin).min(b.bmin.into()), Vec3A::from(a.bmax).max(b.bmax.into())), "node {i}");+ }+ }+ }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));@@ -1181,7 +1745,7 @@ mod tests {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 };+ let mut u = Units { layout: Layout::new(10, ns + nl, 4), trees: vec![], slots: vec![], count: 0, records: 4, kept: Default::default() };// 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));@@ -1252,7 +1816,7 @@ mod tests {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 };+ let mut u = Units { layout: Layout::new(1, 8, 2), trees: vec![], slots: vec![], count: 0, records: 2, kept: Default::default() };u.add_tree(0, &first).unwrap();u.set(0, u.unit(0, Mat4::IDENTITY, false));let top = u.top().unwrap();@@ -1267,4 +1831,169 @@ mod tests {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]);}++ /// Units that only move keep their top tree, its boxes theirs again (each leaf's its unit's box, each node's what+ /// holds its children's), while it costs a ray no more than `REFIT_SLACK` of what it did when built; a unit that+ /// goes far, comes, goes, is hidden or shown has it built again. A kept tree is one a build could have made: the+ /// same checks pass, and a build over the same units costs no more.+ #[test]+ fn a_top_tree_is_kept_while_units_only_move() {+ let mut rng = Rng(21);+ let mesh = mesh_tree(&rng.tris(30, 1.0, 0.3)).unwrap();+ let n = 200;+ let mut u = Units { layout: Layout::new(1, mesh.nodes.len(), n + 200), trees: vec![], slots: vec![], count: 0, records: n + 200, kept: Default::default() };+ u.add_tree(0, &mesh).unwrap();+ let mut at: Vec<Vec3> = (0..n).map(|_| Vec3::from(rng.v(40.0))).collect();+ for (k, p) in at.iter().enumerate() {+ u.set(k, u.unit(0, Mat4::from_translation(*p), false));+ }+ let holds = |u: &Units, top: &[GpuNode]| {+ check_top(top, |r| u.slots.get(r as usize).is_some_and(|s| s.is_some_and(|s| !s.hidden))).unwrap();+ for node in top {+ if node.count > 0 {+ let unit = u.slots[node.left_or_first as usize].unwrap();+ let b = UnitBox::new(node.left_or_first, unit.world, mesh.lo, mesh.hi);+ assert_eq!((Vec3A::from(node.bmin), Vec3A::from(node.bmax)), (b.lo, b.hi));+ } else {+ let (a, b) = (top[node.left_or_first as usize], top[node.left_or_first as usize + 1]);+ assert_eq!((Vec3A::from(node.bmin), Vec3A::from(node.bmax)), (Vec3A::from(a.bmin).min(b.bmin.into()), Vec3A::from(a.bmax).max(b.bmax.into())));+ }+ }+ };+ let first = u.top().unwrap();+ holds(&u, &first);+ assert_eq!((u.kept.builds, u.kept.refits), (1, 0));+ // Nothing moved: the same tree, to the byte.+ assert_eq!(bytemuck::cast_slice::<_, u8>(&u.top().unwrap()), bytemuck::cast_slice::<_, u8>(&first));+ assert_eq!((u.kept.builds, u.kept.refits), (1, 1));+ // Every unit a little a frame (bodies that settle): the tree is kept.+ for _ in 0..60 {+ for (k, p) in at.iter_mut().enumerate() {+ *p += Vec3::from(rng.v(0.02));+ u.moved(k, Mat4::from_translation(*p), None);+ }+ let top = u.top().unwrap();+ holds(&u, &top);+ }+ assert_eq!((u.kept.builds, u.kept.changes, u.kept.refits), (1, 0, 61));+ // Units close together, each grown to nearly twice its size where it is: none has gone astray, and the tree+ // costs too much: built.+ let mut d = Units { layout: Layout::new(1, mesh.nodes.len(), 100), trees: vec![], slots: vec![], count: 0, records: 100, kept: Default::default() };+ d.add_tree(0, &mesh).unwrap();+ let close: Vec<Vec3> = (0..100).map(|_| Vec3::from(rng.v(2.0))).collect();+ for (k, p) in close.iter().enumerate() {+ d.set(k, d.unit(0, Mat4::from_translation(*p), false));+ }+ d.top().unwrap();+ for (k, p) in close.iter().enumerate() {+ d.moved(k, Mat4::from_translation(*p) * Mat4::from_scale(Vec3::splat(1.9)), None);+ }+ d.top().unwrap();+ assert_eq!((d.kept.builds, d.kept.changes, d.kept.refits), (2, 0, 0));+ for (k, p) in at.iter().enumerate() {+ u.moved(k, Mat4::from_translation(*p) * Mat4::from_scale(Vec3::splat(1.5)), None);+ }+ let top = u.top().unwrap();+ holds(&u, &top);+ assert_eq!((u.kept.builds, u.kept.changes, u.kept.refits), (1, 0, 62));+ // Ten of them fly, a step of their own size a frame: they are the loose ones, their tree is built each+ // frame, the others' is kept; and the whole is near what a tree built over all would cost.+ let boxes_of = |u: &Units| u.slots.iter().enumerate().filter_map(|(r, s)| s.filter(|s| !s.hidden).map(|s| UnitBox::new(r as u32, s.world, mesh.lo, mesh.hi))).collect::<Vec<UnitBox>>();+ let mut worst: f64 = 0.0;+ for _ in 0..40 {+ for (k, p) in at.iter_mut().enumerate().take(10) {+ *p += Vec3::from(rng.v(6.0));+ u.moved(k, Mat4::from_translation(*p) * Mat4::from_scale(Vec3::splat(1.5)), None);+ }+ let top = u.top().unwrap();+ holds(&u, &top);+ worst = worst.max(top_cost(&top) / top_cost(&top_tree(&boxes_of(&u)).unwrap()));+ }+ assert_eq!((u.kept.builds, u.kept.loose, u.kept.settled.len()), (1, 10, 2 * (n - 10) - 1));+ assert!(u.kept.changes >= 30 && worst < 1.25, "{} times the loose tree; at worst {worst:.2} of a built tree's cost", u.kept.changes);+ // One of the settled far off: loose too. A unit hidden, shown (loose now), gone, another come.+ u.moved(77, Mat4::from_translation(Vec3::splat(4000.0)), None);+ let top = u.top().unwrap();+ holds(&u, &top);+ assert_eq!((u.kept.builds, u.kept.loose), (1, 11));+ u.moved(33, Mat4::IDENTITY, Some(true));+ let top = u.top().unwrap();+ holds(&u, &top);+ assert_eq!((top.len(), u.kept.builds, u.kept.loose), (2 * (n - 1) - 1, 1, 11));+ u.moved(33, Mat4::IDENTITY, Some(false));+ let top = u.top().unwrap();+ holds(&u, &top);+ assert_eq!((top.len(), u.kept.builds, u.kept.loose), (2 * n - 1, 1, 12));+ u.set(55, None);+ u.set(n, u.unit(0, Mat4::IDENTITY, false));+ let top = u.top().unwrap();+ holds(&u, &top);+ assert_eq!((top.len(), u.kept.builds, u.kept.loose), (2 * n - 1, 1, 13), "as many units, not the same ones");+ // The loose ones gone: the settled tree alone again.+ for k in (0..10).chain([33, 77, n]) {+ u.set(k, None);+ }+ let top = u.top().unwrap();+ holds(&u, &top);+ assert_eq!((top.len(), u.kept.builds, u.kept.loose, u.kept.settled.len()), (2 * (n - 13) - 1, 1, 0, 0));+ // Pieces thrown, thirty at a time, that fly a while and come to rest; once those at rest are an eighth of the+ // units, one tree is built over all, and they are settled.+ let (builds, mut next, mut folded) = (u.kept.builds, n + 1, 0);+ let mut flying: Vec<(usize, Vec3, u32)> = vec![];+ for frame in 0..200 {+ if frame % 20 == 0 && frame < 120 {+ let from = Vec3::from(rng.v(30.0));+ for _ in 0..30 {+ flying.push((next, from, 0));+ u.set(next, u.unit(0, Mat4::from_translation(from), false));+ next += 1;+ }+ }+ for f in flying.iter_mut().filter(|f| f.2 < 12) {+ f.1 += Vec3::from(rng.v(3.0));+ f.2 += 1;+ u.moved(f.0, Mat4::from_translation(f.1), None);+ }+ let was = u.kept.builds;+ let top = u.top().unwrap();+ holds(&u, &top);+ assert_eq!(top.len(), 2 * boxes_of(&u).len() - 1);+ folded += (u.kept.builds > was) as usize;+ assert!(top_cost(&top) <= 1.25 * top_cost(&top_tree(&boxes_of(&u)).unwrap()), "frame {frame}");+ }+ assert!((1..=4).contains(&folded) && u.kept.builds == builds + folded as u64, "{folded} built over all in 200 frames");+ assert!(u.kept.loose <= 60, "{} loose at the end", u.kept.loose);+ // `thin_top` by itself: leaves taken out down to one; what it refuses. `join_tops`: a tree.+ let boxes = |records: &[u32]| records.iter().map(|&k| UnitBox::new(k, Mat4::from_translation(Vec3::X * k as f32 * 3.0), Vec3A::ZERO, Vec3A::ONE)).collect::<Vec<UnitBox>>();+ let eight = top_tree(&boxes(&[0, 1, 2, 3, 4, 5, 6, 7])).unwrap();+ let (five, [before, after]) = thin_top(&eight, &boxes(&[0, 2, 3, 6, 7])).unwrap();+ assert_eq!((five.len(), check_top(&five, |r| [0, 2, 3, 6, 7].contains(&r)).is_ok()), (9, true));+ assert!(before == top_cost(&eight) && after == top_cost(&five) && after < before);+ let (one, [_, after]) = thin_top(&five, &boxes(&[6])).unwrap();+ assert_eq!((one.len(), one[0].left_or_first, one[0].count, after), (1, 6, 1, 0.0));+ assert!(thin_top(&eight, &boxes(&[0, 9])).is_none(), "a unit without a leaf");+ assert!(thin_top(&eight, &boxes(&[1, 1])).is_none(), "a record twice");+ assert!(thin_top(&[], &boxes(&[1])).is_none() && thin_top(&eight, &[]).is_none());+ let mut broken = eight.clone();+ broken[0].left_or_first = 0;+ assert!(thin_top(&broken, &boxes(&[0, 1])).is_none());+ let mut shared = eight.clone();+ let inner: Vec<usize> = (1..shared.len()).filter(|&i| shared[i].count == 0).collect();+ shared[inner[1]].left_or_first = shared[inner[0]].left_or_first.max(inner[1] as u32 + 1);+ assert!(thin_top(&shared, &boxes(&[0, 1])).is_none(), "two nodes with the same children");+ let joined = join_tops(&five, &top_tree(&boxes(&[10, 11, 12])).unwrap());+ assert_eq!((joined.len(), check_top(&joined, |r| [0, 2, 3, 6, 7, 10, 11, 12].contains(&r)).unwrap()), (15, 1 + check_top(&five, |_| true).unwrap()));+ let joined = join_tops(&one, &one);+ assert_eq!((joined.len(), joined[0].left_or_first, joined[1].count, joined[2].count), (3, 1, 1, 1));+ // A built tree is a level short of the bound: two of them joined are at it.+ assert!(check_tree(&build_sah(&(0..1 << 12).map(|k| (Vec3A::splat(k as f32), Vec3A::splat(k as f32 + 1.0))).collect::<Vec<_>>(), 12).0, 64, |_, _| Ok(())).unwrap() <= 12);+ // The record's word for a placement by a translation alone.+ let rec = |world: Mat4| unit_record(crate::scene::Instance { mesh: 0, world, object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false }.gpu(0, 0), 9, true);+ assert_eq!(rec(Mat4::IDENTITY).n[2][3].to_bits(), 1);+ assert_eq!(rec(Mat4::from_translation(Vec3::new(3.0, -2.0, 0.5))).n[2][3].to_bits(), 1);+ assert_eq!(rec(Mat4::from_rotation_y(0.3)).n[2][3].to_bits(), 0);+ assert_eq!(rec(Mat4::from_scale(Vec3::splat(2.0))).n[2][3].to_bits(), 0);+ assert_eq!(rec(Mat4::from_scale(Vec3::new(1.0, -1.0, 1.0))).n[2][3].to_bits(), 0, "a mirror");+ assert_eq!((rec(Mat4::IDENTITY).n[0][3].to_bits(), rec(Mat4::IDENTITY).n[1][3].to_bits()), (9, 1));+ }}diff --git a/renderer/src/units_cost.rs b/renderer/src/units_cost.rsnew file mode 100644index 0000000..1f03f5a--- /dev/null+++ b/renderer/src/units_cost.rs@@ -0,0 +1,447 @@+//! What a ray costs under software traversal, counted on the CPU (no GPU): the kernel's walks as units.rs transcribes+//! them, over a bundle's scene as `prepare` lays it out, with units and flattened, for the same rays (a frame's kinds:+//! the camera's, shadow rays to a far and to a near light, one bounce and its shadow rays). Counted per ray: the loop+//! iterations (what the loop guard counts), the nodes read of each tree, the triangles tested, the unit records read.+//! The rays are made once from the flattened scene and kept (`/tmp/units-cost`), with its answers: every layout must+//! give them again.+//!+//! UNITS_COST=out/bundles/kabukicho.js cargo test --release --lib units_cost -- --ignored --nocapture+//!+//! `UNITS_COST_FLAT=1`: the flattened scene's counts too (it is built anyway when the rays are not there yet).+//! `UNITS_COST_VIEW=WxH` (192x108). `UNITS_COST_ASSETS` (`.`).+use crate::units::cpu::{Kernel, Reads, INF, NO_INST, TRACE_CLOSEST, TRACE_SHADOW};+use crate::{bvh, default_presets_dir, prepare_as, scene, units};+use glam::Vec3A;+use std::time::Instant;++/// A scene as the kernel is given it.+struct Laid {+ nodes: Vec<bvh::GpuNode>,+ tri_verts: Vec<[f32; 4]>,+ instances: Vec<scene::GpuInstance>,+ top: u32,+ units: u32,+ /// For the report.+ what: String,+ /// The still scene's triangles (the first so many), and each unit's: its record, its first triangle, how many.+ still: u32,+ unit_tris: Vec<(u32, u32, u32)>,+}++/// A ray and the flattened scene's answer to it (`t`: the hit's distance, INF for none).+#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+struct Ray {+ o: [f32; 3],+ tmax: f32,+ d: [f32; 3],+ mode: u32,+ t: f32,+ /// 0: the camera's, 1: a shadow ray, 2: a bounce.+ kind: u32,+}++fn lay(world: &crate::world::World, assets: &std::path::Path, with_units: bool) -> (Laid, scene::Scene) {+ let mut sc = scene::build(world, assets, &default_presets_dir(), None).unwrap();+ let (flat, placed) = (sc.tris.len(), sc.instances.iter().map(|i| sc.meshes[i.mesh as usize].count as usize).sum::<usize>());+ let t = Instant::now();+ let p = prepare_as(false, with_units, &mut sc, &mut vec![]);+ let s = t.elapsed().as_secs_f64();+ let (top, count) = (p.params.motion[2].to_bits(), p.params.motion[3].to_bits());+ let stored = p.tri_verts.len() / 3;+ let what = format!("{} triangles stored ({:.1} MiB of vertices + attributes), {} nodes ({:.1} MiB), {} units; flattened {} triangles; prepare {s:.2} s", stored, (stored * 144) as f64 / 1048576.0, p.nodes.len(), (p.nodes.len() * 32) as f64 / 1048576.0, sc.units.as_ref().map_or(0, |u| u.count), flat + placed);+ let instances = if sc.gpu_instances.is_empty() { vec![scene::GpuInstance::default()] } else { sc.gpu_instances.clone() };+ let unit_tris = sc.units.as_ref().map_or(vec![], |u| sc.instances.iter().enumerate().filter(|(r, i)| !i.hidden && u.slots.get(*r).is_some_and(|s| s.is_some())).map(|(r, i)| (r as u32, sc.gpu_instances[r].info[0], sc.meshes[i.mesh as usize].count)).collect());+ (Laid { nodes: p.nodes, tri_verts: p.tri_verts, instances, top, units: if sc.units.is_some() { count } else { 0 }, what, still: sc.tris.len() as u32, unit_tris }, sc)+}++impl Laid {+ /// The closest hit by every triangle tested one by one, the still scene's in the world and each unit's in the+ /// unit's space, as the walk tests them: what the walk must find, whatever its trees are.+ fn brute(&self, o: Vec3A, d: Vec3A, tmax: f32) -> f32 {+ let k = Kernel { budget: u64::MAX, ..self.kernel() };+ let mut best = tmax;+ for ti in 0..self.still {+ best = best.min(k.intersect_tri(o, d, ti, best).unwrap());+ }+ for &(rec, first, count) in &self.unit_tris {+ let r = &self.instances[rec as usize];+ let (lo, ld) = (Kernel::proc_point(r, o), Kernel::proc_dir(r, d));+ for ti in first..first + count {+ best = best.min(k.intersect_tri(lo, ld, ti, best).unwrap());+ }+ }+ best+ }++ fn kernel(&self) -> Kernel<'_> {+ Kernel { nodes: &self.nodes, tri_verts: &self.tri_verts, instances: &self.instances, top: self.top, units: self.units, steps: Default::default(), budget: 1 << 26, deepest: Default::default(), reads: Default::default() }+ }+}++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+ }+}++/// A frame's rays through the flattened scene `l`: the camera's over a `w` x `h` view; from each hit a shadow ray to+/// a far light (one direction for all: a sun), one to a point a few metres off (a lamp), and a bounce (cosine+/// distributed); from the bounce's hit the two shadow rays again.+fn rays(l: &Laid, cam: &scene::CameraData, w: usize, h: usize) -> Vec<Ray> {+ let (pos, fwd, right, up) = (Vec3A::from(cam.position), Vec3A::from(cam.forward), Vec3A::from(cam.right), Vec3A::from(cam.up));+ let sun = Vec3A::new(0.35, 0.8, 0.5).normalize();+ let mut rng = Rng(77);+ let mut out = vec![];+ let ask = |o: Vec3A, d: Vec3A, tmax: f32, mode: u32, kind: u32, out: &mut Vec<Ray>| {+ let hit = l.kernel().trace(o, d, tmax, mode).unwrap();+ let t = if hit.tri == 0xffff_ffff { INF } else { hit.t };+ out.push(Ray { o: o.into(), tmax, d: d.into(), mode, t, kind });+ (t < INF).then(|| {+ // The hit's point, a little off the triangle on the ray's side.+ let v = |k: u32| { let v = l.tri_verts[(hit.tri * 3 + k) as usize]; Vec3A::new(v[0], v[1], v[2]) };+ let n = v(1).cross(v(2)).normalize_or_zero();+ // (A unit's triangle is in the unit's space: its normal by the record's normal rows.)+ let n = if hit.inst == NO_INST { n } else { let r = &l.instances[hit.inst as usize]; Vec3A::new(Vec3A::from_slice(&r.n[0]).dot(n), Vec3A::from_slice(&r.n[1]).dot(n), Vec3A::from_slice(&r.n[2]).dot(n)).normalize_or_zero() };+ let n = if n.dot(d) > 0.0 { -n } else { n };+ (o + d * hit.t + n * 1e-3, n)+ })+ };+ let lit = |p: Vec3A, n: Vec3A, rng: &mut Rng, out: &mut Vec<Ray>| {+ if n.dot(sun) > 0.0 {+ ask(p, sun, INF, TRACE_SHADOW, 1, out);+ }+ let q = p + n * (0.5 + 3.0 * rng.f()) + Vec3A::new(rng.f() - 0.5, rng.f() - 0.5, rng.f() - 0.5) * 8.0;+ let (d, far) = ((q - p).normalize_or_zero(), (q - p).length());+ if n.dot(d) > 0.0 {+ ask(p, d, far, TRACE_SHADOW, 1, out);+ }+ };+ for y in 0..h {+ for x in 0..w {+ let (u, v) = ((x as f32 + 0.5) / w as f32 * 2.0 - 1.0, 1.0 - (y as f32 + 0.5) / h as f32 * 2.0);+ let d = (fwd + right * (u * cam.tan_half_fov * w as f32 / h as f32) + up * (v * cam.tan_half_fov)).normalize();+ let Some((p, n)) = ask(pos, d, INF, TRACE_CLOSEST, 0, &mut out) else { continue };+ lit(p, n, &mut rng, &mut out);+ // A cosine-distributed direction about n.+ let (r1, r2) = (rng.f(), rng.f());+ let (t, b) = n.any_orthonormal_pair();+ let (s, phi) = (r1.sqrt(), std::f32::consts::TAU * r2);+ let d = (t * (s * phi.cos()) + b * (s * phi.sin()) + n * (1.0 - r1).max(0.0).sqrt()).normalize();+ let Some((p, n)) = ask(p, d, INF, TRACE_CLOSEST, 2, &mut out) else { continue };+ lit(p, n, &mut rng, &mut out);+ }+ }+ out+}++#[derive(Default, Clone, Copy)]+struct Sum {+ rays: u64,+ steps: u64,+ most: u64,+ r: [u64; 7],+ wrong: u64,+ deepest: usize,+}++/// The rays through `l`, counted; by kind (the camera's, shadow, bounce) and all together.+fn count(l: &Laid, rays: &[Ray]) -> [Sum; 4] {+ let mut sums = [Sum::default(); 4];+ for ray in rays {+ let k = l.kernel();+ let hit = k.trace(Vec3A::from(ray.o), Vec3A::from(ray.d), ray.tmax, ray.mode).unwrap_or_else(|e| panic!("the kernel {e}"));+ let t = if hit.tri == 0xffff_ffff { INF } else { hit.t };+ // A closest hit at the flattened scene's distance (to the rounding of a triangle tested in its own space); a+ // shadow ray blocked or not as there.+ let same = if ray.mode == TRACE_CLOSEST { (t == INF) == (ray.t == INF) && (t == INF || (t - ray.t).abs() <= 2e-4 * (1.0 + ray.t.min(1e4))) } else { (t == INF) == (ray.t == INF) };+ let Reads { still_nodes, top_nodes, mesh_nodes, still_verts, mesh_verts, records, still_steps, .. } = k.reads.get();+ for which in [ray.kind as usize, 3] {+ let s = &mut sums[which];+ s.rays += 1;+ s.steps += k.steps.get();+ s.most = s.most.max(k.steps.get());+ for (a, b) in s.r.iter_mut().zip([still_nodes, top_nodes, mesh_nodes, still_verts / 3, mesh_verts / 3, records, still_steps]) {+ *a += b;+ }+ s.wrong += !same as u64;+ s.deepest = s.deepest.max(k.deepest.get());+ }+ if !same && sums[3].wrong <= 8 {+ println!(" differs: a ray of kind {} from {:?} along {:?}, mode {}: {} here (triangle {}, record {}), {} in the flattened scene; every triangle here tested one by one: {}", ray.kind, ray.o, ray.d, ray.mode, t, hit.tri, if hit.inst == NO_INST { -1 } else { hit.inst as i64 }, ray.t, l.brute(Vec3A::from(ray.o), Vec3A::from(ray.d), ray.tmax));+ }+ }+ sums+}++fn report(name: &str, l: &Laid, rays: &[Ray], pixels: usize, base: Option<f64>) -> f64 {+ let t = Instant::now();+ let sums = count(l, rays);+ println!("{name}: {}", l.what);+ println!(" {:<8} {:>8} {:>9} {:>8} | {:>9} {:>9} {:>9} | {:>9} {:>9} {:>8} | {:>9} {:>6}", "rays", "count", "steps", "most", "still nd", "top nd", "mesh nd", "still tri", "mesh tri", "records", "bytes", "wrong");+ let mut all = 0.0;+ for (kind, s) in ["camera", "shadow", "bounce", "all"].iter().zip(&sums) {+ let per = |v: u64| v as f64 / s.rays.max(1) as f64;+ // What a ray reads: 32 bytes a node, 48 a triangle, 112 a record's rows.+ let bytes = 32.0 * per(s.r[0] + s.r[1] + s.r[2]) + 48.0 * per(s.r[3] + s.r[4]) + 112.0 * per(s.r[5]);+ println!(" {kind:<8} {:>8} {:>9.2} {:>8} | {:>9.2} {:>9.2} {:>9.2} | {:>9.2} {:>9.2} {:>8.3} | {:>9.0} {:>6}", s.rays, per(s.steps), s.most, per(s.r[0]), per(s.r[1]), per(s.r[2]), per(s.r[3]), per(s.r[4]), per(s.r[5]), bytes, s.wrong);+ all = bytes * s.rays as f64 / pixels as f64;+ }+ let s = &sums[3];+ println!(" a pixel: {:.0} steps ({:.0} of them the still walk's), {:.0} bytes read{}; the stack's deepest {}; counted in {:.1} s", s.steps as f64 / pixels as f64, s.r[6] as f64 / pixels as f64, all, base.map_or(String::new(), |b| format!(" ({:+.1} % on the flattened scene's)", (all / b - 1.0) * 100.0)), s.deepest, t.elapsed().as_secs_f64());+ all+}++/// A top tree's cost to a ray by the surface-area measure: the chance a ray through the root's box meets each+/// node's, summed (interior nodes: two boxes tested; leaves: a unit entered).+fn top_cost(nodes: &[bvh::GpuNode]) -> (f64, f64, usize) {+ let area = |n: &bvh::GpuNode| { let e = Vec3A::from(n.bmax) - Vec3A::from(n.bmin); 2.0 * (e.x * e.y + e.y * e.z + e.z * e.x) as f64 };+ let root = area(&nodes[0]).max(1e-30);+ let (mut inner, mut leaves, mut depth) = (0.0, 0.0, 0);+ let mut stack = vec![(0usize, 0usize)];+ while let Some((i, d)) = stack.pop() {+ depth = depth.max(d);+ let n = &nodes[i];+ if n.count > 0 {+ leaves += area(n) / root;+ } else {+ inner += area(n) / root;+ stack.push((n.left_or_first as usize, d + 1));+ stack.push((n.left_or_first as usize + 1, d + 1));+ }+ }+ (inner, leaves, depth)+}++#[test]+#[ignore = "a measurement: UNITS_COST=<bundle.js>"]+fn units_cost() {+ let Ok(bundle) = std::env::var("UNITS_COST") else { return println!("UNITS_COST=<bundle.js>") };+ let assets = std::path::PathBuf::from(std::env::var("UNITS_COST_ASSETS").unwrap_or(".".into()));+ let view = std::env::var("UNITS_COST_VIEW").unwrap_or("192x108".into());+ let (w, h) = view.split_once('x').map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap())).unwrap();+ let host = crate::script::ScriptHost::new(&std::fs::read_to_string(&bundle).unwrap()).unwrap();+ host.setup("r", None).unwrap();+ // (A voxel level the scene code asked for: loaded before the first scene build, as the session does.)+ if host.voxels.borrow_mut().realize(&mut host.world.borrow_mut(), &assets).unwrap().is_some() {+ let _ = host.world.borrow_mut().take_changes();+ }+ let world = host.world.borrow();+ let stem = std::path::Path::new(&bundle).file_stem().unwrap().to_string_lossy().to_string();+ let kept = std::path::PathBuf::from(format!("/tmp/units-cost/{stem}-{view}.rays"));+ let mut base = std::fs::read_to_string(kept.with_extension("flat")).ok().and_then(|s| s.trim().parse::<f64>().ok());+ if !kept.exists() || std::env::var("UNITS_COST_FLAT").is_ok() {+ let (flat, sc) = lay(&world, &assets, false);+ if !kept.exists() {+ std::fs::create_dir_all(kept.parent().unwrap()).unwrap();+ std::fs::write(&kept, bytemuck::cast_slice::<Ray, u8>(&rays(&flat, &sc.camera, w, h))).unwrap();+ }+ let rays: Vec<Ray> = bytemuck::pod_collect_to_vec(&std::fs::read(&kept).unwrap());+ let b = report(&format!("{stem}, flattened"), &flat, &rays, w * h, None);+ std::fs::write(kept.with_extension("flat"), format!("{b}")).unwrap();+ base = Some(b);+ }+ let rays: Vec<Ray> = bytemuck::pod_collect_to_vec(&std::fs::read(&kept).unwrap());+ let (with, mut sc) = lay(&world, &assets, true);+ let Some(u) = sc.units.as_mut() else { return println!("{stem}: no units") };+ report(&format!("{stem}, units"), &with, &rays, w * h, base);+ // The top tree: its build's time, its depth, its cost by the surface-area measure.+ let (mut ms, mut refit) = (vec![], vec![]);+ let mut top = vec![];+ for _ in 0..20 {+ u.kept.nodes.clear();+ let t = Instant::now();+ top = u.top().unwrap();+ ms.push(t.elapsed().as_secs_f64() * 1e3);+ // (Again with nothing moved: the kept tree, its boxes brought up to date and checked.)+ let t = Instant::now();+ assert_eq!(bytemuck::cast_slice::<_, u8>(&u.top().unwrap()), bytemuck::cast_slice::<_, u8>(&top));+ refit.push(t.elapsed().as_secs_f64() * 1e3);+ }+ ms.sort_by(f64::total_cmp);+ refit.sort_by(f64::total_cmp);+ if !top.is_empty() {+ let (inner, leaves, depth) = top_cost(&top);+ println!(" the top tree: {} units, depth {depth}, built in {:.3} ms, kept (refit) in {:.3} ms (medians of 20); by surface area a ray through its root's box tests {:.2} pairs of boxes and enters {:.2} units", u.count, ms[10], refit[10], inner, leaves);+ }+ // The units' transforms, and how many units a mesh has.+ let (mut identity, mut moved, mut scaled, mut general) = (0, 0, 0, 0);+ for i in sc.instances.iter().filter(|i| !i.hidden) {+ let m = glam::Mat3A::from_mat4(i.world);+ let diagonal = m.x_axis.y == 0.0 && m.x_axis.z == 0.0 && m.y_axis.x == 0.0 && m.y_axis.z == 0.0 && m.z_axis.x == 0.0 && m.z_axis.y == 0.0;+ if m == glam::Mat3A::IDENTITY {+ *(if i.world.w_axis.truncate() == glam::Vec3::ZERO { &mut identity } else { &mut moved }) += 1;+ } else if diagonal {+ scaled += 1;+ } else {+ general += 1;+ }+ }+ let mut uses = vec![0usize; sc.meshes.len()];+ for i in sc.instances.iter().filter(|i| !i.hidden) {+ uses[i.mesh as usize] += 1;+ }+ let once: Vec<usize> = (0..uses.len()).filter(|&k| uses[k] == 1).collect();+ let tris = |ks: &mut dyn Iterator<Item = usize>| ks.map(|k| sc.meshes[k].count as usize * uses[k]).sum::<usize>();+ println!(" transforms: {identity} the identity, {moved} a translation alone, {scaled} a scale along the axes, {general} others");+ println!(" meshes: {} with one unit ({} triangles), {} with more ({} units, {} triangles placed, {} stored)", once.len(), tris(&mut once.iter().copied()), uses.iter().filter(|&&n| n > 1).count(), uses.iter().filter(|&&n| n > 1).sum::<usize>(), tris(&mut (0..uses.len()).filter(|&k| uses[k] > 1)), (0..uses.len()).filter(|&k| uses[k] > 1).map(|k| sc.meshes[k].count as usize).sum::<usize>());+ let _ = units::MAX_UNITS;+}++/// A lump of three boxes about the origin, a metre across: a piece of debris (36 triangles).+fn lump() -> Vec<[Vec3A; 3]> {+ let mut tris = vec![];+ for (c, h) in [(Vec3A::ZERO, Vec3A::new(0.5, 0.35, 0.4)), (Vec3A::new(0.25, 0.3, -0.1), Vec3A::new(0.25, 0.2, 0.3)), (Vec3A::new(-0.3, -0.1, 0.25), Vec3A::new(0.2, 0.3, 0.25))] {+ let p = |k: usize| c + h * Vec3A::new(if k & 1 == 0 { -1.0 } else { 1.0 }, if k & 2 == 0 { -1.0 } else { 1.0 }, if k & 4 == 0 { -1.0 } else { 1.0 });+ for q in [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]] {+ tris.push([p(q[0]), p(q[1]), p(q[2])]);+ tris.push([p(q[0]), p(q[2]), p(q[3])]);+ }+ }+ tris+}++/// Step 8's question on the CPU (out/web-probe/gpu-runs-c.md V5): pieces of debris as units on top of a scene's own.+/// Eight piles on the ground ahead of the camera, one thrown every 30 frames: its pieces are added in one frame, fly+/// for 60 (every one moves every frame) and come to rest on one another. Counted: the top tree's time in each kind of+/// frame and how it was made (built, changed, kept); then, with every piece at rest, what a frame's rays read, and how+/// many units a ray enters. No GPU.+///+/// UNITS_PILE=out/bundles/voxel-level-destruction-mesh.js cargo test --release --lib units_pile -- --ignored --nocapture+///+/// `UNITS_PILE_N=0,250,1000` (the pieces in all), `UNITS_COST_VIEW`, `UNITS_COST_ASSETS`.+#[test]+#[ignore = "a measurement: UNITS_PILE=<bundle.js>"]+fn units_pile() {+ use glam::{Mat4, Quat, Vec3};+ let Ok(bundle) = std::env::var("UNITS_PILE") else { return println!("UNITS_PILE=<bundle.js>") };+ let assets = std::path::PathBuf::from(std::env::var("UNITS_COST_ASSETS").unwrap_or(".".into()));+ let view = std::env::var("UNITS_COST_VIEW").unwrap_or("192x108".into());+ let (w, h) = view.split_once('x').map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap())).unwrap();+ let ns: Vec<usize> = std::env::var("UNITS_PILE_N").unwrap_or("0,250,1000,4000,16000".into()).split(',').map(|v| v.parse().unwrap()).collect();+ let host = crate::script::ScriptHost::new(&std::fs::read_to_string(&bundle).unwrap()).unwrap();+ host.setup("r", None).unwrap();+ if host.voxels.borrow_mut().realize(&mut host.world.borrow_mut(), &assets).unwrap().is_some() {+ let _ = host.world.borrow_mut().take_changes();+ }+ let world = host.world.borrow();+ let stem = std::path::Path::new(&bundle).file_stem().unwrap().to_string_lossy().to_string();+ let mut base = None;+ for &n in &ns {+ let (mut l, mut sc) = lay(&world, &assets, true);+ let Some(mut u) = sc.units.take() else { return println!("{stem}: no units") };+ let own = u.count as usize;+ // Room: the top tree's range is the node buffer's last, the records' table is this probe's own.+ let first_rec = l.instances.len();+ u.layout.top_cap = (2 * (own + n).max(1) - 1) as u32;+ u.records = first_rec + n;+ l.nodes.resize((u.layout.top_first + u.layout.top_cap) as usize, units::FILL);+ l.instances.resize(first_rec + n, scene::GpuInstance::default());+ // The piece's mesh: its triangles after the scene's, its tree in the mesh range.+ let tris = lump();+ let tree = units::mesh_tree(&tris).unwrap();+ let first_tri = (l.tri_verts.len() / 3) as u32;+ for &i in &tree.order {+ let [a, b, c] = tris[i as usize];+ l.tri_verts.extend([[a.x, a.y, a.z, 0.0], [(b - a).x, (b - a).y, (b - a).z, 0.0], [(c - a).x, (c - a).y, (c - a).z, 0.0]]);+ }+ let mesh = u.trees.len() as u32;+ let root = u.add_tree(mesh, &tree).expect("room for one small tree") as usize;+ l.nodes[root..root + tree.nodes.len()].copy_from_slice(&tree.nodes);+ // The piles: where each is (the ground under a point ahead of the camera), and each piece's rest.+ let cam = &sc.camera;+ let (pos, fwd, right) = (Vec3A::from(cam.position), Vec3A::from(cam.forward), Vec3A::from(cam.right));+ let flat = |v: Vec3A| Vec3A::new(v.x, 0.0, v.z).normalize_or_zero();+ let mut rng = Rng(9);+ let piles = 8;+ let per = n.div_ceil(piles);+ let spots: Vec<Vec3A> = (0..piles)+ .map(|k| {+ let p = pos + flat(fwd) * (8.0 + 3.0 * k as f32) + flat(right) * ((k % 3) as f32 - 1.0) * 3.0;+ let from = Vec3A::new(p.x, pos.y + 40.0, p.z);+ let hit = l.kernel().trace(from, -Vec3A::Y, INF, TRACE_CLOSEST).unwrap();+ Vec3A::new(p.x, if hit.tri == 0xffff_ffff { pos.y - 2.0 } else { from.y - hit.t }, p.z)+ })+ .collect();+ struct Piece { pile: usize, rest: Vec3A, axis: Vec3, turn: f32, size: Vec3 }+ let radius = 0.3 * (per as f32).sqrt();+ let pieces: Vec<Piece> = (0..n)+ .map(|j| {+ let (r, a) = (radius * rng.f().sqrt(), std::f32::consts::TAU * rng.f());+ let s = 0.15 + 0.45 * rng.f();+ let rest = spots[j % piles] + Vec3A::new(r * a.cos(), s * 0.5 + rng.f() * (radius - r) * 0.6, r * a.sin());+ Piece { pile: j % piles, rest, axis: Vec3::new(rng.f() - 0.5, rng.f() - 0.5, rng.f() - 0.5).normalize_or(Vec3::Y), turn: rng.f() * 6.0, size: Vec3::new(s, s * (0.6 + 0.8 * rng.f()), s * (0.6 + 0.8 * rng.f())) }+ })+ .collect();+ let pose = |p: &Piece, tau: f32| {+ let at = (spots[p.pile] + Vec3A::Y).lerp(p.rest, tau) + Vec3A::Y * (12.0 * tau * (1.0 - tau));+ Mat4::from_scale_rotation_translation(p.size, Quat::from_axis_angle(p.axis, p.turn + (1.0 - tau) * 6.0), Vec3::from(at))+ };+ // The frames. [built, changed, kept]: the top tree's ms in the frames that ended each way.+ let (mut ms, mut top): ([Vec<f64>; 3], Vec<bvh::GpuNode>) = (Default::default(), u.kept.nodes.clone());+ let was = (u.kept.builds, u.kept.changes, u.kept.refits);+ let (thrown_every, flight) = (30usize, 60usize);+ for f in 0..(piles - 1) * thrown_every + flight + 1 {+ let mut any = false;+ for (j, p) in pieces.iter().enumerate() {+ let (r, born) = (first_rec + j, p.pile * thrown_every);+ if f < born || f > born + flight {+ continue;+ }+ let m = pose(p, (f - born) as f32 / flight as f32);+ if f == born {+ u.set(r, u.unit(mesh, m, false));+ } else {+ u.moved(r, m, None);+ }+ any = true;+ }+ if any {+ let k = (u.kept.builds, u.kept.changes, u.kept.refits);+ let t = Instant::now();+ top = u.top().unwrap();+ let which = if u.kept.builds > k.0 { 0 } else if u.kept.changes > k.1 { 1 } else { 2 };+ ms[which].push(t.elapsed().as_secs_f64() * 1e3);+ }+ }+ let made = (u.kept.builds - was.0, u.kept.changes - was.1, u.kept.refits - was.2);+ // At rest: the kernel's buffers as a session would have written them.+ for (j, p) in pieces.iter().enumerate() {+ let inst = scene::Instance { mesh, world: pose(p, 1.0), object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false };+ l.instances[first_rec + j] = units::unit_record(inst.gpu(first_tri, tris.len() as u32), root as u32, true);+ }+ let at = u.layout.top_first as usize;+ l.nodes[at..at + top.len()].copy_from_slice(&top);+ (l.top, l.units) = (u.layout.top_first, u.count);+ let boxes: Vec<units::UnitBox> = u.slots.iter().enumerate().filter_map(|(r, s)| s.filter(|s| !s.hidden).map(|s| { let t = u.trees[s.mesh as usize].unwrap(); units::UnitBox::new(r as u32, s.world, t.lo, t.hi) })).collect();+ let fresh = units::top_tree(&boxes).unwrap();+ let (kept_cost, fresh_cost) = (units::top_cost(&top), units::top_cost(&fresh));+ let rays = rays(&l, cam, w, h);+ let all = report(&format!("{stem} + {n} pieces in {piles} piles (radius {radius:.1} m)"), &l, &rays, w * h, base);+ base = base.or(Some(all));+ // The units a ray enters: the camera's rays, and those of them through a pile's box.+ let entered = |ray: &Ray| { let k = l.kernel(); k.trace(Vec3A::from(ray.o), Vec3A::from(ray.d), ray.tmax, ray.mode).unwrap(); (k.reads.get().records, k.steps.get()) };+ let near = |ray: &Ray| spots.iter().any(|s| { let (o, d) = (Vec3A::from(ray.o), Vec3A::from(ray.d)); let t = (*s - o).dot(d).max(0.0); (o + d * t - *s).length() < radius + 0.5 });+ let through: Vec<(u64, u64)> = rays.iter().filter(|r| r.kind == 0 && near(r)).map(entered).collect();+ let q = |xs: &mut Vec<u64>, p: f64| { xs.sort_unstable(); if xs.is_empty() { 0 } else { xs[((xs.len() - 1) as f64 * p) as usize] } };+ let (mut recs, mut steps): (Vec<u64>, Vec<u64>) = through.iter().copied().unzip();+ println!(" camera rays past a pile ({}): units entered {:.2} a ray (p50 {}, p99 {}, most {}); steps p50 {}, p99 {}, most {}", through.len(), recs.iter().sum::<u64>() as f64 / recs.len().max(1) as f64, q(&mut recs, 0.5), q(&mut recs, 0.99), q(&mut recs, 1.0), q(&mut steps, 0.5), q(&mut steps, 0.99), q(&mut steps, 1.0));+ let med = |xs: &mut Vec<f64>| { xs.sort_by(f64::total_cmp); if xs.is_empty() { (0.0, 0.0) } else { (xs[xs.len() / 2], xs[xs.len() - 1]) } };+ let [mut b, mut c, mut k] = ms;+ println!(" the top tree over {} units ({own} the scene's): built {} times ({:.3} ms p50, {:.3} at most), changed {} ({:.3}, {:.3}), kept {} ({:.3}, {:.3}); at the end it costs {:.3} of a tree built now ({:.3} ms)", u.count, made.0, med(&mut b).0, med(&mut b).1, made.1, med(&mut c).0, med(&mut c).1, made.2, med(&mut k).0, med(&mut k).1, kept_cost / fresh_cost, { let t = Instant::now(); let _ = units::top_tree(&boxes); t.elapsed().as_secs_f64() * 1e3 });+ // One pile cleared away at once.+ for (j, p) in pieces.iter().enumerate() {+ if p.pile == 0 {+ u.set(first_rec + j, None);+ }+ }+ if n > 0 {+ let k = (u.kept.builds, u.kept.changes);+ let t = Instant::now();+ u.top().unwrap();+ println!(" a pile's {} pieces removed in one frame: the top tree {} in {:.3} ms", per, if u.kept.builds > k.0 { "built" } else if u.kept.changes > k.1 { "changed" } else { "kept" }, t.elapsed().as_secs_f64() * 1e3);+ }+ }+}