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
The engine in a browser: renderer/web, the merged binding layout, a loop guard; the physics hello world in Chrome (#13)
Yujiacf1d014bf5b3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex bfe9c72..6029f04 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -32,6 +32,7 @@ jobs:rendererrenderer/voxel-corerenderer/physics-core+ renderer/web- run: cd renderer && cargo build --release --locked# The voxel engine's core builds for the browser (wasm32: players run the game there) and passes its tests.- run: rustup target add wasm32-unknown-unknown@@ -44,3 +45,13 @@ jobs:- run: node tools/physics-determinism.ts# The engine's library builds for the browser (wasm32; docs/RUNTIME.md "The engine's library in a browser").- run: cd renderer && cargo build --release --locked --lib --target wasm32-unknown-unknown+ # And the module a page loads: the engine's exports for the browser's JavaScript (renderer/web; docs/RUNTIME.md+ # "The engine in a browser"). Running it needs a browser with a GPU: tools/web-hello.ts, on a developer's machine.+ - run: cd renderer/web && cargo build --release --locked --target wasm32-unknown-unknown+ # The browser's side of it without a browser or a GPU: the module in Node, the page's `__engine` over its exports,+ # the game bundle the native runtime loads, the physics hello world's script and its checks (tools/web-engine.ts).+ # wasm-bindgen's CLI writes the module's JavaScript; its version is the crate's (renderer/web/Cargo.toml).+ - run: |+ V=$(grep -o 'wasm-bindgen = "=[0-9.]*"' renderer/web/Cargo.toml | grep -o '[0-9][0-9.]*')+ wasm-bindgen --version 2>/dev/null | grep -q "$V" || cargo install wasm-bindgen-cli --version "$V" --locked+ - run: node tools/web-engine.tsdiff --git a/README.md b/README.mdindex 023c110..e078e80 100644--- a/README.md+++ b/README.md@@ -78,9 +78,10 @@ npm run test:render # the render test suite on the GPU- the renderer's release build;- the voxel core's wasm32 build and tests, and native / wasm32 edit determinism;- the physics core's wasm32 build and tests, and native / wasm32 determinism (a script and 1,200 random worlds);-- the engine library's wasm32 build.+- the engine library's wasm32 build, the browser module's (`renderer/web`), and the physics hello world on that+ module in Node (`tools/web-engine.ts`: no browser, no GPU).-The GPU checks (`test:render`, the perf smoke, the benches) run on a Mac, per [`docs/WORKFLOW.md`](docs/WORKFLOW.md).+The GPU checks (`test:render`, the perf smoke, the benches, the browser test `tools/web-hello.ts`) run on a Mac, per [`docs/WORKFLOW.md`](docs/WORKFLOW.md).## Assets and third-party contentdiff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 82451e9..6359c45 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -3888,6 +3888,40 @@ benchmark level. The order follows the dependencies; a step that meets a further- This step: the library builds for `wasm32-unknown-unknown` with the native shell left out, the GPU fromfutures, `web_time`, and file reads behind one module (docs/RUNTIME.md "The engine's library in a browser").Natively the renders are byte-identical.+ - **The engine in a browser** (2026-11-11, branch `web-hello`; the second half of layout C: the physics hello+ world runs in Chrome to the native run's numbers).+ - `renderer/web`: the wasm module (the engine API's 35 exports, one for one with the native `__engine`, on the+ same code, `renderer/src/api.rs`; the session's), the page (`__engine` over the exports, the node host called+ as `GameSession` calls it, the canvas' clicks) and `tools/build-web.ts`. The game bundle is the native one.+ - The merged binding layout (`renderer/src/merged.rs`): the browser's shaders written from the one source with 8+ storage buffers a stage (the kernel as written binds 20, the live passes 28), guarded by a test that reads+ them with naga; `THREERT_MERGED=1` runs it natively.+ - **A GPU job that did not end took the machine's display down** (2026-11-11 01:42, WindowServer's watchdog)+ while the atomic tests ran under software traversal: at `geometry/instanced-procedural` in the layout as+ written, then at `environment/background` in the merged one. Neither scene has a triangle. The likely cause,+ by reading: the tree over no triangle was one node with `count: 0`, an interior node to the kernel,+ whose children were itself and the bytes after its 32-byte buffer; zeros end the walk, an earlier scene's+ bytes need not. Fixed in `bvh.rs` (a leaf of the empty vertex buffer's zero triangle), with a test that walks+ the kernel's loop on the CPU. **Not confirmed as what hung**: the same sequence on a build without the fix,+ with the guard, passed (both scenes alone, with the fix and the guard, give their tests' answers). And a **loop guard** (`merged::guard`): every loop of the kernel bounded and+ what it stops counted and read back; always on in a browser, `THREERT_LOOP_GUARD` natively.+ - `tools/web-engine.ts` (CI): the module in Node with the page's `__engine` and the native bundle runs the+ physics hello world's script to the native test's numbers.+ - **In Chrome 157 on the machine's GPU** (`tools/web-hello.ts`, Playwright; docs/RUNTIME.md "Measured in a+ browser"): the scripted test passes at 1280 × 720 and its report is the native run's number for number. A+ still frame is 6.6 ms of GPU and 0.3 ms of the page (natively under software traversal 6.9–8.0 ms of GPU).+ **Every frame in which a body moves rebuilds the scene: 16.5 ms in the page** (9.0 natively), and a click that+ adds a box 17–24 ms: what hello world ships with until software traversal edits in place. The view opens in+ 1.13 s, 1.08 s of it the sky's bake on one thread; a kernel the browser has not compiled takes 1.4 s before+ the first frame, 26 ms after that. Engine calls cost 40 ns (a scalar) to about a microsecond (a descriptor),+ 10,000 poses 0.3 ms. The module is 7.3 MiB (1.5 MiB with brotli).+ - Open, first: **a frame in which a body moves costs the page 16.7 ms, 16.4–16.6 of it the rebuild** (9.0+ natively under software traversal, nothing under hardware traversal): in-place edits under software+ traversal, the two-level tree, the next step. Then: the browser's image is not bit-identical to the native+ one (the guard changes the kernel's last bits; natively it is off and the catalog is byte-identical to main);+ 1.4 s for a kernel's first compile and 1.09 s of sky bake on the page's thread before the first frame; a+ scene larger than hello world in a browser, and the merged layout's cost on one natively; what hung on+ 2026-11-11 is not confirmed; other browsers.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 7181181..30ea183 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -234,8 +234,8 @@ Decided by the user on 2026-11-10, with the measurements below.the Rust application, as now, and nothing in the design needs a JIT.- **On the web: layout C.** The Rust engine (scene, Rapier, voxels) is compiled to wasm, and the gameplay TypeScriptruns in the browser's own JS engine, calling the wasm module's exports: the same game code and the same four- channels, with the `Engine` interface implemented by the wasm exports and a thin layer of JS. Not built yet (it is- what follows the world handlers; ROADMAP § 6). The layouts considered:+ channels, with the `Engine` interface implemented by the wasm exports and a thin layer of JS ("The engine in a+ browser" below: built, and measured in Chrome on the physics hello world). The layouts considered:| layout | what | why not / why || --- | --- | --- |@@ -327,6 +327,168 @@ changed: the same sources, the same shaders, byte-identical renders. What runs i- Checked: the library's wasm32 build in CI; the physics' recorded hashes in the renderer's wasm32 graph(`tools/physics-determinism.ts`). Not yet run in a page: that is `renderer/web`'s to show.+## The engine in a browser (`renderer/web`)++Layout C's second half: the physics hello world runs in Chrome (2026-11-11), the same game file and the same numbers+as natively. Measured on hello world only; larger scenes, and scenes that edit themselves, wait for the two-level+tree (ROADMAP § 6).++- **The module** (`renderer/web`, a `cdylib` for `wasm32-unknown-unknown`, wasm-bindgen): the engine's world, the+ voxels, the physics and the live view. Its exports are of two kinds:+ - the engine API: one export for each function the native runtime installs as `__engine` (35; `script.rs`+ `install_engine`), under the same name. Both call the same code (`renderer/src/api.rs`); a descriptor crosses as+ JSON text, an array as a typed array;+ - the session, what `GameSession` and the native window do around the script: `start` (the GPU from futures, the+ view of the world the setup built, shown on a canvas), `frameBegin` / `frameEnd` around the node host's `frame`+ (the scene's time and sway; then the physics' ticks, the commit, the frame), `click` (the pick and the event's+ payload with the view ray), `commit`, `tick` (a frame's end with no view).+- **The page** (`renderer/web/www`): `engine.ts` makes `__engine` of the exports (typed against `packages/scene`'s+ `Engine`); `main.ts` loads **the game bundle the native runtime loads** (`tools/bundle-game.ts`, unchanged), calls+ the node host as `GameSession` does, and sends the canvas' clicks down the same path. `node tools/build-web.ts+ [game.ts] --serve` builds and serves it (needs the wasm-bindgen CLI of the crate's version).+- **The merged binding layout** (`renderer/src/merged.rs`). WebGPU gives a stage 8 storage buffers by default; the+ kernel binds 20 and the live passes 28. There is one source: the browser's shaders are written from+ `pathtrace.wgsl` and `live.wgsl` as text when a module is compiled, and the native ones are untouched.+ - The kernel's seven tables become the arrays of one struct in one buffer; their lengths are in the source, each a+ power of two above a floor, so a kernel is compiled again only when a table doubles. The renderer keeps writing+ its own buffers and a frame copies them into the struct's.+ - The kernel's seven group-1 buffers (radiance cache, reservoirs, what the live passes read of a trace) are ranges+ of one buffer, the arrays of a second struct.+ - The live passes' buffers of one element type are ranges of a slab each, indexed from offsets in a uniform: the+ history's two bind groups are two sets of offsets.+ - A use of a merged name the generator does not know, a declaration not found exactly once, a name it would add+ that is taken: each stops the renderer, with the line. Locals that shadow a name are followed through their+ scopes. A test reads the result with naga: valid WGSL, 8 storage buffers for the kernel and for the live passes+ (20 and 28 as written), the structs' arrays where the Rust side puts them.+ - `THREERT_MERGED=1` runs it natively (software traversal, the device held to 8).+- **The loop guard** (`merged::guard`). The kernel's traversals follow indices they read from buffers and end only on+ sound data. On 2026-11-11 two dispatches that did not return took this machine's display down (WindowServer's+ watchdog; software traversal under the atomic tests, at two scenes without a triangle; the cause below is likely,+ not confirmed). A page's shader runs on the+ player's GPU beside everything else, so **a browser's kernel always has the guard**: every loop body counts the+ invocation's iterations and leaves past a limit (65,536; a page can set it). No formula changes, but the image is+ not bit-identical to the kernel's without the guard: the compiler arranges the arithmetic of the functions it is in+ differently (hello world, one sample: 354 of 43,200 numbers differ, by at most 2 × 10⁻⁷ of their value). What it+ stops it counts: the count is read back without waiting (`LiveCore::guard_trips`, the page's `guardTrips()`, the frame log), an offline+ render in which it moved is an error, and anything but 0 means wrong pixels. Natively it is off unless+ `THREERT_LOOP_GUARD=<limit>`. The live passes need none: their loops are counted loops over constants and clamped+ parameters.+- **A tree over nothing** (`bvh.rs`). A node with `count: 0` is an interior node to the kernel, and the one-node tree+ of a scene without triangles had itself and the bytes after its buffer for children. It is now a leaf of triangle+ 0, which an empty vertex buffer's zeros make a triangle without area; a procedural object without boxes is left out+ under software traversal. A test walks the kernel's loop on the CPU with every read checked. That read is certain;+ **that it is what kept the two dispatches from returning is not confirmed**: the sequence that hung, run again on+ a build without the fix and with the guard, passed (the bytes after the buffer ended the walk that time; a hang+ needs them to be a box the ray meets and a count or child indices that do not end).+- **What a browser does not have.** Hardware ray queries, so software traversal: no particles of either kind, no+ translucency pass, and no in-place edits (every added object and every frame a body moves rebuilds the scene; the+ two-level tree is the step after this one). The denoiser (OIDN, offline only), the offline render, snapshots and+ the profile's readbacks. The dynamic sky's bake thread (a sky whose sun moves keeps the sky it was built with).++Checked without a GPU:+- `tools/web-engine.ts` (CI): the module in Node (V8), `__engine` made by the page's code, the game bundle, the+ physics hello world's five clicks (as view rays) and frames, and the native test's checks; the engine API one for+ one with `install_engine` (35 functions natively, in the page's `__engine`, in the module's exports).+- The generator's and the guard's tests (naga), the tree walk, the web crate's wasm32 build (CI).++### Measured in a browser (2026-11-11)++Three things first:+- **A frame in which a rigid body moves costs the page 16.7 ms, 16.4–16.6 of it rebuilding the scene** (p50; natively+ under software traversal 9.0 ms, under hardware traversal nothing). The CPU side alone fills a 60 fps frame. It is+ what the next step, in-place edits under software traversal, is for.+- **The browser's image is not bit-identical to the native one.** A browser's kernel has the loop guard, and the+ kernel with the guard differs from the kernel without it in the last bits (rounding: 354 of 43,200 numbers of a+ one-sample hello world, by at most 2 × 10⁻⁷ of their value). Natively the guard is off by default, so native+ renders are what they were (the catalog is byte-identical to main). The game's numbers (the physics, the clicks)+ are the native run's exactly.+- **The first frame waits about 1.4 s for a kernel the browser has not compiled, and opening the view takes 1.1 s, of+ which the sky's bake on the page's one thread is 1.09 s.**++Apple M5 Pro, Chrome 157.0.8103.40 driven by Playwright (`node tools/web-hello.ts`; a Chrome of its own profile),+its WebGPU adapter `apple` / `metal-3`, not a fallback adapter (the machine's GPU). The adapter allows 10 storage+buffers a stage; the device was asked for 8 and got 8. Loop guard on (65,536; its count 0 in every run below).+1280 × 720 traced at half (the dynamic resolution's floor), other applications holding 15–40 % of the GPU. The runs+and their order are in `out/web-probe/gpu-runs.md` (kept beside the checkout).++**The scripted test** (`tools/physics-hello.ts`'s: 822 frames in lockstep, five clicks at the same view+coordinates through the page's click path, the same checks): passes at 640 × 360 and at 1280 × 720, after a first+step of 14 frames at 160 × 90. **The report and the clicks' log are the native run's, number for number**: boxes at rest at (−1.0002, 0.2498, −0.3052),+(−1.0109, 0.7481, −0.2996), (−1.0023, 1.2475, −0.3001), the kicked one at (1.7011, 0.2499, 1.6092), 0.913 m along the+kick (0.917 predicted), all asleep. The same ticks give the same bits: nothing to explain away. A real mouse click on+the canvas adds its box 1.1–1.3 cm from where it was aimed (a mouse lands on whole pixels). The canvas against a+native live snapshot of the same frame count ± 1: 1.2 of 255 a channel, mean.++**Frame times**, ms p50 / p95, the same five clicks in real time, content at 60 fps (two runs; the second's figures):++| | still | a body moves |+| --- | --- | --- |+| frame interval | 16.67 / 17.29 | 16.67 / 25.0 |+| the page's own time in a frame | 0.29 / 0.81 | 16.7 / 18.0 |+| of it: the node host's `frame` (script) | 0.08 / 0.20 | 0.05 / 0.08 |+| engine calls made by the script | 1 a frame (not timed apart: the table below) | the same |+| physics: step and scene sync, in wasm | 0.02 / 0.06 | 0.06 / 0.12 |+| commit | 0.005 / 0.01 | 16.5 / 17.7 |+| of it: **rebuilding the scene** (software traversal, every frame a body moves) | 0 | **16.5 / 17.7** |+| recording the frame (the passes, the canvas) | 0.16 / 0.46 | 0.09 / 0.12 |+| GPU | 6.6 / 8.2 | 6.1 / 8.1 |+| of it: the trace | 2.1 / 2.8 | 1.7 / 2.7 |++- Still, a frame is the GPU's 6.6 ms and 0.3 ms of the page. Natively, the same view under software traversal:+ 6.9–8.0 ms of GPU (trace 1.5–1.7), so the browser's frame is the native one within the noise of this machine;+ hardware traversal 4.7 (1.0).+- **Every frame in which a body moves spends the whole 16.7 ms rebuilding the scene** in the page (natively under+ software traversal: 9.0 ms, on every core; hardware traversal: nothing, the body's instance moves in place). The+ interval holds 60 fps at p50 and slips at p95. This is the cost hello world ships with until software traversal+ edits in place.+- A click that adds a box: pick 0.03–0.3 ms, the handler 0.4–1.6 ms, the commit 16.6–24.1 ms (a rebuild; natively+ under software traversal 8.8–10.7 ms, under hardware traversal 0.2–0.6 ms in place after the first box).++**Opening the view:** the module fetched and instantiated 21–65 ms; `setup` 7.4–8.1 ms (28 engine calls); `start`+1.13 s, of which **1.08 s is the sky's bake on the page's one thread** (natively 37–40 ms on every core) and 3–4 ms+the adapter and the device. **The first frame:** its work done on the GPU 26 ms after it was recorded when the+browser has compiled the kernel before; **1.43–1.44 s** with a kernel it has not (measured by giving the page a guard+limit it had not had, a new constant in the kernel's source; a fresh browser profile is not enough, the system keeps+compiled shaders across profiles). The live passes' own first compile was not separated.++**The boundary in Chrome** (`?bench=1`; a world of 10,000 objects with a body each, ticked once), ns a call, the best+of five runs; beside it the same module in Node 24 (`tools/web-engine.ts --bench`):++| call | Chrome 157 | Node 24 |+| --- | ---: | ---: |+| `visible(id, bool)` | 38 | 39 |+| `power(id, number)` | 39 | 40 |+| `transform(id, Float32Array(10))` | 54 | 55 |+| `customData(id, [4])` | 95 | 98 |+| `material(id, desc)` (JSON) | 1,190–1,200 | 1,410 |+| `object(id, desc)` (JSON) | 790–800 | 910 |+| `physics("state", { body })` (JSON both ways) | 1,490–1,520 | 1,590 |+| `physics("impulse", { body, impulse })` | 590 | 610 |+| `physics("ray", …)` in that world | 1,700–1,740 | 1,860 |+| `physicsPoses()` for 10,000 bodies, not read (70,000 floats copied out) | 20,000–21,600 | 25,100 |+| 1,000 bodies' poses fetched and read | 0.05–0.07 ms | 0.05 ms |+| 10,000 bodies' poses fetched and read | 0.30–0.32 ms | 0.30 ms |++The runtime probe's "a call costs about 1 ns" was an empty export; these are the engine's own calls, with the work+they do (a lookup, the change sets, for a descriptor its JSON). A scalar call is 40 ns, a descriptor about a+microsecond, 10,000 poses 0.3 ms (QuickJS natively: 0.94 ms). One finding beside the boundary: a physics query+tests every collider added since the last tick one by one, so in a world that has never ticked a ray over 1,000+bodies costs 42 µs (after a tick: 1.7 µs over 10,000).++**Natively, the merged layout and the guard** (hello world, software traversal): offline, the merged layout's bytes+are the layout's as written (with the guard in both; and without it in both); live, the scripted test's report in+the merged layout with the guard is the hardware run's number for number. Their cost on this scene is inside the+run-to-run spread (GPU ms a frame p50, each twice: as written 8.0, 6.9; merged 6.3, 7.0; as written + guard 7.1,+6.1; merged + guard 10.2, 6.7): a 106-triangle frame is not where a trace's cost shows.++**Size:** the module 7.34 MiB (gzip 2.28 MiB, brotli 1.51 MiB; no `wasm-opt`), wasm-bindgen's JavaScript and the+page's 105 KiB (brotli 17 KiB), hello world's bundle 230 KiB (brotli 53 KiB).++**Not measured:** any scene but hello world in a browser; the merged layout's and the guard's cost on a scene whose+trace is the frame (Kabukichō); the atomic tests in the merged layout as a suite (two of them alone: the scenes+without a triangle, both layouts, the tests' answers); Safari and Firefox (nothing Chrome-only was written: WebGPU+through wgpu, default limits except buffer sizes, timestamp queries only if the adapter has them).+## Correctness* `threert-render edit-check` builds the GPU tables both ways for a list of events: edited in place, and built freshdiff --git a/package-lock.json b/package-lock.jsonindex c8a63bf..fae3f46 100644--- a/package-lock.json+++ b/package-lock.json@@ -13,6 +13,7 @@"@types/three": "^0.187.0","earcut": "^3.2.4","esbuild": "^0.28.2",+ "playwright-core": "^1.65.0","pngjs": "^7.0.0","polygon-clipping": "^0.15.7","sharp": "^0.35.5",@@ -1186,6 +1187,19 @@"dev": true,"license": "MIT"},+ "node_modules/playwright-core": {+ "version": "1.65.0",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.0.tgz",+ "integrity": "sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/pngjs": {"version": "7.0.0","resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz",diff --git a/package.json b/package.jsonindex c705b5c..9d2deff 100644--- a/package.json+++ b/package.json@@ -6,7 +6,7 @@"packages/*"],"scripts": {- "typecheck": "tsc -p packages/scene && tsc -p packages/gameplay && tsc -p packages/voxel && tsc -p games && tsc -p tools && tsc -p tests",+ "typecheck": "tsc -p packages/scene && tsc -p packages/gameplay && tsc -p packages/voxel && tsc -p games && tsc -p tools && tsc -p tests && tsc -p renderer/web/www","test": "node --test packages/*/test/*.test.ts tools/*/test/*.test.ts","scenes": "node tools/build-scenes.ts","test:render": "node tools/test-render.ts",@@ -18,6 +18,7 @@"@types/three": "^0.187.0","earcut": "^3.2.4","esbuild": "^0.28.2",+ "playwright-core": "^1.65.0","pngjs": "^7.0.0","polygon-clipping": "^0.15.7","sharp": "^0.35.5",diff --git a/renderer/Cargo.lock b/renderer/Cargo.lockindex a540263..135d6c7 100644--- a/renderer/Cargo.lock+++ b/renderer/Cargo.lock@@ -2357,6 +2357,7 @@ dependencies = ["gltf","half","image",+ "naga","oidn","physics-core","pollster",diff --git a/renderer/Cargo.toml b/renderer/Cargo.tomlindex e15a211..f6734d7 100644--- a/renderer/Cargo.toml+++ b/renderer/Cargo.toml@@ -34,6 +34,11 @@ oidn = { version = "2.5", optional = true }# Scene runtime of the render node (game bundles run in the renderer process, src/script.rs).rquickjs = "0.12"+# src/merged.rs's tests read the generated shaders with the compiler wgpu uses: they are valid, and no stage binds more+# storage buffers than a browser allows.+[dev-dependencies]+naga = { version = "30", features = ["wgsl-in"] }+# tools/physics-determinism.ts: the physics' recorded hashes in this crate's wasm32 graph.[[example]]name = "physics_bits"diff --git a/renderer/src/api.rs b/renderer/src/api.rsnew file mode 100644index 0000000..61dd7ad--- /dev/null+++ b/renderer/src/api.rs@@ -0,0 +1,247 @@+//! The engine API scene code calls (`globalThis.__engine`, packages/scene/src/engine.ts): what each call does to the+//! engine's world, apart from how the call arrives. Natively it arrives from the embedded QuickJS (script.rs+//! `install_engine`), in a browser from the page's own JavaScript through the wasm module's exports (renderer/web):+//! both hand a call's descriptor over as JSON and its arrays as slices, and both get the same world.++use crate::desc;+use crate::physics::PhysicsWorld;+use crate::voxel::VoxelWorld;+use crate::world::{Geometry, Kind, Settings, Texture, TextureSource, World};+use glam::{Quat, Vec3};+use serde_json::Value;+use std::sync::Arc;++/// A call that failed: `Type` for an argument of the wrong shape (a `TypeError` to scene code), `Other` for what the+/// engine refused (an `Error` with its message).+pub enum Error {+ Type(String),+ Other(anyhow::Error),+}++impl From<anyhow::Error> for Error {+ fn from(e: anyhow::Error) -> Error {+ Error::Other(e)+ }+}++impl std::fmt::Display for Error {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ match self {+ Error::Type(m) => write!(f, "{m}"),+ Error::Other(e) => write!(f, "{e:#}"),+ }+ }+}++pub type Result<T> = std::result::Result<T, Error>;++/// A descriptor as the engine's own type.+pub fn parse<T: serde::de::DeserializeOwned>(what: &str, v: &Value) -> Result<T> {+ serde_json::from_value(v.clone()).map_err(|e| Error::Type(format!("engine.{what}: {e}")))+}++/// Physics (renderer/src/physics.rs): one call, `physics(op, args)`, answering in JSON. The world is made by the first+/// call; the engine steps it, scene code cannot.+pub fn physics(p: &mut Option<PhysicsWorld>, w: &mut World, op: &str, args: &Value) -> Result<String> {+ Ok(p.get_or_insert_with(Default::default).call(w, op, args)?.to_string())+}++/// The poses of the objects that bodies drive, by the slot the binding gave each body (7 floats: position, rotation+/// xyzw, as scene code reads an object's): one copy for all a frame reads. Empty without a world.+pub fn physics_poses(p: &Option<PhysicsWorld>) -> &[f32] {+ p.as_ref().map_or(&[], |p| p.poses())+}++/// The voxel engine's level (renderer/src/voxel.rs): loaded once the session knows the asset root.+pub fn voxel_level(v: &mut VoxelWorld, d: &Value) -> Result<()> {+ let d: crate::voxel::LevelDesc = parse("voxelLevel", d)?;+ Ok(v.request(d)?)+}++/// An explosion: what it did, as JSON.+pub fn voxel_explode(v: &mut VoxelWorld, w: &mut World, x: f64, y: f64, z: f64, r: f64) -> Result<String> {+ Ok(v.explode(w, Vec3::new(x as f32, y as f32, z as f32), r as f32)?.to_string())+}++/// An edit of the level (`voxelEdit({ op, sphere | box | capsule, material })`; voxel.rs `EditOp`).+pub fn voxel_edit(v: &mut VoxelWorld, w: &mut World, d: &Value) -> Result<String> {+ let op = crate::voxel::EditOp::parse(d)?;+ Ok(v.edit(w, &op)?.to_string())+}++/// The level's hash (16 hex digits; "" before a level): the same commands give the same hash.+pub fn voxel_hash(v: &VoxelWorld) -> String {+ v.hash().map_or(String::new(), |h| format!("{h:016x}"))+}++pub fn voxel_frame(v: &mut VoxelWorld, w: &mut World, dt: f64) -> Result<String> {+ Ok(v.frame(w, dt)?.to_string())+}++/// (`groups`: triples of u32; `colors`: per vertex.)+pub fn geometry(w: &mut World, id: u32, p: &[f32], n: &[f32], uv: &[f32], idx: &[u32], groups: Option<&[u32]>, colors: Option<&[f32]>) -> Result<()> {+ let groups = groups.map_or(vec![], |g| g.chunks_exact(3).map(|c| [c[0], c[1], c[2]]).collect());+ let g = Geometry { positions: p.to_vec(), normals: n.to_vec(), uvs: uv.to_vec(), indices: idx.to_vec(), groups, colors: colors.map_or(vec![], |c| c.to_vec()) };+ Ok(w.set_geometry(id, g)?)+}++pub fn texture(w: &mut World, id: u32, j: &Value, data: Option<&[u8]>) -> Result<()> {+ let pair = |k: &str, def: f32| -> [f32; 2] { [0, 1].map(|i| j[k][i].as_f64().map_or(def, |x| x as f32)) };+ let source = match (data, j["uri"].as_str()) {+ (Some(bytes), _) if j["size"].is_array() => {+ let (width, height) = (j["size"][0].as_u64().unwrap_or(0) as u32, j["size"][1].as_u64().unwrap_or(0) as u32);+ if bytes.len() != width as usize * height as usize * 4 {+ return Err(Error::Type(format!("engine.texture: {} bytes are not {width}x{height} RGBA8 pixels", bytes.len())));+ }+ TextureSource::Pixels { width, height, rgba: Arc::new(bytes.to_vec()) }+ }+ (Some(bytes), _) => TextureSource::Encoded(Arc::new(bytes.to_vec())),+ (None, Some(uri)) => TextureSource::File(uri.to_string()),+ (None, None) => return Err(Error::Type("engine.texture: needs a uri or data".into())),+ };+ let t = Texture { source, srgb: j["srgb"].as_bool().unwrap_or(true), wrap: j["wrap"].as_bool().unwrap_or(true), repeat: pair("repeat", 1.0), offset: pair("offset", 0.0) };+ w.set_texture(id, t)?;+ Ok(())+}++/// Density grids (ROADMAP § 6 step 5b): a grid (its size, channels, program and data).+pub fn density_grid(w: &mut World, id: u32, j: &Value, data: Option<&[f32]>) -> Result<()> {+ let n = |k: usize| j["size"][k].as_u64().unwrap_or(0).min(u32::MAX as u64) as u32;+ let program = j["program"]["id"].as_str().map(|id| (id.to_string(), j["program"]["params"].as_array().map_or(vec![], |a| a.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect())));+ Ok(w.set_grid(id, [n(0), n(1), n(2)], j["channels"].as_u64().unwrap_or(1) as u32, data, program)?)+}++pub fn material(w: &mut World, id: u32, d: &Value) -> Result<()> {+ let m: desc::Material = parse("material", d)?;+ w.set_material(id, m);+ Ok(())+}++pub fn object(w: &mut World, id: u32, j: &Value) -> Result<()> {+ let num = |k: &str| j[k].as_u64().map(|x| x as u32);+ // `body`: a rigid body will drive it (physics.rs). A mesh is then an instance of its own BLAS, so one added while+ // the game runs is placed in place and its moves are its instance's transform.+ let body = j["body"].as_bool().unwrap_or(false);+ let kind = match j["kind"].as_str().unwrap_or("group") {+ "mesh" => {+ let materials: Vec<u32> = j["materials"].as_array().map_or(vec![], |a| a.iter().filter_map(|v| v.as_u64().map(|x| x as u32)).collect());+ Kind::Mesh { geometry: num("geometry").unwrap_or(0), material: num("material").unwrap_or(0), own_blas: j["dynamicGeometry"].as_bool().unwrap_or(false) || (body && materials.len() <= 1), materials }+ }+ "model" => Kind::Model { uri: j["uri"].as_str().unwrap_or_default().to_string(), nodes: serde_json::from_value(j["nodes"].clone()).ok(), animation: serde_json::from_value(j["animation"].clone()).ok(), functions: serde_json::from_value(j["functions"].clone()).unwrap_or_default() },+ "light" => Kind::Light(serde_json::from_value(j["light"].clone()).map_err(|e| Error::Type(format!("engine.object light: {e}")))?),+ "camera" => Kind::Camera(serde_json::from_value(j["camera"].clone()).map_err(|e| Error::Type(format!("engine.object camera: {e}")))?),+ "volume" => Kind::Volume {+ function: j["volume"]["id"].as_str().unwrap_or_default().to_string(),+ params: j["volume"]["params"].as_array().map_or(vec![], |a| a.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect()),+ shape: if j["shape"].as_str() == Some("sphere") { 1 } else { 0 },+ majorant: j["majorant"].as_f64().unwrap_or(0.0) as f32,+ g: j["g"].as_f64().unwrap_or(0.0) as f32,+ homogeneous: j["homogeneous"].as_bool().unwrap_or(false),+ grid: num("grid"),+ },+ "instanced" => Kind::Instanced {+ geometry: num("geometry").unwrap_or(0),+ procedural: j["procedural"].as_bool().unwrap_or(false),+ materials: j["materials"].as_array().map_or(vec![], |a| a.iter().filter_map(|v| v.as_u64().map(|x| x as u32)).collect()),+ capacity: num("count").unwrap_or(0),+ },+ "procedural" => Kind::Procedural {+ geometry: num("geometry").unwrap_or(0),+ materials: j["materials"].as_array().map_or(vec![], |a| a.iter().filter_map(|v| v.as_u64().map(|x| x as u32)).collect()),+ },+ "gpuParticles" => Kind::GpuParticles {+ capacity: num("capacity").unwrap_or(0).min(1 << 21),+ program: j["program"]["id"].as_str().unwrap_or_default().to_string(),+ params: j["program"]["params"].as_array().map_or(vec![], |a| a.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect()),+ material: num("material").unwrap_or(0),+ emitter_area: j["emitterArea"].as_f64().unwrap_or(0.0) as f32,+ rate: (j["rate"].as_f64().unwrap_or(0.0) as f32).max(0.0),+ collide: crate::world::ParticleCollide {+ plane: j["collide"]["plane"].as_f64().map(|v| v as f32),+ voxels: j["collide"]["voxels"].as_bool().unwrap_or(false),+ restitution: (j["collide"]["restitution"].as_f64().unwrap_or(0.3) as f32).clamp(0.0, 1.0),+ friction: (j["collide"]["friction"].as_f64().unwrap_or(0.4) as f32).clamp(0.0, 1.0),+ },+ },+ "particles" => Kind::Particles {+ count: num("count").unwrap_or(0),+ emitter: j["emitter"]["id"].as_str().unwrap_or_default().to_string(),+ params: j["emitter"]["params"].as_array().map_or(vec![], |a| a.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect()),+ material: num("material").unwrap_or(0),+ emitter_area: j["emitterArea"].as_f64().unwrap_or(0.0) as f32,+ },+ _ => Kind::Group,+ };+ w.set_object(id, j["name"].as_str().unwrap_or_default().to_string(), num("parent"), kind, j["castShadow"].as_bool().unwrap_or(true), j["movable"].as_bool().unwrap_or(false))?;+ if body {+ w.set_driven(id)?;+ }+ Ok(())+}++/// (Ten numbers: position, rotation xyzw, scale.)+pub fn transform(w: &mut World, id: u32, t: &[f32]) -> Result<()> {+ if t.len() < 10 {+ return Err(Error::Type("engine.transform: needs 10 numbers".into()));+ }+ let q = Quat::from_xyzw(t[3], t[4], t[5], t[6]);+ Ok(w.set_transform(id, Vec3::new(t[0], t[1], t[2]), if q.length_squared() > 0.0 { q.normalize() } else { Quat::IDENTITY }, Vec3::new(t[7], t[8], t[9]))?)+}++pub fn custom_data(w: &mut World, id: u32, v: &[f64]) -> Result<()> {+ let mut c = [0.0f32; 4];+ for (k, x) in v.iter().take(4).enumerate() {+ c[k] = *x as f32;+ }+ Ok(w.set_custom(id, c)?)+}++/// (None: no sway.)+pub fn sway(w: &mut World, id: u32, d: Option<&Value>) -> Result<()> {+ let s: Option<crate::world::Sway> = d.map(|d| parse("sway", d)).transpose()?;+ Ok(w.set_sway(id, s)?)+}++pub fn light(w: &mut World, id: u32, d: &Value) -> Result<()> {+ let l: desc::Light = parse("light", d)?;+ Ok(w.set_light(id, l)?)+}++pub fn camera(w: &mut World, id: u32, d: &Value) -> Result<()> {+ let c: desc::Camera = parse("camera", d)?;+ Ok(w.set_camera_desc(id, c)?)+}++/// (None: no animation.)+pub fn animation(w: &mut World, id: u32, d: Option<&Value>) -> Result<()> {+ let a: Option<desc::Animation> = d.map(|d| parse("animation", d)).transpose()?;+ Ok(w.set_animation(id, a)?)+}++/// Removes an object and what is under it; their bodies go with them (a body asleep would never find out its object+/// went; the object's id may come again).+pub fn remove(w: &mut World, p: &mut Option<PhysicsWorld>, id: u32) {+ let gone = w.remove(id);+ if let Some(p) = p.as_mut() {+ p.objects_removed(&gone);+ }+}++pub fn environment(w: &mut World, d: &Value) -> Result<()> {+ let env: desc::Environment = parse("environment", d)?;+ w.set_environment(env);+ Ok(())+}++pub fn settings(w: &mut World, j: &Value) {+ let s = Settings {+ name: j["name"].as_str().unwrap_or("scene").to_string(),+ preset: j["preset"].as_str().unwrap_or("cinematic").to_string(),+ overrides: Some(j["overrides"].clone()).filter(|o| !o.is_null()),+ width: j["width"].as_u64().unwrap_or(1280) as u32,+ height: j["height"].as_u64().unwrap_or(720) as u32,+ time: j["time"].as_f64().unwrap_or(0.0) as f32,+ camera: j["camera"].as_u64().map(|c| c as u32),+ };+ w.set_settings(s);+}diff --git a/renderer/src/bvh.rs b/renderer/src/bvh.rsindex 51ead79..662bdaa 100644--- a/renderer/src/bvh.rs+++ b/renderer/src/bvh.rs@@ -44,7 +44,19 @@ pub struct Bvh {const BINS: usize = 16;const MAX_LEAF: usize = 4;+/// The tree over no triangle, as the kernel can walk it. A node with `count: 0` is an interior node to the kernel+/// (pathtrace.wgsl `trace`): the one-node tree this module used to make for nothing had itself for a left child and,+/// for a right child, whatever lay after the node buffer's 32 bytes. Where that was zeros the walk ended; where it was+/// what an earlier scene left there, it might not (a dispatch that does not end: docs/RUNTIME.md "The engine in a+/// browser"). The encoding has no empty leaf, so this is a leaf of one triangle, triangle 0: with no triangles the+/// vertex buffer is zeros (gpu.rs `upload`), a triangle without area that no ray meets (`intersect_tri`: its+/// determinant is 0). One node read, no child, no box.+pub const EMPTY: GpuNode = GpuNode { bmin: [0.0; 3], left_or_first: 0, bmax: [0.0; 3], count: 1 };+pub fn build(tris: &[[V; 3]]) -> Bvh {+ if tris.is_empty() {+ return Bvh { nodes: vec![EMPTY], order: vec![] };+ }let n = tris.len();let mut boxes = Vec::with_capacity(n);let mut centroids = Vec::with_capacity(n);@@ -60,6 +72,8 @@ pub fn build(tris: &[[V; 3]]) -> Bvh {}/// The same BVH over boxes (min xyz, max xyz each; procedural geometry, software traversal), split at their centres.+/// Over no box it is one node the kernel cannot walk (`EMPTY`'s comment; a leaf would name a box that is not there):+/// software traversal leaves objects without boxes out of what the kernel is given (lib.rs `prepare`).pub fn build_boxes(b: &[f32]) -> Bvh {let boxes: Vec<Aabb> = b.chunks_exact(6).map(|c| Aabb { min: V::new(c[0], c[1], c[2]), max: V::new(c[3], c[4], c[5]) }).collect();let centroids = boxes.iter().map(|a| (a.min + a.max) * 0.5).collect();@@ -158,3 +172,160 @@ fn build_from(boxes: Vec<Aabb>, centroids: Vec<V>) -> Bvh {}Bvh { nodes, order }}++#[cfg(test)]+mod tests {+ use super::*;++ const INF: f32 = 3.0e38;++ /// pathtrace.wgsl `ray_aabb`, as written.+ fn ray_aabb(o: V, inv_d: V, bmin: [f32; 3], bmax: [f32; 3], tmax: f32) -> f32 {+ let t0 = (V::from(bmin) - o) * inv_d;+ let t1 = (V::from(bmax) - o) * inv_d;+ let (tmin_v, tmax_v) = (t0.min(t1), t0.max(t1));+ let tn = tmin_v.x.max(tmin_v.y).max(tmin_v.z.max(0.0));+ let tf = tmax_v.x.min(tmax_v.y).min(tmax_v.z.min(tmax));+ if tn <= tf {+ tn+ } else {+ INF+ }+ }++ /// The kernel's software traversal (pathtrace.wgsl `trace`, its loop statement for statement) on the CPU, with+ /// what the kernel does not have: every read checked, and the steps counted. `tris`: the triangles the vertex+ /// buffer holds. Returns the triangles the ray is tested against; an error where the kernel would read a node or+ /// a triangle that is not there, or would not stop. No triangle is ever hit here (the ray keeps its full length),+ /// so the walk visits at least every node the kernel visits for the same ray.+ fn walk(nodes: &[GpuNode], tris: usize, o: V, d: V) -> Result<Vec<u32>, String> {+ let node_at = |i: u32| nodes.get(i as usize).copied().ok_or(format!("reads node {i} of {}", nodes.len()));+ let inv_d = V::ONE / V::select(d.abs().cmplt(V::splat(1e-20)), V::splat(1e-20), d);+ let (mut stack, mut sp, mut node) = ([0u32; 48], 0usize, 0u32);+ let mut tested = vec![];+ for _ in 0..4 * nodes.len() + 8 {+ let n = node_at(node)?;+ if n.count > 0 {+ for k in 0..n.count {+ let ti = n.left_or_first + k;+ if ti as usize >= tris {+ return Err(format!("reads triangle {ti} of {tris}"));+ }+ tested.push(ti);+ }+ if sp == 0 {+ return Ok(tested);+ }+ sp -= 1;+ node = stack[sp];+ continue;+ }+ let l = n.left_or_first;+ let r = l + 1;+ let (nl, nr) = (node_at(l)?, node_at(r)?);+ let mut tl = ray_aabb(o, inv_d, nl.bmin, nl.bmax, INF);+ let mut tr = ray_aabb(o, inv_d, nr.bmin, nr.bmax, INF);+ if tl == INF && tr == INF {+ if sp == 0 {+ return Ok(tested);+ }+ sp -= 1;+ node = stack[sp];+ continue;+ }+ let (mut near, mut far) = (l, r);+ if tr < tl {+ (near, far) = (r, l);+ std::mem::swap(&mut tl, &mut tr);+ }+ node = near;+ if tr != INF && sp < 48 {+ stack[sp] = far;+ sp += 1;+ }+ }+ Err("does not stop".into())+ }++ /// `walk` is the kernel's loop: the lines of pathtrace.wgsl it transcribes are still there, in this order. (A+ /// change to the kernel's traversal fails here, and `walk` is to follow it.)+ #[test]+ fn the_walk_is_the_kernels_loop() {+ let src = include_str!("../shaders/pathtrace.wgsl");+ let (_, rest) = src.split_once("fn trace(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mode: u32) -> Hit {").expect("the kernel's trace");+ let (body, _) = rest.split_once("if (has(F_PROC)) { return trace_procs(o, d, hit, mode); }").expect("the end of the triangles' loop");+ let lines = [+ "let inv_d = 1.0 / select(d, vec3<f32>(1e-20), abs(d) < vec3<f32>(1e-20));",+ "var stack: array<u32, 48>;",+ "var node = 0u;",+ "let n = nodes[node];",+ "if (n.count > 0u) {",+ "for (var k = 0u; k < n.count; k++) {",+ "let ti = n.left_or_first + k;",+ "if (sp == 0u) { break; }",+ "node = stack[sp];",+ "let l = 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 (tr < tl) {",+ "node = near;",+ "if (tr != INF && sp < 48u) {",+ "stack[sp] = far;",+ ];+ let mut at = 0;+ for l in lines {+ at += body[at..].find(l).unwrap_or_else(|| panic!("the kernel's trace no longer has `{l}` where the walk expects it"));+ }+ assert!(src.contains("let tn = max(max(tmin_v.x, tmin_v.y), max(tmin_v.z, 0.0));\n let tf = min(min(tmax_v.x, tmax_v.y), min(tmax_v.z, tmax));\n return select(INF, tn, tn <= tf);"), "ray_aabb");+ assert!(src.contains("const INF: f32 = 3.0e38;"));+ }++ /// A deterministic stream of numbers in [0, 1).+ fn stream(seed: u32) -> impl FnMut() -> f32 {+ let mut s = seed;+ move || {+ s = s.wrapping_mul(1664525).wrapping_add(1013904223);+ (s >> 8) as f32 / (1 << 24) as f32+ }+ }++ /// The kernel walks every tree `build` makes without reading past its nodes or its triangles, and stops: trees+ /// over no triangle (a scene with nothing in it, or with procedural geometry only), one, a leaf's worth, many.+ /// The empty scene's vertex buffer holds zeros (gpu.rs `upload`: 512 bytes, so triangles 0..2 are there, without+ /// area).+ /// The tree over no box is not one the kernel can walk (it reads past it): why `prepare` leaves such objects out.+ #[test]+ fn a_tree_over_no_box_is_left_out() {+ let b = build_boxes(&[]);+ assert_eq!(walk(&b.nodes, 0, V::new(3.0, 4.0, 5.0), V::Y), Err("reads node 1 of 1".into()));+ }++ #[test]+ fn the_kernel_walks_every_tree_within_its_buffers() {+ let mut rnd = stream(7);+ let mut p = |s: f32| V::new(rnd() - 0.5, rnd() - 0.5, rnd() - 0.5) * s;+ for n in [0usize, 1, 2, 4, 5, 17, 1000] {+ let tris: Vec<[V; 3]> = (0..n).map(|_| { let c = p(20.0); [c + p(1.0), c + p(1.0), c + p(1.0)] }).collect();+ let b = build(&tris);+ // (An empty scene's buffer: 512 zero bytes are 10 vec4s, three triangles' worth and a third.)+ let held = if n == 0 { 3 } else { n };+ let mut rays: Vec<(V, V)> = (0..2000).map(|_| (p(60.0), p(2.0).normalize_or(V::X))).collect();+ // Rays through the origin and along the axes (an empty tree's boxes are at the origin).+ for a in [V::X, V::Y, V::Z, V::ONE.normalize(), V::new(1.0, -1.0, 0.0).normalize()] {+ rays.extend([(V::ZERO, a), (-a * 5.0, a), (a * 5.0, -a), (V::new(0.0, 4.5, 0.001), -a), (V::new(1.0, 1.0, 5.0), (-V::new(1.0, 1.0, 5.0)).normalize())]);+ }+ let mut seen = vec![false; held];+ for (o, d) in rays {+ let tested = walk(&b.nodes, held, o, d).unwrap_or_else(|e| panic!("{n} triangles, ray {o} {d}: the kernel {e}"));+ tested.iter().for_each(|&t| seen[t as usize] = true);+ }+ if n > 0 {+ assert!(seen.iter().filter(|&&s| s).count() * 2 > n, "{n} triangles: the rays reach the leaves");+ }+ }+ }+}diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex eb59f3e..da74ed8 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -16,19 +16,25 @@ pub struct Gpu {pub adapter_info: wgpu::AdapterInfo,/// Kernel source (hardware or software traversal spliced in); scenes with material functions get their own module.source: String,- module: wgpu::ShaderModule,- /// By (material-function code hash, the source-patching features: `kernel_source`).- modules: std::sync::Mutex<std::collections::HashMap<(u64, u32), wgpu::ShaderModule>>,+ /// The kernel as written (none in the merged layout: its sources are written for their arrays' lengths).+ module: Option<wgpu::ShaderModule>,+ /// The merged binding layout (merged.rs): a browser's, where a stage has eight storage buffers. Natively with+ /// THREERT_MERGED=1 (software traversal, the device held to eight too).+ pub merged: bool,+ /// By (material-function code hash, the source-patching features: `kernel_source`, the merged layout's lengths).+ modules: std::sync::Mutex<std::collections::HashMap<(u64, u32, Option<crate::merged::Caps>), wgpu::ShaderModule>>,pipeline_layout: wgpu::PipelineLayout,/// Kernel variants by (feature mask, material-function code hash, LIVE): `FEAT` compiles out the features a scene/// does not use (they cost registers even when idle); `LIVE` = one fresh sample per dispatch for the viewport.- pipelines: std::sync::Mutex<std::collections::HashMap<(u32, u64, bool), wgpu::ComputePipeline>>,+ pipelines: std::sync::Mutex<std::collections::HashMap<(u32, u64, bool, Option<crate::merged::Caps>), wgpu::ComputePipeline>>,layout: wgpu::BindGroupLayout,/// Group 1, the live viewport's: primary visibility (texture_2d<u32>), the radiance cache (`CacheBuffers`) and/// the emitter reservoirs (`reservoirs`). Offline renders bind `no_vis` (1x1 texture `no_vis_view`, one-entry/// cache, one reservoir).pub vis_layout: wgpu::BindGroupLayout,pub no_vis: wgpu::BindGroup,+ /// `no_vis`'s buffers (the merged layout: an offline kernel's source is written for their lengths).+ no_vis_bufs: KernelBufs,pub no_vis_view: wgpu::TextureView,/// Binding 19 of scenes without density grids (one cell), and the grid pass's bind group layout (grid_sim.wgsl).no_grid_view: wgpu::TextureView,@@ -43,7 +49,7 @@ pub struct Gpu {tl_pipeline_layout: Option<wgpu::PipelineLayout>,tl_pipelines: std::sync::Mutex<std::collections::HashMap<(u32, u64, bool), TranslucentPipelines>>,/// The live media passes (pathtrace.wgsl `media_train`, `media_composite`) by kernel variant and entry point.- media_passes: std::sync::Mutex<std::collections::HashMap<(u32, u64, &'static str), wgpu::ComputePipeline>>,+ media_passes: std::sync::Mutex<std::collections::HashMap<(u32, u64, &'static str, Option<crate::merged::Caps>), wgpu::ComputePipeline>>,/// The procedural blobs of the last upload (`upload_procs`).proc_cache: std::sync::Mutex<Option<ProcCache>>,/// The last upload's procedural BLASes by geometry hash (read-only once built; another upload may share them), with@@ -157,6 +163,16 @@ pub struct PendingProc {size: wgpu::BlasAABBGeometrySizeDescriptor,}+/// The kernel's bindings of the seven tables the merged layout holds in one (merged.rs `TABLES`, in its order).+const MERGED_TABLE_BINDINGS: [u32; 7] = [4, 5, 6, 14, 15, 17, 18];++impl Uploaded {+ /// The seven tables, in merged.rs `TABLES`' order.+ fn table_buffers(&self) -> [&wgpu::Buffer; 7] {+ [&self.materials, &self.lights, &self.emitters, &self.bg_parts.texinfo, &self.objects, &self.instances, &self.media]+ }+}+/// What the scene bind group holds besides `Uploaded`'s buffers (`Gpu::rebind_scene` makes it again).pub struct BindParts {pub nodes: wgpu::Buffer,@@ -172,6 +188,9 @@ pub struct BindParts {pub struct Uploaded {pub bg: wgpu::BindGroup,pub bg_parts: BindParts,+ /// The merged layout (merged.rs): the buffer of the kernel's `MergedTables`, the seven tables below as its arrays+ /// (`Gpu::sync_tables` copies them there each frame; their lengths: `kernel.caps`).+ pub tables: Option<wgpu::Buffer>,pub accum: wgpu::Buffer,pub params: wgpu::Buffer,pub width: u32,@@ -607,6 +626,55 @@ pub fn kernel_source(src: &str, features: u32) -> String {s}+/// The loop guard's limit, if the kernel is to have one (merged.rs `guard`: every loop of it bounded, so a dispatch+/// ends whatever the data): THREERT_LOOP_GUARD=<iterations an invocation> natively, where the kernel is otherwise as+/// written; always in a browser, where a dispatch that does not end is the player's whole GPU.+pub fn loop_guard() -> Option<u32> {+ match LOOP_GUARD.load(std::sync::atomic::Ordering::Relaxed) {+ 0 => {}+ n => return Some(n),+ }+ match std::env::var("THREERT_LOOP_GUARD").ok().and_then(|v| v.parse::<u32>().ok()) {+ Some(0) => None,+ Some(n) => Some(n),+ None => cfg!(target_arch = "wasm32").then_some(1 << 16),+ }+}++/// The loop guard's limit as a page set it (0: not set), before the GPU is opened: a browser has no environment.+static LOOP_GUARD: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);++/// Sets the loop guard's limit (a page's first runs of a new kernel take a low one); 0 leaves it as it is. Before+/// `Gpu::new_async`: the limit is in the kernels' source.+pub fn set_loop_guard(limit: u32) {+ if limit > 0 {+ LOOP_GUARD.store(limit, std::sync::atomic::Ordering::Relaxed);+ }+}++/// The kernel's source for a traversal: pathtrace.wgsl as it is (software), or with the hardware traversal in the+/// software one's place and the translucency pass after it.+pub fn kernel_base(hwrt: bool) -> String {+ let base = include_str!("../shaders/pathtrace.wgsl");+ if hwrt {+ let (head, rest) = base.split_once("// @trace-begin").unwrap();+ let (_, tail) = rest.split_once("// @trace-end").unwrap();+ format!("enable wgpu_ray_query;\n{head}{}{tail}{}", include_str!("../shaders/trace_hw.wgsl"), include_str!("../shaders/translucent.wgsl"))+ } else {+ base.to_string()+ }+}++/// A kernel source as it is compiled: with the loop guard if there is one, its count in `MergedLive` (the merged+/// layout) or in a buffer of its own (group 1, `merged::GUARD_BINDING`).+fn guarded(src: &str, merged: bool) -> String {+ match loop_guard() {+ None => src.to_string(),+ Some(n) if merged => crate::merged::guard(src, n, "ML.loop_guard_trips"),+ Some(n) => crate::merged::guard(&format!("{src}\n{}", crate::merged::guard_decl()), n, crate::merged::GUARD_TRIPS.name),+ }+}+pub fn tlas_rows(w: glam::Mat4) -> [f32; 12] {let row = |r: usize| [w.x_axis[r], w.y_axis[r], w.z_axis[r], w.w_axis[r]];let [r0, r1, r2] = [row(0), row(1), row(2)];@@ -616,23 +684,53 @@ pub fn tlas_rows(w: glam::Mat4) -> [f32; 12] {/// Entries of the live radiance cache (pathtrace.wgsl CACHE_SIZE).pub const CACHE_SIZE: u64 = 1 << 18;+/// A buffer, or a range of one: in the merged layout (merged.rs) several of the engine's buffers are ranges of the one+/// buffer a binding holds.+#[derive(Clone)]+pub struct Buf {+ pub buffer: wgpu::Buffer,+ pub offset: u64,+ pub size: u64,+}++impl Buf {+ pub fn whole(buffer: wgpu::Buffer) -> Buf {+ let size = buffer.size();+ Buf { buffer, offset: 0, size }+ }++ /// As a binding (a whole buffer: `as_entire_binding`).+ pub fn binding(&self) -> wgpu::BindingResource<'_> {+ if self.offset == 0 && self.size == self.buffer.size() {+ self.buffer.as_entire_binding()+ } else {+ wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &self.buffer, offset: self.offset, size: std::num::NonZeroU64::new(self.size) })+ }+ }++ pub fn clear(&self, e: &mut wgpu::CommandEncoder) {+ e.clear_buffer(&self.buffer, self.offset, Some(self.size));+ }+}+/// The radiance cache's storage (pathtrace.wgsl): voxel keys, this frame's training sums, resolved values.+#[derive(Clone)]pub struct CacheBuffers {- pub keys: wgpu::Buffer,- pub acc: wgpu::Buffer,- pub val: wgpu::Buffer,+ pub keys: Buf,+ pub acc: Buf,+ pub val: Buf,}impl CacheBuffers {pub fn new(d: &wgpu::Device, entries: u64) -> CacheBuffers {- let b = |label, size| d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });+ let b = |label, size| Buf::whole(d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }));CacheBuffers { keys: b("cache keys", entries * 4), acc: b("cache sums", entries * 32), val: b("cache values", entries * 32) }}/// Empties the cache (a different world).pub fn clear(&self, e: &mut wgpu::CommandEncoder) {for b in [&self.keys, &self.acc, &self.val] {- e.clear_buffer(b, 0, None);+ b.clear(e);}}}@@ -642,17 +740,54 @@ pub fn reservoirs(d: &wgpu::Device, pixels: u64) -> wgpu::Buffer {d.create_buffer(&wgpu::BufferDescriptor { label: Some("reservoirs"), size: pixels * 64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false })}+/// The kernel's group-1 buffers: the radiance cache, the emitter reservoirs, and what the live passes read of a trace+/// (live.rs `Targets`): the specular-lobe rays, the motion vectors, the directional lights' direct light. In the+/// merged layout they are ranges of one buffer, the arrays of the kernel's `MergedLive` (merged.rs `KERNEL_LIVE`).+pub struct KernelBufs {+ pub cache: CacheBuffers,+ pub resv: Buf,+ pub refl: Buf,+ pub motion: Buf,+ pub direct: Buf,+ /// The loop guard's count (merged.rs `guard`: its first word, the invocations a loop of which was stopped): with+ /// the guard, and always in the merged layout (the last array of `MergedLive`).+ pub guard: Option<Buf>,+ /// The merged layout: the one buffer, and its arrays' lengths.+ pub merged: Option<(wgpu::Buffer, [u32; 7])>,+}++impl KernelBufs {+ /// For a cache of `entries`, reservoirs for `pixels` and the live passes' three of these bytes.+ pub fn new(d: &wgpu::Device, merged: bool, entries: u64, pixels: u64, refl: u64, motion: u64, direct: u64) -> KernelBufs {+ if !merged {+ let sb = |label: &str, size: u64| Buf::whole(d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }));+ let guard = loop_guard().map(|_| sb("loop guard", crate::merged::GUARD_WORDS as u64 * 4));+ return KernelBufs { cache: CacheBuffers::new(d, entries), resv: Buf::whole(reservoirs(d, pixels)), refl: sb("refl", refl), motion: sb("motion", motion), direct: sb("direct", direct), guard, merged: None };+ }+ let bytes = [entries * 4, entries * 32, entries * 32, pixels * 64, refl, motion, direct, crate::merged::GUARD_WORDS as u64 * 4];+ let caps: [u32; 7] = std::array::from_fn(|k| crate::merged::live_cap(k, bytes[k]));+ let (at, size) = crate::merged::live_layout(&caps);+ let buffer = d.create_buffer(&wgpu::BufferDescriptor { label: Some("merged live"), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });+ let b = |k: usize| Buf { buffer: buffer.clone(), offset: at[k], size: bytes[k] };+ KernelBufs { cache: CacheBuffers { keys: b(0), acc: b(1), val: b(2) }, resv: b(3), refl: b(4), motion: b(5), direct: b(6), guard: Some(b(7)), merged: Some((buffer, caps)) }+ }+}+/// Group-1 bind group of the kernel: a primary-visibility texture, the radiance cache, the emitter reservoirs and the-/// reflection resolve's inputs (live.rs `Targets::refl`).-pub fn vis_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, view: &wgpu::TextureView, cache: &CacheBuffers, resv: &wgpu::Buffer, refl: &wgpu::Buffer, motion: &wgpu::Buffer, direct: &wgpu::Buffer) -> wgpu::BindGroup {- fn e(binding: u32, b: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {- wgpu::BindGroupEntry { binding, resource: b.as_entire_binding() }- }- d.create_bind_group(&wgpu::BindGroupDescriptor {- label: Some("vis"),- layout,- entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) }, e(1, &cache.keys), e(2, &cache.acc), e(3, &cache.val), e(4, resv), e(5, refl), e(6, motion), e(7, direct)],- })+/// reflection resolve's inputs (`KernelBufs`); in the merged layout, the texture and the one buffer.+pub fn vis_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, view: &wgpu::TextureView, b: &KernelBufs) -> wgpu::BindGroup {+ fn e(binding: u32, b: &Buf) -> wgpu::BindGroupEntry<'_> {+ wgpu::BindGroupEntry { binding, resource: b.binding() }+ }+ let tex = wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) };+ match &b.merged {+ Some((buffer, _)) => d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("vis"), layout, entries: &[tex, wgpu::BindGroupEntry { binding: crate::merged::KERNEL_LIVE_BINDING, resource: buffer.as_entire_binding() }] }),+ None => {+ let mut entries = vec![tex, e(1, &b.cache.keys), e(2, &b.cache.acc), e(3, &b.cache.val), e(4, &b.resv), e(5, &b.refl), e(6, &b.motion), e(7, &b.direct)];+ entries.extend(b.guard.as_ref().map(|g| e(crate::merged::GUARD_BINDING, g)));+ d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("vis"), layout, entries: &entries })+ }+ }}/// Whether a material function's WGSL (`fn mf_<name>(...) -> MatOut { var o = base; ... return o; }`) can change its@@ -678,6 +813,9 @@ pub struct Kernel {/// The scene's geometry functions and their dispatch (pathtrace.wgsl `geometry_function`), spliced like `functions`.pub geometry_functions: String,pub hash: u64,+ /// The merged layout (merged.rs): the lengths of the merged structs' arrays this kernel's source is written for+ /// (the tables': `Gpu::upload`; group 1's: an offline render's `no_vis`, a live view's `KernelBufs`).+ pub caps: Option<crate::merged::Caps>,}impl Kernel {@@ -767,7 +905,18 @@ impl Kernel {functions.hash(&mut h);volume_functions.hash(&mut h);geometry_functions.hash(&mut h);- Kernel { features: features(scene, groups), functions, volume_functions, geometry_functions, hash: h.finish() }+ Kernel { features: features(scene, groups), functions, volume_functions, geometry_functions, hash: h.finish(), caps: None }+ }++ /// The kernel as written (no feature, no function of a scene's), in the merged layout for arrays of `caps`'+ /// lengths: the radiance cache's resolve.+ fn plain(caps: crate::merged::Caps) -> Kernel {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ for _ in 0..3 {+ String::new().hash(&mut h);+ }+ Kernel { features: 0, functions: String::new(), volume_functions: String::new(), geometry_functions: String::new(), hash: h.finish(), caps: Some(caps) }}}@@ -960,14 +1109,18 @@ impl Gpu {limits.max_buffer_size = al.max_buffer_size;limits.max_texture_array_layers = al.max_texture_array_layers;limits.max_texture_dimension_2d = al.max_texture_dimension_2d;- limits.max_storage_buffers_per_shader_stage = al.max_storage_buffers_per_shader_stage.min(31);+ // The merged binding layout (merged.rs): a browser's, where a stage has eight storage buffers; natively with+ // THREERT_MERGED=1, on software traversal (what a browser has) and the device held to the same eight (a+ // layout with more does not validate).+ let merged = cfg!(target_arch = "wasm32") || std::env::var("THREERT_MERGED").is_ok_and(|v| v == "1");+ limits.max_storage_buffers_per_shader_stage = if merged { crate::merged::STORAGE_BUFFERS } else { al.max_storage_buffers_per_shader_stage.min(31) };// Storage + uniform buffers together (the live passes bind 29; Metal allows 31).limits.max_buffers_and_acceleration_structures_per_shader_stage = al.max_buffers_and_acceleration_structures_per_shader_stage.min(31);limits.max_acceleration_structures_per_shader_stage = al.max_acceleration_structures_per_shader_stage;limits.max_blas_geometry_count = al.max_blas_geometry_count;limits.max_blas_primitive_count = al.max_blas_primitive_count;limits.max_tlas_instance_count = al.max_tlas_instance_count;- let hwrt = adapter.features().contains(wgpu::Features::EXPERIMENTAL_RAY_QUERY) && std::env::var("THREERT_HWRT").map(|v| v != "0").unwrap_or(true);+ let hwrt = !merged && adapter.features().contains(wgpu::Features::EXPERIMENTAL_RAY_QUERY) && std::env::var("THREERT_HWRT").map(|v| v != "0").unwrap_or(true);let timestamps = adapter.features().contains(wgpu::Features::TIMESTAMP_QUERY);let mut features = if hwrt { wgpu::Features::EXPERIMENTAL_RAY_QUERY } else { wgpu::Features::empty() };if timestamps {@@ -981,21 +1134,14 @@ impl Gpu {experimental_features: if hwrt { unsafe { wgpu::ExperimentalFeatures::enabled() } } else { wgpu::ExperimentalFeatures::disabled() },..Default::default()}).await?;- let base = include_str!("../shaders/pathtrace.wgsl");- let src = if hwrt {- let (head, rest) = base.split_once("// @trace-begin").unwrap();- let (_, tail) = rest.split_once("// @trace-end").unwrap();- format!("enable wgpu_ray_query;\n{head}{}{tail}{}", include_str!("../shaders/trace_hw.wgsl"), include_str!("../shaders/translucent.wgsl"))- } else {- base.to_string()- };+ let src = kernel_base(hwrt);// Bounds checks are not needed: all indices come from our own BVH / scene builder.- let module = unsafe {+ let module = (!merged).then(|| unsafe {device.create_shader_module_trusted(- wgpu::ShaderModuleDescriptor { label: Some("pathtrace"), source: wgpu::ShaderSource::Wgsl(src.as_str().into()) },+ wgpu::ShaderModuleDescriptor { label: Some("pathtrace"), source: wgpu::ShaderSource::Wgsl(guarded(&src, false).into()) },wgpu::ShaderRuntimeChecks::unchecked(),)- };+ });let storage = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry {binding,visibility: wgpu::ShaderStages::COMPUTE,@@ -1048,25 +1194,34 @@ impl Gpu {if hwrt {entries.push(wgpu::BindGroupLayoutEntry { binding: 13, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::AccelerationStructure { vertex_return: false }, count: None });}+ // The merged layout: the seven tables are one binding, the first of theirs (merged.rs `TABLES`).+ if merged {+ entries.retain(|e| !MERGED_TABLE_BINDINGS[1..].contains(&e.binding));+ }let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &entries });- let vis_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {- label: Some("vis"),- entries: &[- wgpu::BindGroupLayoutEntry {- binding: 0,- visibility: wgpu::ShaderStages::COMPUTE,- ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Uint, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false },- count: None,- },- storage(1, false),- storage(2, false),- storage(3, false),- storage(4, false),- storage(5, false),- storage(6, false),- storage(7, false),- ],- });+ let mut vis_entries = vec![+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::COMPUTE,+ ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Uint, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false },+ count: None,+ },+ storage(1, false),+ storage(2, false),+ storage(3, false),+ storage(4, false),+ storage(5, false),+ storage(6, false),+ storage(7, false),+ ];+ // The merged layout: group 1's seven buffers are one (merged.rs `KERNEL_LIVE`), the loop guard's count in it.+ // As written, a kernel with the guard has the count in a buffer of its own.+ if merged {+ vis_entries.truncate(2);+ } else if loop_guard().is_some() {+ vis_entries.push(storage(crate::merged::GUARD_BINDING, false));+ }+ let vis_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("vis"), entries: &vis_entries });let one = device.create_texture(&wgpu::TextureDescriptor {label: Some("no vis"),size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },@@ -1091,7 +1246,8 @@ impl Gpu {storage(6, true),],});- let no_vis = vis_bind_group(&device, &vis_layout, &no_vis_view, &CacheBuffers::new(&device, 1), &reservoirs(&device, 1), &reservoirs(&device, 1), &reservoirs(&device, 1), &reservoirs(&device, 1));+ let no_vis_bufs = KernelBufs::new(&device, merged, 1, 1, 64, 64, 64);+ let no_vis = vis_bind_group(&device, &vis_layout, &no_vis_view, &no_vis_bufs);let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout), Some(&vis_layout)], immediate_size: 0 });let (tl_layout, tl_pipeline_layout) = if hwrt {let st = |b: u32| wgpu::BindGroupLayoutEntry { binding: b, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: false }, has_dynamic_offset: false, min_binding_size: None }, count: None };@@ -1111,14 +1267,14 @@ impl Gpu {} else {(None, None)};- Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, source: src, module, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_view, no_grid_view, grid_layout, hwrt, pages: Default::default(), tl_layout, tl_pipeline_layout, tl_pipelines: Default::default(), media_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })+ Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, hwrt, pages: Default::default(), tl_layout, tl_pipeline_layout, tl_pipelines: Default::default(), media_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })}/// The path-tracing kernel specialised for a scene (feature mask + material functions), compiled on first use.pub fn pipeline(&self, k: &Kernel, live: bool) -> wgpu::ComputePipeline {let mut cache = self.pipelines.lock().unwrap();cache- .entry((k.features, k.hash, live))+ .entry((k.features, k.hash, live, k.caps)).or_insert_with(|| {let module = self.kernel_module(k);let constants = [("LIVE", if live { 1.0 } else { 0.0 }), ("FEAT", k.features as f64)];@@ -1137,11 +1293,12 @@ impl Gpu {/// The kernel module for a scene: the shared one, or with its material functions spliced in.fn kernel_module(&self, k: &Kernel) -> wgpu::ShaderModule {let patches = k.features & F_SOURCE;- if patches == 0 && k.functions.is_empty() && k.volume_functions.is_empty() && k.geometry_functions.is_empty() {- return self.module.clone();+ assert_eq!(self.merged, k.caps.is_some(), "a kernel of the merged layout has its arrays' lengths");+ if let (Some(m), true) = (&self.module, patches == 0 && k.functions.is_empty() && k.volume_functions.is_empty() && k.geometry_functions.is_empty()) {+ return m.clone();}let mut mods = self.modules.lock().unwrap();- mods.entry((k.hash, patches))+ mods.entry((k.hash, patches, k.caps)).or_insert_with(|| {let splice = |src: &str, marker: &str, code: &str| -> String {if code.is_empty() {@@ -1153,9 +1310,11 @@ impl Gpu {};let base = kernel_source(&self.source, patches);let src = splice(&splice(&splice(&base, "material-functions", &k.functions), "volume-functions", &k.volume_functions), "geometry-functions", &k.geometry_functions);+ // The merged layout: the same source, its buffers merged for this kernel's arrays (merged.rs).+ let src = k.caps.as_ref().map_or(src.clone(), |c| crate::merged::kernel(&src, c));unsafe {self.device.create_shader_module_trusted(- wgpu::ShaderModuleDescriptor { label: Some("pathtrace+functions"), source: wgpu::ShaderSource::Wgsl(src.as_str().into()) },+ wgpu::ShaderModuleDescriptor { label: Some("pathtrace+functions"), source: wgpu::ShaderSource::Wgsl(guarded(&src, self.merged).into()) },wgpu::ShaderRuntimeChecks::unchecked(),)}@@ -1168,7 +1327,7 @@ impl Gpu {pub fn media_pipeline(&self, k: &Kernel, entry: &'static str) -> wgpu::ComputePipeline {let mut cache = self.media_passes.lock().unwrap();cache- .entry((k.features, k.hash, entry))+ .entry((k.features, k.hash, entry, k.caps)).or_insert_with(|| {let module = self.kernel_module(k);let constants = [("LIVE", 1.0), ("FEAT", k.features as f64)];@@ -1220,11 +1379,17 @@ impl Gpu {}/// The radiance cache's per-frame resolve (pathtrace.wgsl `cache_resolve`; kernel bind groups).- pub fn cache_resolve_pipeline(&self) -> wgpu::ComputePipeline {+ pub fn cache_resolve_pipeline(&self, bufs: &KernelBufs) -> wgpu::ComputePipeline {+ // (The merged layout: the kernel written for these buffers' lengths, and the least tables.)+ let module = match (&self.module, &bufs.merged) {+ (Some(m), _) => m.clone(),+ (None, Some((_, live))) => self.kernel_module(&Kernel::plain(crate::merged::Caps { tables: crate::merged::TABLE_MIN, live: *live })),+ (None, None) => unreachable!("the merged layout's group 1 is one buffer"),+ };self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {label: Some("cache resolve"),layout: Some(&self.pipeline_layout),- module: &self.module,+ module: &module,entry_point: Some("cache_resolve"),compilation_options: Default::default(),cache: None,@@ -1265,7 +1430,8 @@ impl Gpu {}}let view = tex.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() });- let info = d.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("tex_info"), contents: bytemuck::cast_slice(&packed.info), usage: wgpu::BufferUsages::STORAGE });+ // (The merged layout copies it into the tables' buffer, `sync_tables`.)+ let info = d.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("tex_info"), contents: bytemuck::cast_slice(&packed.info), usage: if self.merged { wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC } else { wgpu::BufferUsages::STORAGE } });timings.push(("texture_pages_ms".into(), t.elapsed().as_secs_f64() * 1000.0));*cache = Some((key, view.clone(), info.clone()));(view, info)@@ -1278,6 +1444,8 @@ impl Gpu {let d = &self.device;let t0 = Instant::now();// Empty tables still bind one zeroed element (the largest is a material, 368 B).+ // (The vertices too: the kernel's tree over no triangle is a leaf of triangle 0, which these zeros make a+ // triangle without area; bvh.rs `EMPTY`.)let buf = |label: &str, bytes: &[u8], usage: wgpu::BufferUsages| {let data: &[u8] = if bytes.is_empty() { &[0u8; 512] } else { bytes };d.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: data, usage })@@ -1630,7 +1798,16 @@ impl Gpu {if let Some(a) = &accel {bg_entries.push(wgpu::BindGroupEntry { binding: 13, resource: a.tlas.as_binding() });}+ // The merged layout: the tables' one buffer in their place (merged.rs).+ let tables = self.merged.then(|| self.tables_buffer([&b_mats, &b_lights, &b_emit, &b_texinfo, &b_objects, &b_instances, &b_media]));+ if let Some((t, _)) = &tables {+ bg_entries.retain(|e| !MERGED_TABLE_BINDINGS.contains(&e.binding));+ bg_entries.push(e(crate::merged::TABLES_BINDING, t));+ }let bg = d.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &self.layout, entries: &bg_entries });+ let mut kernel = Kernel::new(scene, groups);+ kernel.caps = tables.as_ref().map(|t| crate::merged::Caps { tables: t.1, live: self.no_vis_bufs.merged.as_ref().expect("merged").1 });+ let tables = tables.map(|t| t.0);// Translucent particles (hardware RT): their own BLAS + TLAS, rebuilt after the particle pass.let translucent = match &accel {Some(_) if !scene.trans_tris.is_empty() => {@@ -1743,7 +1920,7 @@ impl Gpu {self.device.poll(wgpu::PollType::wait_indefinitely())?;timings.push(("upload_ms".into(), t0.elapsed().as_secs_f64() * 1000.0));let bg_parts = BindParts { nodes: b_nodes, energy: b_energy, texinfo: b_texinfo, tex_view, env_view, sampler, grid_view };- Ok(Uploaded { bg, bg_parts, accum: b_accum, params: b_params, width: w, height: h, kernel: Kernel::new(scene, groups), materials: b_mats, lights: b_lights, objects: b_objects, emitters: b_emit, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, particles, gpu_particles, grids, translucent, media: b_media, vcolor_base: (!scene.gpu_vcolors.is_empty()).then_some(scene.vcolor_base as u64 * 16), media_nodes: scene.media_nodes.clone(), instances: b_instances, room, cdf: b_cdf, cdf_words: env_cdf.len(), region_words, env_tex })+ Ok(Uploaded { bg, bg_parts, tables, accum: b_accum, params: b_params, width: w, height: h, kernel, materials: b_mats, lights: b_lights, objects: b_objects, emitters: b_emit, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, particles, gpu_particles, grids, translucent, media: b_media, vcolor_base: (!scene.gpu_vcolors.is_empty()).then_some(scene.vcolor_base as u64 * 16), media_nodes: scene.media_nodes.clone(), instances: b_instances, room, cdf: b_cdf, cdf_words: env_cdf.len(), region_words, env_tex })}/// Bytes Metal allocates for an AABB BLAS over `count` boxes in `boxes` (its own size query through wgpu-hal; None@@ -2288,7 +2465,60 @@ impl Gpu {if let Some(a) = &up.accel {entries.push(wgpu::BindGroupEntry { binding: 13, resource: a.tlas.as_binding() });}- up.bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &self.layout, entries: &entries });+ // The merged layout: the tables' buffer, a larger one if a table outgrew its array (the kernel's source then+ // has the new lengths: compiled on its next use).+ let now: [u32; 7] = std::array::from_fn(|k| crate::merged::table_cap(k, up.table_buffers()[k].size()));+ let tables = match (&up.tables, &up.kernel.caps) {+ (Some(t), Some(caps)) if now == caps.tables => Some(t.clone()),+ (Some(_), Some(_)) => Some(self.tables_buffer(up.table_buffers()).0),+ _ => None,+ };+ if let Some(t) = &tables {+ entries.retain(|e| !MERGED_TABLE_BINDINGS.contains(&e.binding));+ entries.push(e(crate::merged::TABLES_BINDING, t));+ }+ let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &self.layout, entries: &entries });+ drop(entries);+ up.bg = bg;+ if let (Some(_), Some(caps)) = (&tables, &mut up.kernel.caps) {+ caps.tables = now;+ }+ up.tables = tables;+ }++ /// The loop guard's count as the GPU has it now (None: no guard): the invocations it stopped since the buffers+ /// were made. Waits for the GPU.+ #[cfg(not(target_arch = "wasm32"))]+ pub fn guard_trips(&self, bufs: &KernelBufs) -> Result<Option<u32>> {+ let Some(g) = bufs.guard.as_ref().filter(|_| loop_guard().is_some()) else { return Ok(None) };+ let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("loop guard read"), size: 4, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });+ let mut e = self.device.create_command_encoder(&Default::default());+ e.copy_buffer_to_buffer(&g.buffer, g.offset, &read, 0, 4);+ self.queue.submit([e.finish()]);+ read.slice(..).map_async(wgpu::MapMode::Read, |_| {});+ self.device.poll(wgpu::PollType::wait_indefinitely())?;+ let n = u32::from_le_bytes(read.slice(..).get_mapped_range()?[..4].try_into().expect("four bytes"));+ Ok(Some(n))+ }++ /// The buffer of the merged layout's `MergedTables` for these seven tables (merged.rs `TABLES`' order), and its+ /// arrays' lengths.+ fn tables_buffer(&self, tables: [&wgpu::Buffer; 7]) -> (wgpu::Buffer, [u32; 7]) {+ let caps: [u32; 7] = std::array::from_fn(|k| crate::merged::table_cap(k, tables[k].size()));+ let (_, size) = crate::merged::offsets(&crate::merged::TABLES, &caps);+ (self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("merged tables"), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }), caps)+ }++ /// The merged layout: the tables as they are now, copied into the struct's buffer. The renderer writes the tables+ /// where it always did; the passes that read the scene read this copy, so it is made in their encoder, before+ /// them, each frame (the tables are small: a few copies of kilobytes).+ pub fn sync_tables(&self, up: &Uploaded, e: &mut wgpu::CommandEncoder) {+ let (Some(t), Some(caps)) = (&up.tables, &up.kernel.caps) else { return };+ let (at, _) = crate::merged::offsets(&crate::merged::TABLES, &caps.tables);+ for (k, src) in up.table_buffers().into_iter().enumerate() {+ let room = crate::merged::TABLES[k].stride * caps.tables[k] as u64;+ e.copy_buffer_to_buffer(src, 0, t, at[k], src.size().min(room));+ }}pub fn rebuild_tlas(&self, accel: &Accel, e: &mut wgpu::CommandEncoder) {@@ -2454,11 +2684,13 @@ impl Gpu {}let (b_accum, b_params, bg) = (&up.accum, &up.params, &up.bg);let accum_size = b_accum.size();+ let stopped_before = self.guard_trips(&self.no_vis_bufs)?;let t1 = Instant::now();let mut enc = d.create_command_encoder(&Default::default());enc.clear_buffer(b_accum, 0, None);+ self.sync_tables(&up, &mut enc);self.queue.submit([enc.finish()]);// One dispatch per sample; params are rewritten between submissions. Batch a few per submit.let batch = 4u32;@@ -2482,6 +2714,12 @@ impl Gpu {self.device.poll(wgpu::PollType::wait_indefinitely())?;}timings.push(("trace_ms".into(), t1.elapsed().as_secs_f64() * 1000.0));+ // The loop guard, if the kernel has it: a render in which it stopped a loop has wrong pixels, and is an error.+ if let (Some(before), Some(now)) = (stopped_before, self.guard_trips(&self.no_vis_bufs)?) {+ if now != before {+ return Err(anyhow!("the loop guard stopped {} of the kernel's invocations at {} iterations (THREERT_LOOP_GUARD): a traversal that does not end on this scene's data, or a limit too low for it", now.wrapping_sub(before), loop_guard().unwrap_or(0)));+ }+ }let t_tl = Instant::now();let overlay = self.render_translucent(&up, base, spp)?;if up.translucent.is_some() {@@ -2560,6 +2798,37 @@ mod tests {/// The source-patching features (`kernel_source`) find their anchors in pathtrace.wgsl, once each, alone and all/// together; no feature leaves the source as it is.+ /// The native default (no merged layout, no loop guard): what is handed to wgpu is the source as it was before+ /// either existed. `guarded` gives a kernel back untouched; the live passes are their file. Prints the sources'+ /// SHA-256 (`--nocapture`), which docs/WORKFLOW.md's gate compares with main's (PR #13).+ #[test]+ fn the_default_sources_are_untouched() {+ use sha2::{Digest, Sha256};+ if std::env::var("THREERT_LOOP_GUARD").is_ok() {+ return;+ }+ assert_eq!(loop_guard(), None);+ let sha = |s: &str| Sha256::digest(s.as_bytes()).iter().map(|b| format!("{b:02x}")).collect::<String>();+ let live = include_str!("../shaders/live.wgsl");+ assert_eq!(crate::live::live_source(false), live);+ println!("source live {}", sha(&crate::live::live_source(false)));+ for hwrt in [false, true] {+ let base = kernel_base(hwrt);+ assert_eq!(guarded(&base, false), base);+ println!("source kernel hwrt={hwrt} {}", sha(&guarded(&base, false)));+ // Every combination of the features that patch the source (`kernel_source`), each as compiled.+ let bits = [F_TINT, F_UNLIT, F_BACKGROUND, F_VCOLOR, F_GRID];+ let mut all = Sha256::new();+ for m in 0..32u32 {+ let f = bits.iter().enumerate().filter(|(k, _)| m >> k & 1 == 1).fold(0, |a, (_, b)| a | b);+ let src = kernel_source(&base, f);+ assert_eq!(guarded(&src, false), src);+ all.update(guarded(&src, false).as_bytes());+ }+ println!("source kernel hwrt={hwrt} x32 features {}", all.finalize().iter().map(|b| format!("{b:02x}")).collect::<String>());+ }+ }+#[test]fn kernel_source_finds_its_anchors() {let base = include_str!("../shaders/pathtrace.wgsl");diff --git a/renderer/src/lib.rs b/renderer/src/lib.rsindex 11c8e72..8104bff 100644--- a/renderer/src/lib.rs+++ b/renderer/src/lib.rs@@ -1,6 +1,7 @@//! threert-render as a library: scene loading, the GPU path tracer, the real-time LiveCore (used by the//! `threert-render` CLI and by the native playground client).+pub mod api;pub mod bvh;#[cfg(not(target_arch = "wasm32"))]pub mod compare;@@ -11,6 +12,7 @@ pub mod files;pub mod gpu;pub mod live;pub mod ltree;+pub mod merged;pub mod post;pub mod procasset;pub mod scene;@@ -354,6 +356,11 @@ pub fn prepare(g: &gpu::Gpu, sc: &mut scene::Scene, timings: &mut Vec<(String, fif !g.hwrt && !sc.instances.is_empty() {flatten_instances(sc);}+ // Software traversal walks each procedural object's boxes through a tree of its own, and the tree over no box is+ // not one the kernel can walk (bvh.rs `EMPTY`): an object without boxes has nothing to meet, and is left out.+ if !g.hwrt {+ sc.procs.retain(|p| !p.blob.boxes.is_empty());+ }// Hardware RT only needs triangles grouped by shadow casting; software traversal needs our BVH.let bvh = if g.hwrt {let mut order: Vec<u32> = (0..sc.tris.len() as u32).collect();diff --git a/renderer/src/live.rs b/renderer/src/live.rsindex 385bf2c..4d9b473 100644--- a/renderer/src/live.rs+++ b/renderer/src/live.rs@@ -21,6 +21,7 @@//! (a step: camera, frames, and the sync answer / snapshot at its last frame, in one command)//! | {"cmd":"scale","scale":s (0 = auto)} | {"cmd":"quit"}+use crate::gpu::Buf;use crate::world::World;use crate::{gpu, post, prepare, scene, tables};// (The headless runner below, native only, is what uses all of it.)@@ -194,14 +195,25 @@ fn tonemap_lut(p: &crate::desc::PostPreset) -> Vec<u16> {out}+/// The live passes' source: live.wgsl as it is, or in the merged layout its buffers merged into slabs (merged.rs).+pub(crate) fn live_source(merged: bool) -> std::borrow::Cow<'static, str> {+ let src = include_str!("../shaders/live.wgsl");+ if merged {+ crate::merged::live(src).into()+ } else {+ src.into()+ }+}+struct Passes {layout: wgpu::BindGroupLayout,pipes: Vec<(&'static str, wgpu::ComputePipeline)>,}impl Passes {- fn new(d: &wgpu::Device) -> Passes {- let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("live"), source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/live.wgsl").into()) });+ fn new(g: &gpu::Gpu) -> Passes {+ let d = &g.device;+ let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("live"), source: wgpu::ShaderSource::Wgsl(live_source(g.merged).into()) });let buf = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry {binding,visibility: wgpu::ShaderStages::COMPUTE,@@ -224,6 +236,13 @@ impl Passes {entries.push(wgpu::BindGroupLayoutEntry { binding: 12, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None });entries.extend([buf(13, false), buf(14, false), buf(15, false), buf(16, false), buf(17, true), buf(18, false)]);entries.extend([buf(19, true), buf(20, false), buf(21, true), buf(22, false), buf(23, false), buf(24, false), buf(25, true), buf(26, false), buf(27, true), buf(28, true), buf(29, true), buf(30, false)]);+ // The merged layout: the buffers that stay, the slabs, and the offsets' uniform (merged.rs).+ if g.merged {+ use crate::merged::{LIVE_KEPT, OFFSETS_BINDING, SLABS};+ entries.retain(|e| !matches!(e.ty, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { .. }, .. }) || LIVE_KEPT.iter().any(|k| k.0 == e.binding));+ entries.extend(SLABS.iter().map(|s| buf(s.binding, s.read_only)));+ entries.push(wgpu::BindGroupLayoutEntry { binding: OFFSETS_BINDING, ..entries[0] });+ }let layout = d.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("live"), entries: &entries });let pl = d.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout)], immediate_size: 0 });let pipes = ["refl", "dtemporal", "atrous0", "atrous1", "atrous2", "atrous3", "atrous4", "temporal", "spec0", "spec1", "spec2", "dof_tiles", "dof", "mblur", "lum_down", "exposure", "lum_blur", "bloom_down", "bloom_dn1", "bloom_dn2", "bloom_dn3", "bloom_dn4",@@ -240,42 +259,46 @@ impl Passes {/// Screen-size targets shared across scene reloads.pub struct Targets {params: wgpu::Buffer,- hist: [wgpu::Buffer; 2],- gb: [wgpu::Buffer; 2],+ hist: [Buf; 2],+ gb: [Buf; 2],/// Accumulated base color (the denoiser's demodulation albedo) + directly seen emission (kept out of the/// denoiser), output resolution, f16.- alb: [wgpu::Buffer; 2],+ alb: [Buf; 2],/// Specular history, diffuse luminance moments (ping-pong), specular denoiser scratch.- shist: [wgpu::Buffer; 2],- mom: [wgpu::Buffer; 2],- sa: wgpu::Buffer,- sb: wgpu::Buffer,- /// Reflection resolve: the trace kernel's specular-lobe rays (2 vec4 per traced pixel, pathtrace.wgsl `refl`) and- /// the resolved specular reflection per traced pixel (live.wgsl `refl`).- refl: wgpu::Buffer,- refl_res: wgpu::Buffer,- /// Motion vectors per traced pixel (pathtrace.wgsl `motion_out`).- motion: wgpu::Buffer,- /// Deterministic direct light per traced pixel (pathtrace.wgsl `direct_out`) and its history (ping-pong).- direct: wgpu::Buffer,- xhist: [wgpu::Buffer; 2],- fa: wgpu::Buffer,- fb: wgpu::Buffer,- bloom: [wgpu::Buffer; 2],+ shist: [Buf; 2],+ mom: [Buf; 2],+ sa: Buf,+ sb: Buf,+ /// Reflection resolve: the resolved specular reflection per traced pixel (live.wgsl `refl`), from the trace+ /// kernel's specular-lobe rays (2 vec4 per traced pixel, pathtrace.wgsl `refl`: `kernel.refl`).+ refl_res: Buf,+ /// The history of the deterministic direct light (`kernel.direct`), ping-pong.+ xhist: [Buf; 2],+ fa: Buf,+ fb: Buf,+ bloom: [Buf; 2],pub out: wgpu::Buffer,/// Auto exposure: 64 histogram buckets (fixed point), state (exposure, target, mean log2 luminance, valid).ae_bins: wgpu::Buffer,- ae_state: wgpu::Buffer,+ ae_state: Buf,/// Quarter-resolution log2 luminance and its edge-aware blur (local exposure base).- lumq: wgpu::Buffer,- lumb: wgpu::Buffer,+ lumq: Buf,+ lumb: Buf,+ /// The kernel's group 1 (`gpu::KernelBufs`): the radiance cache, the reservoirs, and what the passes here read of+ /// a trace: the specular-lobe rays (`refl`), motion vectors per traced pixel (pathtrace.wgsl `motion_out`) and the+ /// deterministic direct light per traced pixel (`direct_out`).+ pub kernel: gpu::KernelBufs,+ /// The merged layout (merged.rs): the slabs the buffers above are ranges of (`SLABS`' first four).+ slabs: Option<[wgpu::Buffer; 4]>,lut_tex: wgpu::Texture,lut_view: wgpu::TextureView,sampler: wgpu::Sampler,}impl Targets {- fn new(g: &gpu::Gpu, w: u32, h: u32, lut: &[u16]) -> Targets {+ /// For a view of `w` x `h`, a radiance cache of `cache` entries and reservoirs for `resv` pixels.+ fn new(g: &gpu::Gpu, w: u32, h: u32, lut: &[u16], cache: u64, resv: u64) -> Targets {+ use crate::merged::{SLABS, SLAB_F1, SLAB_U2, SLAB_U4, SLAB_V4};let d = &g.device;let n = (w * h) as u64;let sb = |label: &str, bytes: u64| d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: bytes, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });@@ -298,78 +321,149 @@ impl Targets {wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(LUT * 8), rows_per_image: Some(LUT) },wgpu::Extent3d { width: LUT, height: LUT, depth_or_array_layers: LUT },);+ // The buffers, in the order of the fields below: a buffer each, or in the merged layout (merged.rs) a range of+ // the slab of its element type (each range starts at a multiple of 16 bytes: of every slab's element).+ let specs: [(&str, u64, usize); 22] = [+ ("hist0", n * 32, SLAB_V4), // traced grid, then output grid (live.wgsl `out_hist`)+ ("hist1", n * 32, SLAB_V4),+ ("gb0", n * 16, SLAB_U2),+ ("gb1", n * 16, SLAB_U2),+ ("alb0", n * 16, SLAB_U4),+ ("alb1", n * 16, SLAB_U4),+ ("shist0", n * 16, SLAB_V4),+ ("shist1", n * 16, SLAB_V4),+ ("mom0", n * 16, SLAB_V4),+ ("mom1", n * 16, SLAB_V4),+ ("spec_a", n * 16, SLAB_U2),+ ("spec_b", n * 16, SLAB_V4),+ ("refl_res", n * 16, SLAB_V4),+ ("direct_hist_a", n * 16, SLAB_V4),+ ("direct_hist_b", n * 16, SLAB_V4),+ ("fa", n * 16, SLAB_V4),+ ("fb", n * 16, SLAB_V4),+ ("bloom_a", bloom_texels * 16, SLAB_V4),+ ("bloom_b", bn, SLAB_V4),+ ("ae_state", 32, SLAB_V4),+ ("lumq", bn / 4, SLAB_F1),+ ("lumb", bn / 4, SLAB_F1),+ ];+ let slabs: Option<[wgpu::Buffer; 4]> = g.merged.then(|| std::array::from_fn(|k| sb(SLABS[k].name, specs.iter().filter(|s| s.2 == k).map(|s| s.1.next_multiple_of(16)).sum())));+ let mut at = [0u64; 4];+ let bufs: Vec<Buf> = specs+ .iter()+ .map(|&(label, bytes, slab)| match &slabs {+ None => Buf::whole(sb(label, bytes)),+ Some(s) => {+ let b = Buf { buffer: s[slab].clone(), offset: at[slab], size: bytes };+ at[slab] += bytes.next_multiple_of(16);+ b+ }+ })+ .collect();+ let mut bufs = bufs.into_iter();+ let mut b = || bufs.next().expect("a buffer of `specs`");Targets {params: d.create_buffer(&wgpu::BufferDescriptor { label: Some("live params"), size: std::mem::size_of::<LiveParams>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }),- hist: [sb("hist0", n * 32), sb("hist1", n * 32)], // traced grid, then output grid (live.wgsl `out_hist`)- gb: [sb("gb0", n * 16), sb("gb1", n * 16)],- alb: [sb("alb0", n * 16), sb("alb1", n * 16)],- shist: [sb("shist0", n * 16), sb("shist1", n * 16)],- mom: [sb("mom0", n * 16), sb("mom1", n * 16)],- sa: sb("spec_a", n * 16),- sb: sb("spec_b", n * 16),- refl: sb("refl", n * 32),- refl_res: sb("refl_res", n * 16),- motion: sb("motion", n * 16),- direct: sb("direct", n * 16),- xhist: [sb("direct_hist_a", n * 16), sb("direct_hist_b", n * 16)],- fa: sb("fa", n * 16),- fb: sb("fb", n * 16),- bloom: [sb("bloom_a", bloom_texels * 16), sb("bloom_b", bn)],+ hist: [b(), b()],+ gb: [b(), b()],+ alb: [b(), b()],+ shist: [b(), b()],+ mom: [b(), b()],+ sa: b(),+ sb: b(),+ refl_res: b(),+ xhist: [b(), b()],+ fa: b(),+ fb: b(),+ bloom: [b(), b()],out: sb("out", n * 4),ae_bins: sb("ae_bins", 64 * 4),- ae_state: sb("ae_state", 32),- lumq: sb("lumq", bn / 4),- lumb: sb("lumb", bn / 4),+ ae_state: b(),+ lumq: b(),+ lumb: b(),+ kernel: gpu::KernelBufs::new(d, g.merged, cache, resv, n * 32, n * 16, n * 16),+ slabs,lut_view: lut_tex.create_view(&Default::default()),lut_tex,sampler: d.create_sampler(&wgpu::SamplerDescriptor { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() }),}}- /// Two bind groups that swap history / g-buffer ping-pong roles on alternate frames.+ /// What live.wgsl's buffer bindings hold in the bind group of parity `a` (besides the uniforms at 0, the trace's+ /// samples at 1, `out` at 10 and the histogram at 13): the history and the g-buffer swap roles with the parity.+ fn buffers(&self, a: usize) -> [(u32, &Buf); 25] {+ let b = 1 - a;+ [+ (2, &self.hist[a]),+ (3, &self.hist[b]),+ (4, &self.gb[a]),+ (5, &self.gb[b]),+ (6, &self.fa),+ (7, &self.fb),+ (8, &self.bloom[0]),+ (9, &self.bloom[1]),+ (14, &self.ae_state),+ (15, &self.lumq),+ (16, &self.lumb),+ (17, &self.alb[a]),+ (18, &self.alb[b]),+ (19, &self.shist[a]),+ (20, &self.shist[b]),+ (21, &self.mom[a]),+ (22, &self.mom[b]),+ (23, &self.sa),+ (24, &self.sb),+ (25, &self.kernel.refl),+ (26, &self.refl_res),+ (27, &self.kernel.motion),+ (28, &self.kernel.direct),+ (29, &self.xhist[a]),+ (30, &self.xhist[b]),+ ]+ }++ /// Two bind groups that swap history / g-buffer ping-pong roles on alternate frames. In the merged layout+ /// (merged.rs) they bind the same slabs, and differ in the offsets the passes read (`LO`).fn bind_groups(&self, d: &wgpu::Device, layout: &wgpu::BindGroupLayout, sample: &wgpu::Buffer) -> [wgpu::BindGroup; 2] {let mk = |a: usize| {- let b = 1 - a;fn e(binding: u32, buf: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {wgpu::BindGroupEntry { binding, resource: buf.as_entire_binding() }}- d.create_bind_group(&wgpu::BindGroupDescriptor {- label: Some("live"),- layout,- entries: &[- e(0, &self.params),- e(1, sample),- e(2, &self.hist[a]),- e(3, &self.hist[b]),- e(4, &self.gb[a]),- e(5, &self.gb[b]),- e(6, &self.fa),- e(7, &self.fb),- e(8, &self.bloom[0]),- e(9, &self.bloom[1]),- e(10, &self.out),- wgpu::BindGroupEntry { binding: 11, resource: wgpu::BindingResource::TextureView(&self.lut_view) },- wgpu::BindGroupEntry { binding: 12, resource: wgpu::BindingResource::Sampler(&self.sampler) },- e(13, &self.ae_bins),- e(14, &self.ae_state),- e(15, &self.lumq),- e(16, &self.lumb),- e(17, &self.alb[a]),- e(18, &self.alb[b]),- e(19, &self.shist[a]),- e(20, &self.shist[b]),- e(21, &self.mom[a]),- e(22, &self.mom[b]),- e(23, &self.sa),- e(24, &self.sb),- e(25, &self.refl),- e(26, &self.refl_res),- e(27, &self.motion),- e(28, &self.direct),- e(29, &self.xhist[a]),- e(30, &self.xhist[b]),- ],- })+ let mut entries = vec![+ e(0, &self.params),+ e(1, sample),+ e(10, &self.out),+ wgpu::BindGroupEntry { binding: 11, resource: wgpu::BindingResource::TextureView(&self.lut_view) },+ wgpu::BindGroupEntry { binding: 12, resource: wgpu::BindingResource::Sampler(&self.sampler) },+ e(13, &self.ae_bins),+ ];+ let buffers = self.buffers(a);+ let offsets;+ match (&self.slabs, &self.kernel.merged) {+ (Some(slabs), Some((live, _))) => {+ use crate::merged::{LIVE_BUFS, OFFSETS_BINDING, SLABS, SLAB_K};+ // Each merged buffer's (first element, length) in its slab, in `MergedOffsets`' order.+ let lo: Vec<[u32; 2]> = LIVE_BUFS+ .iter()+ .map(|m| {+ let buf = buffers.iter().find(|b| b.0 == m.binding).expect("a merged buffer's binding").1;+ let stride = SLABS[m.slab].stride;+ debug_assert!(buf.offset % stride == 0 && buf.size % stride == 0);+ [(buf.offset / stride) as u32, (buf.size / stride) as u32]+ })+ .collect();+ // (And the struct's unused last pair: `merged::OFFSETS_BYTES`.)+ let mut lo = lo;+ lo.push([0, 0]);+ debug_assert_eq!(lo.len() * 8, crate::merged::OFFSETS_BYTES);+ offsets = wgpu::util::DeviceExt::create_buffer_init(d, &wgpu::util::BufferInitDescriptor { label: Some("live offsets"), contents: bytemuck::cast_slice(&lo), usage: wgpu::BufferUsages::UNIFORM });+ entries.extend(slabs.iter().zip(&SLABS).map(|(s, m)| e(m.binding, s)));+ entries.push(e(SLABS[SLAB_K].binding, live));+ entries.push(e(OFFSETS_BINDING, &offsets));+ }+ _ => entries.extend(buffers.iter().map(|(binding, buf)| wgpu::BindGroupEntry { binding: *binding, resource: buf.binding() })),+ }+ d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("live"), layout, entries: &entries })};[mk(0), mk(1)]}@@ -872,7 +966,11 @@ fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Path, w: u32tables.defer_powers = emit.is_some();let (mat_runs, tri_order) = (std::mem::take(&mut prep.mat_runs), std::mem::take(&mut prep.tri_order));let fixed_features = (!sc.textures.is_empty(), !sc.shaders.is_empty(), prep.groups);- let up = g.upload(&sc, w, h, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;+ let mut up = g.upload(&sc, w, h, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;+ // The merged layout: the kernel written for this view's group-1 buffers (merged.rs).+ if let (Some(caps), Some((_, live))) = (&mut up.kernel.caps, &targets.kernel.merged) {+ caps.live = *live;+ }let _ = g.pipeline(&up.kernel, true); // compile the scene's kernel variant now, not in the first framelet sky_inputs = ((prep.env.width, prep.env.height), sc.camera.position.y.max(0.0), prep.env_nee_floor);let mut base = prep.params;@@ -1110,6 +1208,12 @@ pub struct LiveCore {pub cpu_wait_ms: f32,/// The cloud cover the sky and the sun light were made with (`move_sun`).sky_cover: f32,+ /// The loop guard (merged.rs `guard`), if the kernel has it: the invocations it has stopped at its limit since the+ /// view was made, as last read back (a frame or two behind, without waiting). Above zero: frames with wrong+ /// pixels, a traversal that did not end on the scene's data. None without the guard.+ pub guard_trips: Option<u32>,+ /// Its readback: the buffer and its state (0 free, 1 mapping, 2 mapped), as the frame timer's.+ guard_read: Option<(wgpu::Buffer, Arc<AtomicU32>)>,}/// GPU time per frame from timestamp queries (start of the first trace pass .. end of the post pass), read back a few@@ -1454,9 +1558,12 @@ impl LiveCore {/// A live view of the engine's world; asset files resolve against `assets`.pub fn new(g: gpu::Gpu, world: &World, assets: &Path, presets: &Path, w: u32, h: u32) -> Result<LiveCore> {- let passes = Passes::new(&g.device);+ let passes = Passes::new(&g);// The scene's post preset replaces this LUT below (apply_post).- let targets = Targets::new(&g, w, h, &vec![0u16; (LUT * LUT * LUT * 4) as usize]);+ let cache_on = !std::env::var("THREERT_CACHE").is_ok_and(|v| v == "0");+ let restir = std::env::var("THREERT_RESTIR").is_ok_and(|v| v == "1");+ // (Without the cache the kernel binds one of one entry; without ReSTIR, one reservoir.)+ let targets = Targets::new(&g, w, h, &vec![0u16; (LUT * LUT * LUT * 4) as usize], if cache_on { gpu::CACHE_SIZE } else { 1 }, if restir { w as u64 * h as u64 } else { 1 });let (sc, pp) = load_scene(&g, world, assets, presets, w, h, &targets, &passes)?;let cam = sc.scene_camera;let (triangles, scene_name) = (sc.triangles, sc.name.clone());@@ -1481,11 +1588,11 @@ impl LiveCore {});let timer = (g.timestamps && profile.is_none()).then(|| FrameTimer::new(&g.device));let raster = std::env::var("THREERT_RASTER").is_ok_and(|v| v == "1").then(|| Raster::new(&g, w, h));- let cache = (!std::env::var("THREERT_CACHE").is_ok_and(|v| v == "0")).then(|| RadianceCache { bufs: gpu::CacheBuffers::new(&g.device, gpu::CACHE_SIZE), resolve: g.cache_resolve_pipeline() });- let restir = std::env::var("THREERT_RESTIR").is_ok_and(|v| v == "1");- let resv = gpu::reservoirs(&g.device, if restir { w as u64 * h as u64 } else { 1 });- let kernel_bg = gpu::vis_bind_group(&g.device, &g.vis_layout, raster.as_ref().map_or(&g.no_vis_view, |r| &r.vis), &cache.as_ref().map_or_else(|| gpu::CacheBuffers::new(&g.device, 1), |c| gpu::CacheBuffers { keys: c.bufs.keys.clone(), acc: c.bufs.acc.clone(), val: c.bufs.val.clone() }), &resv, &targets.refl, &targets.motion, &targets.direct);- let mut core = LiveCore { particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, cap_next: None, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), still: 0, inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, motion_blur_off: false, ghost_fix_off: false, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, over_budget: (0, 0), profile, timer, raster, cache, restir, restir_prev: None, kernel_bg, prev_span: None, reposed: false, emitters_moved: false, cold_frames: 0, pose_span: None, pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), lit_changed: 0, spark_lights: false, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, sky_cover: 0.0 };+ let cache = cache_on.then(|| RadianceCache { bufs: targets.kernel.cache.clone(), resolve: g.cache_resolve_pipeline(&targets.kernel) });+ let kernel_bg = gpu::vis_bind_group(&g.device, &g.vis_layout, raster.as_ref().map_or(&g.no_vis_view, |r| &r.vis), &targets.kernel);+ let guard_read = (gpu::loop_guard().is_some() && targets.kernel.guard.is_some())+ .then(|| (g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("loop guard read"), size: 4, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }), Arc::new(AtomicU32::new(0))));+ let mut core = LiveCore { particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, cap_next: None, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), still: 0, inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, motion_blur_off: false, ghost_fix_off: false, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, over_budget: (0, 0), profile, timer, raster, cache, restir, restir_prev: None, kernel_bg, prev_span: None, reposed: false, emitters_moved: false, cold_frames: 0, pose_span: None, pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), lit_changed: 0, spark_lights: false, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, sky_cover: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);core.sky_cover = core.sc.tables.cloud_cover;core.apply_post(&pp);@@ -3436,6 +3543,20 @@ impl LiveCore {let _ = g.device.poll(wgpu::PollType::Wait { submission_index: Some(oldest), timeout: None });}let waited = t_wait.elapsed().as_secs_f32() * 1000.0;+ // The loop guard's count, read back since an earlier frame.+ let mut guard_free = false;+ if let Some((read, state)) = &self.guard_read {+ if state.load(Ordering::Acquire) == 2 {+ let n = u32::from_le_bytes(read.slice(..).get_mapped_range().unwrap()[..4].try_into().expect("four bytes"));+ read.unmap();+ state.store(0, Ordering::Release);+ if self.guard_trips != Some(n) {+ eprintln!("live: the loop guard has stopped {n} of the kernel's invocations: frames with wrong pixels (a traversal that does not end on this scene's data)");+ }+ self.guard_trips = Some(n);+ }+ guard_free = state.load(Ordering::Acquire) == 0;+ }// GPU time drives adaptive resolution / samples per frame: timestamps when available (no stall), else twice a// second a frame timed in isolation (idle GPU -> submit -> wait).let period = g.queue.get_timestamp_period();@@ -3529,6 +3650,10 @@ impl LiveCore {p.counts[3] = p.counts[3].min(2);g.queue.write_buffer(&self.sc.up.params, 0, bytemuck::bytes_of(&p));let mut e = g.device.create_command_encoder(&Default::default());+ // (The merged layout: the tables as this frame's edits left them, where the kernel reads them; merged.rs.)+ if k == 0 {+ g.sync_tables(&self.sc.up, &mut e);+ }// Particles: placed for this frame's time and camera, then the dynamic BLASes rebuilt (before the raster and// the trace).// The grid programs (density grids changed on the GPU), before anything reads the grids.@@ -3651,7 +3776,7 @@ impl LiveCore {// (Nothing to draw while every translucent particle system is hidden in place.)let tl = self.sc.up.translucent.as_ref().filter(|_| g.translucent_particles_live(&self.sc.up)).map(|t| {let pipes = g.translucent_pipelines(&self.sc.up.kernel, true);- let target = if lp.misc2[2] > 0.0 || lp.dof[0] > 0.0 { &self.targets.fb } else { &self.targets.fa };+ let target = if lp.misc2[2] > 0.0 || lp.dof[0] > 0.0 { &self.targets.fb.buffer } else { &self.targets.fa.buffer };// Below full resolution the particles are drawn per traced pixel, then laid over the output (`translucent_up`).let low = (iw, ih) != (w, h);let tp = gpu::TranslucentParams { size: [w, h, t.first, 1], view: [iw, ih, gpu::VOLUME_TRAIN_CAP, low as u32], misc: [VOLUME_TRAIN_SHARE, translucent_hidden(self.frame) as u32 as f32, 0.0, 0.0] };@@ -3737,10 +3862,18 @@ impl LiveCore {e.copy_buffer_to_buffer(&t.resolve, at, &t.reads[slot].0, 16, 16);}}+ if let (Some((read, _)), Some(count), true) = (&self.guard_read, &self.targets.kernel.guard, guard_free) {+ e.copy_buffer_to_buffer(&count.buffer, count.offset, read, 0, 4);+ }extra(&mut e, &self.targets.out);let done = g.queue.submit([e.finish()]);self.inflight.push_back(done);self.cpu_wait_ms = waited;+ if let (Some((read, state)), true) = (&self.guard_read, guard_free) {+ let state = state.clone();+ state.store(1, Ordering::Release);+ read.slice(..).map_async(wgpu::MapMode::Read, move |r| state.store(if r.is_ok() { 2 } else { 0 }, Ordering::Release));+ }if let (Some(t), Some(slot)) = (&self.timer, timed) {let state = t.reads[slot].1.clone();state.store(1, Ordering::Release);@@ -3805,7 +3938,7 @@ impl LiveCore {let size = self.w as u64 * self.h as u64 * 16;let read = d.create_buffer(&wgpu::BufferDescriptor { label: Some("hdr read"), size, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });let mut e = d.create_command_encoder(&Default::default());- e.copy_buffer_to_buffer(&self.targets.fa, 0, &read, 0, size);+ e.copy_buffer_to_buffer(&self.targets.fa.buffer, self.targets.fa.offset, &read, 0, size);self.g.queue.submit([e.finish()]);read.slice(..).map_async(wgpu::MapMode::Read, |_| {});d.poll(wgpu::PollType::wait_indefinitely())?;@@ -3824,10 +3957,10 @@ impl LiveCore {// The frame just rendered wrote the ping-pong histories at index frame % 2 (`bind_groups`: frame f writes 1 - f % 2).let k = (self.frame % 2) as usize;let t = &self.targets;- let read = |buf: &wgpu::Buffer, offset: u64, size: u64| -> Result<Vec<u8>> {+ let read = |buf: &Buf, offset: u64, size: u64| -> Result<Vec<u8>> {let r = d.create_buffer(&wgpu::BufferDescriptor { label: Some("signals read"), size, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });let mut e = d.create_command_encoder(&Default::default());- e.copy_buffer_to_buffer(buf, offset, &r, 0, size);+ e.copy_buffer_to_buffer(&buf.buffer, buf.offset + offset, &r, 0, size);self.g.queue.submit([e.finish()]);r.slice(..).map_async(wgpu::MapMode::Read, |_| {});d.poll(wgpu::PollType::wait_indefinitely())?;@@ -3861,7 +3994,7 @@ impl LiveCore {let d = &self.g.device;let read = d.create_buffer(&wgpu::BufferDescriptor { label: Some("ae read"), size: 16, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });let mut e = d.create_command_encoder(&Default::default());- e.copy_buffer_to_buffer(&self.targets.ae_state, 0, &read, 0, 16);+ e.copy_buffer_to_buffer(&self.targets.ae_state.buffer, self.targets.ae_state.offset, &read, 0, 16);self.g.queue.submit([e.finish()]);read.slice(..).map_async(wgpu::MapMode::Read, |_| {});d.poll(wgpu::PollType::wait_indefinitely())?;@@ -4163,7 +4296,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,+ "cpu": t_frame.elapsed().as_secs_f64() * 1e3, "script": game.frame_ms, "js": game.js_ms, "commit": game.commit_ms, "skin": core.cpu_skin_ms, "upload": core.cpu_upload_ms, "blas": core.gpu_blas_ms, "wait": core.cpu_wait_ms, "gpu": core.gpu_ms, "trace": core.gpu_trace_ms, "edit": core.edit_ms, "instanced": core.instanced_ms, "edit_split": [core.edit_split.tris, core.edit_split.upload, core.edit_split.blas, core.edit_split.added, core.edit_split.deformed, core.edit_split.objects], "rebuild": core.rebuild_ms, "fallback": core.fallback, "fallbacks": core.fallbacks, "room": core.room_stats(), "voxel": std::mem::take(&mut game.host.voxels.borrow_mut().ticks), "physics": game.host.physics.borrow_mut().as_mut().map(|p| { let s = p.take_stats(); serde_json::json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved }) }), "scale": core.render_scale, "history": core.history_len, "guard": core.guard_trips,});writeln!(l, "{line}")?;}diff --git a/renderer/src/merged.rs b/renderer/src/merged.rsnew file mode 100644index 0000000..3b39757--- /dev/null+++ b/renderer/src/merged.rs@@ -0,0 +1,639 @@+//! The merged binding layout: the engine's shaders with at most eight storage buffers a stage, WebGPU's default limit+//! (`maxStorageBuffersPerShaderStage`). The kernel binds 20 as it is written and the live passes 28: more than a+//! browser gives a page. There is one source: pathtrace.wgsl and live.wgsl, and the bindings gpu.rs and live.rs make for+//! them, are what the native renderer runs, unchanged. This module writes the browser's from them, as text (as+//! `gpu::kernel_source` patches the kernel for a scene's features), and gives the Rust side the numbers that go with+//! it. `THREERT_MERGED=1` runs the same layout natively (software traversal), so the tests that check the renderer+//! check it too (docs/RUNTIME.md "The engine in a browser").+//!+//! What is merged, and how:+//! - The kernel's seven tables (`TABLES`: materials, lights, emitters, texture pages, objects, instances, media)+//! become the arrays of one struct, `MT: MergedTables`, in one buffer. Their lengths are written into the source+//! (a struct's arrays are sized), each a power of two no less than `TABLE_MIN`, so a scene that grows compiles a+//! kernel again only when a table doubles. The renderer keeps writing its own buffers; each frame copies them into+//! the struct's (`Gpu::sync_tables`; they are small).+//! - The kernel's seven group-1 buffers (`KERNEL_LIVE`: the radiance cache, the reservoirs, what the live passes read+//! of a trace) become the arrays of `ML: MergedLive`, one buffer that they are ranges of (`gpu::KernelBufs`).+//! - The live passes' buffers of one element type are ranges of one slab each (`SLABS`), indexed from an offset+//! the pass reads from a uniform (`LO`): the source does not change with the size of the view, and the two+//! bind groups of the history's ping-pong are two sets of offsets. `MK` is the kernel's `ML` buffer read as vec4s.+//!+//! A use of a merged name the generator does not know (anything but `name[...]`, `&name[...]` and+//! `arrayLength(&name)`), a declaration that is not found exactly once, a name the generator adds that the source+//! already has: each stops the renderer with the name and the line. Locals and parameters that shadow a merged name+//! are followed through their scopes and left alone. The test below reads what comes out with naga: it is valid WGSL,+//! no stage has more than `STORAGE_BUFFERS`, and the structs' arrays are where the Rust side puts them.++/// WebGPU's default `maxStorageBuffersPerShaderStage`: what the merged layout fits.+pub const STORAGE_BUFFERS: u32 = 8;++/// One of the kernel's buffers that becomes an array of a merged struct.+pub struct Member {+ pub name: &'static str,+ /// Its element type, the element's size and alignment in a storage buffer.+ pub ty: &'static str,+ pub stride: u64,+ pub align: u64,+ /// Its declaration in pathtrace.wgsl, as written.+ pub decl: &'static str,+}++/// The kernel's tables, in `MergedTables`' order (group 0, binding `TABLES_BINDING`).+pub const TABLES: [Member; 7] = [+ Member { name: "materials", ty: "Material", stride: 288, align: 16, decl: "@group(0) @binding(4) var<storage, read> materials: array<Material>;" },+ Member { name: "lights", ty: "Light", stride: 80, align: 16, decl: "@group(0) @binding(5) var<storage, read> lights: array<Light>;" },+ Member { name: "emitters", ty: "vec4<f32>", stride: 16, align: 16, decl: "@group(0) @binding(6) var<storage, read> emitters: array<vec4<f32>>;" },+ Member { name: "tex_info", ty: "vec4<f32>", stride: 16, align: 16, decl: "@group(0) @binding(14) var<storage, read> tex_info: array<vec4<f32>>;" },+ Member { name: "objects", ty: "vec4<f32>", stride: 16, align: 16, decl: "@group(0) @binding(15) var<storage, read> objects: array<vec4<f32>>;" },+ Member { name: "instances", ty: "Instance", stride: 160, align: 16, decl: "@group(0) @binding(17) var<storage, read> instances: array<Instance>;" },+ Member { name: "media", ty: "Medium", stride: 224, align: 16, decl: "@group(0) @binding(18) var<storage, read> media: array<Medium>;" },+];+pub const TABLES_BINDING: u32 = 4;+/// The least length of each table's array: scenes below it share one kernel source.+pub const TABLE_MIN: [u32; 7] = [64, 64, 1024, 256, 1024, 64, 16];++/// The kernel's group-1 buffers, in `MergedLive`'s order (group 1, binding `KERNEL_LIVE_BINDING`).+pub const KERNEL_LIVE: [Member; 7] = [+ Member { name: "cache_keys", ty: "atomic<u32>", stride: 4, align: 4, decl: "@group(1) @binding(1) var<storage, read_write> cache_keys: array<atomic<u32>>;" },+ Member { name: "cache_acc", ty: "atomic<u32>", stride: 4, align: 4, decl: "@group(1) @binding(2) var<storage, read_write> cache_acc: array<atomic<u32>>;" },+ Member { name: "cache_val", ty: "vec4<f32>", stride: 16, align: 16, decl: "@group(1) @binding(3) var<storage, read_write> cache_val: array<vec4<f32>>;" },+ Member { name: "resv", ty: "vec4<u32>", stride: 16, align: 16, decl: "@group(1) @binding(4) var<storage, read_write> resv: array<vec4<u32>>;" },+ Member { name: "refl", ty: "vec4<f32>", stride: 16, align: 16, decl: "@group(1) @binding(5) var<storage, read_write> refl: array<vec4<f32>>;" },+ Member { name: "motion_out", ty: "vec4<f32>", stride: 16, align: 16, decl: "@group(1) @binding(6) var<storage, read_write> motion_out: array<vec4<f32>>;" },+ Member { name: "direct_out", ty: "vec4<f32>", stride: 16, align: 16, decl: "@group(1) @binding(7) var<storage, read_write> direct_out: array<vec4<f32>>;" },+];+pub const KERNEL_LIVE_BINDING: u32 = 1;+/// `MergedLive`'s last array, after `KERNEL_LIVE`'s: the loop guard's count (`guard`; its first word: the invocations+/// a loop of which was stopped). Always there in the merged layout, written only by a kernel with the guard.+pub const GUARD_TRIPS: Member = Member { name: "loop_guard_trips", ty: "atomic<u32>", stride: 4, align: 4, decl: "" };+/// The same count in the layout as written, when the kernel has the guard (group 1, binding `GUARD_BINDING`).+pub const GUARD_BINDING: u32 = 8;+pub const GUARD_WORDS: u32 = 4;++/// Where `MergedLive`'s arrays are for these lengths (bytes): `KERNEL_LIVE`'s seven, then the loop guard's count; and+/// the struct's size.+pub fn live_layout(caps: &[u32; 7]) -> (Vec<u64>, u64) {+ let members: Vec<&Member> = KERNEL_LIVE.iter().chain([&GUARD_TRIPS]).collect();+ let caps: Vec<u32> = caps.iter().copied().chain([GUARD_WORDS]).collect();+ let (mut at, mut out) = (0u64, vec![]);+ for (m, &c) in members.iter().zip(&caps) {+ at = at.next_multiple_of(m.align);+ out.push(at);+ at += m.stride * c as u64;+ }+ (out, at.next_multiple_of(16))+}++/// The lengths of the merged structs' arrays: what a kernel's source is written for (`gpu::Kernel::caps`).+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]+pub struct Caps {+ pub tables: [u32; 7],+ pub live: [u32; 7],+}++/// A table's array length for a buffer of `bytes`.+pub fn table_cap(k: usize, bytes: u64) -> u32 {+ (bytes.div_ceil(TABLES[k].stride).max(1) as u32).next_power_of_two().max(TABLE_MIN[k])+}++/// A group-1 buffer's array length: its own (the kernel reads some of them, `arrayLength`).+pub fn live_cap(k: usize, bytes: u64) -> u32 {+ assert_eq!(bytes % KERNEL_LIVE[k].stride, 0, "merged layout: {} of {bytes} bytes", KERNEL_LIVE[k].name);+ (bytes / KERNEL_LIVE[k].stride) as u32+}++/// Where a merged struct's arrays are (bytes), and the struct's size: WGSL's layout rules.+pub fn offsets(members: &[Member], caps: &[u32]) -> (Vec<u64>, u64) {+ let (mut at, mut out) = (0u64, vec![]);+ for (m, &c) in members.iter().zip(caps) {+ at = at.next_multiple_of(m.align);+ out.push(at);+ at += m.stride * c as u64;+ }+ (out, at.next_multiple_of(members.iter().map(|m| m.align).max().unwrap_or(1)))+}++/// A slab of the live passes: buffers of one element type as ranges of one buffer.+pub struct Slab {+ pub name: &'static str,+ pub ty: &'static str,+ pub stride: u64,+ pub binding: u32,+ pub read_only: bool,+}++pub const SLABS: [Slab; 5] = [+ Slab { name: "MV4", ty: "vec4<f32>", stride: 16, binding: 2, read_only: false },+ Slab { name: "MU2", ty: "vec2<u32>", stride: 8, binding: 4, read_only: false },+ Slab { name: "MF1", ty: "f32", stride: 4, binding: 15, read_only: false },+ Slab { name: "MU4", ty: "vec4<u32>", stride: 16, binding: 17, read_only: false },+ // The kernel's `ML` buffer (what the live passes read of a trace), as vec4s: every array of it starts at a+ // multiple of 16 bytes.+ Slab { name: "MK", ty: "vec4<f32>", stride: 16, binding: 25, read_only: true },+];+pub const SLAB_V4: usize = 0;+pub const SLAB_U2: usize = 1;+pub const SLAB_F1: usize = 2;+pub const SLAB_U4: usize = 3;+pub const SLAB_K: usize = 4;++/// One of the live passes' buffers that becomes a range of a slab: its binding in live.wgsl as written (what+/// `live::Targets` binds there), its slab, its declaration up to the `;`.+pub struct LiveBuf {+ pub name: &'static str,+ pub binding: u32,+ pub slab: usize,+ pub decl: &'static str,+}++/// In `MergedOffsets`' order (group 0, binding `OFFSETS_BINDING`: an (offset, length) pair of u32 each, in elements).+pub const LIVE_BUFS: [LiveBuf; 25] = [+ LiveBuf { name: "hist_in", binding: 2, slab: SLAB_V4, decl: "@group(0) @binding(2) var<storage, read> hist_in: array<vec4<f32>>;" },+ LiveBuf { name: "hist_out", binding: 3, slab: SLAB_V4, decl: "@group(0) @binding(3) var<storage, read_write> hist_out: array<vec4<f32>>;" },+ LiveBuf { name: "gb_in", binding: 4, slab: SLAB_U2, decl: "@group(0) @binding(4) var<storage, read> gb_in: array<vec2<u32>>;" },+ LiveBuf { name: "gb_out", binding: 5, slab: SLAB_U2, decl: "@group(0) @binding(5) var<storage, read_write> gb_out: array<vec2<u32>>;" },+ LiveBuf { name: "fa", binding: 6, slab: SLAB_V4, decl: "@group(0) @binding(6) var<storage, read_write> fa: array<vec4<f32>>;" },+ LiveBuf { name: "fb", binding: 7, slab: SLAB_V4, decl: "@group(0) @binding(7) var<storage, read_write> fb: array<vec4<f32>>;" },+ LiveBuf { name: "bloom_a", binding: 8, slab: SLAB_V4, decl: "@group(0) @binding(8) var<storage, read_write> bloom_a: array<vec4<f32>>;" },+ LiveBuf { name: "bloom_b", binding: 9, slab: SLAB_V4, decl: "@group(0) @binding(9) var<storage, read_write> bloom_b: array<vec4<f32>>;" },+ LiveBuf { name: "ae_state", binding: 14, slab: SLAB_V4, decl: "@group(0) @binding(14) var<storage, read_write> ae_state: array<vec4<f32>, 2>;" },+ LiveBuf { name: "lumq", binding: 15, slab: SLAB_F1, decl: "@group(0) @binding(15) var<storage, read_write> lumq: array<f32>;" },+ LiveBuf { name: "lumb", binding: 16, slab: SLAB_F1, decl: "@group(0) @binding(16) var<storage, read_write> lumb: array<f32>;" },+ LiveBuf { name: "ae_in", binding: 17, slab: SLAB_U4, decl: "@group(0) @binding(17) var<storage, read> ae_in: array<vec4<u32>>;" },+ LiveBuf { name: "ae_out", binding: 18, slab: SLAB_U4, decl: "@group(0) @binding(18) var<storage, read_write> ae_out: array<vec4<u32>>;" },+ LiveBuf { name: "shist_in", binding: 19, slab: SLAB_V4, decl: "@group(0) @binding(19) var<storage, read> shist_in: array<vec4<f32>>;" },+ LiveBuf { name: "shist_out", binding: 20, slab: SLAB_V4, decl: "@group(0) @binding(20) var<storage, read_write> shist_out: array<vec4<f32>>;" },+ LiveBuf { name: "mom_in", binding: 21, slab: SLAB_V4, decl: "@group(0) @binding(21) var<storage, read> mom_in: array<vec4<f32>>;" },+ LiveBuf { name: "mom_out", binding: 22, slab: SLAB_V4, decl: "@group(0) @binding(22) var<storage, read_write> mom_out: array<vec4<f32>>;" },+ LiveBuf { name: "spec_pp", binding: 23, slab: SLAB_U2, decl: "@group(0) @binding(23) var<storage, read_write> spec_pp: array<vec2<u32>>;" },+ LiveBuf { name: "sb", binding: 24, slab: SLAB_V4, decl: "@group(0) @binding(24) var<storage, read_write> sb: array<vec4<f32>>;" },+ LiveBuf { name: "refl_in", binding: 25, slab: SLAB_K, decl: "@group(0) @binding(25) var<storage, read> refl_in: array<vec4<f32>>;" },+ LiveBuf { name: "refl_res", binding: 26, slab: SLAB_V4, decl: "@group(0) @binding(26) var<storage, read_write> refl_res: array<vec4<f32>>;" },+ LiveBuf { name: "motion_in", binding: 27, slab: SLAB_K, decl: "@group(0) @binding(27) var<storage, read> motion_in: array<vec4<f32>>;" },+ LiveBuf { name: "direct_in", binding: 28, slab: SLAB_K, decl: "@group(0) @binding(28) var<storage, read> direct_in: array<vec4<f32>>;" },+ LiveBuf { name: "xhist_in", binding: 29, slab: SLAB_V4, decl: "@group(0) @binding(29) var<storage, read> xhist_in: array<vec4<f32>>;" },+ LiveBuf { name: "xhist_out", binding: 30, slab: SLAB_V4, decl: "@group(0) @binding(30) var<storage, read_write> xhist_out: array<vec4<f32>>;" },+];+pub const OFFSETS_BINDING: u32 = 31;+/// `MergedOffsets`' size: a pair for each of `LIVE_BUFS`, and one unused that makes it a multiple of 16 bytes.+pub const OFFSETS_BYTES: usize = (LIVE_BUFS.len() + 1) * 8;++/// The live passes' storage bindings that stay as they are: (binding, read only).+pub const LIVE_KEPT: [(u32, bool); 3] = [(1, true), (10, false), (13, false)];++/// How a merged name's uses are rewritten.+struct Rule {+ name: &'static str,+ /// What `name[` becomes, and what goes before the `]` that closes it.+ open: String,+ close: &'static str,+ /// What `arrayLength(&name)` becomes.+ len: String,+}++fn fail(what: &str, src: &str, at: usize) -> ! {+ panic!("merged layout: {what} (line {})", src[..at].matches('\n').count() + 1)+}++/// The identifier at `i` (bytes), if one starts there.+fn ident(b: &[u8], i: usize) -> Option<usize> {+ let start = |c: u8| c.is_ascii_alphabetic() || c == b'_';+ if i >= b.len() || !start(b[i]) {+ return None;+ }+ let mut j = i + 1;+ while j < b.len() && (start(b[j]) || b[j].is_ascii_digit()) {+ j += 1;+ }+ Some(j)+}++fn skip_space(b: &[u8], mut i: usize) -> usize {+ while i < b.len() && b[i].is_ascii_whitespace() {+ i += 1;+ }+ i+}++/// Rewrites every use of the rules' names in `src` (WGSL): a scan that knows comments, blocks and the locals and+/// parameters that shadow a name (from the end of their declaration to the end of their block).+fn rewrite(src: &str, rules: &[Rule]) -> String {+ let b = src.as_bytes();+ let rule = |name: &[u8]| rules.iter().position(|r| r.name.as_bytes() == name);+ let mut out: Vec<u8> = Vec::with_capacity(b.len() + b.len() / 16);+ // Blocks and brackets open; the brackets a rewritten index closes with more than `]`.+ let (mut depth, mut brackets, mut parens) = (0usize, 0usize, 0usize);+ let mut closes: Vec<(usize, &'static str)> = vec![];+ // Names shadowed, each with the block depth it lives in; those declared in the statement being read.+ let mut shadows: Vec<(usize, usize)> = vec![];+ let mut pending: Vec<(usize, usize)> = vec![];+ // The last byte of code before here (not space, not comment); after `var` / `let` / `const` in a function; in a+ // function's header (its parameters).+ let (mut last, mut declares, mut header) = (0u8, false, false);+ let mut i = 0;+ while i < b.len() {+ if b[i..].starts_with(b"//") {+ let j = b[i..].iter().position(|&c| c == b'\n').map_or(b.len(), |k| i + k);+ out.extend_from_slice(&b[i..j]);+ i = j;+ continue;+ }+ if b[i..].starts_with(b"/*") {+ let j = src[i + 2..].find("*/").map_or(b.len(), |k| i + 2 + k + 2);+ out.extend_from_slice(&b[i..j]);+ i = j;+ continue;+ }+ let Some(j) = ident(b, i) else {+ let c = b[i];+ match c {+ b'{' => {+ depth += 1;+ header = false;+ }+ b'}' => {+ depth = depth.checked_sub(1).unwrap_or_else(|| fail("an unmatched }", src, i));+ shadows.retain(|s| s.1 <= depth);+ }+ b';' => shadows.append(&mut pending),+ b'(' => parens += 1,+ b')' => parens = parens.saturating_sub(1),+ b'[' => brackets += 1,+ b']' => {+ if closes.last().is_some_and(|c| c.0 == brackets) {+ out.extend_from_slice(closes.pop().unwrap().1.as_bytes());+ }+ brackets = brackets.checked_sub(1).unwrap_or_else(|| fail("an unmatched ]", src, i));+ }+ _ => {}+ }+ if !c.is_ascii_whitespace() {+ last = c;+ }+ out.push(c);+ i += 1;+ continue;+ };+ let word = &b[i..j];+ let after = skip_space(b, j);+ let next = b.get(after).copied().unwrap_or(0);+ let (was, declared) = (last, std::mem::take(&mut declares));+ last = b'a';+ if depth > 0 && matches!(word, b"var" | b"let" | b"const") {+ declares = true;+ } else if depth == 0 && word == b"fn" {+ header = true;+ } else if word == b"arrayLength" && next == b'(' {+ // `arrayLength(&name)` of a merged name that nothing shadows: its length.+ let amp = skip_space(b, after + 1);+ if b.get(amp) == Some(&b'&') {+ let n0 = skip_space(b, amp + 1);+ if let Some(n1) = ident(b, n0) {+ let end = skip_space(b, n1);+ if let Some(r) = rule(&b[n0..n1]).filter(|r| !shadows.iter().any(|s| s.0 == *r)) {+ if b.get(end) != Some(&b')') {+ fail(&format!("arrayLength of something inside `{}`", rules[r].name), src, i);+ }+ out.extend_from_slice(rules[r].len.as_bytes());+ last = b')';+ i = end + 1;+ continue;+ }+ }+ }+ } else if let Some(r) = rule(word) {+ let name = rules[r].name;+ if declared {+ // A local of that name: it shadows the buffer from the end of this statement to the end of its block+ // (a `for`'s own variable: the loop's block).+ pending.push((r, depth + (parens > 0) as usize));+ } else if was == b'.' {+ // A member of something else.+ } else if next == b':' && b.get(after + 1) != Some(&b':') {+ // A parameter of that name shadows the buffer in the function's body; a struct's member does nothing.+ if header {+ shadows.push((r, 1));+ }+ } else if shadows.iter().any(|s| s.0 == r) {+ // The local.+ } else if next == b'[' {+ out.extend_from_slice(rules[r].open.as_bytes());+ brackets += 1;+ if !rules[r].close.is_empty() {+ closes.push((brackets, rules[r].close));+ }+ last = b'[';+ i = after + 1;+ continue;+ } else {+ fail(&format!("`{name}` is used in a way the generator does not know"), src, i);+ }+ }+ out.extend_from_slice(word);+ i = j;+ }+ if depth != 0 || brackets != 0 || !closes.is_empty() {+ fail("unbalanced braces or brackets", src, b.len());+ }+ String::from_utf8(out).expect("the source's own bytes")+}++/// Takes the declaration `decl` out of `s` (it is there exactly once), leaving `with` in its place.+fn take(s: &mut String, decl: &str, with: &str) {+ assert_eq!(s.matches(decl).count(), 1, "merged layout: the declaration {decl:?}");+ *s = s.replacen(decl, with, 1);+}++/// Stops if the source already has a name the generator adds.+fn fresh(src: &str, names: &[&str]) {+ let b = src.as_bytes();+ let mut i = 0;+ while i < b.len() {+ if b[i..].starts_with(b"//") {+ i = b[i..].iter().position(|&c| c == b'\n').map_or(b.len(), |k| i + k);+ } else if let Some(j) = ident(b, i) {+ if names.iter().any(|n| n.as_bytes() == &b[i..j]) {+ fail(&format!("the source already has a `{}`", &src[i..j]), src, i);+ }+ i = j;+ } else {+ i += 1;+ }+ }+}++fn merged_struct(name: &str, members: &[&Member], caps: &[u32]) -> String {+ let fields: Vec<String> = members.iter().zip(caps).map(|(m, c)| format!(" {}: array<{}, {c}>,", m.name, m.ty)).collect();+ format!("struct {name} {{\n{}\n}};\n", fields.join("\n"))+}++/// The kernel (pathtrace.wgsl as a scene's variant: `gpu::kernel_source`, its functions spliced in) in the merged+/// layout for arrays of `caps`' lengths: group 0 binds tri_verts, attrs, nodes, `MT`, env_cdf, accum and prev_verts,+/// group 1 `ML`.+pub fn kernel(src: &str, caps: &Caps) -> String {+ fresh(src, &["MT", "ML", "MergedTables", "MergedLive", GUARD_TRIPS.name]);+ let mut s = src.to_string();+ for (k, m) in TABLES.iter().enumerate() {+ let with = if k == 0 {+ format!("{}@group(0) @binding({TABLES_BINDING}) var<storage, read> MT: MergedTables;", merged_struct("MergedTables", &TABLES.iter().collect::<Vec<_>>(), &caps.tables))+ } else {+ String::new()+ };+ take(&mut s, m.decl, &with);+ }+ for (k, m) in KERNEL_LIVE.iter().enumerate() {+ let with = if k == 0 {+ format!("{}@group(1) @binding({KERNEL_LIVE_BINDING}) var<storage, read_write> ML: MergedLive;", merged_struct("MergedLive", &KERNEL_LIVE.iter().chain([&GUARD_TRIPS]).collect::<Vec<_>>(), &caps.live.iter().copied().chain([GUARD_WORDS]).collect::<Vec<_>>()))+ } else {+ String::new()+ };+ take(&mut s, m.decl, &with);+ }+ let rule = |var: &str, m: &Member, cap: u32| Rule { name: m.name, open: format!("{var}.{}[", m.name), close: "", len: format!("{cap}u") };+ let rules: Vec<Rule> = TABLES.iter().zip(caps.tables).map(|(m, c)| rule("MT", m, c)).chain(KERNEL_LIVE.iter().zip(caps.live).map(|(m, c)| rule("ML", m, c))).collect();+ rewrite(&s, &rules)+}++/// The live passes (live.wgsl) in the merged layout: sample_px, out_px and ae_bins as they are, the slabs, and the+/// offsets `LO`.+pub fn live(src: &str) -> String {+ let mut names: Vec<&str> = SLABS.iter().map(|s| s.name).collect();+ names.extend(["LO", "MergedOffsets", "merged_pad"]);+ fresh(src, &names);+ let mut s = src.to_string();+ for b in LIVE_BUFS.iter() {+ take(&mut s, b.decl, "");+ }+ // (A last pair unused: the struct is 208 bytes, a multiple of 16. WebGPU does not ask for that, but wgpu's+ // downlevel targets do of a uniform binding's size, and it costs nothing; `OFFSETS_BYTES`.)+ let fields: Vec<String> = LIVE_BUFS.iter().map(|b| format!(" {}: vec2<u32>,", b.name)).chain([" merged_pad: vec2<u32>,".to_string()]).collect();+ let mut head = format!("// The merged layout (renderer/src/merged.rs): each buffer's (first element, length) in its slab.\nstruct MergedOffsets {{\n{}\n}};\n@group(0) @binding({OFFSETS_BINDING}) var<uniform> LO: MergedOffsets;\n", fields.join("\n"));+ for sl in &SLABS {+ head += &format!("@group(0) @binding({}) var<storage, {}> {}: array<{}>;\n", sl.binding, if sl.read_only { "read" } else { "read_write" }, sl.name, sl.ty);+ }+ // After the uniforms' declaration (the file's first binding).+ let anchor = "@group(0) @binding(0) var<uniform> L: LiveParams;\n";+ take(&mut s, anchor, &format!("{anchor}{head}"));+ let rules: Vec<Rule> = LIVE_BUFS.iter().map(|b| Rule { name: b.name, open: format!("{}[LO.{}.x + (", SLABS[b.slab].name, b.name), close: ")", len: format!("LO.{}.y", b.name) }).collect();+ rewrite(&s, &rules)+}++/// A bound on every loop of a shader: each `loop`, `for` and `while` body begins with a count of the invocation's+/// loop iterations so far, and leaves the loop past `limit`. The kernel's traversals (the BVH, the light tree, the+/// procedural boxes) follow indices they read from buffers and end only if the data is sound: on data that is not, a+/// dispatch never ends, and a GPU that never gets a dispatch back takes the whole machine's display with it (it did:+/// docs/RUNTIME.md "The engine in a browser"). With the bound a dispatch always ends: wrong pixels instead of no+/// frame. No formula changes, but the image is not bit-identical to the kernel's without the guard: the compiler+/// arranges the arithmetic of the functions it is in differently (hello world, one sample a pixel: 354 of 43,200+/// numbers differ, by at most 2 x 10^-7 of their value). Between the two layouts, guard or not, the bytes are equal.+/// `THREERT_LOOP_GUARD=<limit>` natively (`gpu::loop_guard`); a browser's kernel always has it.+///+/// A stopped loop is counted, not hidden: the invocation that reaches the limit adds one to the first word of `trips`+/// (an `array<atomic<u32>, 4>` the source can name: `ML.loop_guard_trips` in the merged layout, the buffer `guard_decl`+/// declares in the layout as written), which the renderer reads back (`live::LiveCore::guard_trips`, an offline+/// render's error). A frame with a count above zero is a frame with wrong pixels, and says so.+pub fn guard(src: &str, limit: u32, trips: &str) -> String {+ fresh(src, &["loop_guard", "LOOP_GUARD_N"]);+ let b = src.as_bytes();+ let mut out: Vec<u8> = Vec::with_capacity(b.len() + 4096);+ let mut i = 0;+ while i < b.len() {+ if b[i..].starts_with(b"//") {+ let j = b[i..].iter().position(|&c| c == b'\n').map_or(b.len(), |k| i + k);+ out.extend_from_slice(&b[i..j]);+ i = j;+ continue;+ }+ if b[i..].starts_with(b"/*") {+ let j = src[i + 2..].find("*/").map_or(b.len(), |k| i + 2 + k + 2);+ out.extend_from_slice(&b[i..j]);+ i = j;+ continue;+ }+ let Some(j) = ident(b, i) else {+ out.push(b[i]);+ i += 1;+ continue;+ };+ let word = &b[i..j];+ let mut body = None;+ let after = skip_space(b, j);+ if word == b"loop" && b.get(after) == Some(&b'{') {+ body = Some(after);+ } else if matches!(word, b"for" | b"while") && b.get(after) == Some(&b'(') {+ // The header's closing parenthesis, then the body.+ let (mut depth, mut k) = (0usize, after);+ while k < b.len() {+ match b[k] {+ b'(' => depth += 1,+ b')' => {+ depth -= 1;+ if depth == 0 {+ break;+ }+ }+ _ => {}+ }+ k += 1;+ }+ let open = skip_space(b, k + 1);+ if b.get(open) != Some(&b'{') {+ fail("a loop without a body the guard can open", src, i);+ }+ body = Some(open);+ }+ match body {+ Some(open) => {+ out.extend_from_slice(&b[i..=open]);+ out.extend_from_slice(b" if (loop_guard()) { break; }");+ i = open + 1;+ }+ None => {+ out.extend_from_slice(word);+ i = j;+ }+ }+ }+ let mut s = String::from_utf8(out).expect("the source's own bytes");+ s += &format!("\n// The loop guard (renderer/src/merged.rs `guard`): an invocation's loop iterations, all its loops together; the\n// invocations stopped at the limit are counted.\nvar<private> LOOP_GUARD_N: u32 = 0u;\nfn loop_guard() -> bool {{\n LOOP_GUARD_N += 1u;\n if (LOOP_GUARD_N == {limit}u + 1u) {{ atomicAdd(&{trips}[0], 1u); }}\n return LOOP_GUARD_N > {limit}u;\n}}\n");+ s+}++/// The loop guard's count as a buffer of its own, for a kernel in the layout as written (the merged layout has it in+/// `MergedLive`): the declaration `guard`'s `trips` names.+pub fn guard_decl() -> String {+ format!("@group(1) @binding({GUARD_BINDING}) var<storage, read_write> {}: array<atomic<u32>, {GUARD_WORDS}>;\n", GUARD_TRIPS.name)+}++#[cfg(test)]+mod tests {+ use super::*;++ const KERNEL: &str = include_str!("../shaders/pathtrace.wgsl");+ const LIVE: &str = include_str!("../shaders/live.wgsl");++ fn caps() -> Caps {+ // A cache of one entry, a view of 64 x 36: lengths that are not round.+ let n = 64 * 36;+ Caps { tables: TABLE_MIN, live: [1, 8, 2, 4, 2 * n, n, n] }+ }++ fn parse(src: &str) -> (naga::Module, naga::valid::ModuleInfo) {+ let m = naga::front::wgsl::parse_str(src).unwrap_or_else(|e| panic!("{}", e.emit_to_string(src)));+ let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all()).validate(&m).unwrap_or_else(|e| panic!("{}", e.emit_to_string(src)));+ (m, info)+ }++ /// The storage buffers each entry point of a module uses, and the module declares.+ fn storage_buffers(m: &naga::Module, info: &naga::valid::ModuleInfo) -> (Vec<(String, usize)>, usize) {+ let storage = |v: &naga::GlobalVariable| matches!(v.space, naga::AddressSpace::Storage { .. });+ let used = m.entry_points.iter().enumerate().map(|(k, e)| (e.name.clone(), m.global_variables.iter().filter(|(h, v)| storage(v) && !info.get_entry_point(k)[*h].is_empty()).count())).collect();+ (used, m.global_variables.iter().filter(|(_, v)| storage(v)).count())+ }++ /// The members' offsets and the size of a struct as the shader compiler lays it out.+ fn layout(m: &naga::Module, name: &str) -> (Vec<u64>, u64) {+ let (_, ty) = m.types.iter().find(|(_, t)| t.name.as_deref() == Some(name)).unwrap_or_else(|| panic!("no struct {name}"));+ match &ty.inner {+ naga::TypeInner::Struct { members, span } => (members.iter().map(|m| m.offset as u64).collect(), *span as u64),+ _ => panic!("{name} is not a struct"),+ }+ }++ /// Every kernel variant the source patches make, in the merged layout: valid WGSL, no entry point with more than+ /// eight storage buffers, none declared beyond them (a pipeline layout counts what is declared), and the merged+ /// structs' arrays where `offsets` puts them. The source as written has 20, so the count is the generator's.+ #[test]+ fn the_merged_kernel_fits_eight_storage_buffers() {+ let (m, info) = parse(KERNEL);+ let (used, declared) = storage_buffers(&m, &info);+ assert_eq!(declared, 20, "the kernel as written");+ assert_eq!(used.iter().map(|u| u.1).max(), Some(20), "{used:?}");+ let caps = caps();+ for features in [0, crate::gpu::F_VCOLOR, crate::gpu::F_GRID, crate::gpu::F_TINT | crate::gpu::F_UNLIT | crate::gpu::F_BACKGROUND, crate::gpu::F_SOURCE] {+ let src = kernel(&crate::gpu::kernel_source(KERNEL, features), &caps);+ let (m, info) = parse(&src);+ let (used, declared) = storage_buffers(&m, &info);+ assert!(declared as u32 <= STORAGE_BUFFERS, "features {features:#x}: {declared} declared");+ assert!(used.iter().all(|u| u.1 as u32 <= STORAGE_BUFFERS), "features {features:#x}: {used:?}");+ assert_eq!(used.iter().find(|u| u.0 == "main").map(|u| u.1), Some(8), "the trace reads all eight");+ assert_eq!(layout(&m, "MergedTables"), offsets(&TABLES, &caps.tables));+ assert_eq!(layout(&m, "MergedLive"), live_layout(&caps.live));+ }+ }++ /// The same for the live passes (28 as written).+ #[test]+ fn the_merged_live_passes_fit_eight_storage_buffers() {+ let (m, info) = parse(LIVE);+ assert_eq!(storage_buffers(&m, &info).1, 28, "the live passes as written");+ let passes = m.entry_points.len();+ let (m, info) = parse(&live(LIVE));+ let (used, declared) = storage_buffers(&m, &info);+ assert_eq!(declared as u32, STORAGE_BUFFERS);+ assert!(used.iter().all(|u| u.1 as u32 <= STORAGE_BUFFERS), "{used:?}");+ assert_eq!(used.len(), passes, "every pass is still there");+ // The offsets' struct: a pair of u32 each, in order (what `live::Targets` writes).+ assert_eq!(layout(&m, "MergedOffsets"), ((0..26).map(|k| k * 8).collect(), OFFSETS_BYTES as u64));+ assert_eq!(OFFSETS_BYTES % 16, 0);+ assert_eq!(LIVE_BUFS.len(), 25);+ }++ /// The Rust side's records are the size the merged structs give their elements.+ #[test]+ fn the_tables_strides_are_the_records() {+ use crate::scene::{GpuInstance, GpuLight, GpuMaterial, MediumGpu};+ let sizes = [std::mem::size_of::<GpuMaterial>(), std::mem::size_of::<GpuLight>(), 16, 16, 16, std::mem::size_of::<GpuInstance>(), std::mem::size_of::<MediumGpu>()];+ assert_eq!(TABLES.iter().map(|m| m.stride as usize).collect::<Vec<_>>(), sizes);+ assert_eq!(table_cap(0, 0), 64);+ assert_eq!(table_cap(0, 288 * 65), 128);+ assert_eq!(table_cap(2, 512), 1024);+ }++ /// The scan follows scopes: a local or a parameter of a merged name is left alone, from the end of its+ /// declaration to the end of its block; comments are not read.+ #[test]+ fn locals_that_shadow_a_buffer_are_left_alone() {+ let rules = [Rule { name: "refl", open: "ML.refl[".into(), close: "", len: "7u".into() }, Rule { name: "fa", open: "MV4[LO.fa.x + (".into(), close: ")", len: "LO.fa.y".into() }];+ let src = "struct S { refl: f32 };\nfn f(i: u32) -> f32 {\n let a = refl[i].x; // refl[0] }\n {\n let refl = refl[i + 1u].y;\n if (refl > 0.0) { return refl; }\n }\n var s: S;\n return s.refl + refl[arrayLength(&refl) - 1u].x + fa[fa[i].x].y;\n}\nfn g(refl: array<f32, 4>) -> f32 { return refl[1]; }\nfn h() -> f32 { return refl[2].x; }\n";+ let want = "struct S { refl: f32 };\nfn f(i: u32) -> f32 {\n let a = ML.refl[i].x; // refl[0] }\n {\n let refl = ML.refl[i + 1u].y;\n if (refl > 0.0) { return refl; }\n }\n var s: S;\n return s.refl + ML.refl[7u - 1u].x + MV4[LO.fa.x + (MV4[LO.fa.x + (i)].x)].y;\n}\nfn g(refl: array<f32, 4>) -> f32 { return refl[1]; }\nfn h() -> f32 { return ML.refl[2].x; }\n";+ assert_eq!(rewrite(src, &rules), want);+ }++ /// The loop guard opens every loop of the kernel and of the live passes, in the layout as written and in the+ /// merged one, and what comes out is valid WGSL.+ #[test]+ fn the_guard_bounds_every_loop() {+ let loops = |s: &str| {+ let code: String = s.lines().map(|l| l.split("//").next().unwrap_or("")).collect::<Vec<_>>().join("\n");+ let words = |w: &str| code.match_indices(w).filter(|(k, _)| !code[..*k].ends_with(|c: char| c.is_alphanumeric() || c == '_')).count();+ words("loop {") + words("for (") + words("while (")+ };+ // The kernel as written (its count a buffer of its own) and merged (its count in `MergedLive`).+ let merged = kernel(&crate::gpu::kernel_source(KERNEL, crate::gpu::F_SOURCE), &caps());+ for (src, trips) in [(format!("{KERNEL}{}", guard_decl()), "loop_guard_trips"), (merged, "ML.loop_guard_trips")] {+ let g = guard(&src, 1 << 16, trips);+ assert!(loops(&src) > 40, "the kernel's loops");+ assert_eq!(g.matches("if (loop_guard()) { break; }").count(), loops(&src));+ let (m, info) = parse(&g);+ let (used, declared) = storage_buffers(&m, &info);+ // (As written: one buffer more, where the device has room. Merged: still eight.)+ assert!(declared == 21 || declared as u32 == STORAGE_BUFFERS, "{declared}: {used:?}");+ }+ let g = guard("fn f() {\n for (var i = 0u; i < n(2u); i++) { x(); }\n loop { // {\n break;\n }\n while (a) { }\n}\n", 9, "T");+ assert!(g.starts_with("fn f() {\n for (var i = 0u; i < n(2u); i++) { if (loop_guard()) { break; } x(); }\n loop { if (loop_guard()) { break; } // {\n break;\n }\n while (a) { if (loop_guard()) { break; } }\n}\n"), "{g}");+ assert!(g.ends_with("fn loop_guard() -> bool {\n LOOP_GUARD_N += 1u;\n if (LOOP_GUARD_N == 9u + 1u) { atomicAdd(&T[0], 1u); }\n return LOOP_GUARD_N > 9u;\n}\n"), "{g}");+ }++ #[test]+ #[should_panic(expected = "`refl` is used in a way the generator does not know (line 2)")]+ fn a_use_the_generator_does_not_know_stops_it() {+ rewrite("fn f() {\n let p = &refl;\n}\n", &[Rule { name: "refl", open: "ML.refl[".into(), close: "", len: "7u".into() }]);+ }++ #[test]+ #[should_panic(expected = "the declaration")]+ fn a_declaration_that_moved_stops_it() {+ kernel(&KERNEL.replace("var<storage, read> lights: array<Light>;", "var<storage, read> lights: array<Light>;"), &caps());+ }+}diff --git a/renderer/src/script.rs b/renderer/src/script.rsindex 7597d2b..ec283cb 100644--- a/renderer/src/script.rs+++ b/renderer/src/script.rs@@ -8,10 +8,8 @@//! monotonic clock and the engine API. Memory is capped and every call runs under a time budget (the interrupt//! handler aborts it).-use crate::desc;-use crate::world::{Geometry, Kind, Settings, Texture, TextureSource, World};+use crate::world::World;use anyhow::{anyhow, Result};-use glam::{Quat, Vec3};use rquickjs::{CatchResultExt, Context, Ctx, Exception, Function, Module, Object, Runtime, TypedArray, Value};use std::cell::RefCell;use std::rc::Rc;@@ -130,86 +128,57 @@ fn fail(ctx: &Ctx, e: anyhow::Error) -> rquickjs::Error {Exception::throw_message(ctx, &format!("{e:#}"))}-/// The engine API (`globalThis.__engine`), see packages/scene/src/engine.ts.+/// A failed engine call as the exception scene code catches (`api::Error`).+fn thrown(ctx: &Ctx, e: crate::api::Error) -> rquickjs::Error {+ match e {+ crate::api::Error::Type(m) => Exception::throw_type(ctx, &m),+ crate::api::Error::Other(e) => fail(ctx, e),+ }+}++/// The engine API (`globalThis.__engine`), see packages/scene/src/engine.ts: each call's arguments out of QuickJS,+/// then what the call does (api.rs: the same code a browser's exports run, renderer/web).fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<RefCell<crate::voxel::VoxelWorld>>, physics: &Rc<RefCell<Option<crate::physics::PhysicsWorld>>>) -> rquickjs::Result<()> {+ use crate::api;let e = Object::new(ctx.clone())?;// Physics (renderer/src/physics.rs): one call, `physics(op, args)`, answering in JSON. The world is made by the// first call; the engine steps it, scene code cannot.let (p, w) = (physics.clone(), world.clone());e.set("physics", Function::new(ctx.clone(), move |ctx: Ctx<'js>, op: String, args: Value<'js>| -> rquickjs::Result<String> {let a: serde_json::Value = if args.is_undefined() || args.is_null() { serde_json::Value::Null } else { parse(&ctx, "physics", &args)? };- let out = p.borrow_mut().get_or_insert_with(Default::default).call(&mut w.borrow_mut(), &op, &a).map_err(|e| fail(&ctx, e))?;- Ok(out.to_string())+ api::physics(&mut p.borrow_mut(), &mut w.borrow_mut(), &op, &a).map_err(|e| thrown(&ctx, e))})?)?;// The poses of the objects that bodies drive, by the slot the binding gave each body (7 floats: position, rotation// xyzw, as scene code reads an object's): one copy for all a frame reads. Empty without a world.let p = physics.clone();- e.set("physicsPoses", Function::new(ctx.clone(), move |ctx: Ctx<'js>| -> rquickjs::Result<TypedArray<'js, f32>> { TypedArray::new(ctx, p.borrow().as_ref().map_or(vec![], |p| p.poses().to_vec())) })?)?;+ e.set("physicsPoses", Function::new(ctx.clone(), move |ctx: Ctx<'js>| -> rquickjs::Result<TypedArray<'js, f32>> { TypedArray::new(ctx, api::physics_poses(&p.borrow()).to_vec()) })?)?;// The voxel engine's level and explosions (renderer/src/voxel.rs): the level is loaded natively once the session// knows the asset root; an explosion returns what it did as JSON.let v = voxels.clone();- e.set("voxelLevel", Function::new(ctx.clone(), move |ctx: Ctx, d: Value| -> rquickjs::Result<()> {- let d: crate::voxel::LevelDesc = parse(&ctx, "voxelLevel", &d)?;- v.borrow_mut().request(d).map_err(|e| fail(&ctx, e))- })?)?;+ e.set("voxelLevel", Function::new(ctx.clone(), move |ctx: Ctx, d: Value| -> rquickjs::Result<()> { api::voxel_level(&mut v.borrow_mut(), &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;let (v, w) = (voxels.clone(), world.clone());- e.set("voxelExplode", Function::new(ctx.clone(), move |ctx: Ctx, x: f64, y: f64, z: f64, r: f64| -> rquickjs::Result<String> {- let out = v.borrow_mut().explode(&mut w.borrow_mut(), glam::Vec3::new(x as f32, y as f32, z as f32), r as f32).map_err(|e| fail(&ctx, e))?;- Ok(out.to_string())- })?)?;+ e.set("voxelExplode", Function::new(ctx.clone(), move |ctx: Ctx, x: f64, y: f64, z: f64, r: f64| -> rquickjs::Result<String> { api::voxel_explode(&mut v.borrow_mut(), &mut w.borrow_mut(), x, y, z, r).map_err(|e| thrown(&ctx, e)) })?)?;// An edit of the level (`voxelEdit({ op, sphere | box | capsule, material })`; voxel.rs `EditOp`), and the level's// hash (16 hex digits; "" before a level): the same commands give the same hash.let (v, w) = (voxels.clone(), world.clone());- e.set("voxelEdit", Function::new(ctx.clone(), move |ctx: Ctx<'js>, d: Value<'js>| -> rquickjs::Result<String> {- let j: serde_json::Value = parse(&ctx, "voxelEdit", &d)?;- let op = crate::voxel::EditOp::parse(&j).map_err(|e| fail(&ctx, e))?;- let out = v.borrow_mut().edit(&mut w.borrow_mut(), &op).map_err(|e| fail(&ctx, e))?;- Ok(out.to_string())- })?)?;+ e.set("voxelEdit", Function::new(ctx.clone(), move |ctx: Ctx<'js>, d: Value<'js>| -> rquickjs::Result<String> { api::voxel_edit(&mut v.borrow_mut(), &mut w.borrow_mut(), &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;let v = voxels.clone();- e.set("voxelHash", Function::new(ctx.clone(), move || -> String { v.borrow().hash().map_or(String::new(), |h| format!("{h:016x}")) })?)?;+ e.set("voxelHash", Function::new(ctx.clone(), move || -> String { api::voxel_hash(&v.borrow()) })?)?;let v = voxels.clone();e.set("voxelDebris", Function::new(ctx.clone(), move |ctx: Ctx<'js>| -> rquickjs::Result<TypedArray<'js, f32>> { TypedArray::new(ctx, v.borrow_mut().take_debris()) })?)?;let (v, w) = (voxels.clone(), world.clone());- e.set("voxelFrame", Function::new(ctx.clone(), move |ctx: Ctx, dt: f64| -> rquickjs::Result<String> {- let out = v.borrow_mut().frame(&mut w.borrow_mut(), dt).map_err(|e| fail(&ctx, e))?;- Ok(out.to_string())- })?)?;+ e.set("voxelFrame", Function::new(ctx.clone(), move |ctx: Ctx, dt: f64| -> rquickjs::Result<String> { api::voxel_frame(&mut v.borrow_mut(), &mut w.borrow_mut(), dt).map_err(|e| thrown(&ctx, e)) })?)?;let w = world.clone();// (…, groups?, colors?): the optional arguments as the rest (rquickjs takes seven parameters at most).e.set("geometry", Function::new(ctx.clone(), move |ctx: Ctx<'js>, id: u32, p: TypedArray<f32>, n: TypedArray<f32>, uv: TypedArray<f32>, idx: TypedArray<u32>, rest: rquickjs::function::Rest<Value<'js>>| -> rquickjs::Result<()> {let opt = |k: usize| rest.0.get(k).filter(|v| !v.is_null() && !v.is_undefined());- let groups = match opt(0) {- Some(v) => AsRef::<[u32]>::as_ref(&TypedArray::<u32>::from_value(v.clone())?).chunks_exact(3).map(|c| [c[0], c[1], c[2]]).collect(),- None => vec![],- };- let colors = match opt(1) {- Some(v) => AsRef::<[f32]>::as_ref(&TypedArray::<f32>::from_value(v.clone())?).to_vec(),- None => vec![],- };- let g = Geometry { positions: AsRef::<[f32]>::as_ref(&p).to_vec(), normals: AsRef::<[f32]>::as_ref(&n).to_vec(), uvs: AsRef::<[f32]>::as_ref(&uv).to_vec(), indices: AsRef::<[u32]>::as_ref(&idx).to_vec(), groups, colors };- w.borrow_mut().set_geometry(id, g).map_err(|e| fail(&ctx, e))+ let groups = opt(0).map(|v| TypedArray::<u32>::from_value(v.clone())).transpose()?;+ let colors = opt(1).map(|v| TypedArray::<f32>::from_value(v.clone())).transpose()?;+ api::geometry(&mut w.borrow_mut(), id, p.as_ref(), n.as_ref(), uv.as_ref(), idx.as_ref(), groups.as_ref().map(|g| g.as_ref()), colors.as_ref().map(|c| c.as_ref())).map_err(|e| thrown(&ctx, e))})?)?;let w = world.clone();e.set("texture", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value, data: Option<TypedArray<u8>>| -> rquickjs::Result<()> {- let j = to_json(&d)?;- let pair = |k: &str, def: f32| -> [f32; 2] { [0, 1].map(|i| j[k][i].as_f64().map_or(def, |x| x as f32)) };- let source = match (data, j["uri"].as_str()) {- (Some(bytes), _) if j["size"].is_array() => {- let (width, height) = (j["size"][0].as_u64().unwrap_or(0) as u32, j["size"][1].as_u64().unwrap_or(0) as u32);- let rgba = AsRef::<[u8]>::as_ref(&bytes).to_vec();- if rgba.len() != width as usize * height as usize * 4 {- return Err(Exception::throw_type(&ctx, &format!("engine.texture: {} bytes are not {width}x{height} RGBA8 pixels", rgba.len())));- }- TextureSource::Pixels { width, height, rgba: Arc::new(rgba) }- }- (Some(bytes), _) => TextureSource::Encoded(Arc::new(AsRef::<[u8]>::as_ref(&bytes).to_vec())),- (None, Some(uri)) => TextureSource::File(uri.to_string()),- (None, None) => return Err(Exception::throw_type(&ctx, "engine.texture: needs a uri or data")),- };- let t = Texture { source, srgb: j["srgb"].as_bool().unwrap_or(true), wrap: j["wrap"].as_bool().unwrap_or(true), repeat: pair("repeat", 1.0), offset: pair("offset", 0.0) };- w.borrow_mut().set_texture(id, t).map_err(|e| fail(&ctx, e))?;- Ok(())+ api::texture(&mut w.borrow_mut(), id, &to_json(&d)?, data.as_ref().map(|d| d.as_ref())).map_err(|e| thrown(&ctx, e))})?)?;let w = world.clone();e.set("shader", Function::new(ctx.clone(), move |name: String, code: String, helpers: String| w.borrow_mut().set_shader(&name, code, helpers))?)?;@@ -226,10 +195,8 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<Rlet w = world.clone();e.set("densityGrid", Function::new(ctx.clone(), move |ctx: Ctx<'js>, id: u32, d: Value<'js>, data: Value<'js>| -> rquickjs::Result<()> {let j: serde_json::Value = parse(&ctx, "densityGrid", &d)?;- let n = |k: usize| j["size"][k].as_u64().unwrap_or(0).min(u32::MAX as u64) as u32;- let program = j["program"]["id"].as_str().map(|id| (id.to_string(), j["program"]["params"].as_array().map_or(vec![], |a| a.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect())));let data = if data.is_null() || data.is_undefined() { None } else { Some(TypedArray::<f32>::from_value(data)?) };- w.borrow_mut().set_grid(id, [n(0), n(1), n(2)], j["channels"].as_u64().unwrap_or(1) as u32, data.as_ref().map(|d| d.as_ref()), program).map_err(|e| fail(&ctx, e))+ api::density_grid(&mut w.borrow_mut(), id, &j, data.as_ref().map(|d| d.as_ref())).map_err(|e| thrown(&ctx, e))})?)?;let w = world.clone();e.set("gridSources", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, data: TypedArray<f32>| -> rquickjs::Result<()> { w.borrow_mut().add_grid_sources(id, data.as_ref()).map_err(|e| fail(&ctx, e)) })?)?;@@ -246,84 +213,11 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<Rw.borrow_mut().set_proc_asset(id, function, uri).map_err(|e| fail(&ctx, e))})?)?;let w = world.clone();- e.set("material", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> {- let m: desc::Material = parse(&ctx, "material", &d)?;- w.borrow_mut().set_material(id, m);- Ok(())- })?)?;+ e.set("material", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> { api::material(&mut w.borrow_mut(), id, &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;let w = world.clone();- e.set("object", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> {- let j = to_json(&d)?;- let num = |k: &str| j[k].as_u64().map(|x| x as u32);- // `body`: a rigid body will drive it (physics.rs). A mesh is then an instance of its own BLAS, so one added while- // the game runs is placed in place and its moves are its instance's transform.- let body = j["body"].as_bool().unwrap_or(false);- let kind = match j["kind"].as_str().unwrap_or("group") {- "mesh" => {- let materials: Vec<u32> = j["materials"].as_array().map_or(vec![], |a| a.iter().filter_map(|v| v.as_u64().map(|x| x as u32)).collect());- Kind::Mesh { geometry: num("geometry").unwrap_or(0), material: num("material").unwrap_or(0), own_blas: j["dynamicGeometry"].as_bool().unwrap_or(false) || (body && materials.len() <= 1), materials }- }- "model" => Kind::Model { uri: j["uri"].as_str().unwrap_or_default().to_string(), nodes: serde_json::from_value(j["nodes"].clone()).ok(), animation: serde_json::from_value(j["animation"].clone()).ok(), functions: serde_json::from_value(j["functions"].clone()).unwrap_or_default() },- "light" => Kind::Light(serde_json::from_value(j["light"].clone()).map_err(|e| Exception::throw_type(&ctx, &format!("engine.object light: {e}")))?),- "camera" => Kind::Camera(serde_json::from_value(j["camera"].clone()).map_err(|e| Exception::throw_type(&ctx, &format!("engine.object camera: {e}")))?),- "volume" => Kind::Volume {- function: j["volume"]["id"].as_str().unwrap_or_default().to_string(),- params: j["volume"]["params"].as_array().map_or(vec![], |a| a.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect()),- shape: if j["shape"].as_str() == Some("sphere") { 1 } else { 0 },- majorant: j["majorant"].as_f64().unwrap_or(0.0) as f32,- g: j["g"].as_f64().unwrap_or(0.0) as f32,- homogeneous: j["homogeneous"].as_bool().unwrap_or(false),- grid: num("grid"),- },- "instanced" => Kind::Instanced {- geometry: num("geometry").unwrap_or(0),- procedural: j["procedural"].as_bool().unwrap_or(false),- materials: j["materials"].as_array().map_or(vec![], |a| a.iter().filter_map(|v| v.as_u64().map(|x| x as u32)).collect()),- capacity: num("count").unwrap_or(0),- },- "procedural" => Kind::Procedural {- geometry: num("geometry").unwrap_or(0),- materials: j["materials"].as_array().map_or(vec![], |a| a.iter().filter_map(|v| v.as_u64().map(|x| x as u32)).collect()),- },- "gpuParticles" => Kind::GpuParticles {- capacity: num("capacity").unwrap_or(0).min(1 << 21),- program: j["program"]["id"].as_str().unwrap_or_default().to_string(),- params: j["program"]["params"].as_array().map_or(vec![], |a| a.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect()),- material: num("material").unwrap_or(0),- emitter_area: j["emitterArea"].as_f64().unwrap_or(0.0) as f32,- rate: (j["rate"].as_f64().unwrap_or(0.0) as f32).max(0.0),- collide: crate::world::ParticleCollide {- plane: j["collide"]["plane"].as_f64().map(|v| v as f32),- voxels: j["collide"]["voxels"].as_bool().unwrap_or(false),- restitution: (j["collide"]["restitution"].as_f64().unwrap_or(0.3) as f32).clamp(0.0, 1.0),- friction: (j["collide"]["friction"].as_f64().unwrap_or(0.4) as f32).clamp(0.0, 1.0),- },- },- "particles" => Kind::Particles {- count: num("count").unwrap_or(0),- emitter: j["emitter"]["id"].as_str().unwrap_or_default().to_string(),- params: j["emitter"]["params"].as_array().map_or(vec![], |a| a.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect()),- material: num("material").unwrap_or(0),- emitter_area: j["emitterArea"].as_f64().unwrap_or(0.0) as f32,- },- _ => Kind::Group,- };- let mut w = w.borrow_mut();- w.set_object(id, j["name"].as_str().unwrap_or_default().to_string(), num("parent"), kind, j["castShadow"].as_bool().unwrap_or(true), j["movable"].as_bool().unwrap_or(false)).map_err(|e| fail(&ctx, e))?;- if body {- w.set_driven(id).map_err(|e| fail(&ctx, e))?;- }- Ok(())- })?)?;+ e.set("object", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> { api::object(&mut w.borrow_mut(), id, &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;let w = world.clone();- e.set("transform", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, t: TypedArray<f32>| -> rquickjs::Result<()> {- let t: &[f32] = t.as_ref();- if t.len() < 10 {- return Err(Exception::throw_type(&ctx, "engine.transform: needs 10 numbers"));- }- let q = Quat::from_xyzw(t[3], t[4], t[5], t[6]);- w.borrow_mut().set_transform(id, Vec3::new(t[0], t[1], t[2]), if q.length_squared() > 0.0 { q.normalize() } else { Quat::IDENTITY }, Vec3::new(t[7], t[8], t[9])).map_err(|e| fail(&ctx, e))- })?)?;+ e.set("transform", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, t: TypedArray<f32>| -> rquickjs::Result<()> { api::transform(&mut w.borrow_mut(), id, t.as_ref()).map_err(|e| thrown(&ctx, e)) })?)?;// An instanced mesh's instances: count drawn, then matrices (16 numbers each), colours (3) and per-instance data// (4) for its whole capacity, each null to keep what it had (world.rs `set_instances` checks them).let w = world.clone();@@ -336,61 +230,29 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<Rlet w = world.clone();e.set("power", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, p: f64| w.borrow_mut().set_power(id, p as f32).map_err(|e| fail(&ctx, e)))?)?;let w = world.clone();- e.set("customData", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, v: Vec<f64>| {- let mut c = [0.0f32; 4];- for (k, x) in v.iter().take(4).enumerate() {- c[k] = *x as f32;- }- w.borrow_mut().set_custom(id, c).map_err(|e| fail(&ctx, e))- })?)?;+ e.set("customData", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, v: Vec<f64>| api::custom_data(&mut w.borrow_mut(), id, &v).map_err(|e| thrown(&ctx, e)))?)?;let w = world.clone();e.set("sway", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> {- let s: Option<crate::world::Sway> = if d.is_null() || d.is_undefined() { None } else { Some(parse(&ctx, "sway", &d)?) };- w.borrow_mut().set_sway(id, s).map_err(|e| fail(&ctx, e))+ let j = if d.is_null() || d.is_undefined() { None } else { Some(to_json(&d)?) };+ api::sway(&mut w.borrow_mut(), id, j.as_ref()).map_err(|e| thrown(&ctx, e))})?)?;let w = world.clone();- e.set("light", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> {- let l: desc::Light = parse(&ctx, "light", &d)?;- w.borrow_mut().set_light(id, l).map_err(|e| fail(&ctx, e))- })?)?;+ e.set("light", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> { api::light(&mut w.borrow_mut(), id, &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;let w = world.clone();- e.set("camera", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> {- let c: desc::Camera = parse(&ctx, "camera", &d)?;- w.borrow_mut().set_camera_desc(id, c).map_err(|e| fail(&ctx, e))- })?)?;+ e.set("camera", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> { api::camera(&mut w.borrow_mut(), id, &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;let w = world.clone();e.set("animation", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> {- let a: Option<desc::Animation> = if d.is_null() || d.is_undefined() { None } else { Some(parse(&ctx, "animation", &d)?) };- w.borrow_mut().set_animation(id, a).map_err(|e| fail(&ctx, e))+ let j = if d.is_null() || d.is_undefined() { None } else { Some(to_json(&d)?) };+ api::animation(&mut w.borrow_mut(), id, j.as_ref()).map_err(|e| thrown(&ctx, e))})?)?;let w = world.clone();let p = physics.clone();- e.set("remove", Function::new(ctx.clone(), move |id: u32| {- let gone = w.borrow_mut().remove(id);- // (A body asleep would never find out its object went; the object's id may come again.)- if let Some(p) = p.borrow_mut().as_mut() {- p.objects_removed(&gone);- }- })?)?;+ e.set("remove", Function::new(ctx.clone(), move |id: u32| api::remove(&mut w.borrow_mut(), &mut p.borrow_mut(), id))?)?;let w = world.clone();- e.set("environment", Function::new(ctx.clone(), move |ctx: Ctx, d: Value| -> rquickjs::Result<()> {- let env: desc::Environment = parse(&ctx, "environment", &d)?;- w.borrow_mut().set_environment(env);- Ok(())- })?)?;+ e.set("environment", Function::new(ctx.clone(), move |ctx: Ctx, d: Value| -> rquickjs::Result<()> { api::environment(&mut w.borrow_mut(), &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;let w = world.clone();e.set("settings", Function::new(ctx.clone(), move |d: Value| -> rquickjs::Result<()> {- let j = to_json(&d)?;- let s = Settings {- name: j["name"].as_str().unwrap_or("scene").to_string(),- preset: j["preset"].as_str().unwrap_or("cinematic").to_string(),- overrides: Some(j["overrides"].clone()).filter(|o| !o.is_null()),- width: j["width"].as_u64().unwrap_or(1280) as u32,- height: j["height"].as_u64().unwrap_or(720) as u32,- time: j["time"].as_f64().unwrap_or(0.0) as f32,- camera: j["camera"].as_u64().map(|c| c as u32),- };- w.borrow_mut().set_settings(s);+ api::settings(&mut w.borrow_mut(), &to_json(&d)?);Ok(())})?)?;ctx.globals().set("__engine", e)@@ -750,6 +612,8 @@ impl GameSession {#[cfg(test)]mod tests {use super::*;+ use crate::world::TextureSource;+ use glam::Vec3;// A hand-written bundle: what the binding (packages/scene/src/engine.ts) does, reduced to engine calls.const GAME: &str = r#"diff --git a/renderer/web/Cargo.lock b/renderer/web/Cargo.locknew file mode 100644index 0000000..485c36d--- /dev/null+++ b/renderer/web/Cargo.lock@@ -0,0 +1,3265 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "ab_glyph"+version = "0.2.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2"+dependencies = [+ "ab_glyph_rasterizer",+ "owned_ttf_parser",+]++[[package]]+name = "ab_glyph_rasterizer"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618"++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if",+ "getrandom 0.3.4",+ "once_cell",+ "version_check",+ "zerocopy",+]++[[package]]+name = "allocator-api2"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"++[[package]]+name = "android-activity"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd"+dependencies = [+ "android-properties",+ "bitflags 2.13.2",+ "cc",+ "jni",+ "libc",+ "log",+ "ndk",+ "ndk-context",+ "ndk-sys",+ "num_enum",+ "thiserror 2.0.21",+]++[[package]]+name = "android-properties"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"++[[package]]+name = "android_system_properties"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"+dependencies = [+ "libc",+]++[[package]]+name = "anyhow"+version = "1.0.104"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"++[[package]]+name = "approx"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"+dependencies = [+ "num-traits",+]++[[package]]+name = "arrayref"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"++[[package]]+name = "arrayvec"+version = "0.7.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"++[[package]]+name = "as-raw-xcb-connection"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"++[[package]]+name = "ash"+version = "0.38.0+1.3.281"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"+dependencies = [+ "libloading",+]++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "base64"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"++[[package]]+name = "bit-set"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"++[[package]]+name = "bit_field"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"++[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]]+name = "block2"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"+dependencies = [+ "objc2 0.5.3",+]++[[package]]+name = "block2"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"+dependencies = [+ "objc2 0.6.5",+]++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"++[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "byteorder"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"++[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "calloop"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec"+dependencies = [+ "bitflags 2.13.2",+ "log",+ "polling",+ "rustix 0.38.44",+ "slab",+ "thiserror 1.0.69",+]++[[package]]+name = "calloop-wayland-source"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20"+dependencies = [+ "calloop",+ "rustix 0.38.44",+ "wayland-backend",+ "wayland-client",+]++[[package]]+name = "cc"+version = "1.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155"+dependencies = [+ "find-msvc-tools",+ "jobserver",+ "libc",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "cfg_aliases"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"++[[package]]+name = "codespan-reporting"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"+dependencies = [+ "serde",+ "termcolor",+ "unicode-width",+]++[[package]]+name = "combine"+version = "4.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "concurrent-queue"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "core-foundation"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "core-graphics"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"+dependencies = [+ "bitflags 1.3.2",+ "core-foundation",+ "core-graphics-types",+ "foreign-types",+ "libc",+]++[[package]]+name = "core-graphics-types"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"+dependencies = [+ "bitflags 1.3.2",+ "core-foundation",+ "libc",+]++[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "crc32fast"+version = "1.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-deque"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"++[[package]]+name = "crunchy"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "cursor-icon"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]++[[package]]+name = "dispatch"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b"++[[package]]+name = "dispatch2"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"+dependencies = [+ "bitflags 2.13.2",+ "objc2 0.6.5",+]++[[package]]+name = "dlib"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"+dependencies = [+ "libloading",+]++[[package]]+name = "document-features"+version = "0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"+dependencies = [+ "litrs",+]++[[package]]+name = "downcast-rs"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"++[[package]]+name = "downcast-rs"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"++[[package]]+name = "dpi"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"++[[package]]+name = "either"+version = "1.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"++[[package]]+name = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "exr"+version = "1.74.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6"+dependencies = [+ "bit_field",+ "half",+ "lebe",+ "miniz_oxide 0.8.9",+ "multiversion",+ "smallvec",+ "zune-inflate",+]++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "find-msvc-tools"+version = "0.1.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"++[[package]]+name = "flate2"+version = "1.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"+dependencies = [+ "crc32fast",+ "miniz_oxide 0.9.1",+ "zlib-rs",+]++[[package]]+name = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[package]]+name = "foreign-types"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"+dependencies = [+ "foreign-types-macros",+ "foreign-types-shared",+]++[[package]]+name = "foreign-types-macros"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "foreign-types-shared"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"++[[package]]+name = "futures-core"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"++[[package]]+name = "futures-task"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"++[[package]]+name = "futures-util"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"+dependencies = [+ "futures-core",+ "futures-task",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "gethostname"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"+dependencies = [+ "rustix 1.1.6",+ "windows-link",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi 5.3.0",+ "wasip2",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi 6.0.0",+]++[[package]]+name = "gl_generator"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d"+dependencies = [+ "khronos_api",+ "log",+ "xml-rs",+]++[[package]]+name = "glam"+version = "0.30.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"+dependencies = [+ "bytemuck",+]++[[package]]+name = "glam"+version = "0.33.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37bfe73dc8ec21f54d181e5a60554327ec3f1c600c455a75ccbfc65d2106a6c4"+dependencies = [+ "approx",+ "libm",+]++[[package]]+name = "glamx"+version = "0.3.1"+dependencies = [+ "approx",+ "glam 0.33.12",+ "nalgebra",+ "num-traits",+ "simba",+]++[[package]]+name = "glow"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5"+dependencies = [+ "js-sys",+ "slotmap",+ "wasm-bindgen",+ "web-sys",+]++[[package]]+name = "gltf"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3ce1918195723ce6ac74e80542c5a96a40c2b26162c1957a5cd70799b8cacf7"+dependencies = [+ "base64",+ "byteorder",+ "gltf-json",+ "image",+ "lazy_static",+ "serde_json",+ "urlencoding",+]++[[package]]+name = "gltf-derive"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "14070e711538afba5d6c807edb74bcb84e5dbb9211a3bf5dea0dfab5b24f4c51"+dependencies = [+ "inflections",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "gltf-json"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6176f9d60a7eab0a877e8e96548605dedbde9190a7ae1e80bbcc1c9af03ab14"+dependencies = [+ "gltf-derive",+ "serde",+ "serde_derive",+ "serde_json",+]++[[package]]+name = "glutin_wgl_sys"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e"+dependencies = [+ "gl_generator",+]++[[package]]+name = "gpu-allocator"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795"+dependencies = [+ "ash",+ "hashbrown 0.16.1",+ "log",+ "presser",+ "thiserror 2.0.21",+ "windows",+]++[[package]]+name = "half"+version = "2.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"+dependencies = [+ "bytemuck",+ "cfg-if",+ "crunchy",+ "num-traits",+ "zerocopy",+]++[[package]]+name = "hash32"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606"+dependencies = [+ "byteorder",+]++[[package]]+name = "hashbrown"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"+dependencies = [+ "allocator-api2",+ "equivalent",+ "foldhash",+]++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+dependencies = [+ "allocator-api2",+ "equivalent",+ "foldhash",+]++[[package]]+name = "heapless"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"+dependencies = [+ "hash32",+ "stable_deref_trait",+]++[[package]]+name = "hermit-abi"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"++[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "exr",+ "moxcms",+ "num-traits",+ "png",+ "zune-core",+ "zune-jpeg",+]++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown 0.17.1",+ "serde",+ "serde_core",+]++[[package]]+name = "inflections"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a"++[[package]]+name = "itoa"+version = "1.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"++[[package]]+name = "jni"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"+dependencies = [+ "cfg-if",+ "combine",+ "jni-macros",+ "jni-sys 0.4.1",+ "log",+ "simd_cesu8",+ "thiserror 2.0.21",+ "walkdir",+ "windows-link",+]++[[package]]+name = "jni-macros"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"+dependencies = [+ "proc-macro2",+ "quote",+ "rustc_version",+ "simd_cesu8",+ "syn 2.0.119",+]++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "jobserver"+version = "0.1.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"+dependencies = [+ "getrandom 0.4.3",+ "libc",+]++[[package]]+name = "js-sys"+version = "0.3.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "khronos-egl"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76"+dependencies = [+ "libc",+ "libloading",+ "pkg-config",+]++[[package]]+name = "khronos_api"+version = "3.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"++[[package]]+name = "lazy_static"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"++[[package]]+name = "lebe"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]++[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"++[[package]]+name = "libredox"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"+dependencies = [+ "bitflags 2.13.2",+ "libc",+ "plain",+ "redox_syscall 0.9.5",+]++[[package]]+name = "linux-raw-sys"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"++[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"++[[package]]+name = "litrs"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "memmap2"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"+dependencies = [+ "libc",+]++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "miniz_oxide"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]++[[package]]+name = "multiversion"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076"+dependencies = [+ "multiversion-macros",+ "target-features",+]++[[package]]+name = "multiversion-macros"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "target-features",+]++[[package]]+name = "naga"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"+dependencies = [+ "arrayvec",+ "bit-set",+ "bitflags 2.13.2",+ "cfg-if",+ "cfg_aliases",+ "codespan-reporting",+ "half",+ "hashbrown 0.17.1",+ "indexmap",+ "libm",+ "log",+ "naga-types",+ "num-traits",+ "once_cell",+ "rustc-hash",+ "spirv",+ "thiserror 2.0.21",+ "unicode-ident",+]++[[package]]+name = "naga-types"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49"+dependencies = [+ "hashbrown 0.17.1",+ "indexmap",+ "rustc-hash",+ "thiserror 2.0.21",+]++[[package]]+name = "nalgebra"+version = "0.35.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "adc43a60c217b0c6ff46e47f26911015ad8d2e5a8be1af668c67e370d99a4346"+dependencies = [+ "approx",+ "glam 0.33.12",+ "nalgebra-macros",+ "num-complex",+ "num-rational",+ "num-traits",+ "simba",+ "typenum",+]++[[package]]+name = "nalgebra-macros"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "973e7178a678cfd059ccec50887658d482ce16b0aa9da3888ddeab5cd5eb4889"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "ndk"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"+dependencies = [+ "bitflags 2.13.2",+ "jni-sys 0.3.1",+ "log",+ "ndk-sys",+ "num_enum",+ "raw-window-handle",+ "thiserror 1.0.69",+]++[[package]]+name = "ndk-context"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"++[[package]]+name = "ndk-sys"+version = "0.6.0+11769913"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"+dependencies = [+ "jni-sys 0.3.1",+]++[[package]]+name = "num-complex"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"+dependencies = [+ "num-traits",+]++[[package]]+name = "num-derive"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4e98dc3b890f6c23a0f9d3d491a2823d0dea0fa656302a13dd225fa924112a8"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "num-integer"+version = "0.1.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"+dependencies = [+ "num-traits",+]++[[package]]+name = "num-rational"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"+dependencies = [+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+ "libm",+]++[[package]]+name = "num_enum"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"+dependencies = [+ "num_enum_derive",+ "rustversion",+]++[[package]]+name = "num_enum_derive"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "objc-sys"+version = "0.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"++[[package]]+name = "objc2"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b"+dependencies = [+ "objc-sys",+ "objc2-encode",+]++[[package]]+name = "objc2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"+dependencies = [+ "objc2-encode",+]++[[package]]+name = "objc2-app-kit"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff"+dependencies = [+ "bitflags 2.13.2",+ "block2 0.5.1",+ "libc",+ "objc2 0.5.3",+ "objc2-core-data",+ "objc2-core-image",+ "objc2-foundation 0.2.2",+ "objc2-quartz-core 0.2.2",+]++[[package]]+name = "objc2-cloud-kit"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009"+dependencies = [+ "bitflags 2.13.2",+ "block2 0.5.1",+ "objc2 0.5.3",+ "objc2-core-location",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-contacts"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889"+dependencies = [+ "block2 0.5.1",+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-core-data"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef"+dependencies = [+ "bitflags 2.13.2",+ "block2 0.5.1",+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.13.2",+ "dispatch2",+ "objc2 0.6.5",+]++[[package]]+name = "objc2-core-graphics"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"+dependencies = [+ "dispatch2",+ "objc2 0.6.5",+ "objc2-core-foundation",+ "objc2-io-surface",+]++[[package]]+name = "objc2-core-image"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80"+dependencies = [+ "block2 0.5.1",+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+ "objc2-metal 0.2.2",+]++[[package]]+name = "objc2-core-location"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781"+dependencies = [+ "block2 0.5.1",+ "objc2 0.5.3",+ "objc2-contacts",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-encode"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"++[[package]]+name = "objc2-foundation"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"+dependencies = [+ "bitflags 2.13.2",+ "block2 0.5.1",+ "dispatch",+ "libc",+ "objc2 0.5.3",+]++[[package]]+name = "objc2-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"+dependencies = [+ "bitflags 2.13.2",+ "objc2 0.6.5",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-io-surface"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"+dependencies = [+ "bitflags 2.13.2",+ "objc2 0.6.5",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-link-presentation"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398"+dependencies = [+ "block2 0.5.1",+ "objc2 0.5.3",+ "objc2-app-kit",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-metal"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6"+dependencies = [+ "bitflags 2.13.2",+ "block2 0.5.1",+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-metal"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"+dependencies = [+ "bitflags 2.13.2",+ "block2 0.6.2",+ "objc2 0.6.5",+ "objc2-foundation 0.3.2",+]++[[package]]+name = "objc2-quartz-core"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a"+dependencies = [+ "bitflags 2.13.2",+ "block2 0.5.1",+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+ "objc2-metal 0.2.2",+]++[[package]]+name = "objc2-quartz-core"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"+dependencies = [+ "bitflags 2.13.2",+ "objc2 0.6.5",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-foundation 0.3.2",+ "objc2-metal 0.3.2",+]++[[package]]+name = "objc2-symbols"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc"+dependencies = [+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-ui-kit"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f"+dependencies = [+ "bitflags 2.13.2",+ "block2 0.5.1",+ "objc2 0.5.3",+ "objc2-cloud-kit",+ "objc2-core-data",+ "objc2-core-image",+ "objc2-core-location",+ "objc2-foundation 0.2.2",+ "objc2-link-presentation",+ "objc2-quartz-core 0.2.2",+ "objc2-symbols",+ "objc2-uniform-type-identifiers",+ "objc2-user-notifications",+]++[[package]]+name = "objc2-uniform-type-identifiers"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe"+dependencies = [+ "block2 0.5.1",+ "objc2 0.5.3",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-user-notifications"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3"+dependencies = [+ "bitflags 2.13.2",+ "block2 0.5.1",+ "objc2 0.5.3",+ "objc2-core-location",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "orbclient"+version = "0.3.55"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747"+dependencies = [+ "libc",+ "libredox",+]++[[package]]+name = "ordered-float"+version = "5.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab"+dependencies = [+ "num-traits",+]++[[package]]+name = "owned_ttf_parser"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b"+dependencies = [+ "ttf-parser",+]++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall 0.5.18",+ "smallvec",+ "windows-link",+]++[[package]]+name = "parry3d"+version = "0.31.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b626edc0b497dba4bdf6e1e0797895294ed9f61dac2bd28cb5d34d37ad2ca7e"+dependencies = [+ "approx",+ "arrayvec",+ "bitflags 2.13.2",+ "downcast-rs 2.0.2",+ "either",+ "foldhash",+ "glamx",+ "hashbrown 0.17.1",+ "indexmap",+ "log",+ "num-derive",+ "num-traits",+ "ordered-float",+ "rstar",+ "simba",+ "smallvec",+ "static_assertions",+ "thiserror 2.0.21",+]++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "physics-core"+version = "0.1.0"+dependencies = [+ "libm",+ "rapier3d",+ "serde_json",+]++[[package]]+name = "pin-project"+version = "1.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"+dependencies = [+ "pin-project-internal",+]++[[package]]+name = "pin-project-internal"+version = "1.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "plain"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"++[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags 2.13.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]++[[package]]+name = "polling"+version = "3.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"+dependencies = [+ "cfg-if",+ "concurrent-queue",+ "hermit-abi",+ "pin-project-lite",+ "rustix 1.1.6",+ "windows-sys 0.61.2",+]++[[package]]+name = "pollster"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"++[[package]]+name = "portable-atomic"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"++[[package]]+name = "portable-atomic-util"+version = "0.2.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"+dependencies = [+ "portable-atomic",+]++[[package]]+name = "presser"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"++[[package]]+name = "proc-macro-crate"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"+dependencies = [+ "toml_edit",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "profiling"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"+dependencies = [+ "profiling-procmacros",+]++[[package]]+name = "profiling-procmacros"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "pxfm"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"++[[package]]+name = "quick-xml"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"+dependencies = [+ "memchr",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "range-alloc"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"++[[package]]+name = "rapier3d"+version = "0.36.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "033e2edc815d61ab97bd74ed5d1cbea5ebe575218774a7cfedbd3551f0033317"+dependencies = [+ "approx",+ "arrayvec",+ "bitflags 2.13.2",+ "glamx",+ "log",+ "nalgebra",+ "num-traits",+ "parry3d",+ "profiling",+ "serde",+ "simba",+ "static_assertions",+ "thiserror 2.0.21",+ "wide",+]++[[package]]+name = "raw-window-handle"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"++[[package]]+name = "raw-window-metal"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135"+dependencies = [+ "objc2 0.6.5",+ "objc2-core-foundation",+ "objc2-foundation 0.3.2",+ "objc2-quartz-core 0.3.2",+]++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "redox_syscall"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"+dependencies = [+ "bitflags 1.3.2",+]++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "redox_syscall"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "relative-path"+version = "2.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38540a682c6e9bca04a8bca9e5ec5a6ba168dfbb04c9998fe517a9befb92eb68"+dependencies = [+ "serde_core",+]++[[package]]+name = "renderdoc-sys"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"++[[package]]+name = "rquickjs"+version = "0.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e04e4eedfb060b503b5f0a2644abb890b0b3620d3fb674f9455f230014964e4"+dependencies = [+ "rquickjs-core",+]++[[package]]+name = "rquickjs-core"+version = "0.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "16e4f499ac5b943d97ee6dbc44f23c2c10426f420f7d2f1793d6318911b6608c"+dependencies = [+ "hashbrown 0.17.1",+ "relative-path",+ "rquickjs-sys",+]++[[package]]+name = "rquickjs-sys"+version = "0.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a13ac243b86a74120814ef7e9e30ad5a2c1199b7b9963b1cf7c84e4cdc1cad99"+dependencies = [+ "cc",+]++[[package]]+name = "rstar"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90e7279515baf3838062fa9c495a408bc2f3abbf9cd2ac8c2d4108b90fa29b89"+dependencies = [+ "heapless",+ "num-traits",+ "smallvec",+]++[[package]]+name = "rustc-hash"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"++[[package]]+name = "rustc_version"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"+dependencies = [+ "semver",+]++[[package]]+name = "rustix"+version = "0.38.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"+dependencies = [+ "bitflags 2.13.2",+ "errno",+ "libc",+ "linux-raw-sys 0.4.15",+ "windows-sys 0.59.0",+]++[[package]]+name = "rustix"+version = "1.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"+dependencies = [+ "bitflags 2.13.2",+ "errno",+ "libc",+ "linux-raw-sys 0.12.1",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "safe_arch"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42c6efa15875e6ecb39ca61fb0b0c1a40b84fac5a5ffe71eef7d1000c8eb3f5f"+dependencies = [+ "bytemuck",+]++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "scoped-tls"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "sctk-adwaita"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"+dependencies = [+ "ab_glyph",+ "log",+ "memmap2",+ "smithay-client-toolkit",+ "tiny-skia",+]++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"++[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "serde_json"+version = "1.0.154"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "simba"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1a7200d82ff1c7b4235efd12f11e2537a402c91cf83a5cb97ce80eef787fde7"+dependencies = [+ "approx",+ "libm",+ "num-complex",+ "num-traits",+ "wide",+]++[[package]]+name = "simd-adler32"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"++[[package]]+name = "simd_cesu8"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"+dependencies = [+ "rustc_version",+ "simdutf8",+]++[[package]]+name = "simdutf8"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "slotmap"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"+dependencies = [+ "version_check",+]++[[package]]+name = "smallvec"+version = "1.16.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"++[[package]]+name = "smithay-client-toolkit"+version = "0.19.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016"+dependencies = [+ "bitflags 2.13.2",+ "calloop",+ "calloop-wayland-source",+ "cursor-icon",+ "libc",+ "log",+ "memmap2",+ "rustix 0.38.44",+ "thiserror 1.0.69",+ "wayland-backend",+ "wayland-client",+ "wayland-csd-frame",+ "wayland-cursor",+ "wayland-protocols",+ "wayland-protocols-wlr",+ "wayland-scanner",+ "xkeysym",+]++[[package]]+name = "smol_str"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead"+dependencies = [+ "serde",+]++[[package]]+name = "spirv"+version = "0.4.0+sdk-1.4.341.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "static_assertions"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"++[[package]]+name = "strict-num"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "target-features"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5"++[[package]]+name = "termcolor"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"+dependencies = [+ "winapi-util",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"+dependencies = [+ "thiserror-impl 2.0.21",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "thiserror-impl"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "threert-render"+version = "0.1.0"+dependencies = [+ "anyhow",+ "bytemuck",+ "glam 0.30.10",+ "gltf",+ "half",+ "image",+ "physics-core",+ "pollster",+ "rayon",+ "rquickjs",+ "serde",+ "serde_json",+ "sha2",+ "voxel-core",+ "web-time",+ "wgpu",+ "winit",+]++[[package]]+name = "threert-web"+version = "0.1.0"+dependencies = [+ "glam 0.30.10",+ "js-sys",+ "serde_json",+ "threert-render",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "web-time",+ "wgpu",+]++[[package]]+name = "tiny-skia"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab"+dependencies = [+ "arrayref",+ "arrayvec",+ "bytemuck",+ "cfg-if",+ "log",+ "tiny-skia-path",+]++[[package]]+name = "tiny-skia-path"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"+dependencies = [+ "arrayref",+ "bytemuck",+ "strict-num",+]++[[package]]+name = "tokio"+version = "1.54.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"+dependencies = [+ "pin-project-lite",+]++[[package]]+name = "toml_datetime"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_edit"+version = "0.25.19+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218"+dependencies = [+ "indexmap",+ "toml_datetime",+ "toml_parser",+ "winnow",+]++[[package]]+name = "toml_parser"+version = "1.1.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"+dependencies = [+ "winnow",+]++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-core",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"++[[package]]+name = "ttf-parser"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "unicode-width"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"++[[package]]+name = "urlencoding"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "voxel-core"+version = "0.1.0"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "wasip2"+version = "1.0.4+wasi-0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"+dependencies = [+ "cfg-if",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.80"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501"+dependencies = [+ "js-sys",+ "tokio",+ "wasm-bindgen",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 3.0.10",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "wayland-backend"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"+dependencies = [+ "cc",+ "downcast-rs 1.2.1",+ "rustix 1.1.6",+ "scoped-tls",+ "smallvec",+ "wayland-sys",+]++[[package]]+name = "wayland-client"+version = "0.31.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"+dependencies = [+ "bitflags 2.13.2",+ "rustix 1.1.6",+ "wayland-backend",+ "wayland-scanner",+]++[[package]]+name = "wayland-csd-frame"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e"+dependencies = [+ "bitflags 2.13.2",+ "cursor-icon",+ "wayland-backend",+]++[[package]]+name = "wayland-cursor"+version = "0.31.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d"+dependencies = [+ "rustix 1.1.6",+ "wayland-client",+ "xcursor",+]++[[package]]+name = "wayland-protocols"+version = "0.32.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6"+dependencies = [+ "bitflags 2.13.2",+ "wayland-backend",+ "wayland-client",+ "wayland-scanner",+]++[[package]]+name = "wayland-protocols-plasma"+version = "0.3.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91"+dependencies = [+ "bitflags 2.13.2",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-scanner",+]++[[package]]+name = "wayland-protocols-wlr"+version = "0.3.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"+dependencies = [+ "bitflags 2.13.2",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-scanner",+]++[[package]]+name = "wayland-scanner"+version = "0.31.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"+dependencies = [+ "proc-macro2",+ "quick-xml",+ "quote",+]++[[package]]+name = "wayland-sys"+version = "0.31.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"+dependencies = [+ "dlib",+ "log",+ "once_cell",+ "pkg-config",+]++[[package]]+name = "web-sys"+version = "0.3.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "web-time"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "wgpu"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e"+dependencies = [+ "arrayvec",+ "bitflags 2.13.2",+ "bytemuck",+ "cfg-if",+ "cfg_aliases",+ "document-features",+ "hashbrown 0.17.1",+ "js-sys",+ "log",+ "naga",+ "parking_lot",+ "portable-atomic",+ "profiling",+ "raw-window-handle",+ "smallvec",+ "static_assertions",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "wgpu-core",+ "wgpu-hal",+ "wgpu-types",+]++[[package]]+name = "wgpu-core"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14"+dependencies = [+ "arrayvec",+ "bit-set",+ "bit-vec",+ "bitflags 2.13.2",+ "bytemuck",+ "cfg_aliases",+ "document-features",+ "hashbrown 0.17.1",+ "indexmap",+ "log",+ "naga",+ "naga-types",+ "once_cell",+ "parking_lot",+ "portable-atomic",+ "profiling",+ "raw-window-handle",+ "rustc-hash",+ "smallvec",+ "thiserror 2.0.21",+ "wgpu-core-deps-apple",+ "wgpu-core-deps-emscripten",+ "wgpu-core-deps-windows-linux-android",+ "wgpu-hal",+ "wgpu-naga-bridge",+ "wgpu-types",+]++[[package]]+name = "wgpu-core-deps-apple"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-core-deps-emscripten"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d98b86cf4abf524a902dd35f18ca6a3f08fc2ae9847c8f10b48e30491b1f0b86"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-core-deps-windows-linux-android"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-hal"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58"+dependencies = [+ "android_system_properties",+ "arrayvec",+ "ash",+ "bit-set",+ "bitflags 2.13.2",+ "block2 0.6.2",+ "bytemuck",+ "cfg-if",+ "cfg_aliases",+ "glow",+ "glutin_wgl_sys",+ "gpu-allocator",+ "hashbrown 0.17.1",+ "js-sys",+ "khronos-egl",+ "libc",+ "libloading",+ "log",+ "naga",+ "naga-types",+ "ndk-sys",+ "objc2 0.6.5",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-foundation 0.3.2",+ "objc2-metal 0.3.2",+ "objc2-quartz-core 0.3.2",+ "once_cell",+ "ordered-float",+ "parking_lot",+ "portable-atomic",+ "portable-atomic-util",+ "profiling",+ "range-alloc",+ "raw-window-handle",+ "raw-window-metal",+ "renderdoc-sys",+ "smallvec",+ "static_assertions",+ "thiserror 2.0.21",+ "wasm-bindgen",+ "wayland-sys",+ "web-sys",+ "wgpu-naga-bridge",+ "wgpu-types",+ "windows",+ "windows-core",+ "windows-result",+]++[[package]]+name = "wgpu-naga-bridge"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081"+dependencies = [+ "naga",+ "wgpu-types",+]++[[package]]+name = "wgpu-types"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "js-sys",+ "log",+ "naga-types",+ "raw-window-handle",+ "static_assertions",+ "web-sys",+]++[[package]]+name = "wide"+version = "1.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d920ac99c3c8edce110cb8d07dbb324d6d026011dce85b1e9355b70f0adacc4f"+dependencies = [+ "bytemuck",+ "safe_arch",+]++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections",+ "windows-core",+ "windows-future",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core",+ "windows-link",+ "windows-threading",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core",+ "windows-link",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.59.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_gnullvm",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "winit"+version = "0.30.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d"+dependencies = [+ "ahash",+ "android-activity",+ "atomic-waker",+ "bitflags 2.13.2",+ "block2 0.5.1",+ "bytemuck",+ "calloop",+ "cfg_aliases",+ "concurrent-queue",+ "core-foundation",+ "core-graphics",+ "cursor-icon",+ "dpi",+ "js-sys",+ "libc",+ "memmap2",+ "ndk",+ "objc2 0.5.3",+ "objc2-app-kit",+ "objc2-foundation 0.2.2",+ "objc2-ui-kit",+ "orbclient",+ "percent-encoding",+ "pin-project",+ "raw-window-handle",+ "redox_syscall 0.4.1",+ "rustix 0.38.44",+ "sctk-adwaita",+ "smithay-client-toolkit",+ "smol_str",+ "tracing",+ "unicode-segmentation",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-protocols-plasma",+ "web-sys",+ "web-time",+ "windows-sys 0.52.0",+ "x11-dl",+ "x11rb",+ "xkbcommon-dl",+]++[[package]]+name = "winnow"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"+dependencies = [+ "memchr",+]++[[package]]+name = "wit-bindgen"+version = "0.57.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"++[[package]]+name = "x11-dl"+version = "2.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f"+dependencies = [+ "libc",+ "once_cell",+ "pkg-config",+]++[[package]]+name = "x11rb"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"+dependencies = [+ "as-raw-xcb-connection",+ "gethostname",+ "libc",+ "libloading",+ "once_cell",+ "rustix 1.1.6",+ "x11rb-protocol",+]++[[package]]+name = "x11rb-protocol"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"++[[package]]+name = "xcursor"+version = "0.3.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23"++[[package]]+name = "xkbcommon-dl"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5"+dependencies = [+ "bitflags 2.13.2",+ "dlib",+ "log",+ "once_cell",+ "xkeysym",+]++[[package]]+name = "xkeysym"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"++[[package]]+name = "xml-rs"+version = "0.8.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"++[[package]]+name = "zerocopy"+version = "0.8.63"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.63"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "zlib-rs"+version = "0.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"++[[package]]+name = "zune-core"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"++[[package]]+name = "zune-inflate"+version = "0.2.54"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core",+]diff --git a/renderer/web/Cargo.toml b/renderer/web/Cargo.tomlnew file mode 100644index 0000000..e7a403c--- /dev/null+++ b/renderer/web/Cargo.toml@@ -0,0 +1,33 @@+[package]+name = "threert-web"+version = "0.1.0"+edition = "2021"+description = "ThreeRT in a browser: the engine's library as a wasm32 module (the world, the physics, the live view on WebGPU), driven by the page's own JavaScript."+license = "MIT"+publish = false++[lib]+crate-type = ["cdylib"]++[dependencies]+threert-render = { path = ".." }+wgpu = "30"+glam = "0.30"+serde_json = "1"+# The module's JavaScript side (tools/build-web.ts runs the wasm-bindgen CLI of this exact version on the build).+wasm-bindgen = "=0.2.130"+wasm-bindgen-futures = "0.4"+js-sys = "0.3"+web-sys = { version = "0.3", features = ["HtmlCanvasElement", "console"] }+# The page's clock (`performance.now()`), as the engine's library reads it.+web-time = "1.1"++[profile.release]+opt-level = 3+debug = false+lto = "thin"++# As the renderer's own manifest: cargo reads this table from the crate it builds only, and the physics' bits must not+# depend on the platform's math functions (../third_party/glamx/PATCH.md).+[patch.crates-io]+glamx = { path = "../third_party/glamx" }diff --git a/renderer/web/src/lib.rs b/renderer/web/src/lib.rsnew file mode 100644index 0000000..eba16e3--- /dev/null+++ b/renderer/web/src/lib.rs@@ -0,0 +1,594 @@+//! ThreeRT in a browser (docs/RUNTIME.md "The engine in a browser"): the engine's library as a wasm32 module. The+//! page's own JavaScript runs the game (the same bundle the native runtime loads in QuickJS: game code, the scene+//! binding and the node host); this module holds what the native process holds around the script: the engine's world,+//! the voxels, the physics, and the live view, on WebGPU.+//!+//! Two sets of exports:+//! - The engine API, one export for each native function of `globalThis.__engine` (renderer/src/script.rs+//! `install_engine`), under the same name, doing the same thing (renderer/src/api.rs is the code of both). A+//! descriptor crosses as JSON text, an array as a typed array copied into the module's memory. www/engine.js makes+//! `__engine` of them.+//! - The session, what `GameSession` and the native window do around the script: `start` (the GPU, the view of the+//! world the setup built), `frameBegin` / `frameEnd` around the node host's `frame`, `click` (the pick and the+//! event's payload), `commit`.+//!+//! Nothing here blocks: the GPU comes from futures (`Gpu::new_async`), a frame is recorded and submitted, and the+//! browser presents the canvas when the page's callback returns.++use glam::Vec3;+use serde_json::{json, Value};+use std::cell::RefCell;+use std::path::Path;+use threert_render::live::{Camera, LiveCore};+use threert_render::physics::PhysicsWorld;+use threert_render::voxel::VoxelWorld;+use threert_render::world::World;+use threert_render::{api, files, gpu};+use wasm_bindgen::prelude::*;++/// What scene code edits through `__engine`: as the native `ScriptHost`'s.+#[derive(Default)]+struct Engine {+ world: World,+ voxels: VoxelWorld,+ physics: Option<PhysicsWorld>,+}++/// The live view and the canvas it is shown on.+struct View {+ core: LiveCore,+ surface: wgpu::Surface<'static>,+ blit: wgpu::RenderPipeline,+ blit_bg: wgpu::BindGroup,+ /// The frame script's clock (`f.time`): each frame's dt clamped to [0, 0.1] s, in f64 (script.rs `GameClock`).+ clock: f64,+ /// Of the node host's `describe()`: the game has a frame script; it has world handlers.+ has_frame: bool,+ has_on: bool,+ /// The camera the scene had when the view last followed it.+ scene_cam: Camera,+ fps: u32,+ /// Lockstep (a scripted test): a frame's own time is the `dt` it is given, whatever the page's clock says.+ lockstep: bool,+ /// The first frame: when its recording began (the page's clock, ms) and, once the GPU has finished it, how long+ /// that took (f64 bits; 0: not yet). The kernels and the passes are compiled by the browser when they first run.+ first: (f64, std::sync::Arc<std::sync::atomic::AtomicU64>),+}++thread_local! {+ static ENGINE: RefCell<Engine> = RefCell::default();+ static VIEW: RefCell<Option<View>> = const { RefCell::new(None) };+}++fn thrown(e: api::Error) -> JsValue {+ match e {+ api::Error::Type(m) => js_sys::TypeError::new(&m).into(),+ api::Error::Other(e) => js_sys::Error::new(&format!("{e:#}")).into(),+ }+}++fn failed(e: impl std::fmt::Display) -> JsValue {+ js_sys::Error::new(&format!("{e:#}")).into()+}++/// A descriptor: the JSON text www/engine.js made of scene code's object.+fn desc(what: &str, json: &str) -> Result<Value, JsValue> {+ serde_json::from_str(json).map_err(|e| js_sys::TypeError::new(&format!("engine.{what}: {e}")).into())+}++fn engine<T>(f: impl FnOnce(&mut Engine) -> T) -> T {+ ENGINE.with_borrow_mut(f)+}++// ---- The engine API (script.rs `install_engine`, one for one) ----++#[wasm_bindgen]+pub fn physics(op: &str, args: &str) -> Result<String, JsValue> {+ let a = desc("physics", args)?;+ engine(|e| api::physics(&mut e.physics, &mut e.world, op, &a)).map_err(thrown)+}++#[wasm_bindgen(js_name = physicsPoses)]+pub fn physics_poses() -> Vec<f32> {+ engine(|e| api::physics_poses(&e.physics).to_vec())+}++#[wasm_bindgen(js_name = voxelLevel)]+pub fn voxel_level(d: &str) -> Result<(), JsValue> {+ let d = desc("voxelLevel", d)?;+ engine(|e| api::voxel_level(&mut e.voxels, &d)).map_err(thrown)+}++#[wasm_bindgen(js_name = voxelExplode)]+pub fn voxel_explode(x: f64, y: f64, z: f64, r: f64) -> Result<String, JsValue> {+ engine(|e| api::voxel_explode(&mut e.voxels, &mut e.world, x, y, z, r)).map_err(thrown)+}++#[wasm_bindgen(js_name = voxelEdit)]+pub fn voxel_edit(d: &str) -> Result<String, JsValue> {+ let d = desc("voxelEdit", d)?;+ engine(|e| api::voxel_edit(&mut e.voxels, &mut e.world, &d)).map_err(thrown)+}++#[wasm_bindgen(js_name = voxelHash)]+pub fn voxel_hash() -> String {+ engine(|e| api::voxel_hash(&e.voxels))+}++#[wasm_bindgen(js_name = voxelDebris)]+pub fn voxel_debris() -> Vec<f32> {+ engine(|e| e.voxels.take_debris())+}++#[wasm_bindgen(js_name = voxelFrame)]+pub fn voxel_frame(dt: f64) -> Result<String, JsValue> {+ engine(|e| api::voxel_frame(&mut e.voxels, &mut e.world, dt)).map_err(thrown)+}++#[wasm_bindgen]+pub fn geometry(id: u32, p: &[f32], n: &[f32], uv: &[f32], idx: &[u32], groups: Option<Vec<u32>>, colors: Option<Vec<f32>>) -> Result<(), JsValue> {+ engine(|e| api::geometry(&mut e.world, id, p, n, uv, idx, groups.as_deref(), colors.as_deref())).map_err(thrown)+}++#[wasm_bindgen]+pub fn texture(id: u32, d: &str, data: Option<Vec<u8>>) -> Result<(), JsValue> {+ let d = desc("texture", d)?;+ engine(|e| api::texture(&mut e.world, id, &d, data.as_deref())).map_err(thrown)+}++#[wasm_bindgen]+pub fn shader(name: &str, code: String, helpers: String) {+ engine(|e| e.world.set_shader(name, code, helpers))+}++#[wasm_bindgen(js_name = particleFunction)]+pub fn particle_function(name: &str, code: String, helpers: String) {+ engine(|e| e.world.set_particle_fn(name, code, helpers))+}++#[wasm_bindgen(js_name = particleProgram)]+pub fn particle_program(name: &str, emit: String, update: String, helpers: String) {+ engine(|e| e.world.set_particle_program(name, emit, update, helpers))+}++#[wasm_bindgen(js_name = particlesSpawn)]+pub fn particles_spawn(id: u32, data: &[f32]) -> Result<(), JsValue> {+ engine(|e| e.world.spawn_particles(id, data)).map_err(failed)+}++#[wasm_bindgen(js_name = gridProgram)]+pub fn grid_program(name: &str, code: String, helpers: String) {+ engine(|e| e.world.set_grid_program(name, code, helpers))+}++#[wasm_bindgen(js_name = densityGrid)]+pub fn density_grid(id: u32, d: &str, data: Option<Vec<f32>>) -> Result<(), JsValue> {+ let d = desc("densityGrid", d)?;+ engine(|e| api::density_grid(&mut e.world, id, &d, data.as_deref())).map_err(thrown)+}++#[wasm_bindgen(js_name = gridSources)]+pub fn grid_sources(id: u32, data: &[f32]) -> Result<(), JsValue> {+ engine(|e| e.world.add_grid_sources(id, data)).map_err(failed)+}++#[wasm_bindgen(js_name = volumeFunction)]+pub fn volume_function(name: &str, code: String, helpers: String) {+ engine(|e| e.world.set_volume_fn(name, code, helpers))+}++#[wasm_bindgen(js_name = geometryFunction)]+pub fn geometry_function(name: &str, code: String, helpers: String) {+ engine(|e| e.world.set_geometry_fn(name, code, helpers))+}++#[wasm_bindgen]+pub fn procedural(id: u32, function: String, boxes: Vec<f32>, data: Vec<u32>) -> Result<(), JsValue> {+ engine(|e| e.world.set_proc_geometry(id, function, boxes, data)).map_err(failed)+}++#[wasm_bindgen(js_name = proceduralAsset)]+pub fn procedural_asset(id: u32, function: String, uri: String) -> Result<(), JsValue> {+ engine(|e| e.world.set_proc_asset(id, function, uri)).map_err(failed)+}++#[wasm_bindgen]+pub fn material(id: u32, d: &str) -> Result<(), JsValue> {+ let d = desc("material", d)?;+ engine(|e| api::material(&mut e.world, id, &d)).map_err(thrown)+}++#[wasm_bindgen]+pub fn object(id: u32, d: &str) -> Result<(), JsValue> {+ let d = desc("object", d)?;+ engine(|e| api::object(&mut e.world, id, &d)).map_err(thrown)+}++#[wasm_bindgen]+pub fn transform(id: u32, t: &[f32]) -> Result<(), JsValue> {+ engine(|e| api::transform(&mut e.world, id, t)).map_err(thrown)+}++#[wasm_bindgen]+pub fn instances(id: u32, count: u32, m: Option<Vec<f32>>, c: Option<Vec<f32>>, d: Option<Vec<f32>>) -> Result<(), JsValue> {+ engine(|e| e.world.set_instances(id, count, m, c, d)).map_err(failed)+}++#[wasm_bindgen]+pub fn visible(id: u32, v: bool) -> Result<(), JsValue> {+ engine(|e| e.world.set_visible(id, v)).map_err(failed)+}++#[wasm_bindgen]+pub fn power(id: u32, p: f64) -> Result<(), JsValue> {+ engine(|e| e.world.set_power(id, p as f32)).map_err(failed)+}++#[wasm_bindgen(js_name = customData)]+pub fn custom_data(id: u32, v: &[f64]) -> Result<(), JsValue> {+ engine(|e| api::custom_data(&mut e.world, id, v)).map_err(thrown)+}++/// (`d`: JSON, `null` for none.)+#[wasm_bindgen]+pub fn sway(id: u32, d: &str) -> Result<(), JsValue> {+ let d = desc("sway", d)?;+ engine(|e| api::sway(&mut e.world, id, Some(&d).filter(|d| !d.is_null()))).map_err(thrown)+}++#[wasm_bindgen]+pub fn light(id: u32, d: &str) -> Result<(), JsValue> {+ let d = desc("light", d)?;+ engine(|e| api::light(&mut e.world, id, &d)).map_err(thrown)+}++#[wasm_bindgen]+pub fn camera(id: u32, d: &str) -> Result<(), JsValue> {+ let d = desc("camera", d)?;+ engine(|e| api::camera(&mut e.world, id, &d)).map_err(thrown)+}++/// (`d`: JSON, `null` for none.)+#[wasm_bindgen]+pub fn animation(id: u32, d: &str) -> Result<(), JsValue> {+ let d = desc("animation", d)?;+ engine(|e| api::animation(&mut e.world, id, Some(&d).filter(|d| !d.is_null()))).map_err(thrown)+}++#[wasm_bindgen]+pub fn remove(id: u32) {+ engine(|e| api::remove(&mut e.world, &mut e.physics, id))+}++#[wasm_bindgen]+pub fn environment(d: &str) -> Result<(), JsValue> {+ let d = desc("environment", d)?;+ engine(|e| api::environment(&mut e.world, &d)).map_err(thrown)+}++#[wasm_bindgen]+pub fn settings(d: &str) -> Result<(), JsValue> {+ let d = desc("settings", d)?;+ engine(|e| api::settings(&mut e.world, &d));+ Ok(())+}++// ---- The session ----++/// The canvas' pixels from the view's output (sRGB BGRA8 per pixel, live.wgsl `out_px`), bilinear to the canvas' size:+/// the native window's blit (renderer/src/view.rs).+const BLIT: &str = r#"+override W: f32 = 1280.0;+override H: f32 = 720.0;+override SW: f32 = 1280.0;+override SH: f32 = 720.0;+@group(0) @binding(0) var<storage, read> px: array<u32>;++@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {+ let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));+ return vec4<f32>(p * 2.0 - 1.0, 0.0, 1.0);+}++fn texel(x: i32, y: i32) -> vec4<f32> {+ let c = px[u32(clamp(y, 0, i32(H) - 1)) * u32(W) + u32(clamp(x, 0, i32(W) - 1))];+ return vec4<f32>(f32((c >> 16u) & 255u), f32((c >> 8u) & 255u), f32(c & 255u), 255.0) / 255.0;+}++@fragment fn fs(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {+ let dims = vec2<f32>(W, H);+ let uv = p.xy / vec2<f32>(SW, SH);+ let q = uv * dims - 0.5;+ let f = fract(q);+ let i = vec2<i32>(floor(q));+ let a = mix(texel(i.x, i.y), texel(i.x + 1, i.y), f.x);+ let b = mix(texel(i.x, i.y + 1), texel(i.x + 1, i.y + 1), f.x);+ return mix(a, b, f.y);+}+"#;++/// A panic's message on the page's console (the module is unusable after one).+fn hook() {+ std::panic::set_hook(Box::new(|info| web_sys::console::error_1(&format!("threert: {info}").into())));+}++/// A file the scene reads (a model, a texture, a preset), fetched by the page before `start`: the module has no file+/// system (renderer/src/files.rs).+#[wasm_bindgen]+pub fn provide(path: &str, bytes: Vec<u8>) {+ files::provide(Path::new(path), bytes);+}++/// Opens the live view of the world the game's setup built (the node host's `setup` ran before this) on `canvas`, at+/// `width` x `height` (the view's own pixels; the canvas may be larger). `info`: the node host's `describe()`.+/// `guard`: the loop guard's limit, iterations an invocation (0: 65,536; it cannot be switched off here).+/// `scale`: the traced resolution's share of the view's, 0 for dynamic resolution toward `fps`. Resolves to what it+/// opened, as JSON: the adapter, the device's limits that matter here, the times of the load.+#[wasm_bindgen]+pub async fn start(canvas: web_sys::HtmlCanvasElement, width: u32, height: u32, info: String, scale: f32, fps: u32, guard: u32) -> Result<String, JsValue> {+ hook();+ gpu::set_loop_guard(guard);+ let t0 = js_sys::Date::now();+ let info: Value = serde_json::from_str(&info).map_err(failed)?;+ let g = gpu::Gpu::new_async().await.map_err(failed)?;+ let t_gpu = js_sys::Date::now();+ let surface = g.instance.create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone())).map_err(failed)?;+ let caps = surface.get_capabilities(&g.adapter);+ // The view's output is sRGB-encoded bytes already: shown through a format that does not encode again.+ let format = caps.formats.iter().copied().find(|f| !f.is_srgb()).ok_or_else(|| failed("the canvas has no format"))?;+ let (sw, sh) = (canvas.width().max(1), canvas.height().max(1));+ surface.configure(+ &g.device,+ &wgpu::SurfaceConfiguration {+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT,+ format,+ width: sw,+ height: sh,+ present_mode: wgpu::PresentMode::Fifo,+ desired_maximum_frame_latency: 2,+ alpha_mode: caps.alpha_modes[0],+ view_formats: vec![],+ color_space: Default::default(),+ },+ );+ let limits = g.device.limits();+ let adapter = g.adapter_info.clone();+ let timestamps = g.timestamps;+ // As `GameSession::start`: the setup's changes are the scene the view is built from, not edits of it; a voxel+ // level the scene asked for is loaded now.+ let mut core = engine(|e| {+ e.world.take_changes();+ if e.voxels.realize(&mut e.world, Path::new(""))?.is_some() {+ e.world.take_changes();+ }+ LiveCore::new(g, &e.world, Path::new(""), Path::new(""), width, height)+ })+ .map_err(failed)?;+ core.dynamic_res = scale <= 0.0;+ if scale > 0.0 {+ core.render_scale = scale.clamp(threert_render::live::MIN_SCALE, 1.0);+ }+ let d = &core.g.device;+ let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("blit"), source: wgpu::ShaderSource::Wgsl(BLIT.into()) });+ let layout = d.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("blit"),+ entries: &[wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: None },+ count: None,+ }],+ });+ let pl = d.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout)], immediate_size: 0 });+ let blit = d.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("blit"),+ layout: Some(&pl),+ vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() },+ fragment: Some(wgpu::FragmentState {+ module: &module,+ entry_point: Some("fs"),+ targets: &[Some(format.into())],+ compilation_options: wgpu::PipelineCompilationOptions { constants: &[("W", width as f64), ("H", height as f64), ("SW", sw as f64), ("SH", sh as f64)], ..Default::default() },+ }),+ primitive: Default::default(),+ depth_stencil: None,+ multisample: Default::default(),+ multiview_mask: None,+ cache: None,+ });+ let blit_bg = d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("blit"), layout: &layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: core.targets.out.as_entire_binding() }] });+ let out = json!({+ "adapter": { "name": adapter.name, "vendor": adapter.vendor, "device": adapter.device, "backend": format!("{:?}", adapter.backend), "type": format!("{:?}", adapter.device_type) },+ "format": format!("{format:?}"),+ "timestamps": timestamps,+ "merged": core.g.merged,+ "loop_guard": gpu::loop_guard(),+ "limits": { "maxStorageBuffersPerShaderStage": limits.max_storage_buffers_per_shader_stage, "maxBufferSize": limits.max_buffer_size, "maxStorageBufferBindingSize": limits.max_storage_buffer_binding_size },+ "triangles": core.triangles,+ "ms": { "gpu": t_gpu - t0, "view": js_sys::Date::now() - t_gpu },+ "load": core.load_timings().iter().map(|(k, v)| (k.clone(), json!(v))).collect::<serde_json::Map<_, _>>(),+ });+ let on = |k: &str| info[k].as_array().is_some_and(|a| !a.is_empty());+ let scene_cam = core.scene_camera();+ VIEW.set(Some(View { core, surface, blit, blit_bg, clock: 0.0, has_frame: info["frame"].as_bool().unwrap_or(false), has_on: on("on"), scene_cam, fps: fps.max(1), lockstep: false, first: (0.0, Default::default()) }));+ Ok(out.to_string())+}++fn view<T>(f: impl FnOnce(&mut View) -> Result<T, JsValue>) -> Result<T, JsValue> {+ VIEW.with_borrow_mut(|v| f(v.as_mut().ok_or_else(|| failed("no view: `start` has not resolved"))?))+}++/// The view shows the scene's camera: when scene code moved it (or made another the scene's), the view follows.+fn follow(v: &mut View) {+ let cam = v.core.scene_camera();+ if cam != v.scene_cam {+ v.scene_cam = cam;+ v.core.set_camera(cam);+ }+}++/// Applies what scene code changed to the view (`LiveCore::commit`): true if that rebuilt the scene.+fn commit_view(v: &mut View) -> Result<bool, JsValue> {+ let rebuilt = engine(|e| v.core.commit(&mut e.world)).map_err(failed)?;+ follow(v);+ Ok(rebuilt)+}++/// Lockstep on or off (a scripted test's clock: every frame takes the `dt` it is given, as the native runner's+/// `lockstep` command).+#[wasm_bindgen(js_name = setLockstep)]+pub fn set_lockstep(on: bool) -> Result<(), JsValue> {+ view(|v| {+ v.lockstep = on;+ Ok(())+ })+}++/// A frame begins, `dt` seconds after the last (`GameSession::frame` up to the frame script): the scene's time, wind+/// sway. True if the page is to run the node host's `frame` now (script.rs `ScriptHost::frames`: a frame script,+/// world handlers, or a physics world whose events are delivered once a frame).+#[wasm_bindgen(js_name = frameBegin)]+pub fn frame_begin(dt: f32) -> Result<bool, JsValue> {+ view(|v| {+ v.core.fixed_dt = v.lockstep.then_some(dt);+ v.core.advance_time(dt);+ let frames = v.has_frame || v.has_on || engine(|e| e.physics.is_some());+ if frames && v.has_frame {+ v.clock += (dt as f64).clamp(0.0, 0.1);+ v.core.set_time(v.clock as f32);+ }+ let t = v.core.scene_time();+ engine(|e| e.world.apply_sway(t));+ Ok(frames)+ })+}++/// The frame's end: the physics' ticks (after the frame script: its impulses and targets act in this frame's ticks),+/// what the script and the bodies changed committed, the frame rendered and shown. Returns the frame's numbers as+/// JSON (ms): the physics (ticks, step, sync, bodies, moved), the commit and whether it rebuilt the scene, the+/// rebuild, recording the frame, the GPU's time for the last frame that was timed and its trace pass, the traced+/// resolution's scale; and `guard_trips`, the kernel's invocations the loop guard has stopped since the view opened+/// (renderer/src/merged.rs `guard`; read back a frame or two late): anything but 0 means frames with wrong pixels.+#[wasm_bindgen(js_name = frameEnd)]+pub fn frame_end(dt: f32) -> Result<String, JsValue> {+ view(|v| {+ let now = web_time_now;+ let p0 = now();+ engine(|e| {+ if let Some(p) = e.physics.as_mut() {+ p.advance(&mut e.world, dt as f64);+ }+ });+ let p1 = now();+ let rebuilt = commit_view(v)?;+ let p2 = now();+ let tex = match v.surface.get_current_texture() {+ wgpu::CurrentSurfaceTexture::Success(t) | wgpu::CurrentSurfaceTexture::Suboptimal(t) => t,+ other => return Err(failed(format!("the canvas' texture: {other:?}"))),+ };+ let target = tex.texture.create_view(&Default::default());+ let (blit, bg) = (&v.blit, &v.blit_bg);+ v.core.render(1, |e, _| {+ let mut rp = e.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("blit"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &target, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store } })],+ depth_stencil_attachment: None,+ timestamp_writes: None,+ occlusion_query_set: None,+ multiview_mask: None,+ });+ rp.set_pipeline(blit);+ rp.set_bind_group(0, bg, &[]);+ rp.draw(0..3, 0..1);+ });+ v.core.g.queue.present(tex);+ let p3 = now();+ if v.first.0 == 0.0 {+ v.first.0 = p2;+ let done = v.first.1.clone();+ v.core.g.queue.on_submitted_work_done(move || done.store((web_time_now() - p2).to_bits(), std::sync::atomic::Ordering::Relaxed));+ }+ v.core.govern_resolution(v.fps);+ let physics = engine(|e| e.physics.as_mut().map(|p| p.take_stats()));+ // (The frame's rebuilds and why, summed over its commits, an event's included; then cleared, as the native+ // runner does when it logs a frame.)+ let (rebuild_ms, fallback) = (std::mem::take(&mut v.core.rebuild_ms), v.core.fallback.take());+ (v.core.edit_ms, v.core.instanced_ms) = (0.0, 0.0);+ Ok(json!({+ "physics": physics.map(|s| json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved })),+ "physics_ms": p1 - p0,+ "commit_ms": p2 - p1,+ "rebuilt": rebuilt,+ "rebuild_ms": rebuild_ms,+ "render_ms": p3 - p2,+ "gpu_ms": v.core.gpu_ms,+ "trace_ms": v.core.gpu_trace_ms,+ "scale": v.core.render_scale,+ "frame": v.core.frame,+ "fallback": fallback,+ "guard_trips": v.core.guard_trips,+ })+ .to_string())+ })+}++/// The page's clock, ms (`performance.now()`: what `web_time::Instant` reads).+fn web_time_now() -> f64 {+ thread_local! { static T0: web_time::Instant = web_time::Instant::now(); }+ T0.with(|t| t.elapsed().as_secs_f64() * 1e3)+}++/// A click at (u, v) of the view: the object under it as the `click` event's payload, JSON (`GameSession::click`:+/// `{ target, point, player, ray: { origin, direction }, instanceId? }`), or nothing where the click meets nothing.+/// The page sends it to the node host (`event("click", payload)`), then calls `commit`.+#[wasm_bindgen]+pub fn click(u: f32, v: f32) -> Result<Option<String>, JsValue> {+ view(|view| {+ let Some((target, p, sub)) = view.core.pick(u, v) else { return Ok(None) };+ let r = |x: f32| (x * 1e4).round() / 1e4;+ let (o, d): (Vec3, Vec3) = view.core.ray(u, v);+ let mut payload = json!({ "target": target, "point": [r(p.x), r(p.y), r(p.z)], "player": "you", "ray": { "origin": o.to_array(), "direction": d.to_array() } });+ if let Some(i) = sub {+ payload["instanceId"] = i.into();+ }+ Ok(Some(payload.to_string()))+ })+}++/// Applies what an event's handlers changed to the view, `seq` the event's sequence number (`GameSession::event`).+/// True if that rebuilt the scene.+#[wasm_bindgen]+pub fn commit(seq: f64) -> Result<bool, JsValue> {+ view(|v| {+ let rebuilt = commit_view(v)?;+ v.core.seq = seq as i64;+ Ok(rebuilt)+ })+}++/// A frame's end without a view (no GPU, no canvas: tools/web-engine.ts runs the module in Node): the physics' ticks,+/// as `frameEnd` makes them, and the scene's changes taken where a view would apply them. Returns the physics'+/// numbers as JSON (null without a world).+#[wasm_bindgen]+pub fn tick(dt: f32) -> String {+ engine(|e| {+ if let Some(p) = e.physics.as_mut() {+ p.advance(&mut e.world, dt as f64);+ }+ e.world.take_changes();+ json!(e.physics.as_mut().map(|p| { let s = p.take_stats(); json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved }) })).to_string()+ })+}++/// How long the GPU took over the view's first frame, ms from the start of its recording to its last pass done+/// (0 until then): the first use of every pipeline, so the browser's compile of the kernel and the live passes.+#[wasm_bindgen(js_name = firstFrame)]+pub fn first_frame() -> f64 {+ VIEW.with_borrow(|v| v.as_ref().map_or(0.0, |v| f64::from_bits(v.first.1.load(std::sync::atomic::Ordering::Relaxed))))+}++/// The physics world's hash (16 hex digits; "" without a world): the same calls and ticks give the same hash natively+/// and here.+#[wasm_bindgen(js_name = physicsHash)]+pub fn physics_hash() -> String {+ engine(|e| e.physics.as_ref().map_or(String::new(), |p| format!("{:016x}", p.hash())))+}diff --git a/renderer/web/www/bench.ts b/renderer/web/www/bench.tsnew file mode 100644index 0000000..9eceb87--- /dev/null+++ b/renderer/web/www/bench.ts@@ -0,0 +1,70 @@+// The boundary's cost: engine calls and the pose table timed on the module (the page runs it in a browser, `?bench=1`;+// tools/web-engine.ts --bench in Node, the same JavaScript engine without a page).+import type { WebEngine } from "./engine.ts";++/** The boundary's cost: each kind of engine call timed over many (ns a call), and the pose table of `n` bodies read+ * (ms). The engine's world gets `n` objects with a body each (weightless spheres 2 m apart: nothing moves), and one+ * tick (`tick`: the module's). */+export function bench(e: WebEngine, n: number, tick: () => void, progress?: (what: string, ms: number) => void) {+ const tri = [new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]), new Float32Array([0, 0, 1, 0, 0, 1]), new Uint32Array([0, 1, 2])] as const;+ e.geometry(1, ...tri);+ const mat = { name: "m", color: [1, 1, 1], opacity: 1, metalness: 0, roughness: 0.5, emissive: [0, 0, 0], emissiveIntensity: 0, doubleSided: false };+ e.material(2, mat as never);+ const desc = (k: number) => ({ name: `o${k}`, parent: null, castShadow: true, kind: "mesh", geometry: 1, material: 2 });+ const trs = new Float32Array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1]);+ const t_build = performance.now();+ for (let k = 0; k < n; k++) {+ e.object(10 + k, desc(k) as never);+ trs[0] = (k % 100) * 2;+ trs[1] = 1;+ trs[2] = Math.floor(k / 100) * 2;+ e.transform(10 + k, trs);+ e.physics("body", { id: k + 1, object: 10 + k, slot: k, gravityScale: 0 });+ e.physics("collider", { id: k + 1, body: k + 1, shape: { type: "sphere", radius: 0.5 } });+ }+ const build_ms = performance.now() - t_build;+ // One tick: the world as a game's queries find it. Until a tick every collider is one "added since the last tick",+ // which each query tests one by one (physics-core `fresh`): 42 µs a ray over 1,000 of them, measured here in Node,+ // against the settled world's broad phase below.+ tick();+ progress?.(`${n} objects with a body each`, build_ms);+ /** ns a call: the best of five runs of `count` calls. */+ const time = (count: number, f: (k: number) => void) => {+ const t0 = performance.now();+ let best = Infinity;+ for (let r = 0; r < 5; r++) {+ const t = performance.now();+ for (let k = 0; k < count; k++) f(k);+ best = Math.min(best, performance.now() - t);+ }+ progress?.(`${count} calls x 5`, performance.now() - t0);+ return Math.round((best / count) * 1e6 * 10) / 10;+ };+ let sink = 0;+ const calls = {+ "visible(id, bool)": time(1e6, (k) => e.visible(10 + (k % n), true)),+ "power(id, number)": time(1e6, (k) => e.power(10 + (k % n), 1)),+ "transform(id, Float32Array(10))": time(2e5, (k) => e.transform(10 + (k % n), trs)),+ "customData(id, [4])": time(2e5, (k) => e.customData(10 + (k % n), [1, 2, 3, 4])),+ "material(id, desc)": time(5e4, () => e.material(2, mat as never)),+ "object(id, desc)": time(5e4, (k) => e.object(10 + (k % n), desc(k % n) as never)),+ 'physics("state", { body })': time(5e4, (k) => (sink += e.physics("state", { body: 1 + (k % n) }).length)),+ 'physics("impulse", { body, impulse })': time(5e4, (k) => (sink += e.physics("impulse", { body: 1 + (k % n), impulse: [0, 0, 0] }).length)),+ 'physics("ray", { origin, direction })': time(2e4, () => (sink += e.physics("ray", { origin: [0.2, 9, 0.1], direction: [0, -1, 0] }).length)),+ "physicsPoses(), not read": time(2e3, () => (sink += e.physicsPoses().length)),+ };+ /** ms to fetch the table and read every body's seven numbers: the best of 20. */+ const read = (m: number) => {+ let best = Infinity;+ for (let r = 0; r < 20; r++) {+ const t = performance.now();+ const p = e.physicsPoses();+ for (let k = 0; k < m * 7; k++) sink += p[k];+ best = Math.min(best, performance.now() - t);+ }+ return Math.round(best * 1e4) / 1e4;+ };+ const poses: Record<string, number> = {};+ for (const m of [1000, 10000]) if (m <= n) poses[`${m} bodies' poses read from the table, ms`] = read(m);+ return { bodies: n, build_ms, calls_ns: calls, poses, isolated: (globalThis as { crossOriginIsolated?: boolean }).crossOriginIsolated ?? null, sink };+}diff --git a/renderer/web/www/engine.ts b/renderer/web/www/engine.tsnew file mode 100644index 0000000..9d08f44--- /dev/null+++ b/renderer/web/www/engine.ts@@ -0,0 +1,100 @@+// The engine API in a browser: `globalThis.__engine` (packages/scene/src/engine.ts `Engine`, and the voxel calls of+// packages/voxel/src/native.ts) made of the wasm module's exports (renderer/web/src/lib.rs). One export for each+// function the native runtime installs (renderer/src/script.rs `install_engine`), under the same name; this file only+// turns a descriptor into JSON text, the one thing an export cannot take as it is. Typed arrays cross as they are+// (copied into the module's memory by wasm-bindgen's glue).+import type { Engine } from "@threert/scene";++/** The module's exports this file calls (wasm-bindgen's JavaScript for renderer/web: `threert_web.js`). */+export interface EngineExports {+ physics(op: string, args: string): string;+ physicsPoses(): Float32Array;+ voxelLevel(d: string): void;+ voxelExplode(x: number, y: number, z: number, r: number): string;+ voxelEdit(d: string): string;+ voxelHash(): string;+ voxelDebris(): Float32Array;+ voxelFrame(dt: number): string;+ geometry(id: number, p: Float32Array, n: Float32Array, uv: Float32Array, idx: Uint32Array, groups?: Uint32Array | null, colors?: Float32Array | null): void;+ texture(id: number, d: string, data?: Uint8Array | null): void;+ shader(name: string, code: string, helpers: string): void;+ particleFunction(name: string, code: string, helpers: string): void;+ particleProgram(name: string, emit: string, update: string, helpers: string): void;+ particlesSpawn(id: number, data: Float32Array): void;+ gridProgram(name: string, code: string, helpers: string): void;+ densityGrid(id: number, d: string, data?: Float32Array | null): void;+ gridSources(id: number, data: Float32Array): void;+ volumeFunction(name: string, code: string, helpers: string): void;+ geometryFunction(name: string, code: string, helpers: string): void;+ procedural(id: number, fn: string, boxes: Float32Array, data: Uint32Array): void;+ proceduralAsset(id: number, fn: string, uri: string): void;+ material(id: number, d: string): void;+ object(id: number, d: string): void;+ transform(id: number, trs: Float32Array): void;+ instances(id: number, count: number, m?: Float32Array | null, c?: Float32Array | null, d?: Float32Array | null): void;+ visible(id: number, v: boolean): void;+ power(id: number, p: number): void;+ customData(id: number, v: Float64Array): void;+ sway(id: number, d: string): void;+ light(id: number, d: string): void;+ camera(id: number, d: string): void;+ animation(id: number, d: string): void;+ remove(id: number): void;+ environment(d: string): void;+ settings(d: string): void;+}++/** The voxel engine's calls (packages/voxel/src/native.ts reads them off `__engine`). */+export interface VoxelCalls {+ voxelLevel(d: object): void;+ voxelExplode(x: number, y: number, z: number, r: number): string;+ voxelEdit(d: object): string;+ voxelFrame(dt: number): string;+ voxelDebris(): Float32Array;+ voxelHash(): string;+}++export type WebEngine = Engine & VoxelCalls & { physicsPoses(): Float32Array };++const json = (d: unknown) => JSON.stringify(d ?? null);++/** `__engine` for the page: every call goes to the export of its name. */+export function webEngine(w: EngineExports): WebEngine {+ return {+ physics: (op, args) => w.physics(op, json(args)),+ physicsPoses: () => w.physicsPoses(),+ voxelLevel: (d) => w.voxelLevel(json(d)),+ voxelExplode: (x, y, z, r) => w.voxelExplode(x, y, z, r),+ voxelEdit: (d) => w.voxelEdit(json(d)),+ voxelHash: () => w.voxelHash(),+ voxelDebris: () => w.voxelDebris(),+ voxelFrame: (dt) => w.voxelFrame(dt),+ geometry: (id, p, n, uv, idx, groups, colors) => w.geometry(id, p, n, uv, idx, groups, colors),+ texture: (id, d, data) => w.texture(id, json(d), data),+ shader: (name, code, helpers) => w.shader(name, code, helpers),+ particleFunction: (name, code, helpers) => w.particleFunction(name, code, helpers),+ particleProgram: (name, emit, update, helpers) => w.particleProgram(name, emit, update, helpers),+ particlesSpawn: (id, data) => w.particlesSpawn(id, data),+ gridProgram: (name, code, helpers) => w.gridProgram(name, code, helpers),+ densityGrid: (id, d, data) => w.densityGrid(id, json(d), data),+ gridSources: (id, data) => w.gridSources(id, data),+ volumeFunction: (name, code, helpers) => w.volumeFunction(name, code, helpers),+ geometryFunction: (name, code, helpers) => w.geometryFunction(name, code, helpers),+ procedural: (id, fn, boxes, data) => w.procedural(id, fn, boxes, data),+ proceduralAsset: (id, fn, uri) => w.proceduralAsset(id, fn, uri),+ material: (id, d) => w.material(id, json(d)),+ object: (id, d) => w.object(id, json(d)),+ transform: (id, trs) => w.transform(id, trs),+ instances: (id, count, m, c, d) => w.instances(id, count, m, c, d),+ visible: (id, v) => w.visible(id, v),+ power: (id, p) => w.power(id, p),+ customData: (id, v) => w.customData(id, Float64Array.from(v)),+ sway: (id, d) => w.sway(id, json(d)),+ light: (id, d) => w.light(id, json(d)),+ camera: (id, d) => w.camera(id, json(d)),+ animation: (id, d) => w.animation(id, json(d)),+ remove: (id) => w.remove(id),+ environment: (d) => w.environment(json(d)),+ settings: (d) => w.settings(json(d)),+ };+}diff --git a/renderer/web/www/frame.ts b/renderer/web/www/frame.tsnew file mode 100644index 0000000..5d86fee--- /dev/null+++ b/renderer/web/www/frame.ts@@ -0,0 +1,26 @@+// A frame's numbers as the page records them (main.ts), apart from the page so a tool can name the type+// (tools/web-hello.ts).++/** A frame's numbers (ms): the page's own times around the module's (`frameEnd`'s JSON). */+export interface FrameRow {+ /** Since the frame before (the page's frame callback). */+ interval: number;+ /** `frameBegin`, the node host's `frame` (of which the engine's calls: `calls` of them, `calls_ms`), `frameEnd`. */+ begin: number;+ script: number;+ calls: number;+ calls_ms: number;+ end: number;+ physics: { ticks: number; step: number; sync: number; bodies: number; moved: number } | null;+ physics_ms: number;+ commit_ms: number;+ rebuilt: boolean;+ rebuild_ms: number;+ render_ms: number;+ gpu_ms: number;+ trace_ms: number;+ scale: number;+ frame: number;+ /** The kernel's invocations the loop guard has stopped since the view opened (0: every frame is sound). */+ guard_trips: number | null;+}diff --git a/renderer/web/www/index.html b/renderer/web/www/index.htmlnew file mode 100644index 0000000..35c8b7c--- /dev/null+++ b/renderer/web/www/index.html@@ -0,0 +1,19 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>ThreeRT</title>+ <style>+ html, body { margin: 0; height: 100%; background: #0b0c0e; color: #c9ccd1; font: 13px/1.4 ui-monospace, Menlo, monospace; }+ body { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; }+ /* The view keeps its own pixels and its shape; the page shows it as large as fits. */+ canvas { max-width: 100vw; max-height: calc(100vh - 32px); aspect-ratio: 16 / 9; }+ </style>+ </head>+ <body>+ <canvas id="view" width="1280" height="720"></canvas>+ <div id="status">loading</div>+ <script type="module" src="main.js"></script>+ </body>+</html>diff --git a/renderer/web/www/main.ts b/renderer/web/www/main.tsnew file mode 100644index 0000000..1764b6d--- /dev/null+++ b/renderer/web/www/main.ts@@ -0,0 +1,231 @@+// The page of a ThreeRT game in a browser (docs/RUNTIME.md "The engine in a browser"). It does what the native process+// does around the script (renderer/src/script.rs `GameSession`, renderer/src/view.rs):+// 1. loads the engine's wasm module and makes `globalThis.__engine` of its exports (engine.ts);+// 2. runs the game bundle, the same file the native runtime loads in QuickJS (tools/bundle-game.ts: game code, the+// scene binding, the node host), which installs `globalThis.__threert`;+// 3. `setup` builds the scene in the engine's world; the module opens a live view of it on the canvas (WebGPU);+// 4. every frame: the node host's `frame` (the frame script, world handlers' clock, the physics' events), then the+// module's (physics ticks, commit, render, present);+// 5. a click on the canvas: the module picks what is under it and gives the event's payload (with the view ray),+// the node host runs the `click` handlers, the module commits what they changed.+//+// URL parameters: `game` (the bundle, default game.js), `width` / `height` (the view, default 1280 x 720), `scale`+// (the traced resolution's share, default 0: dynamic, toward `fps`), `fps` (default 60), `lockstep=1` (no frame runs+// by itself: `threert.run(n, dt)` runs them, for scripted tests), `guard` (the loop guard's limit, iterations an+// invocation: default 65536; a new kernel's first runs take less), `bench=1` (no game: `threert.bench()`).+import { webEngine, type EngineExports } from "./engine.ts";+import { bench } from "./bench.ts";+import type { FrameRow } from "./frame.ts";++/** The session's exports (renderer/web/src/lib.rs) and wasm-bindgen's initialiser. */+interface Module extends EngineExports {+ default(): Promise<unknown>;+ provide(path: string, bytes: Uint8Array): void;+ start(canvas: HTMLCanvasElement, width: number, height: number, info: string, scale: number, fps: number, guard: number): Promise<string>;+ setLockstep(on: boolean): void;+ tick(dt: number): string;+ firstFrame(): number;+ frameBegin(dt: number): boolean;+ frameEnd(dt: number): string;+ click(u: number, v: number): string | undefined;+ commit(seq: number): boolean;+ physicsHash(): string;+}++/** The node host the bundle installs (packages/gameplay/src/node-host.ts). */+interface NodeHost {+ describe(): string;+ setup(roomId: string, seed?: number): string;+ event(type: string, payload: string, ts: number): string;+ frame(dt: number, now: number): void;+}++const params = new URLSearchParams(location.search);+const num = (k: string, d: number) => (params.has(k) ? Number(params.get(k)) : d);+const status = (text: string) => {+ const el = document.getElementById("status");+ if (el) el.textContent = text;+};++/** How far the page has got, for a test that waits on it: `module`, `game`, `setup`, `start` (inside the module's+ * `start`: the GPU), `running`. */+const stage = (s: string) => Object.assign(window, { threertStage: s });++async function main() {+ const t0 = performance.now();+ stage("module");+ // (A URL the bundler does not follow: wasm-bindgen's module is served beside this one.)+ const wasm = (await import(new URL("./pkg/threert_web.js", import.meta.url).href)) as Module;+ await wasm.default();+ const t_module = performance.now() - t0;++ // The engine API, with the calls counted (and timed with `profile=1`: a clock read on either side of each).+ const counters = { calls: 0, ms: 0 };+ const profile = params.get("profile") === "1";+ const raw = webEngine(wasm) as unknown as Record<string, (...a: unknown[]) => unknown>;+ const engine: Record<string, (...a: unknown[]) => unknown> = {};+ for (const [name, f] of Object.entries(raw)) {+ engine[name] = profile+ ? (...a) => {+ const t = performance.now();+ try {+ return f(...a);+ } finally {+ counters.calls++;+ counters.ms += performance.now() - t;+ }+ }+ : (...a) => (counters.calls++, f(...a));+ }+ (globalThis as { __engine?: unknown }).__engine = engine;++ if (params.get("bench") === "1") {+ Object.assign(window, { threert: { bench: (n: number) => bench(webEngine(wasm), n, () => wasm.tick(1 / 60)) } });+ status("bench");+ return;+ }++ stage("game");+ // The game: one script, as the native runtime evaluates it.+ await new Promise<void>((ok, fail) => {+ const s = document.createElement("script");+ s.src = params.get("game") ?? "game.js";+ s.onload = () => ok();+ s.onerror = () => fail(new Error(`cannot load ${s.src}`));+ document.head.append(s);+ });+ const host = (globalThis as { __threert?: NodeHost }).__threert;+ if (!host) throw new Error("the bundle installed no node host");+ const describe = JSON.parse(host.describe()) as { handlers?: string[]; on?: string[]; frame?: boolean; keys?: Record<string, string> };+ const t1 = performance.now();+ const setup = JSON.parse(host.setup(params.get("room") ?? "local", params.has("seed") ? Number(params.get("seed")) : undefined)) as object;+ const t_setup = performance.now() - t1;+ const setup_calls = { ...counters };++ const canvas = document.getElementById("view") as HTMLCanvasElement;+ const [width, height] = [num("width", 1280), num("height", 720)];+ // The canvas' own pixels: the view's, times the display's pixel ratio where the page is shown smaller than them.+ canvas.width = width;+ canvas.height = height;+ const fps = num("fps", 60);+ stage("start");+ const t2 = performance.now();+ const info = JSON.parse(await wasm.start(canvas, width, height, JSON.stringify(describe), num("scale", 0), fps, num("guard", 0))) as Record<string, unknown>;+ const t_start = performance.now() - t2;++ const handles = (type: string) => [describe.handlers, describe.on].some((h) => h?.includes(type));+ const frames: FrameRow[] = [];+ let last = performance.now();+ let errors = 0;++ /** One frame, `dt` seconds after the one before. */+ const frame = (dt: number, interval: number): FrameRow => {+ const a = performance.now();+ const scripted = wasm.frameBegin(dt);+ const b = performance.now();+ const before = { ...counters };+ if (scripted) {+ // A frame script that throws does not stop the world (as natively): the frame's ticks are made all the same.+ try {+ host.frame(dt, Date.now());+ } catch (e) {+ if (errors++ < 5) console.error(`game: frame script: ${e instanceof Error ? e.message : e}`);+ }+ }+ const c = performance.now();+ const end = JSON.parse(wasm.frameEnd(dt)) as Omit<FrameRow, "interval" | "begin" | "script" | "calls" | "calls_ms" | "end">;+ const d = performance.now();+ const row: FrameRow = { interval, begin: b - a, script: c - b, calls: counters.calls - before.calls, calls_ms: counters.ms - before.ms, end: d - c, ...end };+ frames.push(row);+ if (frames.length > 20000) frames.splice(0, 10000);+ return row;+ };++ /** An event on this page's own node host (local play: the page is the authority), then what it changed committed. */+ const event = (type: string, payload: string) => {+ const t = performance.now();+ const out = JSON.parse(host.event(type, payload, Date.now())) as { log: string[]; seq: number };+ const script = performance.now() - t;+ const rebuilt = wasm.commit(out.seq);+ for (const l of out.log) console.log(`game: ${l}`);+ return { log: out.log, seq: out.seq, script_ms: script, commit_ms: performance.now() - t - script, rebuilt };+ };++ /** A click at (u, v) of the view: the pick, the `click` event with what is under it and the view ray. */+ const click = (u: number, v: number) => {+ if (!handles("click")) return null;+ const t = performance.now();+ const payload = wasm.click(u, v);+ if (payload === undefined) return null;+ const pick_ms = performance.now() - t;+ return { payload: JSON.parse(payload) as object, pick_ms, ...event("click", payload) };+ };+ canvas.addEventListener("click", (e) => {+ const r = canvas.getBoundingClientRect();+ const c = click((e.clientX - r.left) / r.width, (e.clientY - r.top) / r.height);+ session.clicks.push(c);+ });+ addEventListener("keydown", (e) => {+ const key = e.key.length === 1 ? e.key.toUpperCase() : e.key;+ const type = describe.keys?.[key];+ if (type && !e.repeat) event(type, "{}");+ });++ const session = {+ info: { ...info, describe, setup, ms: { module: t_module, setup: t_setup, start: t_start, ...(info.ms as object) }, setup_calls },+ frames,+ clicks: [] as (ReturnType<typeof click> | null)[],+ lockstep: params.get("lockstep") === "1",+ /** `n` frames now, each `dt` seconds after the one before (lockstep: a scripted test's clock). */+ step: (n: number, dt = 1 / 60) => {+ for (let k = 0; k < n; k++) frame(dt, 0);+ return frames.length;+ },+ /**+ * `n` frames in lockstep, a few at a time with the browser's own frame between them (the canvas is shown, the+ * loop guard's count comes back): it stops early if the guard has stopped anything, and resolves to the frames+ * it ran.+ */+ run: async (n: number, dt = 1 / 60) => {+ let done = 0;+ while (done < n && !frames.at(-1)?.guard_trips) {+ for (let k = 0; k < 2 && done < n; k++, done++) frame(dt, 0);+ await new Promise(requestAnimationFrame);+ }+ return done;+ },+ click,+ event: (type: string, payload: unknown = {}) => event(type, JSON.stringify(payload)),+ physicsHash: () => wasm.physicsHash(),+ /** The GPU's time over the first frame, ms (0 until it is done): the pipelines' compile. */+ firstFrame: () => wasm.firstFrame(),+ /** The loop guard's count as last read back (null: the kernel has no guard). */+ guardTrips: () => frames.at(-1)?.guard_trips ?? null,+ };+ wasm.setLockstep(session.lockstep);+ Object.assign(window, { threert: session });++ // Frames at `fps` whatever the display's rate (a 120 Hz display shows each twice), as the native window.+ const tick = (now: number) => {+ requestAnimationFrame(tick);+ if (session.lockstep) return;+ const since = now - last;+ if (since < 1000 / fps - 2) return;+ last = now;+ const row = frame(Math.min(since / 1000, 0.1), since);+ if (row.frame % 30 === 0) status(`${(info.adapter as { name: string }).name} · ${(1000 / since).toFixed(0)} fps · GPU ${row.gpu_ms.toFixed(1)} ms · scale ${row.scale.toFixed(2)}${row.guard_trips ? ` · LOOP GUARD: ${row.guard_trips} invocations stopped, the image is wrong` : ""}`);+ };+ // (The first callback's own time may be from before `start` held the thread: the clock's now instead.)+ requestAnimationFrame(() => {+ last = performance.now();+ requestAnimationFrame(tick);+ });+ status("running");+ stage("running");+}++main().catch((e) => {+ status(`failed: ${e instanceof Error ? e.message : e}`);+ console.error(e);+ Object.assign(window, { threertError: String(e instanceof Error ? (e.stack ?? e.message) : e) });+});diff --git a/renderer/web/www/tsconfig.json b/renderer/web/www/tsconfig.jsonnew file mode 100644index 0000000..38d3070--- /dev/null+++ b/renderer/web/www/tsconfig.json@@ -0,0 +1 @@+{ "extends": "../../../tsconfig.base.json", "compilerOptions": { "lib": ["es2023", "dom"] }, "include": ["."] }diff --git a/tools/bench-layout.ts b/tools/bench-layout.tsnew file mode 100644index 0000000..099b8c0--- /dev/null+++ b/tools/bench-layout.ts@@ -0,0 +1,81 @@+// What the merged binding layout and the loop guard cost natively (docs/RUNTIME.md "The engine in a browser"): the+// same scene live under software traversal with the layout as written, the merged one, and each with the loop guard,+// in an order that repeats each (A B B A ...: the same variant twice in a row is the noise), 1280 x 720 at the 0.5+// floor: GPU ms a frame and its trace pass (timestamp queries), the frame interval, and the guard's count (0, or the+// numbers mean nothing). A still view, so nothing rebuilds. The GPU lock is held.+//+// node tools/bench-layout.ts [hello | kabukicho] [--seconds 8] [--json out.json]+//+// Every variant but the first runs the kernel in a form this machine may not have run before. After 2026-11-11 (a+// dispatch that did not end took the display down): the first frame of each variant is waited for with a timeout,+// and a variant that does not give one stops the whole run: nothing is retried, nothing else is started.+import { execFileSync } from "node:child_process";+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { acquireGpuLock, rendererBin, repoRoot } from "./lib/bench.ts";+import { branchBuild } from "./lib/build-at.ts";+import { gpuUtilization, startLive } from "./lib/live.ts";++const args = process.argv.slice(2);+const opt = (f: string, d: string) => (args.includes(f) ? args[args.indexOf(f) + 1] : d);+const scene = args.find((a) => a === "hello" || a === "kabukicho") ?? "hello";+const seconds = Number(opt("--seconds", "8"));+const GUARD = "65536";+const variants: Record<string, Record<string, string>> = {+ written: { THREERT_HWRT: "0" },+ "written+guard": { THREERT_HWRT: "0", THREERT_LOOP_GUARD: GUARD },+ merged: { THREERT_MERGED: "1" },+ "merged+guard": { THREERT_MERGED: "1", THREERT_LOOP_GUARD: GUARD },+};+// Guarded variants first: a kernel that would not end is found by its count, not by the display.+const order = ["written+guard", "merged+guard", "written", "merged", "merged", "written", "merged+guard", "written+guard"];++const holder = acquireGpuLock("bench-layout");+if (holder) { console.log(`not measured: GPU lock held by ${holder.tool} (pid ${holder.pid})`); process.exit(2); }+const b = branchBuild(rendererBin);+const bundle = join(repoRoot, scene === "hello" ? "out/bundles/physics-hello.js" : "out/bundles/kabukicho.js");+if (scene === "hello") execFileSync("node", [join(repoRoot, "tools/bundle-game.ts"), join(repoRoot, "games/physics/hello.game.ts"), "-o", bundle], { stdio: "ignore" });+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));+const q = (xs: number[], p: number) => { const s = [...xs].sort((a, c) => a - c); return s.length ? s[Math.min(s.length - 1, Math.floor(p * s.length))] : NaN; };+const r2 = (v: number) => Math.round(v * 100) / 100;+type Frame = { t: number; interval: number; gpu: number; trace: number; scale: number; guard: number | null };+const log = join(repoRoot, "out/bench/layout-frames.jsonl");+mkdirSync(dirname(log), { recursive: true });++const rows: unknown[] = [];+for (const name of order) {+ const busy = await gpuUtilization(2000);+ const live = startLive(b, bundle, { scale: "0.5", frameLog: log, env: variants[name] });+ // (30 s: the merged kernel is compiled on its first run.)+ const first = await Promise.race([live.firstFrame, sleep(30_000).then(() => null)]).catch((e: Error) => e);+ if (first === null || first instanceof Error) {+ console.log(`bench layout: STOPPED at ${name}: ${first === null ? "no first frame in 30 s" : first.message}`);+ console.log("bench layout: nothing was retried. If the renderer is still there (ps), leave the GPU alone and look before running anything on it again: `sample <pid>`, /Library/Logs/DiagnosticReports.");+ process.exit(3);+ }+ // Frames must be coming: a dispatch that does not end shows as a frame log that stands still.+ const count = () => { try { return readFileSync(log, "utf8").split("\n").slice(0, -1).length; } catch { return 0; } };+ await sleep(4000);+ const mark = count();+ if (mark < 30) {+ console.log(`bench layout: STOPPED at ${name}: ${mark} frames in the first 4 s`);+ console.log("bench layout: nothing was retried and the renderer was not killed. Leave the GPU alone and look before running anything on it again: `ps`, `sample <pid>`, /Library/Logs/DiagnosticReports.");+ process.exit(3);+ }+ await sleep(seconds * 1000);+ await live.quit();+ // The window by the frames' own clock (`t`, ms since the view opened): the last `seconds` of the run. (Not by the+ // log's line count at a moment: the renderer writes its log through a buffer, a dozen frames behind.)+ const all = readFileSync(log, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l) as Frame);+ const end = all.at(-1)?.t ?? 0;+ const F = all.filter((f) => f.t > end - seconds * 1000);+ const trips = F.at(-1)?.guard ?? null;+ const row = { variant: name, frames: F.length, gpu: [r2(q(F.map((f) => f.gpu), 0.5)), r2(q(F.map((f) => f.gpu), 0.95))], trace: [r2(q(F.map((f) => f.trace), 0.5)), r2(q(F.map((f) => f.trace), 0.95))], interval: [r2(q(F.map((f) => f.interval), 0.5)), r2(q(F.map((f) => f.interval), 0.95))], first_frame_s: r2(first / 1000), guard_trips: trips, other_gpu_before_pct: busy === null ? null : r2(busy) };+ rows.push(row);+ console.log(`bench layout: ${scene} ${JSON.stringify(row)}`);+ if (trips) {+ console.log(`bench layout: STOPPED: the loop guard stopped ${trips} invocations in ${name}: a traversal that does not end; the unguarded variants are not run.`);+ process.exit(1);+ }+}+if (args.includes("--json")) writeFileSync(opt("--json", ""), JSON.stringify({ scene, seconds, rows }, null, 1));diff --git a/tools/build-web.ts b/tools/build-web.tsnew file mode 100644index 0000000..fc2f339--- /dev/null+++ b/tools/build-web.ts@@ -0,0 +1,23 @@+// Builds a ThreeRT game as a page (docs/RUNTIME.md "The engine in a browser"): the engine's wasm module+// (renderer/web), wasm-bindgen's JavaScript for it, the page (renderer/web/www) and the game's bundle, the same file+// the native runtime loads. Prints the sizes. `--serve` keeps a server on it (WebGPU needs localhost or https).+//+// node tools/build-web.ts [games/physics/hello.game.ts] [-o out/web/dist] [--serve [port]]+//+// Needs the wasm32 target (rustup target add wasm32-unknown-unknown) and the wasm-bindgen CLI of the version in+// renderer/web/Cargo.toml (cargo install wasm-bindgen-cli --version <it> --locked).+import { join, resolve } from "node:path";+import { repoRoot } from "./bundle-game.ts";+import { buildWeb, describeBuild, serveWeb } from "./lib/web.ts";++const args = process.argv.slice(2);+const game = args.find((a) => a.endsWith(".ts") || a.endsWith(".js")) ?? join(repoRoot, "games/physics/hello.game.ts");+const dir = args.includes("-o") ? resolve(args[args.indexOf("-o") + 1]) : undefined;+const b = await buildWeb(resolve(game), dir);+console.log(describeBuild(b));+console.log(`web build: ${b.dir.replace(repoRoot + "/", "")}`);+if (args.includes("--serve")) {+ const port = Number(args[args.indexOf("--serve") + 1]);+ const { url } = await serveWeb(b.dir, Number.isFinite(port) ? port : 8787);+ console.log(`web build: ${url} (Ctrl-C stops it)`);+}diff --git a/tools/lib/web.ts b/tools/lib/web.tsnew file mode 100644index 0000000..10d18df--- /dev/null+++ b/tools/lib/web.ts@@ -0,0 +1,91 @@+// A ThreeRT game as a page (docs/RUNTIME.md "The engine in a browser"): the build (the engine's wasm module, its+// JavaScript, the page, the game's bundle) and a static server for it. Used by tools/build-web.ts and+// tools/web-hello.ts.+import { execFileSync } from "node:child_process";+import { build } from "esbuild";+import { copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";+import { open, stat } from "node:fs/promises";+import { createServer, type Server } from "node:http";+import { homedir } from "node:os";+import { extname, join, normalize } from "node:path";+import { brotliCompressSync, constants, gzipSync } from "node:zlib";+import { bundleGame, repoRoot } from "../bundle-game.ts";++const crate = join(repoRoot, "renderer/web");+/** The wasm-bindgen CLI's version: the `wasm-bindgen` crate's in renderer/web/Cargo.toml (they must be the same). */+const BINDGEN = /wasm-bindgen = "=([\d.]+)"/.exec(readFileSync(join(crate, "Cargo.toml"), "utf8"))![1];++function bindgen(): string {+ const local = join(homedir(), ".cargo/bin/wasm-bindgen");+ const bin = existsSync(local) ? local : "wasm-bindgen";+ let version = "";+ try {+ version = execFileSync(bin, ["--version"], { encoding: "utf8" }).trim().split(" ").pop() ?? "";+ } catch {}+ if (version !== BINDGEN) throw new Error(`wasm-bindgen ${BINDGEN} is needed (found ${version || "none"}): cargo install wasm-bindgen-cli --version ${BINDGEN} --locked`);+ return bin;+}++export interface WebBuild {+ dir: string;+ /** The module's size, bytes: as built, gzip -9, brotli 11; and the JavaScript beside it (wasm-bindgen's + the page's). */+ wasm: { raw: number; gzip: number; brotli: number };+ js: { raw: number; gzip: number; brotli: number };+ game: { raw: number; gzip: number; brotli: number };+ ms: { cargo: number; bindgen: number; page: number };+}++const sizes = (files: string[]) => {+ const bytes = Buffer.concat(files.map((f) => readFileSync(f)));+ return { raw: bytes.length, gzip: gzipSync(bytes, { level: 9 }).length, brotli: brotliCompressSync(bytes, { params: { [constants.BROTLI_PARAM_QUALITY]: 11, [constants.BROTLI_PARAM_LGWIN]: 24 } }).length };+};++/** Builds the page of `game` (a game or scene module) into `dir`: index.html, main.js, pkg/ (the module), game.js. */+export async function buildWeb(game: string, dir = join(repoRoot, "out/web/dist")): Promise<WebBuild> {+ const t0 = performance.now();+ execFileSync("cargo", ["build", "--release", "--locked", "--target", "wasm32-unknown-unknown"], { cwd: crate, stdio: ["ignore", "ignore", "inherit"] });+ const t1 = performance.now();+ mkdirSync(join(dir, "pkg"), { recursive: true });+ execFileSync(bindgen(), ["--target", "web", "--no-typescript", "--out-dir", join(dir, "pkg"), join(crate, "target/wasm32-unknown-unknown/release/threert_web.wasm")], { stdio: ["ignore", "ignore", "inherit"] });+ const t2 = performance.now();+ await build({ entryPoints: [join(crate, "www/main.ts")], bundle: true, format: "esm", target: "es2022", outfile: join(dir, "main.js"), nodePaths: [join(repoRoot, "node_modules")], logLevel: "warning" });+ copyFileSync(join(crate, "www/index.html"), join(dir, "index.html"));+ await bundleGame(game, join(dir, "game.js"));+ return {+ dir,+ wasm: sizes([join(dir, "pkg/threert_web_bg.wasm")]),+ js: sizes([join(dir, "pkg/threert_web.js"), join(dir, "main.js")]),+ game: sizes([join(dir, "game.js")]),+ ms: { cargo: t1 - t0, bindgen: t2 - t1, page: performance.now() - t2 },+ };+}++const types: Record<string, string> = { ".html": "text/html", ".js": "text/javascript", ".wasm": "application/wasm", ".json": "application/json", ".png": "image/png", ".jpg": "image/jpeg", ".glb": "model/gltf-binary" };++/**+ * Serves `dir` on localhost (a secure context: WebGPU needs one), cross-origin isolated so the page's clock is not+ * coarsened (5 µs instead of 100 µs). Port 0: any free one. Resolves to the server and its URL.+ */+export function serveWeb(dir: string, port = 0): Promise<{ server: Server; url: string }> {+ const server = createServer(async (req, res) => {+ const path = normalize(decodeURIComponent(new URL(req.url ?? "/", "http://x").pathname)).replace(/^(\.\.[/\\])+/, "");+ const file = join(dir, path === "/" ? "index.html" : path);+ try {+ if (!file.startsWith(dir)) throw new Error("outside");+ const size = (await stat(file)).size;+ const f = await open(file);+ res.writeHead(200, { "content-type": types[extname(file)] ?? "application/octet-stream", "content-length": size, "cross-origin-opener-policy": "same-origin", "cross-origin-embedder-policy": "require-corp", "cache-control": "no-store" });+ f.createReadStream().pipe(res).on("close", () => f.close());+ } catch {+ res.writeHead(404).end("not found");+ }+ });+ return new Promise((ok) => server.listen(port, "127.0.0.1", () => ok({ server, url: `http://localhost:${(server.address() as { port: number }).port}/` })));+}++/** A build's line for a log. */+export function describeBuild(b: WebBuild): string {+ const kb = (n: number) => `${(n / 1024).toFixed(0)} KiB`;+ const row = (s: { raw: number; gzip: number; brotli: number }) => `${kb(s.raw)} (gzip ${kb(s.gzip)}, brotli ${kb(s.brotli)})`;+ return `web build: module ${row(b.wasm)}, its JavaScript and the page's ${row(b.js)}, the game's bundle ${row(b.game)}; cargo ${(b.ms.cargo / 1000).toFixed(1)} s, wasm-bindgen ${(b.ms.bindgen / 1000).toFixed(1)} s`;+}diff --git a/tools/web-engine.ts b/tools/web-engine.tsnew file mode 100644index 0000000..346ecd9--- /dev/null+++ b/tools/web-engine.ts@@ -0,0 +1,125 @@+// The physics hello world on the browser's module without a browser (docs/RUNTIME.md "The engine in a browser"):+// renderer/web's wasm module loaded in Node (V8, the JavaScript engine Chrome has), `__engine` made of its exports by+// the page's own code (renderer/web/www/engine.ts), and the game bundle, the file the native runtime loads, run on+// it. No GPU and no view: what is checked is everything else of the browser's side: the exports, a descriptor's way+// across as JSON, the scene binding's calls arriving, the `click` world handler's ray query, the physics' ticks. The+// script is tools/physics-hello.ts's (five clicks, the same frames between them, 1 / 60 s each), the clicks given as+// the view rays the renderer would send, and the checks are its checks on the same numbers. CI runs it.+//+// node tools/web-engine.ts [--native out.json] [--json out.json]+// --native: the native test's numbers (node tools/physics-hello.ts --json out.json), compared number for number.+import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { pathToFileURL } from "node:url";+import { BOX, CAMERA, KICK, OFF, WALL_Z } from "../games/physics/hello.game.ts";+import { repoRoot } from "./bundle-game.ts";+import { buildWeb, describeBuild } from "./lib/web.ts";+import { bench } from "../renderer/web/www/bench.ts";+import { webEngine, type EngineExports } from "../renderer/web/www/engine.ts";++type V3 = [number, number, number];+const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+const unit = (a: V3): V3 => { const l = Math.hypot(...a); return [a[0] / l, a[1] / l, a[2] / l]; };++const args = process.argv.slice(2);+const opt = (f: string) => (args.includes(f) ? args[args.indexOf(f) + 1] : undefined);+const build = await buildWeb(join(repoRoot, "games/physics/hello.game.ts"));+console.log(describeBuild(build));+const wasm = (await import(pathToFileURL(join(build.dir, "pkg/threert_web.js")).href)) as EngineExports & { initSync(o: { module: BufferSource }): unknown; tick(dt: number): string; physicsHash(): string };+wasm.initSync({ module: readFileSync(join(build.dir, "pkg/threert_web_bg.wasm")) });+const engine = webEngine(wasm);+(globalThis as { __engine?: unknown }).__engine = engine;+// One for one: what the native runtime installs as `__engine` (script.rs `install_engine`), the page's `__engine`,+// the module's exports.+const natives = [...readFileSync(join(repoRoot, "renderer/src/script.rs"), "utf8").matchAll(/\be\.set\("(\w+)"/g)].map((m) => m[1]).sort();+const here = Object.keys(engine).sort();+const exported = here.filter((k) => typeof (wasm as unknown as Record<string, unknown>)[k] === "function");++// `--bench [n]`: the boundary's cost on this module in Node (renderer/web/www/bench.ts, what the page runs with+// `?bench=1`), each part's time as it ends; then nothing else.+if (args.includes("--bench")) {+ const n = Number(opt("--bench")) || 10000;+ const t = performance.now();+ const r = bench(engine, n, () => wasm.tick(1 / 60), (what, ms) => console.log(` ${what}: ${ms.toFixed(0)} ms`));+ console.log(`web engine: the boundary in Node ${process.version}, ${((performance.now() - t) / 1000).toFixed(1)} s: ${JSON.stringify(r, null, 1)}`);+ process.exit(0);+}++// The game: one script, as the page evaluates it; its console is the test's record.+const lines: string[] = [];+const log = console.log;+console.log = (...a: unknown[]) => void lines.push(a.map(String).join(" "));+(0, eval)(readFileSync(join(build.dir, "game.js"), "utf8"));+const host = (globalThis as unknown as { __threert: { describe(): string; setup(room: string): string; event(type: string, payload: string, ts: number): string; frame(dt: number, now: number): void } }).__threert;+const describe = JSON.parse(host.describe()) as { on?: string[]; handlers?: string[] };+host.setup("local");++/** The view ray through a point of the world: what the renderer sends with a click (`LiveCore::ray`). */+function ray(p: V3) {+ const o = [...CAMERA.position] as V3;+ return { origin: o, direction: unit(sub(p, o)) };+}+const DT = 1 / 60;+let now = 1_000_000;+const step = (frames: number) => {+ for (let k = 0; k < frames; k++) {+ host.frame(DT, (now += 1000 * DT));+ wasm.tick(DT);+ }+};+const click = (at: V3, settle: number) => {+ host.event("click", JSON.stringify({ target: "", point: at, player: "you", ray: ray(at) }), (now += 1));+ step(settle);+};+step(10);+const column: V3 = [-1, 0, WALL_Z + OFF], lone: V3 = [1.5, 0, 2.5];+click(column, 120);+click([column[0], 1.2, WALL_Z], 150);+click([column[0], 1.7, WALL_Z], 180);+click(lone, 120);+click([lone[0], 0.3, lone[2]], 240);+host.event("report", "{}", (now += 1));+step(2);+console.log = log;++const hello = lines.map((l) => /hello (\{.*\})/.exec(l)?.[1]).filter((x): x is string => !!x).map((x) => JSON.parse(x) as { click: number; add?: string; kick?: string; on?: string; at?: V3 });+const report = lines.map((l) => /report (\{.*\})/.exec(l)?.[1]).filter((x): x is string => !!x).map((x) => JSON.parse(x) as { boxes: { name: string; at: V3; speed: number; asleep: boolean }[]; kicks: number }).pop();+const failures: string[] = [];+const check = (ok: boolean, what: string) => { console.log(`${ok ? "ok " : "FAIL"} ${what}`); if (!ok) failures.push(what); };+const near = (a: V3, b: V3, tol: number) => Math.hypot(...sub(a, b)) <= tol;+const fmt = (a: V3) => `(${a.map((v) => v.toFixed(3)).join(", ")})`;+console.log(`web engine: the module in Node ${process.version}; the game's handlers: ${JSON.stringify(describe.on)}`);+check(natives.length > 30 && natives.join() === here.join() && exported.length === here.length, `the engine API is the native one, one for one: ${natives.length} functions installed natively, ${here.length} in the page's __engine, ${exported.length} of them exports of the module${natives.join() === here.join() ? "" : `: native only ${natives.filter((n) => !here.includes(n))}, here only ${here.filter((n) => !natives.includes(n))}`}`);+for (const h of hello) console.log(` click ${h.click}: ${h.add ? `adds ${h.add} over the ${h.on} at ${fmt(h.at!)}` : h.kick ? `kicks ${h.kick}` : "meets nothing"}`);+check(hello.filter((h) => h.add).length === 4 && hello.filter((h) => h.kick).length === 1, "4 boxes added, 1 kick");+check(hello.filter((h) => h.add).map((h) => h.on).join() === "ground,wall,wall,ground", "added over the ground, the wall twice, the ground");+check(hello.find((h) => h.kick)?.kick === "box3", "the kick meets box3");+const boxes = report?.boxes ?? [];+check(boxes.length === 4 && report?.kicks === 1, "the scene holds 4 boxes");+if (boxes.length === 4) {+ const h = BOX / 2;+ for (const [k, y, tol] of [[0, h, 0.02], [1, h + BOX, 0.05], [2, h + 2 * BOX, 0.05]] as const) {+ check(near(boxes[k].at, [column[0], y, column[2]], tol), `box${k} rests at ${fmt(boxes[k].at)}: ${fmt([column[0], y, column[2]])} within ${tol} m`);+ }+ const from: V3 = [lone[0], h, lone[2]];+ const dir = unit([lone[0] - CAMERA.position[0], 0, lone[2] - CAMERA.position[2]]);+ const expected = (KICK * KICK) / (2 * 0.5 * 9.81);+ const moved = sub(boxes[3].at, from), along = dot(moved, dir), across = Math.hypot(...sub(moved, [dir[0] * along, 0, dir[2] * along]));+ check(Math.abs(along - expected) <= 0.15 * expected && across < 0.05, `box3 slid ${along.toFixed(3)} m along the kick (${across.toFixed(3)} m off it): ${expected.toFixed(3)} m within 15 %`);+ check(Math.abs(boxes[3].at[1] - h) < 0.01, `box3 is on the ground (y ${boxes[3].at[1].toFixed(4)})`);+ check(boxes.every((b) => b.asleep && b.speed === 0), "every box is at rest, asleep");+}+const hash = wasm.physicsHash();+console.log(`web engine: the physics world's hash after the run: ${hash}`);+const native = opt("--native");+if (native && existsSync(native)) {+ const n = JSON.parse(readFileSync(native, "utf8")) as { hello: typeof hello; report: typeof report };+ const same = JSON.stringify(n.report) === JSON.stringify(report);+ check(same, `the report is the native run's, number for number${same ? "" : `: here ${JSON.stringify(report)}, natively ${JSON.stringify(n.report)}`}`);+}+const json = opt("--json");+if (json) writeFileSync(json, JSON.stringify({ hello, report, hash, failures }, null, 1));+console.log(failures.length ? `web engine: FAIL (${failures.length})` : "web engine: pass");+process.exit(failures.length ? 1 : 0);diff --git a/tools/web-hello.ts b/tools/web-hello.tsnew file mode 100644index 0000000..6e88dd5--- /dev/null+++ b/tools/web-hello.ts@@ -0,0 +1,315 @@+// The physics hello world in a browser (docs/RUNTIME.md "The engine in a browser"): games/physics/hello.game.ts, the+// file the native test runs, as a page (tools/build-web.ts) in this machine's Chrome, driven by Playwright. The same+// script as tools/physics-hello.ts and the same checks on the same numbers: frames in lockstep (1 / 60 s each: one+// tick), five clicks made with the mouse on the canvas (the page's own click path: pick, view ray, the node host's+// `click` handler), four boxes added, one kicked, where they rest and how far the kicked one slid.+//+// node tools/web-hello.ts the scripted test (exit 1 on a failed check)+// node tools/web-hello.ts --small only the first step: a 160 x 90 view, fourteen frames (a new kernel's first run)+// node tools/web-hello.ts --frames then the frame times: the same clicks in real time, still and moving frames+// node tools/web-hello.ts --bench then the boundary's cost: engine calls and the pose table, in this Chrome+// --native out.json compare with the native test's numbers (node tools/physics-hello.ts --json out.json)+// --json out.json everything measured+// --headless no window (Chrome's new headless; WebGPU there is not checked on every version)+// --view WxH --scale S the scripted test's view and the traced share of it (default 1280x720, 0.5)+// --guard N the loop guard's limit for every page (default: 8192 for the small step, the page's 65536 after)+// --cold a fresh browser profile: the shaders compiled again (the first visit's times)+//+// A GPU job that does not end takes this machine's display with it (2026-11-11), and a page's shader runs on the same+// GPU as everything else. So: the kernel in the page has the loop guard (renderer/src/merged.rs `guard`), and its+// count is a check here (0, or the frames are wrong); the first step is small; every wait on the page has a timeout;+// and a timeout stops the run where it is: nothing is retried, no second page is opened (exit 3; see the message).+// The GPU lock is held.+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { chromium, type Page } from "playwright-core";+import { BOX, CAMERA, KICK, OFF, WALL_Z } from "../games/physics/hello.game.ts";+import { acquireGpuLock, repoRoot } from "./lib/bench.ts";+import { buildWeb, describeBuild, serveWeb } from "./lib/web.ts";+import type { FrameRow } from "../renderer/web/www/frame.ts";++const args = process.argv.slice(2);+const has = (f: string) => args.includes(f);+const opt = (f: string) => (has(f) ? args[args.indexOf(f) + 1] : undefined);++type V3 = [number, number, number];+const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+const unit = (a: V3): V3 => { const l = Math.hypot(...a); return [a[0] / l, a[1] / l, a[2] / l]; };+/** Where a point of the world is in the image (u, v in 0..1), through the game's camera (as tools/physics-hello.ts). */+function project(p: V3): { u: number; v: number } {+ const c = [...CAMERA.position] as V3, fwd = unit(sub([...CAMERA.target] as V3, c));+ const right = unit(cross(fwd, [0, 1, 0])), up = cross(right, fwd);+ const d = sub(p, c), z = dot(d, fwd), t = Math.tan((CAMERA.fov * Math.PI) / 360);+ return { u: 0.5 + dot(d, right) / z / (2 * t * (CAMERA.width / CAMERA.height)), v: 0.5 - dot(d, up) / z / (2 * t) };+}++/** A wait on the page that did not come back: the run stops here (see the head of this file). */+class Stuck extends Error {}+const TIMEOUT = 30_000;+/** `f` in the page, or `Stuck` after TIMEOUT. */+async function inPage<T, A>(page: Page, what: string, f: (a: A) => T | Promise<T>, arg?: A): Promise<T> {+ let timer: NodeJS.Timeout | undefined;+ const late = new Promise<never>((_, fail) => (timer = setTimeout(() => fail(new Stuck(what)), TIMEOUT)));+ try {+ return await Promise.race([page.evaluate(f as (a: unknown) => T, arg), late]);+ } finally {+ clearTimeout(timer);+ }+}++const holder = acquireGpuLock("web-hello");+if (holder) { console.log(`not run: GPU lock held by ${holder.tool} (pid ${holder.pid}) since ${holder.started}`); process.exit(2); }++const build = await buildWeb(join(repoRoot, "games/physics/hello.game.ts"));+console.log(describeBuild(build));+const { server, url } = await serveWeb(build.dir);+// A profile of its own, kept between runs: the second visit finds the shaders the first compiled (`--cold` drops it).+const profile = join(repoRoot, "out/web/chrome-profile");+if (has("--cold")) rmSync(profile, { recursive: true, force: true });+const context = await chromium.launchPersistentContext(profile, {+ channel: "chrome",+ headless: has("--headless"),+ viewport: { width: 1300, height: 780 },+ // Timestamp queries at full resolution (the frame's GPU time); nothing else is switched.+ args: ["--enable-webgpu-developer-features"],+});+// The loop guard's limit for the small first step (hello world's tree has 77 nodes: a sample is a few hundred+// iterations); the page's default, 65,536, after it.+const GUARD_FIRST = Number(opt("--guard") ?? 8192);+// The view of the scripted test and the frame times: `--view 640x360` (default the game's 1280 x 720), `--scale`+// (the traced share of it, default 0.5).+const [VW, VH] = (opt("--view") ?? `${CAMERA.width}x${CAMERA.height}`).split("x").map(Number);+const VIEW = `width=${VW}&height=${VH}&scale=${opt("--scale") ?? "0.5"}`;+// A tab of the context's own stays open throughout: closing a window's last tab and opening the next page races with+// Chrome's new-tab page (the test's page then never loads).+const keep = context.pages()[0] ?? (await context.newPage());+await keep.goto("about:blank");+const failures: string[] = [];+const check = (ok: boolean, what: string) => { console.log(`${ok ? "ok " : "FAIL"} ${what}`); if (!ok) failures.push(what); };+const out: Record<string, unknown> = { build: { wasm: build.wasm, js: build.js, game: build.game } };+let code = 0;++type Session = {+ info: Record<string, unknown>;+ frames: FrameRow[];+ clicks: unknown[];+ step(n: number, dt?: number): number;+ run(n: number, dt?: number): Promise<number>;+ click(u: number, v: number): unknown;+ event(type: string, payload?: unknown): unknown;+ guardTrips(): number | null;+ firstFrame(): number;+ bench(n: number): unknown;+};+/** What the callbacks below use of the page (they run there; this file is checked without the DOM's types). */+declare const document: { getElementById(id: string): { getBoundingClientRect(): { left: number; top: number; width: number; height: number } } };+declare const navigator: { gpu: { requestAdapter(): Promise<{ info: { vendor: string; architecture: string; device: string; description: string; isFallbackAdapter?: boolean }; isFallbackAdapter?: boolean; limits: { maxStorageBuffersPerShaderStage: number } }> } };++/** Opens the page with `query` and waits for the view (or for the page's own failure). */+async function open(query: string): Promise<{ page: Page; lines: string[]; info: Record<string, unknown> }> {+ const page = await context.newPage();+ const lines: string[] = [];+ page.on("console", (m) => lines.push(m.text()));+ page.on("pageerror", (e) => lines.push(`pageerror: ${e.message}`));+ // (`--guard N`: the loop guard's limit for every page of this run, not only the small first step's.)+ const guard = has("--guard") && !query.includes("guard=") ? `&guard=${GUARD_FIRST}` : "";+ await page.goto(`${url}?${query}${guard}`, { timeout: TIMEOUT });+ const ready = await Promise.race([+ page.waitForFunction(() => "threert" in globalThis || "threertError" in globalThis, undefined, { timeout: TIMEOUT }).then(() => true),+ new Promise<boolean>((ok) => setTimeout(() => ok(false), TIMEOUT)),+ ]).catch(() => false);+ if (!ready) {+ // How far the page got (main.ts `threertStage`): nothing means its script never ran (no GPU work on it); "start"+ // means it is inside the module's `start`, on the GPU.+ const stage = await Promise.race([page.evaluate(() => (globalThis as { threertStage?: string }).threertStage ?? null), new Promise<string>((ok) => setTimeout(() => ok("(no answer)"), 5000))]).catch(() => "(no answer)");+ throw new Stuck(`the page did not open its view (${query}); it is at ${page.url()}, stage ${stage}${stage === null ? " (its script never ran: not a GPU job)" : ""}; its console: ${lines.slice(-5).join(" | ")}`);+ }+ const error = await inPage(page, "reading the page's error", () => (globalThis as { threertError?: string }).threertError);+ if (error) throw new Error(`the page failed: ${error}`);+ const info = query.includes("bench=1") ? {} : await inPage(page, "reading the view's info", () => (globalThis as unknown as { threert: Session }).threert.info);+ return { page, lines, info };+}++/** A click with the mouse on the canvas where (u, v) of the view is shown. */+async function clickAt(page: Page, at: { u: number; v: number }) {+ const r = await inPage(page, "reading the canvas' place", () => { const b = document.getElementById("view")!.getBoundingClientRect(); return { x: b.left, y: b.top, w: b.width, h: b.height }; });+ await page.mouse.click(r.x + at.u * r.w, r.y + at.v * r.h);+}++const q = (xs: number[], p: number) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.min(s.length - 1, Math.floor(p * s.length))] : NaN; };+const r3 = (v: number) => Math.round(v * 1000) / 1000;+const pair = (xs: number[]) => [r3(q(xs, 0.5)), r3(q(xs, 0.95))];++try {+ // 1. Small: the kernel's first frames in this browser, 160 x 90, in lockstep.+ {+ const { page, info } = await open(`width=160&height=90&scale=1&lockstep=1&guard=${GUARD_FIRST}`);+ const adapter = info.adapter as { name: string; type: string; backend: string };+ // What the browser itself says of the adapter (a fallback adapter is a software one: not what this measures).+ const gpu = await inPage(page, "asking the browser for its adapter", async () => {+ const a = await navigator.gpu.requestAdapter();+ return { vendor: a.info.vendor, architecture: a.info.architecture, device: a.info.device, description: a.info.description, fallback: a.isFallbackAdapter ?? a.info.isFallbackAdapter ?? null, maxStorageBuffers: a.limits.maxStorageBuffersPerShaderStage };+ });+ console.log(`web hello: ${JSON.stringify(gpu)}; the view: ${JSON.stringify(info.adapter)}, ${JSON.stringify(info.limits)}, loop guard ${info.loop_guard}, ${JSON.stringify(info.ms)}`);+ check(gpu.fallback !== true, `the adapter is the machine's GPU, not a fallback (${gpu.vendor} ${gpu.architecture})`);+ check(info.merged === true && (info.limits as { maxStorageBuffersPerShaderStage: number }).maxStorageBuffersPerShaderStage === 8, "the device was asked for eight storage buffers a stage, the merged layout fits them");+ check(typeof info.loop_guard === "number", `the kernel has the loop guard (${info.loop_guard} iterations an invocation)`);+ // One frame first, alone; then nine, then a few more for the count (it is read back a frame or two late).+ const t_first = performance.now();+ const first = await inPage(page, "the first frame at 160 x 90", () => (globalThis as unknown as { threert: Session }).threert.run(1));+ // (Until the browser's own next frame after it: with a kernel it has not compiled before, this is where it waits.)+ const first_wall = performance.now() - t_first;+ const more = await inPage(page, "thirteen more frames", () => (globalThis as unknown as { threert: Session }).threert.run(13));+ const trips = await inPage(page, "reading the loop guard's count", () => (globalThis as unknown as { threert: Session }).threert.guardTrips());+ check(first + more === 14 && trips === 0, `fourteen frames drawn at 160 x 90, the loop guard stopped nothing (${trips})`);+ // This page is the run's first: its first frame is every pipeline's first use in this browser session (`--cold`:+ // in this profile, so the shaders' compile; else what the browser kept of it).+ const compile = await inPage(page, "reading the first frame's time", () => (globalThis as unknown as { threert: Session }).threert.firstFrame());+ const row0 = await inPage(page, "reading the first frame's row", () => (globalThis as unknown as { threert: Session }).threert.frames[0]);+ console.log(`web hello: the first frame: ${r3(first_wall)} ms until the browser's next frame after it (the page's own time in it ${r3(row0.begin + row0.script + row0.end)} ms, recording ${r3(row0.render_ms)}); its work done on the GPU ${r3(compile)} ms after it was recorded`);+ out.small = { gpu, adapter, info, first_frame_gpu_ms: compile, first_frame_wall_ms: first_wall, first_frame: row0, cold: has("--cold") };+ await page.screenshot({ path: join(repoRoot, "out/web/hello-small.png") });+ await page.close();+ if (failures.length || has("--small")) throw new Error(failures.length ? "the small run failed: nothing larger is run" : "small");+ }++ // 2. The scripted test in lockstep (1280 x 720 traced at half unless told otherwise): tools/physics-hello.ts's steps.+ // (`--skip-scripted`: not this time; the frame-time page is then the first with its kernel.)+ if (!has("--skip-scripted")) {+ const { page, lines, info } = await open(`${VIEW}&lockstep=1`);+ // (`run` stops early if the loop guard stops anything: then the frames are short of what was asked, and it shows below.)+ const step = (n: number) => inPage(page, `${n} frames`, (k: number) => (globalThis as unknown as { threert: Session }).threert.run(k), n);+ // The clicks at the exact (u, v) the native test sends (`threert.click`: what the canvas' own click listener+ // calls with the mouse's place; a mouse lands on whole pixels, 2 cm apart on the ground at this distance, so its+ // boxes would not be the native run's to the millimetre). The mouse itself is checked after the report.+ const click = async (at: V3, settle: number) => {+ await inPage(page, "a click", (uv: { u: number; v: number }) => { const s = (globalThis as unknown as { threert: Session }).threert; s.clicks.push(s.click(uv.u, uv.v)); }, project(at));+ await step(settle);+ };+ await step(10);+ const column: V3 = [-1, 0, WALL_Z + OFF], lone: V3 = [1.5, 0, 2.5];+ await click(column, 120);+ await click([column[0], 1.2, WALL_Z], 150);+ await click([column[0], 1.7, WALL_Z], 180);+ await click(lone, 120);+ await click([lone[0], 0.3, lone[2]], 240);+ await inPage(page, "the report event", () => (globalThis as unknown as { threert: Session }).threert.event("report"));+ await step(2);+ // The mouse: a real click on the canvas, on the ground to the left: a fifth box appears over where it landed.+ const spot: V3 = [-3, 0, 3.5];+ await clickAt(page, project(spot));+ await step(4);+ const state = await inPage(page, "reading the run", () => { const s = (globalThis as unknown as { threert: Session }).threert; return { clicks: s.clicks, trips: s.guardTrips(), frames: s.frames.length, rebuilt: s.frames.filter((f) => f.rebuilt).length, moved: s.frames.filter((f) => (f.physics?.moved ?? 0) > 0).length }; });+ await page.screenshot({ path: join(repoRoot, "out/web/hello.png") });+ await page.close();++ const hello = lines.map((l) => /hello (\{.*\})/.exec(l)?.[1]).filter((x): x is string => !!x).map((x) => JSON.parse(x) as { click: number; add?: string; kick?: string; on?: string; at?: V3 });+ const report = lines.map((l) => /report (\{.*\})/.exec(l)?.[1]).filter((x): x is string => !!x).map((x) => JSON.parse(x) as { boxes: { name: string; at: V3; speed: number; asleep: boolean }[]; kicks: number }).pop();+ const near = (a: V3, b: V3, tol: number) => Math.hypot(...sub(a, b)) <= tol;+ const fmt = (a: V3) => `(${a.map((v) => v.toFixed(3)).join(", ")})`;+ console.log("web hello: the clicks");+ for (const h of hello) console.log(` click ${h.click}: ${h.add ? `adds ${h.add} over the ${h.on} at ${fmt(h.at!)}` : h.kick ? `kicks ${h.kick}` : "meets nothing"}`);+ // (The mouse's box, added after the report, apart.)+ const mouse = hello.length === 6 ? hello.pop() : undefined;+ check(hello.filter((h) => h.add).length === 4 && hello.filter((h) => h.kick).length === 1, "4 boxes added, 1 kick");+ check(hello.filter((h) => h.add).map((h) => h.on).join() === "ground,wall,wall,ground", "added over the ground, the wall twice, the ground");+ check(hello.find((h) => h.kick)?.kick === "box3", "the kick meets box3");+ // A pixel of the view on the ground there is about 9 m / (view width) x 1.47 wide and a few times that deep.+ check(!!mouse?.add && mouse.on === "ground" && near(mouse.at!, [-3, OFF, 3.5], 60 / VW), `a mouse click on the canvas adds a box where it landed: ${mouse?.add} at ${mouse?.at ? fmt(mouse.at) : "?"}, (-3.000, 1.500, 3.500) within ${(60 / VW).toFixed(3)} m (a pixel)`);+ const boxes = report?.boxes ?? [];+ check(boxes.length === 4 && report?.kicks === 1, "the scene holds 4 boxes");+ if (boxes.length === 4) {+ const h = BOX / 2;+ for (const [k, y, tol] of [[0, h, 0.02], [1, h + BOX, 0.05], [2, h + 2 * BOX, 0.05]] as const) {+ check(near(boxes[k].at, [column[0], y, column[2]], tol), `box${k} rests at ${fmt(boxes[k].at)}: ${fmt([column[0], y, column[2]])} within ${tol} m`);+ }+ const from: V3 = [lone[0], h, lone[2]];+ const dir = unit([lone[0] - CAMERA.position[0], 0, lone[2] - CAMERA.position[2]]);+ const expected = (KICK * KICK) / (2 * 0.5 * 9.81);+ const moved = sub(boxes[3].at, from), along = dot(moved, dir), across = Math.hypot(...sub(moved, [dir[0] * along, 0, dir[2] * along]));+ check(Math.abs(along - expected) <= 0.15 * expected && across < 0.05, `box3 slid ${along.toFixed(3)} m along the kick (${across.toFixed(3)} m off it): ${expected.toFixed(3)} m within 15 %`);+ check(Math.abs(boxes[3].at[1] - h) < 0.01, `box3 is on the ground (y ${boxes[3].at[1].toFixed(4)})`);+ check(boxes.every((b) => b.asleep && b.speed === 0), "every box is at rest, asleep");+ }+ check(state.trips === 0, `the loop guard stopped nothing in ${state.frames} frames (${state.trips})`);+ // Software traversal: every added box and every frame a body moves rebuilds the scene (hardware: once, then in place).+ console.log(`web hello: ${state.frames} frames, ${state.rebuilt} of them rebuilt the scene (software traversal: each box added, each frame a body moved: ${state.moved})`);+ // The native test's numbers, if given: the same ticks, so the same boxes to the report's four decimals.+ const native = opt("--native");+ if (native && existsSync(native)) {+ const n = JSON.parse(readFileSync(native, "utf8")) as { hello: typeof hello; report: typeof report };+ const same = JSON.stringify(n.report) === JSON.stringify(report);+ check(same, `the report is the native run's, number for number${same ? "" : `: here ${JSON.stringify(report)}, natively ${JSON.stringify(n.report)}`}`);+ check(JSON.stringify(n.hello) === JSON.stringify(hello), "the clicks' log is the native run's");+ }+ out.scripted = { info, hello, report, ...state };+ }++ // 3. Frame times: the same clicks in real time (2.5 s apart), frames by what they did.+ if (has("--frames")) {+ const { page, info } = await open(`${VIEW}&fps=60${has("--profile-calls") ? "&profile=1" : ""}`);+ const sleep = (ms: number) => inPage(page, `${ms} ms of frames`, (t: number) => new Promise((ok) => setTimeout(ok, t)), ms);+ await sleep(4000);+ const column: V3 = [-1, 0, WALL_Z + OFF], lone: V3 = [1.5, 0, 2.5];+ for (const at of [column, [column[0], 1.2, WALL_Z] as V3, [column[0], 1.7, WALL_Z] as V3, lone, [lone[0], 0.3, lone[2]] as V3]) {+ await clickAt(page, project(at));+ await sleep(2500);+ }+ await sleep(3000);+ const data = await inPage(page, "reading the frames", () => { const s = (globalThis as unknown as { threert: Session }).threert; return { frames: s.frames, clicks: s.clicks, trips: s.guardTrips(), first: s.firstFrame() }; });+ await page.close();+ const F = data.frames;+ // The first frames (pipelines compiled on first use, caches filling) apart; then still frames, frames in which a+ // body moved (each rebuilds the scene), frames a click's box rebuilt.+ const rows = (name: string, f: FrameRow[]) => ({+ name,+ frames: f.length,+ interval: pair(f.map((x) => x.interval)),+ script: pair(f.map((x) => x.script - x.calls_ms)),+ calls: [Math.max(0, ...f.map((x) => x.calls)), ...pair(f.map((x) => x.calls_ms))],+ physics: pair(f.map((x) => (x.physics ? x.physics.step + x.physics.sync : 0))),+ commit: pair(f.map((x) => x.commit_ms)),+ rebuild: pair(f.map((x) => x.rebuild_ms)),+ record: pair(f.map((x) => x.render_ms)),+ page: pair(f.map((x) => x.begin + x.script + x.end)),+ gpu: pair(f.map((x) => x.gpu_ms)),+ trace: pair(f.map((x) => x.trace_ms)),+ scale: pair(f.map((x) => x.scale)),+ });+ const steady = F.slice(120);+ const table = [rows("still", steady.filter((f) => !f.rebuilt && !(f.physics && f.physics.moved > 0))), rows("a body moves", steady.filter((f) => f.physics && f.physics.moved > 0)), rows("rebuilt", steady.filter((f) => f.rebuilt))];+ console.log("web hello: frame times, ms p50 / p95 (interval; of the page's time: script, engine calls [most, p50, p95], physics, commit, of which rebuild, recording; GPU, of which trace)");+ for (const t of table) console.log(` ${JSON.stringify(t)}`);+ console.log(` the first frame on the GPU (every pipeline's first use: the shaders' compile): ${r3(data.first)} ms; first frames' intervals: ${F.slice(0, 6).map((f) => r3(f.interval)).join(", ")} ms; load: ${JSON.stringify(info.ms)}; ${JSON.stringify(info.load)}`);+ console.log(` the clicks: ${JSON.stringify((data.clicks as ({ pick_ms: number; script_ms: number; commit_ms: number; rebuilt: boolean } | null)[]).map((c) => c && { pick: r3(c.pick_ms), script: r3(c.script_ms), commit: r3(c.commit_ms), rebuilt: c.rebuilt }))}`);+ check(data.trips === 0, `the loop guard stopped nothing in ${F.length} frames (${data.trips})`);+ out.frames = { info, table, first: F.slice(0, 30), clicks: data.clicks, first_frame_gpu_ms: data.first };+ }++ // 4. The boundary's cost in this browser (no GPU: the engine's world and physics alone).+ if (has("--bench")) {+ const { page } = await open("bench=1");+ const b = await inPage(page, "the boundary bench", () => (globalThis as unknown as { threert: Session }).threert.bench(10000));+ await page.close();+ console.log(`web hello: the boundary in this Chrome: ${JSON.stringify(b, null, 1)}`);+ out.bench = b;+ }+} catch (e) {+ if (e instanceof Stuck) {+ // No retry, no second page: whatever the GPU is doing, more work on it is what took the display down.+ console.log(`web hello: STOPPED, the page did not answer within ${TIMEOUT / 1000} s: ${e.message}`);+ console.log("web hello: nothing was retried. Leave the GPU alone, close the Chrome window by hand if it is still open, and look before running anything on the GPU again (the page's console above; `sample <pid>` of Chrome's GPU process; /Library/Logs/DiagnosticReports).");+ code = 3;+ } else if ((e as Error).message !== "small") {+ console.log(`web hello: ${(e as Error).message}`);+ code = 1;+ }+}+if (code !== 3) await context.close();+server.close();+const json = opt("--json");+if (json) { mkdirSync(dirname(json), { recursive: true }); writeFileSync(json, JSON.stringify({ ...out, failures }, null, 1)); }+console.log(code === 3 ? "web hello: STOPPED" : failures.length || code ? `web hello: FAIL (${failures.length})` : "web hello: pass");+process.exit(code || (failures.length ? 1 : 0));