Skip to content

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

Kernel: group 1 without lengths in the source; the light lists a buffer of their own (#90)

Yujia155731cc2b60
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 806e8d2..b20a366 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2372,6 +2372,25 @@ words, vertex colours) are read as integers.
still-kabukicho as main's to the digit (the moving ones within 0.3 %); offline renders of five scenes as main's
(three byte-identical, Bistro and Zero Day within what a build differs from itself).
+**The kernel's group 1 without lengths in its source (2026-11-15, after it).** In the merged layout the buffers the
+kernel writes were the arrays of a struct whose lengths were constants of the source, so each view size, and an
+offline render, compiled a kernel of its own (1.4 s in Chrome). Now the radiance cache's atomic words are at fixed
+places (its size is the kernel's own constant) and the vec4 arrays are the sections of one runtime-sized array, found
+by offsets in the parameters (`heap::Live`): one kernel for every view. The light tiles' lists, which rode after the
+direct buffer's pixels, are a buffer of their own; hardware traversal no longer binds software traversal's trees (a
+placeholder there), so the count of bindings is as it was.
+- Trace against main (1440p at 0.375, alternated, ms): hardware traversal equal (Bistro 8.64 / 8.64, lamp-rooms
+ 3.71 / 3.71, Zero Day 9.60 / 9.59, Kabukichō 16.11 / 16.10); software traversal Bistro equal, lamp-rooms 4.98 ->
+ 5.03; the merged layout Bistro 46.78 -> 47.12 (+0.7 %), lamp-rooms 5.00 -> 5.03.
+- In the merged layout the cache's keys and sums are always there (9 MB), with the cache off and offline too: the
+ price of plain vec4 reads beside them (all of it as atomic words would have made each vec4 four atomic loads).
+- Checks, with the loop guard: the unit tests and test-render (194); bench-window's shots as main's natively and in
+ the merged layout; `tools/web-hello.ts` in Chrome; render-identity against main: 0 of 194 changed natively, under
+ software traversal and with the uniform tables. Merged, it flagged `voxel/joint-moved`: that test has nine
+ outputs over 40 runs, main's own among them differing as much (3e-4, the same pixels), and the new build's output
+ is byte-identical to one main's binary gave; four confirming runs under-read a test whose output holds for a
+ process.
+
## 2. Temporal fixes
Targets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); the
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index a12684b..7f36d1c 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -741,7 +741,7 @@ tree (ROADMAP § 6).
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. (The live passes need none of it: each has a layout of its own, of the bindings its entry point
+ kernel binds 21. (The live passes need none of it: each has a layout of its own, of the bindings its entry point
uses, `renderer/src/live/layout.rs` from live.wgsl as build.rs reads it, and none binds more than eight, a unit
test's check; a page binds them as natively.) There is one source: pathtrace.wgsl declares the views of its
tables and its group-1 buffers in an `@if(merged) { .. } @else { .. }` block each (WESL's conditional
@@ -750,13 +750,15 @@ tree (ROADMAP § 6).
- The scene's tables are the sections of one buffer on every device ("The scene's tables"). Here the kernel has
no views of them and reads its seven tables from the buffer whole: no second copy of a table, nothing copied a
frame, no kernel compiled when one grows.
- - The kernel's six group-1 buffers (the radiance cache, what the live passes read of a trace) are ranges of one
- buffer, the arrays of a struct whose lengths are WESL constants the source imports (gpu.rs
- `KernelVariant::constants`); what the live passes read of it starts at multiples of 256 bytes, so they bind
- those ranges as buffers of their own.
+ - The kernel's seven group-1 buffers (the radiance cache, what the live passes read of a trace, the light tiles'
+ lists) are ranges of one buffer (`heap::Live`): the cache's atomic words at fixed places (its size is the
+ kernel's own constant), then the vec4 arrays as the sections of one array of the buffer's length, each found by
+ an offset in the parameters. No length is the source's: a view of another size, or an offline render, is the
+ same kernel (until 2026-11-15 the lengths were constants of the source, and each view compiled its own). What
+ the live passes read of it starts at multiples of 256 bytes, so they bind those ranges as buffers of their own.
- The merged block declares none of the buffers by its own name, so a read or write that goes past the functions
does not compile in it (naga names the line). A test reads the merged variants with naga: valid WGSL, 8 storage
- buffers for the kernel (20 as written), the struct's arrays where the Rust side puts them.
+ buffers for the kernel (21 as written), the struct's members where the Rust side puts them.
- Until 2026-11-14 the browser's kernel was written from the native one as text: a scanner of WGSL in merged.rs
found every use of the thirteen names, followed the locals that shadowed them through their scopes, and rewrote
each use (the uniform tables and the loop guard were made the same way).
@@ -1242,7 +1244,7 @@ pathtrace.wgsl's head names them; a flag the source names that a kernel is not g
features are bits of `FEAT`, a pipeline-overridable constant: one kernel source for all of them (`OBJECT_STRIDE`
too is an override, from F_TINT).
- The numbers a variant is compiled for are WESL constants, which the source imports (`import constants::..`; gpu.rs
- `KernelVariant::constants`): the merged layout's array lengths, the uniform tables', the loop guard's limit. One
+ `KernelVariant::constants`): the uniform tables' lengths, the loop guard's limit. One
the source imports and is not given is an error.
- The kernel reads its tables and its group-1 buffers only through functions (`material_at`, `instance_at`,
`cache_acc_add`, `refl_store`, ...), declared once in each layout's block, so a layout is its declarations and
@@ -1301,6 +1303,8 @@ The kernel's read-only scene data other than triangles is two storage buffers, e
vertices; and a browser's kernel had seven tables as the sized arrays of a struct, a second copy of each made
every frame, and was compiled again when a table doubled. The count of bindings is as it was: 22 buffers and
acceleration structures a stage natively, 28 of Metal's 29 with the translucency pass (29 with the loop guard's).
+ (Hardware traversal no longer binds software traversal's trees, a placeholder there; the light tiles' lists took
+ the binding.)
## Random numbers
@@ -1323,7 +1327,8 @@ frame found (pathtrace.wgsl "Light tiles", live.wgsl `light_tiles`):
- A camera hit's resampled shadow ray that reaches its light reports the light (the direct buffer's fourth
component).
- `light_tiles`, the live passes' first, makes each 8 x 8 tile's reports a list: the lights reported, each once,
- ascending, after the direct buffer's pixels (64 vec4s a tile). The tile grid shifts by a pixel offset each frame.
+ ascending, in a buffer of their own (64 vec4s a tile; the kernel's group 1 reads it). The tile grid shifts by a
+ pixel offset each frame.
- The next frame's paths read the list of the tile their camera hit was seen in then (its point, moved back by its
motion, through that frame's camera; the nearest tile's when it was off screen). They take 2 candidates from it at
a vertex the camera sees and 1 past it, spread over the list without repeats, beside the uniform candidates (8 and
diff --git a/renderer/shaders/live.wgsl b/renderer/shaders/live.wgsl
index 4b5010e..3ce284f 100644
--- a/renderer/shaders/live.wgsl
+++ b/renderer/shaders/live.wgsl
@@ -32,7 +32,7 @@ struct LiveParams {
dof: vec4<f32>, // depth of field: CoC radius of infinity (output px; 0 = off), focus distance (m), max radius (px), -
jit: vec4<f32>, // this frame's sub-pixel jitter (every traced sample's: x, y in 0 .. 1 of a traced pixel), -, -
state: vec4<u32>, // which half of the lasting buffers is this frame's (0 / 1; `this_half`), -, -, -
- lt: vec4<u32>, // the light tiles (`light_tiles`): this frame's grid offset x, y (traced pixels), the lists' first vec4 in `light_rw`, tiles a row
+ lt: vec4<u32>, // the light tiles (`light_tiles`): this frame's grid offset x, y (traced pixels), -, tiles a row
};
// color = diffuse lighting + first-hit distance, emit = directly seen emission / sky + roughness, spec = specular lighting
// + reflection hit distance, normal.w = the media before the first hit (`medium_tr`, `medium_share`; see pathtrace.wgsl).
@@ -108,9 +108,11 @@ struct Pixel { color: vec4<f32>, albedo: vec4<f32>, normal: vec4<f32>, emit: vec
// (`compose` adds it as it is, UE lights directly).
@group(0) @binding(26) var<storage, read> direct_in: array<vec4<f32>>;
@group(0) @binding(27) var<storage, read_write> lock_fwd: array<atomic<u32>>;
-// The kernel's direct buffer again, to write (`light_tiles` alone): a vec4 a traced pixel (w: the local light its
-// camera hit's resampled shadow ray found; pathtrace.wgsl "Light tiles"), then the tiles' lists.
+// For `light_tiles` alone: the kernel's direct buffer again (w: the local light a traced pixel's camera hit's
+// resampled shadow ray found; pathtrace.wgsl "Light tiles"; read only, bound as the lists are: in the merged layout
+// both are ranges of one buffer, which a pass uses one way), and the tiles' lists it writes.
@group(0) @binding(28) var<storage, read_write> light_rw: array<vec4<f32>>;
+@group(0) @binding(29) var<storage, read_write> light_lists: array<vec4<f32>>;
// Element i of this frame's half of a lasting buffer, and of the previous frame's.
fn this_half(i: u32) -> u32 { return L.state.x * L.size.x * L.size.y + i; }
@@ -281,10 +283,10 @@ fn light_tiles(@builtin(global_invocation_id) gid: vec3<u32>, @builtin(local_inv
less += f * vec4<u32>(vec4<u32>(lt_keys[j], lt_keys[j + 1u], lt_keys[j + 2u], lt_keys[j + 3u]) < k0);
all += f;
}
- let list = L.lt.z + (wg.y * L.lt.w + wg.x) * 64u;
+ let list = (wg.y * L.lt.w + wg.x) * 64u;
let at = less.x + less.y + less.z + less.w;
- if (first && at < 63u) { light_rw[list + at] = vec4<f32>(f32(key), f32(same.x + same.y + same.z + same.w), 0.0, 0.0); }
- if (li == 0u) { light_rw[list + 63u] = vec4<f32>(f32(min(all.x + all.y + all.z + all.w, 63u)), 0.0, 0.0, 0.0); }
+ if (first && at < 63u) { light_lists[list + at] = vec4<f32>(f32(key), f32(same.x + same.y + same.z + same.w), 0.0, 0.0); }
+ if (li == 0u) { light_lists[list + 63u] = vec4<f32>(f32(min(all.x + all.y + all.z + all.w, 63u)), 0.0, 0.0, 0.0); }
}
@compute @workgroup_size(8, 8, 1)
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 05501da..2487106 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -18,8 +18,7 @@
// uniform_tables four tables in uniform buffers (merged.rs `UNIFORM_TABLES`: Android's drivers)
// guard the loop guard (gpu.rs `loop_guard_of`, `guard_loops`)
// The numbers a variant is compiled for are WESL constants (`import constants::`, gpu.rs `KernelVariant::constants`): the
-// merged layout's array lengths, the uniform tables', the loop guard's limit.
-@if(merged) import constants::{ML_CACHE_KEYS, ML_CACHE_ACC, ML_CACHE_VAL, ML_REFL, ML_MOTION_OUT, ML_DIRECT_OUT};
+// uniform tables' lengths, the loop guard's limit.
@if(uniform_tables) import constants::{UT_TEX_INFO, UT_OBJECTS, UT_INSTANCES, UT_MEDIA};
@if(merged || guard) import constants::GUARD_WORDS;
@if(guard) import constants::LOOP_GUARD_LIMIT;
@@ -107,11 +106,13 @@ struct Params {
procs: vec4<u32>, // procedural geometry (F_PROC): -, object count, first record in `instances`, -
aerial: vec4<f32>, // the sky's aerial perspective (F_AERIAL): density multiple, Rayleigh scale, Mie scale, -
background: vec4<f32>, // three.js scene.background (radiance), 1 (F_BACKGROUND)
- ltile: vec4<u32>, // live light tiles (`lt_list_start`): the lists' first vec4 in direct_out (0: none), tiles a row, the grid's offset when they were built (x | y << 16), candidates a vertex the camera sees takes from its list
+ ltile: vec4<u32>, // live light tiles (`lt_list_start`): 1 with last frame's lists (0: none), tiles a row, the grid's offset when they were built (x | y << 16), candidates a vertex the camera sees takes from its list
ltile2: vec4<u32>, // the traced size they were built at, -, -
lt_cam: array<vec4<f32>, 4>, // the camera they were built under: position (w = tan(fov/2)), forward (w = aspect), right, up
table_first: array<vec4<u32>, 3>, // each table's first vec4 in `tables` (heap.rs `Table`): light tree (0), materials, lights, light groups; emitters, tex_info, objects, instances; media, energy LUT, -, -
word_first: vec4<u32>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, -
+ live_first: array<vec4<u32>, 2>, // the merged layout: each of group 1's vec4 sections' first vec4 in `ML.vecs` (heap.rs `Live`): cache values (0), refl, motion, direct; lists, -, -, -
+ live_len: vec4<u32>, // and the vec4s of refl, motion, direct, lists
};
struct TriAttr { n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, uv: vec4<f32>, t: vec4<f32>, x: vec4<f32> };
@@ -132,7 +133,8 @@ struct Pixel { color: vec4<f32>, albedo: vec4<f32>, normal: vec4<f32>, emit: vec
@group(0) @binding(0) var<uniform> P: Params;
@group(0) @binding(1) var<storage, read> tri_verts: array<vec4<f32>>;
@group(0) @binding(2) var<storage, read> attrs: array<TriAttr>;
-@group(0) @binding(3) var<storage, read> nodes: array<Node>;
+// (Software traversal's trees: hardware traversal has no binding for them.)
+@if(!hwrt) @group(0) @binding(3) var<storage, read> nodes: array<Node>;
@group(0) @binding(7) var textures: texture_2d_array<f32>;
@group(0) @binding(8) var samp: sampler;
@group(0) @binding(9) var env_tex: texture_2d<f32>;
@@ -1720,8 +1722,8 @@ fn local_light(li: Light, x: vec3<f32>, u: vec2<f32>) -> LS {
// function) instead of the surface BSDF. Surface results add their specular part to `dl_spec`.
// Light tiles (live; what guides MegaLights' draws and RTXPT's): each camera pixel reports the local light its
// resampled shadow ray found (direct_out's w: `lt_fb`, a light-table index; LT_NONE: none), live.wgsl `light_tiles`
-// makes each 8 x 8 tile's reports a list after the kernel's own data in direct_out (the lights found, each once:
-// index, reports; ascending; the last vec4 their number), and the next frame's paths take resampling candidates
+// makes each 8 x 8 tile's reports a list in `light_lists` (the lights found, each once: index, reports; ascending;
+// the last vec4 their number), and the next frame's paths take resampling candidates
// from the list of the tile their camera hit was seen in then (`lt_list_start`: where the point was, through that
// frame's camera), spread over it without repeats (all of it when it is short). The candidates drawn uniformly, as
// before, then stand for the lights the list lacks (`lt_in_list`). A list is a guide: whatever it holds the estimate
@@ -1748,9 +1750,9 @@ fn lt_list_start(p: vec3<f32>) {
let uv = clamp(vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5), vec2<f32>(0.0), vec2<f32>(1.0));
let q = min(vec2<u32>(uv * vec2<f32>(P.ltile2.xy)), P.ltile2.xy - 1u);
let c = q + vec2<u32>(P.ltile.z & 0xffffu, P.ltile.z >> 16u);
- lt_list = P.ltile.x + ((c.y / LT_TILE) * P.ltile.y + c.x / LT_TILE) * LT_LIST;
- if (lt_list + LT_LIST > direct_len()) { return; }
- lt_list_n = min(u32(direct_load(lt_list + LT_LIST - 1u).x), LT_LIST - 1u);
+ lt_list = ((c.y / LT_TILE) * P.ltile.y + c.x / LT_TILE) * LT_LIST;
+ if (lt_list + LT_LIST > lists_len()) { return; }
+ lt_list_n = min(u32(list_load(lt_list + LT_LIST - 1u).x), LT_LIST - 1u);
}
// Whether the pixel's list holds light `i`.
@@ -1760,7 +1762,7 @@ fn lt_in_list(i: u32) -> bool {
for (var k = 0u; k < 7u; k++) {
if (lo >= hi) { break; }
let mid = (lo + hi) / 2u;
- let km = u32(direct_load(lt_list + mid).x);
+ let km = u32(list_load(lt_list + mid).x);
if (km == i) { return true; }
if (km < i) { lo = mid + 1u; } else { hi = mid; }
}
@@ -1838,7 +1840,7 @@ fn local_lights(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>, x: vec3<f32>,
idx = first + min(u32(r4.x * f32(count)), count - 1u);
} else {
r4 = rng4(rng_sub(rd ^ 0x80000000u, 0x1000u + k));
- idx = u32(direct_load(lt_list + min(u32((f32(k - m_cand) + at) * step), lt_list_n - 1u)).x);
+ idx = u32(list_load(lt_list + min(u32((f32(k - m_cand) + at) * step), lt_list_n - 1u)).x);
if (idx < first || idx >= first + count) { continue; }
stands = listed;
}
@@ -2764,44 +2766,48 @@ fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {
// octahedral ray direction). Neighbours reuse each other's rays weighted by their own BRDF (Lumen / SSSR);
// - motion_out: live motion vectors per traced pixel: where the camera hit was the previous frame, as a world-space
// offset (w = 1: on a moving triangle);
-// - direct_out: live deterministic direct light per traced pixel (`dl_det` at the camera hit);
+// - direct_out: live deterministic direct light per traced pixel (`dl_det` at the camera hit; w: the light it
+// reports, "Light tiles");
+// - light_lists: the light tiles' lists, 64 vec4s a tile, as the live pass `light_tiles` made them last frame;
// - cache_keys, cache_acc, cache_val: the radiance cache (below, at `cache_on`);
// - loop_guard_trips: the loop guard's count (first word: the invocations a loop of which was stopped).
@if(merged) {
- // The merged layout (merged.rs `KERNEL_LIVE`): the arrays of one struct, one buffer they are ranges of
- // (gpu.rs `KernelBufs`). What the live passes read of it starts at a multiple of 256 bytes: they bind those
- // ranges as buffers of their own (WebGPU's `minStorageBufferOffsetAlignment`). The loop guard's count is always
- // there, written only by a kernel with the guard.
+ // The merged layout (merged.rs: a browser's eight storage buffers): one buffer (gpu.rs `KernelBufs`; heap.rs
+ // `Live` places its parts). The radiance cache's atomic words and the loop guard's count are at fixed places (the
+ // cache's size is the kernel's own constant); the vec4 arrays follow as the sections of `vecs`, each from the
+ // vec4 `P.live_first` names and as long as `P.live_len` says, so a view of another size is the same kernel. What
+ // the live passes read of it they bind as buffers of their own (a section starts at a multiple of 256 bytes).
struct MergedLive {
- cache_keys: array<atomic<u32>, ML_CACHE_KEYS>,
- cache_acc: array<atomic<u32>, ML_CACHE_ACC>,
- cache_val: array<vec4<f32>, ML_CACHE_VAL>,
- @align(256) refl: array<vec4<f32>, ML_REFL>,
- @align(256) motion_out: array<vec4<f32>, ML_MOTION_OUT>,
- @align(256) direct_out: array<vec4<f32>, ML_DIRECT_OUT>,
- loop_guard_trips: array<atomic<u32>, GUARD_WORDS>,
+ cache_keys: array<atomic<u32>, CACHE_SIZE>,
+ @align(256) cache_acc: array<atomic<u32>, CACHE_SIZE * 8u>,
+ @align(256) @size(512) loop_guard_trips: array<atomic<u32>, GUARD_WORDS>,
+ @align(256) vecs: array<vec4<f32>>,
};
@group(1) @binding(1) var<storage, read_write> ML: MergedLive;
- fn refl_len() -> u32 { return ML_REFL; }
- fn refl_store(i: u32, v: vec4<f32>) { ML.refl[i] = v; }
- fn motion_len() -> u32 { return ML_MOTION_OUT; }
- fn motion_store(i: u32, v: vec4<f32>) { ML.motion_out[i] = v; }
- fn direct_len() -> u32 { return ML_DIRECT_OUT; }
- fn direct_load(i: u32) -> vec4<f32> { return ML.direct_out[i]; }
- fn direct_store(i: u32, v: vec4<f32>) { ML.direct_out[i] = v; }
+ fn refl_len() -> u32 { return P.live_len.x; }
+ fn refl_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[0].y + i] = v; }
+ fn motion_len() -> u32 { return P.live_len.y; }
+ fn motion_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[0].z + i] = v; }
+ fn direct_len() -> u32 { return P.live_len.z; }
+ fn direct_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[0].w + i]; }
+ fn direct_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[0].w + i] = v; }
+ fn lists_len() -> u32 { return P.live_len.w; }
+ fn list_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[1].x + i]; }
fn cache_key_load(i: u32) -> u32 { return atomicLoad(&ML.cache_keys[i]); }
fn cache_key_claim(i: u32, k: u32) -> bool { let r = atomicCompareExchangeWeak(&ML.cache_keys[i], 0u, k); return r.exchanged || r.old_value == k; }
fn cache_key_clear(i: u32) { atomicStore(&ML.cache_keys[i], 0u); }
fn cache_acc_add(i: u32, v: u32) -> u32 { return atomicAdd(&ML.cache_acc[i], v); }
fn cache_acc_load(i: u32) -> u32 { return atomicLoad(&ML.cache_acc[i]); }
fn cache_acc_clear(i: u32) { atomicStore(&ML.cache_acc[i], 0u); }
- fn cache_val_load(i: u32) -> vec4<f32> { return ML.cache_val[i]; }
- fn cache_val_store(i: u32, v: vec4<f32>) { ML.cache_val[i] = v; }
+ // (The cache's values are `vecs`' first section: from vec4 0.)
+ fn cache_val_load(i: u32) -> vec4<f32> { return ML.vecs[i]; }
+ fn cache_val_store(i: u32, v: vec4<f32>) { ML.vecs[i] = v; }
@if(guard) fn loop_guard_stopped() { atomicAdd(&ML.loop_guard_trips[0], 1u); }
} @else {
@group(1) @binding(1) var<storage, read_write> cache_keys: array<atomic<u32>>;
@group(1) @binding(2) var<storage, read_write> cache_acc: array<atomic<u32>>;
@group(1) @binding(3) var<storage, read_write> cache_val: array<vec4<f32>>;
+ @group(1) @binding(4) var<storage, read> light_lists: array<vec4<f32>>;
@group(1) @binding(5) var<storage, read_write> refl: array<vec4<f32>>;
@group(1) @binding(6) var<storage, read_write> motion_out: array<vec4<f32>>;
@group(1) @binding(7) var<storage, read_write> direct_out: array<vec4<f32>>;
@@ -2812,6 +2818,8 @@ fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {
fn direct_len() -> u32 { return arrayLength(&direct_out); }
fn direct_load(i: u32) -> vec4<f32> { return direct_out[i]; }
fn direct_store(i: u32, v: vec4<f32>) { direct_out[i] = v; }
+ fn lists_len() -> u32 { return arrayLength(&light_lists); }
+ fn list_load(i: u32) -> vec4<f32> { return light_lists[i]; }
fn cache_key_load(i: u32) -> u32 { return atomicLoad(&cache_keys[i]); }
fn cache_key_claim(i: u32, k: u32) -> bool { let r = atomicCompareExchangeWeak(&cache_keys[i], 0u, k); return r.exchanged || r.old_value == k; }
fn cache_key_clear(i: u32) { atomicStore(&cache_keys[i], 0u); }
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index a404a25..e4dd27e 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -1,6 +1,6 @@
//! Headless wgpu backend: uploads the flattened scene once, accumulates path-traced samples, reads back HDR.
-use crate::heap::{Heap, Section, Stream, Table};
+use crate::heap::{Heap, Live, Section, Stream, Table};
use crate::scene::Scene;
use crate::GROUPS;
use anyhow::{anyhow, Result};
@@ -23,17 +23,17 @@ pub struct Gpu {
pipeline_cache: Option<crate::pipeline_cache::PipelineCache>,
/// Kernel source (hardware or software traversal spliced in); scenes with material functions get their own module.
source: String,
- /// The kernel as written (none in the merged layout: its sources are written for their arrays' lengths).
- module: Option<wgpu::ShaderModule>,
+ /// The kernel as written: a scene without features that change the source or functions of its own.
+ module: 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 features that change the source: `KernelVariant::flags`, the merged layout's lengths).
- modules: std::sync::Mutex<std::collections::HashMap<(u64, u32, Option<crate::merged::Caps>), wgpu::ShaderModule>>,
+ /// By (material-function code hash, the features that change the source: `KernelVariant::flags`).
+ modules: std::sync::Mutex<std::collections::HashMap<(u64, u32), 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, Option<crate::merged::Caps>), wgpu::ComputePipeline>>,
+ pipelines: std::sync::Mutex<std::collections::HashMap<(u32, u64, bool), wgpu::ComputePipeline>>,
layout: wgpu::BindGroupLayout,
/// Group 1, the live viewport's: primary visibility (texture_2d<u32>), the radiance cache (`CacheBuffers`) and
/// what the live passes read of a trace (`KernelBufs`). Offline renders bind `no_vis` (1x1 texture `no_vis_view`,
@@ -56,7 +56,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, Option<crate::merged::Caps>), wgpu::ComputePipeline>>,
+ media_passes: std::sync::Mutex<std::collections::HashMap<(u32, u64, &'static str), 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
@@ -115,8 +115,8 @@ pub struct Params {
pub aerial: [f32; 4],
/// three.js `scene.background` (F_BACKGROUND): its radiance, 1.
pub background: [f32; 4],
- /// The live light tiles (pathtrace.wgsl "Light tiles"; live/frame.rs): the lists' first vec4 in the direct
- /// buffer (0: none this frame), tiles a row, the grid's offset when they were built (x | y << 16), candidates a
+ /// The live light tiles (pathtrace.wgsl "Light tiles"; live/frame.rs): 1 with the last frame's lists (0: none
+ /// this frame), tiles a row, the grid's offset when they were built (x | y << 16), candidates a
/// vertex the camera sees takes from its list beside the uniform ones (`live::LIST_CANDIDATES`; half past it).
pub ltile: [u32; 4],
/// The traced size the lists were built at, -, -.
@@ -129,6 +129,11 @@ pub struct Params {
/// Each stream's first word in the words' heap (`heap::Stream`'s order): the environment's CDF, the procedural
/// data, the vertex colours, -.
pub word_first: [u32; 4],
+ /// The merged layout (`KernelBufs::place`): each of group 1's vec4 sections' first vec4 in the tail of its one
+ /// buffer (the cache's values, the specular rays, the motion vectors, the direct light; the light lists), and
+ /// the last four's lengths. As written: zeros (the kernel asks the buffers).
+ pub live_first: [[u32; 4]; 2],
+ pub live_len: [u32; 4],
}
/// Room the live view's in-place geometry edits grow into (live/edits.rs `edit_geometry`), past the scene's own data:
@@ -766,8 +771,8 @@ pub struct KernelVariant {
pub switches: KernelSwitches,
/// The scene's features: `F_SOURCE`'s are flags.
pub features: u32,
- /// The merged layout (merged.rs), with its arrays' lengths.
- pub merged: Option<crate::merged::Caps>,
+ /// The merged layout (merged.rs).
+ pub merged: bool,
/// Four tables in uniform buffers (merged.rs `UNIFORM_TABLES`; `GpuOptions::uniform_tables`). Never with `merged`.
pub uniform_tables: bool,
/// The loop guard's limit, in a kernel with the guard (`loop_guard_of`, `guard_loops`).
@@ -792,24 +797,21 @@ impl KernelVariant {
("last_sun", k.last_sun),
("light_pick", k.light_pick),
("units", f(F_UNITS)),
- ("merged", self.merged.is_some()),
+ ("merged", self.merged),
("uniform_tables", self.uniform_tables),
("guard", self.guard.is_some()),
]
}
- /// The numbers the variant is compiled for, WESL constants (`import constants::`): the merged layout's array
- /// lengths (`ML_<buffer>`), the uniform tables' (`UT_<table>`), the loop guard's count's words and its limit.
+ /// The numbers the variant is compiled for, WESL constants (`import constants::`): the uniform tables' lengths
+ /// (`UT_<table>`), the loop guard's count's words and its limit.
pub fn constants(&self) -> Vec<(String, u32)> {
- use crate::merged::{GUARD_WORDS, KERNEL_LIVE, UNIFORM_TABLES};
+ use crate::merged::{GUARD_WORDS, UNIFORM_TABLES};
let mut out = vec![];
- if let Some(c) = &self.merged {
- out.extend(KERNEL_LIVE.iter().zip(c.live).map(|(m, n)| (format!("ML_{}", m.name.to_uppercase()), n)));
- }
if self.uniform_tables {
out.extend(UNIFORM_TABLES.iter().map(|t| (format!("UT_{}", t.name.to_uppercase()), t.len)));
}
- if self.merged.is_some() || self.guard.is_some() {
+ if self.merged || self.guard.is_some() {
out.push(("GUARD_WORDS".into(), GUARD_WORDS));
}
if let Some(n) = self.guard {
@@ -827,7 +829,7 @@ pub fn kernel_wgsl(src: &str, v: &KernelVariant) -> String {
/// `kernel_wgsl`, saying what did not compile instead of panicking (a scene's own functions are a game's code).
pub fn try_kernel_wgsl(src: &str, v: &KernelVariant) -> Result<String, String> {
- assert!(!(v.merged.is_some() && v.uniform_tables), "the uniform tables are never in the merged layout");
+ assert!(!(v.merged && v.uniform_tables), "the uniform tables are never in the merged layout");
let mut out = try_wesl_wgsl(src, &v.flags(), &v.constants())?;
if v.guard.is_some() {
guard_loops(&mut out);
@@ -1175,39 +1177,56 @@ impl CacheBuffers {
}
}
-/// The kernel's group-1 buffers: the radiance cache, and what the live passes read of a trace
-/// (live/targets.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`).
+/// The kernel's group-1 buffers: the radiance cache, what the live passes read of a trace (live/targets.rs
+/// `Targets`: the specular-lobe rays, the motion vectors, the directional lights' direct light) and the light tiles'
+/// lists. In the merged layout they are the sections of one buffer (`heap::Live`).
pub struct KernelBufs {
pub cache: CacheBuffers,
pub refl: Buf,
pub motion: Buf,
pub direct: Buf,
+ pub lists: Buf,
/// The loop guard's count (`guard_loops`: 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`).
+ /// the guard, and always in the merged layout.
pub guard: Option<Buf>,
- /// The merged layout: the one buffer, and its arrays' lengths.
- pub merged: Option<(wgpu::Buffer, [u32; 6])>,
+ /// The merged layout: the one buffer.
+ pub merged: Option<Heap<Live>>,
}
impl KernelBufs {
- /// For a cache of `entries` and the live passes' three of these bytes.
+ /// For a cache of `entries` and the live passes' four of these bytes.
/// `guard`: the layout as written has the guard's count (`Gpu::guard_room`).
- pub fn new(d: &wgpu::Device, merged: bool, guard: bool, entries: u64, refl: u64, motion: u64, direct: u64) -> KernelBufs {
+ pub fn new(d: &wgpu::Device, merged: bool, guard: bool, entries: u64, refl: u64, motion: u64, direct: u64, lists: 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 = guard.then(|| sb("loop guard", crate::merged::GUARD_WORDS as u64 * 4));
- return KernelBufs { cache: CacheBuffers::new(d, entries), refl: sb("refl", refl), motion: sb("motion", motion), direct: sb("direct", direct), guard, merged: None };
+ return KernelBufs { cache: CacheBuffers::new(d, entries), refl: sb("refl", refl), motion: sb("motion", motion), direct: sb("direct", direct), lists: sb("light lists", lists), guard, merged: None };
}
- let bytes = [entries * 4, entries * 32, entries * 32, refl, motion, direct, crate::merged::GUARD_WORDS as u64 * 4];
- let caps: [u32; 6] = 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) }, refl: b(3), motion: b(4), direct: b(5), guard: Some(b(6)), merged: Some((buffer, caps)) }
+ // (The cache's keys and sums are as long as the kernel's struct says, whatever `entries`: `live_sizes`. A
+ // section's range is the bytes asked for: a pass that binds it sees an array of that length.)
+ let bytes = live_sizes(entries, refl, motion, direct, lists);
+ let heap = Heap::<Live>::new(d, &bytes);
+ let b = |s: Live| Buf { buffer: heap.buffer.clone(), offset: heap.at(s), size: bytes[s.index()] };
+ KernelBufs { cache: CacheBuffers { keys: b(Live::CacheKeys), acc: b(Live::CacheAcc), val: b(Live::CacheVal) }, refl: b(Live::Refl), motion: b(Live::Motion), direct: b(Live::Direct), lists: b(Live::Lists), guard: Some(b(Live::Guard)), merged: Some(heap) }
+ }
+
+ /// Where the kernel finds the vec4 sections in the merged layout (`Params::live_first`, `live_len`): written with
+ /// the parameters of whatever is traced into these buffers.
+ pub fn place(&self, p: &mut Params) {
+ let Some(heap) = &self.merged else { return };
+ let first = |s: Live| ((heap.at(s) - heap.at(Live::CacheVal)) / 16) as u32;
+ p.live_first = [[first(Live::CacheVal), first(Live::Refl), first(Live::Motion), first(Live::Direct)], [first(Live::Lists), 0, 0, 0]];
+ p.live_len = [&self.refl, &self.motion, &self.direct, &self.lists].map(|b| (b.size / 16) as u32);
}
}
+/// The bytes of the merged layout's group-1 buffer's sections (`heap::Live`'s order) for a cache whose values are
+/// `entries` long and the live passes' four of these bytes. The cache's keys and sums and the loop guard's count are
+/// members of the kernel's struct, of the kernel's lengths (pathtrace.wgsl `MergedLive`).
+pub(crate) fn live_sizes(entries: u64, refl: u64, motion: u64, direct: u64, lists: u64) -> [u64; 8] {
+ [CACHE_SIZE * 4, CACHE_SIZE * 32, crate::merged::GUARD_WORDS as u64 * 4, entries * 32, refl, motion, direct, lists]
+}
+
/// Group-1 bind group of the kernel: a primary-visibility texture, the radiance cache and the
/// 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 {
@@ -1216,9 +1235,9 @@ pub fn vis_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, view: &w
}
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() }] }),
+ Some(heap) => d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("vis"), layout, entries: &[tex, wgpu::BindGroupEntry { binding: crate::merged::LIVE_BINDING, resource: heap.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(5, &b.refl), e(6, &b.motion), e(7, &b.direct)];
+ let mut entries = vec![tex, e(1, &b.cache.keys), e(2, &b.cache.acc), e(3, &b.cache.val), e(crate::merged::LISTS_BINDING, &b.lists), 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 })
}
@@ -1248,9 +1267,6 @@ 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 struct's arrays this kernel's source is written for
- /// (an offline render's `no_vis`, a live view's `KernelBufs`).
- pub caps: Option<crate::merged::Caps>,
}
impl Kernel {
@@ -1342,18 +1358,7 @@ 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(), 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) }
+ Kernel { features: features(scene, groups), functions, volume_functions, geometry_functions, hash: h.finish() }
}
}
@@ -1598,10 +1603,10 @@ impl Gpu {
let switches = options.kernel;
let src = kernel_template();
// Bounds checks are not needed: all indices come from our own BVH / scene builder.
- let module = (!merged).then(|| unsafe {
- let wgsl = kernel_wgsl(&src, &KernelVariant { uniform_tables, guard: loop_guard_of(false), ..KernelVariant::new(hwrt, switches, 0) });
+ let module = unsafe {
+ let wgsl = kernel_wgsl(&src, &KernelVariant { merged, uniform_tables, guard: loop_guard_of(false), ..KernelVariant::new(hwrt, switches, 0) });
device.create_shader_module_trusted(wgpu::ShaderModuleDescriptor { label: Some("pathtrace"), source: wgpu::ShaderSource::Wgsl(wgsl.into()) }, kernel_checks())
- });
+ };
let storage = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::COMPUTE,
@@ -1620,15 +1625,14 @@ impl Gpu {
ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension, multisampled: false },
count: None,
};
- // Group 0, the scene (pathtrace.wgsl's declarations): the parameters; triangles, their attributes, the
- // software tree; the tables' heap; the words' heap; the dynamic triangles' previous vertices; the
+ // Group 0, the scene (pathtrace.wgsl's declarations): the parameters; triangles, their attributes, software
+ // traversal's trees (3); the tables' heap; the words' heap; the dynamic triangles' previous vertices; the
// texture pages and their sampler, the environment, the density grids' atlas (a 1-cell texture in scenes
// without grids, whose kernel does not read it); the accumulation buffer; then what only some layouts have.
let mut entries = vec![
uniform(0),
storage(1, true),
storage(2, true),
- storage(3, true),
storage(4, true),
storage(5, true),
storage(6, true),
@@ -1638,6 +1642,9 @@ impl Gpu {
texture(10, wgpu::TextureViewDimension::D3),
storage(11, false),
];
+ if !hwrt {
+ entries.push(storage(3, true));
+ }
// The tables the kernel reads at every hit or light, bound again as typed views of their sections (merged.rs
// `TABLE_VIEWS`; the merged layout has no binding for them), four of them uniform copies where a driver
// needs it (`UNIFORM_TABLES`).
@@ -1659,11 +1666,12 @@ impl Gpu {
storage(1, false),
storage(2, false),
storage(3, false),
+ storage(crate::merged::LISTS_BINDING, true),
storage(5, false),
storage(6, false),
storage(7, false),
];
- // The merged layout: group 1's six buffers are one (merged.rs `KERNEL_LIVE`), the loop guard's count in it.
+ // The merged layout: group 1's buffers are one (`heap::Live`), the loop guard's count in it.
// As written, a kernel with the guard has the count in a buffer of its own: the binding is there whenever a
// kernel of this device may have the guard (`guard_room`; a kernel without it does not name the binding).
if merged {
@@ -1696,7 +1704,7 @@ impl Gpu {
storage(6, true),
],
});
- let no_vis_bufs = KernelBufs::new(&device, merged, guard_room(hwrt), 1, 64, 64, 64);
+ let no_vis_bufs = KernelBufs::new(&device, merged, guard_room(hwrt), 1, 64, 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 {
@@ -1743,7 +1751,7 @@ impl Gpu {
pub fn pipeline(&self, k: &Kernel, live: bool) -> wgpu::ComputePipeline {
let mut cache = self.pipelines.lock().unwrap();
cache
- .entry((k.features, k.hash, live, k.caps))
+ .entry((k.features, k.hash, live))
.or_insert_with(|| {
let module = self.kernel_module(k);
let constants = [("LIVE", if live { 1.0 } else { 0.0 }), ("FEAT", k.features as f64)];
@@ -1764,12 +1772,11 @@ 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;
- 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();
+ if patches == 0 && k.functions.is_empty() && k.volume_functions.is_empty() && k.geometry_functions.is_empty() {
+ return self.module.clone();
}
let mut mods = self.modules.lock().unwrap();
- mods.entry((k.hash, patches, k.caps))
+ mods.entry((k.hash, patches))
.or_insert_with(|| {
let splice = |src: &str, marker: &str, code: &str| -> String {
if code.is_empty() {
@@ -1780,9 +1787,8 @@ impl Gpu {
format!("{head}{code}{tail}")
};
let src = splice(&splice(&splice(&self.source, "material-functions", &k.functions), "volume-functions", &k.volume_functions), "geometry-functions", &k.geometry_functions);
- // The variant: this device's traversal, switches, layout (the merged one with this kernel's arrays'
- // lengths) and loop guard, this scene's features.
- let v = KernelVariant { merged: k.caps, uniform_tables: self.uniform_tables, guard: loop_guard_of(patches & F_UNITS != 0), ..KernelVariant::new(self.hwrt, self.switches, patches) };
+ // The variant: this device's traversal, switches, layout and loop guard, this scene's features.
+ let v = KernelVariant { merged: self.merged, uniform_tables: self.uniform_tables, guard: loop_guard_of(patches & F_UNITS != 0), ..KernelVariant::new(self.hwrt, self.switches, patches) };
// A scene's functions that do not compile (a game's own WGSL) cost the game its functions, not the
// app its renderer: the kernel is made without them, and the game's log says why. (A panic here took
// the engine down, and ThreeRT for Android then took the device for one without a renderer.)
@@ -1804,7 +1810,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, k.caps))
+ .entry((k.features, k.hash, entry))
.or_insert_with(|| {
let module = self.kernel_module(k);
let constants = [("LIVE", 1.0), ("FEAT", k.features as f64)];
@@ -1860,13 +1866,8 @@ impl Gpu {
}
/// The radiance cache's per-frame resolve (pathtrace.wgsl `cache_resolve`; kernel bind groups).
- pub fn cache_resolve_pipeline(&self, bufs: &KernelBufs) -> wgpu::ComputePipeline {
- // (The merged layout: the kernel written for these buffers' lengths.)
- let module = match (&self.module, &bufs.merged) {
- (Some(m), _) => m.clone(),
- (None, Some((_, live))) => self.kernel_module(&Kernel::plain(crate::merged::Caps { live: *live })),
- (None, None) => unreachable!("the merged layout's group 1 is one buffer"),
- };
+ pub fn cache_resolve_pipeline(&self) -> wgpu::ComputePipeline {
+ let module = &self.module;
let p = self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("cache resolve"),
layout: Some(&self.pipeline_layout),
@@ -2267,8 +2268,7 @@ impl Gpu {
});
let bg_parts = BindParts { nodes: b_nodes, tex_view, env_view, sampler, grid_view };
let bg = self.scene_bind_group(&SceneBuffers { params: &b_params, verts: &b_verts, attrs: &b_attrs, heap: &heap, words: &words, prev_verts: &b_prev, accum: &b_accum, parts: &bg_parts, accel: accel.as_ref(), uniform: uniform.as_ref() });
- let mut kernel = Kernel::new(scene, groups);
- kernel.caps = self.no_vis_bufs.merged.as_ref().map(|m| crate::merged::Caps { live: m.1 });
+ let kernel = Kernel::new(scene, groups);
// Translucent particles (hardware RT): their own BLAS + TLAS, rebuilt after the particle pass.
let translucent = match &accel {
Some(_) if !scene.trans_tris.is_empty() => {
@@ -2942,7 +2942,6 @@ impl Gpu {
buffer_entry(0, b.params),
buffer_entry(1, b.verts),
buffer_entry(2, b.attrs),
- buffer_entry(3, &p.nodes),
buffer_entry(4, &b.heap.buffer),
buffer_entry(5, &b.words.buffer),
buffer_entry(6, b.prev_verts),
@@ -2952,6 +2951,9 @@ impl Gpu {
view(10, &p.grid_view),
buffer_entry(11, b.accum),
];
+ if !self.hwrt {
+ entries.push(buffer_entry(3, &p.nodes));
+ }
if !self.merged {
for &(table, binding) in &crate::merged::TABLE_VIEWS {
let copy = b.uniform.and_then(|u| u.iter().zip(&crate::merged::UNIFORM_TABLES).find(|(_, t)| t.binding == binding).map(|(c, _)| c));
@@ -3135,6 +3137,7 @@ impl Gpu {
let mut p = base;
p.size[2] = s;
up.place(&mut p);
+ self.no_vis_bufs.place(&mut p);
self.queue.write_buffer(&up.params, 0, bytemuck::bytes_of(&p));
let mut enc = d.create_command_encoder(&Default::default());
{
@@ -3227,6 +3230,7 @@ impl Gpu {
let mut p = base;
p.size[2] = s + k;
up.place(&mut p);
+ self.no_vis_bufs.place(&mut p);
self.queue.write_buffer(b_params, 0, bytemuck::bytes_of(&p));
let mut enc = d.create_command_encoder(&Default::default());
{
diff --git a/renderer/src/heap.rs b/renderer/src/heap.rs
index 028c0d5..0025427 100644
--- a/renderer/src/heap.rs
+++ b/renderer/src/heap.rs
@@ -79,6 +79,32 @@ impl Section for Stream {
}
}
+/// The kernel's group-1 buffers as the parts of one: the merged layout's (gpu.rs `KernelBufs`; pathtrace.wgsl
+/// `MergedLive`, whose members are where these sections are: a test holds it). The radiance cache's keys and sums
+/// and the loop guard's count, atomic words at fixed places; then the vec4 arrays, the sections of the struct's last
+/// member: the cache's values, what the live passes read of a trace (the specular-lobe rays, the motion vectors, the
+/// direct light), the light tiles' lists.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Live {
+ CacheKeys,
+ CacheAcc,
+ Guard,
+ CacheVal,
+ Refl,
+ Motion,
+ Direct,
+ Lists,
+}
+
+impl Section for Live {
+ const COUNT: usize = 8;
+ const UNIT: u64 = 4;
+ const LABEL: &'static str = "live";
+ fn index(self) -> usize {
+ self as usize
+ }
+}
+
/// A heap: its buffer, and each section's first byte and size.
pub struct Heap<S: Section> {
pub buffer: wgpu::Buffer,
@@ -103,6 +129,12 @@ impl<S: Section> Heap<S> {
place(bytes).2
}
+ /// Where its sections start, and the bytes each holds.
+ pub fn starts_for(bytes: &[u64]) -> (Vec<u64>, Vec<u64>) {
+ let (at, cap, _) = place(bytes);
+ (at, cap)
+ }
+
/// A heap of zeros with sections of at least `bytes` each (`S::COUNT` of them), to be written through the queue.
pub fn new(device: &wgpu::Device, bytes: &[u64]) -> Self {
assert_eq!(bytes.len(), S::COUNT);
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index ecb2073..9243f53 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -737,6 +737,9 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
// (`gpu::Uploaded::place`, with the buffers.)
table_first: [[0; 4]; 3],
word_first: [0; 4],
+ // (`gpu::KernelBufs::place`, with what is traced into.)
+ live_first: [[0; 4]; 2],
+ live_len: [0; 4],
};
let mut params = params;
let mut first = 0u32;
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index 0affeef..ae0d3d2 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -358,12 +358,11 @@ impl LiveCore {
if self.reset || !tiles_on {
self.light_tiles = None;
}
- let lists = layout::light_lists(w, h).0;
let tile_at = (((halton(self.frame % 64 + 1, 2) * 8.0) as u32).min(7), ((halton(self.frame % 64 + 1, 3) * 8.0) as u32).min(7));
for k in 0..spp.max(1) {
let mut p = self.sc.base;
if let Some((row, at, size, cam)) = self.light_tiles {
- (p.ltile[0], p.ltile[1], p.ltile[2]) = (lists, row, at);
+ (p.ltile[0], p.ltile[1], p.ltile[2]) = (1, row, at);
p.ltile2 = [size.0, size.1, 0, 0];
p.lt_cam = cam;
}
@@ -395,6 +394,7 @@ impl LiveCore {
p.counts[2] = p.counts[2].min(self.bounces);
p.counts[3] = p.counts[3].min(2);
self.sc.up.place(&mut p);
+ self.targets.kernel.place(&mut p);
g.queue.write_buffer(&self.sc.up.params, 0, bytemuck::bytes_of(&p));
let mut e = g.device.create_command_encoder(&Default::default());
// Particles: placed for this frame's time and camera, then the dynamic BLASes rebuilt (before the raster and
@@ -518,7 +518,7 @@ impl LiveCore {
dof: dof_params(self.sc.dof.as_ref(), cam.tan_half_fov, w, h),
jit: [jitter.0, jitter.1, 0.0, 0.0],
state: [1 - self.frame % 2, 0, 0, 0],
- lt: [tile_at.0, tile_at.1, lists, layout::light_tiles(iw)],
+ lt: [tile_at.0, tile_at.1, 0, layout::light_tiles(iw)],
};
g.queue.write_buffer(&self.targets.params, 0, bytemuck::bytes_of(&lp));
// Translucent particles: drawn over the upscaled image right after `upscale` (in sb when depth of field / motion
diff --git a/renderer/src/live/layout.rs b/renderer/src/live/layout.rs
index 5f45139..f795187 100644
--- a/renderer/src/live/layout.rs
+++ b/renderer/src/live/layout.rs
@@ -36,8 +36,10 @@ pub(super) enum Res {
KernelRefl,
KernelMotion,
KernelDirect,
- /// The kernel's direct buffer, to write (`light_tiles`: the light tiles' lists after its per-pixel data).
- KernelLights,
+ /// For `light_tiles`: the kernel's direct buffer again (the pixels' reports; bound as the lists are, read-write)
+ /// and the light tiles' lists it writes (`gpu::KernelBufs::lists`).
+ KernelReports,
+ KernelLists,
/// The tonemap LUT and its sampler.
Lut,
LutSampler,
@@ -85,7 +87,8 @@ pub(super) const RESOURCES: &[(&str, Res)] = &[
("refl_res", Res::Own(Count::Pixels(1))),
("motion_in", Res::KernelMotion),
("direct_in", Res::KernelDirect),
- ("light_rw", Res::KernelLights),
+ ("light_rw", Res::KernelReports),
+ ("light_lists", Res::KernelLists),
("lock_fwd", Res::Own(Count::Pixels(1))),
];
@@ -184,10 +187,9 @@ pub(super) fn light_tiles(n: u32) -> u32 {
n.div_ceil(8) + 1
}
-/// The light tiles' lists in the kernel's direct buffer, for an output of `w` x `h`: after its vec4 a pixel, 64 vec4s
-/// a tile. Their first vec4 and how many they are.
-pub(super) fn light_lists(w: u32, h: u32) -> (u32, u32) {
- (w * h, light_tiles(w) * light_tiles(h) * 64)
+/// The vec4s of the light tiles' lists for an output of `w` x `h`: 64 a tile.
+pub(super) fn light_lists(w: u32, h: u32) -> u32 {
+ light_tiles(w) * light_tiles(h) * 64
}
/// The binding live.wgsl gives `name`.
@@ -224,7 +226,7 @@ pub(super) fn check() {
let fits = match (res, &b.kind) {
(Res::Params, Kind::Uniform) | (Res::Lut, Kind::Texture(_)) | (Res::LutSampler, Kind::Sampler) => true,
(Res::Samples | Res::KernelRefl | Res::KernelMotion | Res::KernelDirect, Kind::Storage { read_only, .. }) => *read_only,
- (Res::KernelLights, Kind::Storage { read_only, .. }) => !*read_only,
+ (Res::KernelReports | Res::KernelLists, Kind::Storage { read_only, .. }) => !*read_only,
(Res::Own(Count::Declared), Kind::Storage { len, .. }) => *len > 0,
(Res::Own(_), Kind::Storage { len, .. }) => *len == 0,
_ => false,
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 373fc84..8c1a25e 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -230,11 +230,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
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);
// (The light tree is the tables' by now: its nodes from there.)
- let mut up = g.upload(&sc, w, h, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, crate::ltree::nodes_of(tables.light_tree.as_ref()), &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 up = g.upload(&sc, w, h, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;
let _ = g.pipeline(&up.kernel, true); // compile the scene's kernel variant now, not in the first frame
let sky_inputs = ((prep.env.width, prep.env.height), sc.camera.position.y.max(0.0), prep.env_nee_floor);
let mut base = prep.params;
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 9a67846..95875ca 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -132,8 +132,7 @@ struct LiveParams {
jit: [f32; 4],
/// Which half of the lasting buffers is this frame's (live.wgsl `this_half`; the other the previous frame's), -.
state: [u32; 4],
- /// The light tiles (live.wgsl `light_tiles`): this frame's grid offset x, y, the lists' first vec4 in the kernel's
- /// direct buffer, tiles a row.
+ /// The light tiles (live.wgsl `light_tiles`): this frame's grid offset x, y, -, tiles a row.
lt: [u32; 4],
}
@@ -542,7 +541,7 @@ 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 = cache_on.then(|| RadianceCache { bufs: targets.kernel.cache.clone(), resolve: g.cache_resolve_pipeline(&targets.kernel) });
+ let cache = cache_on.then(|| RadianceCache { bufs: targets.kernel.cache.clone(), resolve: g.cache_resolve_pipeline() });
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);
// (Read whenever a kernel of this session may have the guard: under software traversal a scene's first unit
// brings it, `gpu::loop_guard_of`.)
diff --git a/renderer/src/live/targets.rs b/renderer/src/live/targets.rs
index 3b255c2..8f4f3bf 100644
--- a/renderer/src/live/targets.rs
+++ b/renderer/src/live/targets.rs
@@ -166,8 +166,7 @@ impl 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 }),
bufs,
out,
- // (The direct buffer: a vec4 an output pixel, then the light tiles' lists: `layout::light_lists`.)
- kernel: gpu::KernelBufs::new(d, g.merged, g.guard_room(), cache, n * 32, n * 16, (n + layout::light_lists(w, h).1 as u64) * 16),
+ kernel: gpu::KernelBufs::new(d, g.merged, g.guard_room(), cache, n * 32, n * 16, n * 16, layout::light_lists(w, h) as u64 * 16),
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() }),
@@ -183,7 +182,8 @@ impl Targets {
match layout::resource(b) {
layout::Res::KernelRefl => &self.kernel.refl,
layout::Res::KernelMotion => &self.kernel.motion,
- layout::Res::KernelDirect | layout::Res::KernelLights => &self.kernel.direct,
+ layout::Res::KernelDirect | layout::Res::KernelReports => &self.kernel.direct,
+ layout::Res::KernelLists => &self.kernel.lists,
layout::Res::Own(_) => &self.bufs.iter().find(|x| x.0 == b.binding).expect("an own buffer").1,
r => panic!("`{}` is bound to {r:?}, not a buffer of the passes'", b.name),
}
diff --git a/renderer/src/merged.rs b/renderer/src/merged.rs
index 218dba9..1d2caba 100644
--- a/renderer/src/merged.rs
+++ b/renderer/src/merged.rs
@@ -1,90 +1,44 @@
//! The merged binding layout: the kernel with at most eight storage buffers a stage, WebGPU's default limit
-//! (`maxStorageBuffersPerShaderStage`). The kernel binds 20 as it is written: more than a browser gives a page.
+//! (`maxStorageBuffersPerShaderStage`). The kernel binds 21 as it is written: more than a browser gives a page.
//! (The live passes need none of this: each binds at most eight, live/layout.rs, and a page binds them as they are.)
//!
//! The kernel's source has both layouts: pathtrace.wgsl declares its tables' views and its group-1 buffers in an
//! `@if(merged) { .. } @else { .. }` block each (WESL's conditional translation, `gpu::KernelVariant`), and reads and
-//! writes them only through functions declared in each (`material_at`, `cache_acc_add`, `refl_store`, ...). This
-//! module is the Rust side's half: which views a layout binds, the lengths of the merged struct's arrays (WESL
-//! constants the source imports, `gpu::KernelVariant::constants`) and where the arrays are, for the buffer the
-//! renderer makes. `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").
+//! writes them only through functions declared in each (`material_at`, `cache_acc_add`, `refl_store`, ...).
+//! `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:
-//! - The scene's tables are the sections of one buffer in every layout (heap.rs). As written the kernel binds the
-//! seven it reads at every hit or light again, each section as a typed array (`TABLE_VIEWS`); here it binds none
-//! of them and reads all seven from the buffer whole.
-//! - The kernel's six group-1 buffers (`KERNEL_LIVE`: the radiance cache, what the live passes read of a trace) and
-//! the loop guard's count become the arrays of `ML: MergedLive`, one buffer that they are ranges of
-//! (`gpu::KernelBufs`). What the live passes read of it starts at a multiple of 256 bytes (`@align(256)`): the
-//! passes bind those ranges as buffers of their own, and a binding's offset is a multiple of that (WebGPU's
-//! `minStorageBufferOffsetAlignment`).
+//! What is merged, each into a buffer of sections found by offsets in the kernel's parameters (heap.rs), so no
+//! length is the source's and a scene or a view of another size is the same kernel:
+//! - The scene's tables are the sections of one buffer in every layout. As written the kernel binds the seven it
+//! reads at every hit or light again, each section as a typed array (`TABLE_VIEWS`); here it binds none of them
+//! and reads all seven from the buffer whole.
+//! - The kernel's group-1 buffers (the radiance cache, what the live passes read of a trace, the light tiles'
+//! lists, the loop guard's count) are buffers of their own as written; here the sections of one (`heap::Live`;
+//! `gpu::KernelBufs`), which the live passes bind as buffers of their own (a section starts at a multiple of
+//! WebGPU's `minStorageBufferOffsetAlignment`).
//!
-//! The tests below read every variant with naga: valid WGSL, no stage with more than `STORAGE_BUFFERS`, and the
-//! struct's arrays where `live_layout` puts them.
+//! The tests below read every variant with naga: valid WGSL, and no stage with more than `STORAGE_BUFFERS`.
use crate::heap::Table;
/// 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's size in a storage buffer; where its array may start in the struct: its element's alignment, or
- /// more (`@align` in pathtrace.wgsl's struct).
- pub stride: u64,
- pub align: u64,
-}
-
/// The tables the kernel as written binds again as typed arrays over their sections, and their bindings (group 0;
/// pathtrace.wgsl `materials`, `lights`, `emitters`, `tex_info`, `objects`, `instances`, `media`).
pub const TABLE_VIEWS: [(Table, u32); 7] = [(Table::Materials, 12), (Table::Lights, 13), (Table::Emitters, 14), (Table::TexInfo, 15), (Table::Objects, 16), (Table::Instances, 17), (Table::Media, 18)];
-/// The kernel's group-1 buffers, in `MergedLive`'s order (group 1, binding `KERNEL_LIVE_BINDING`).
-pub const KERNEL_LIVE: [Member; 6] = [
- Member { name: "cache_keys", stride: 4, align: 4 },
- Member { name: "cache_acc", stride: 4, align: 4 },
- Member { name: "cache_val", stride: 16, align: 16 },
- Member { name: "refl", stride: 16, align: 256 },
- Member { name: "motion_out", stride: 16, align: 256 },
- Member { name: "direct_out", stride: 16, align: 256 },
-];
-pub const KERNEL_LIVE_BINDING: u32 = 1;
-/// `MergedLive`'s last array, after `KERNEL_LIVE`'s: the loop guard's count (`gpu::guard_loops`; 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", stride: 4, align: 4 };
-/// The same count in the layout as written, when the kernel has the guard (group 1, binding `GUARD_BINDING`).
+/// The merged layout's one group-1 buffer (group 1, binding `LIVE_BINDING`; pathtrace.wgsl `live`).
+pub const LIVE_BINDING: u32 = 1;
+/// The light tiles' lists in the layout as written (group 1, binding `LISTS_BINDING`).
+pub const LISTS_BINDING: u32 = 4;
+/// The loop guard's count (`gpu::guard_loops`; its first word: the invocations a loop of which was stopped): in the
+/// layout as written a buffer of its own when the kernel has the guard (group 1, binding `GUARD_BINDING`), in the
+/// merged layout a section (`heap::Live::Guard`), written only by a kernel with the guard.
pub const GUARD_BINDING: u32 = 8;
pub const GUARD_WORDS: u32 = 4;
-/// Where `MergedLive`'s arrays are for these lengths (bytes): `KERNEL_LIVE`'s six, then the loop guard's count; and
-/// the struct's size.
-pub fn live_layout(caps: &[u32; 6]) -> (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;
- }
- // (A struct's size is a multiple of its largest member's alignment: 256 where the live passes' ranges are.)
- (out, at.next_multiple_of(members.iter().map(|m| m.align).max().unwrap_or(16)))
-}
-
-/// The lengths of the merged struct's arrays: what a kernel's source is written for (`gpu::Kernel::caps`).
-#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
-pub struct Caps {
- pub live: [u32; 6],
-}
-
-/// 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
-}
-
/// The uniform tables (`gpu::GpuOptions::uniform_tables`; docs/RUNTIME.md "Android"): the tables the kernel reads
/// from uniform buffers, copies of their sections, instead of from views of the sections. Qualcomm's Adreno 740 driver
/// (Vulkan, Android 13) gave the kernel other buffers' contents for these four when each was a read-only storage
@@ -123,15 +77,9 @@ mod tests {
use crate::gpu::{kernel_template, kernel_wgsl, KernelVariant};
- /// A scene's kernel (software traversal, no switch) as compiled, in the merged layout when given its lengths.
- fn variant(features: u32, merged: Option<&Caps>) -> String {
- kernel_wgsl(&kernel_template(), &KernelVariant { merged: merged.copied(), ..KernelVariant::new(false, Default::default(), features) })
- }
-
- fn caps() -> Caps {
- // A cache of one entry, a view of 64 x 36: lengths that are not round.
- let n = 64 * 36;
- Caps { live: [1, 8, 2, 2 * n, n, n] }
+ /// A scene's kernel (software traversal, no switch) as compiled, as written or in the merged layout.
+ fn variant(features: u32, merged: bool) -> String {
+ kernel_wgsl(&kernel_template(), &KernelVariant { merged, ..KernelVariant::new(false, Default::default(), features) })
}
fn parse(src: &str) -> (naga::Module, naga::valid::ModuleInfo) {
@@ -157,26 +105,30 @@ mod tests {
}
/// Kernel variants 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 struct's arrays where
- /// `live_layout` puts them. The layout as written has 20. Because the merged blocks declare none of the views
- /// or of group 1's buffers by their own names, a read or write of one past its accessor does not compile here
- /// (and naga says where), whatever the other layouts take.
+ /// declared beyond them (a pipeline layout counts what is declared), no length of a view's buffer in the source,
+ /// and `MergedLive`'s members where the renderer puts their sections.
+ /// The layout as written has 21 (20 under hardware traversal, which has no trees' buffer). Because the merged
+ /// blocks declare none of the views or of group 1's buffers by their own names, a read or write of one past its
+ /// accessor does not compile here (and naga says where), whatever the other layouts take.
#[test]
fn the_merged_kernel_fits_eight_storage_buffers() {
- let (m, info) = parse(&variant(0, None));
+ let (m, info) = parse(&variant(0, false));
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();
+ assert_eq!(declared, 21, "the kernel as written");
+ assert_eq!(used.iter().map(|u| u.1).max(), Some(21), "{used:?}");
+ let hw = kernel_wgsl(&kernel_template(), &KernelVariant::new(true, Default::default(), 0));
+ assert_eq!(hw.matches("var<storage").count(), 20 + 4, "hardware traversal: no trees' buffer (and the translucency pass's four)");
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 = variant(features, Some(&caps));
- assert!(src.contains(&format!("const ML_REFL = {}u;", caps.live[3])), "the lengths, as constants");
+ let src = variant(features, true);
+ assert!(!src.contains("arrayLength"), "the lengths are the parameters'");
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, "MergedLive"), live_layout(&caps.live));
+ // The struct's members are the first sections; its last, the vec4s, begins where the cache's values do.
+ let (at, _) = crate::heap::Heap::<crate::heap::Live>::starts_for(&crate::gpu::live_sizes(1, 64, 64, 64, 64));
+ assert_eq!(layout(&m, "MergedLive").0, at[..4]);
}
}
@@ -202,11 +154,11 @@ mod tests {
out.sort_by_key(|g| g.1);
out
};
- let (written, _) = parse(&variant(0, None));
+ let (written, _) = parse(&variant(0, false));
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_wgsl(&kernel_template(), &KernelVariant { uniform_tables: true, ..KernelVariant::new(false, Default::default(), features) });
let (m, info) = parse(&src);
- assert_eq!(storage_buffers(&m, &info).1, 16, "features {features:#x}");
+ assert_eq!(storage_buffers(&m, &info).1, 17, "features {features:#x}");
let tables: Vec<(String, u32, u32)> = globals(&m, true).into_iter().filter(|g| g.0 != "P").collect();
let want: Vec<(String, u32, u32)> = UNIFORM_TABLES.iter().map(|t| (t.name.to_string(), t.binding, (t.stride * t.len as u64) as u32)).collect();
assert_eq!(tables, want, "features {features:#x}");
@@ -227,7 +179,7 @@ mod tests {
#[test]
fn the_tables_records_are_the_kernels() {
use crate::scene::{GpuInstance, GpuLight, GpuMaterial, MediumGpu};
- let src = variant(0, Some(&caps()));
+ let src = variant(0, true);
let (m, _) = parse(&src);
// (The views' bindings follow the buffer's, and are the kernel's.)
for (k, (table, binding)) in TABLE_VIEWS.iter().enumerate() {
@@ -239,6 +191,7 @@ mod tests {
assert_eq!(layout(&m, name).1 as usize, bytes, "{name}");
}
assert_eq!(<Table as crate::heap::Section>::COUNT, Table::Energy as usize + 1);
+ assert!(kernel_template().contains(&format!("const CACHE_SIZE: u32 = {}u;", crate::gpu::CACHE_SIZE)));
// What the kernel reads with no offset is its heap's first section.
assert_eq!((Table::LightTree as usize, crate::heap::Stream::EnvCdf as usize), (0, 0));
assert!(kernel_template().contains("fn lt_node(i: u32) -> vec4<f32> { return table_f(i); }") && kernel_template().contains("fn env_cdf_at(i: u32) -> f32 { return bitcast<f32>(words[i]); }"));
@@ -246,8 +199,8 @@ mod tests {
}
/// The loop guard opens every loop of the kernel but counted ones (`for (var i = N; i < M; i++)`, literals), the
- /// scene's functions' too, in the layout as written and in the merged one (its count a buffer of its own, or in
- /// `MergedLive`), and what comes out is valid WGSL.
+ /// scene's functions' too, in the layout as written and in the merged one (its count a buffer of its own, or a
+ /// section of `live`), and what comes out is valid WGSL.
#[test]
fn the_guard_bounds_every_loop() {
let counted = |s: &str| {
@@ -262,7 +215,7 @@ mod tests {
.count()
};
let loops = |s: &str| s.matches("loop {").count() + s.matches("for (").count() + s.matches("while (").count();
- for merged in [None, Some(caps())] {
+ for merged in [false, true] {
let v = KernelVariant { merged, ..KernelVariant::new(false, Default::default(), crate::gpu::F_SOURCE) };
let plain = kernel_wgsl(&kernel_template(), &v);
let g = kernel_wgsl(&kernel_template(), &KernelVariant { guard: Some(1 << 16), ..v });
@@ -271,7 +224,7 @@ mod tests {
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_eq!(declared as u32, if merged.is_some() { STORAGE_BUFFERS } else { 21 }, "{used:?}");
+ assert_eq!(declared as u32, if merged { STORAGE_BUFFERS } else { 22 }, "{used:?}");
}
// The pass on its own: nested loops, a `continuing` block, comments and braces in them, a loop in an `if`; a
// counted loop left alone, one bounded by a variable or assigning its counter guarded.
@@ -284,23 +237,24 @@ mod tests {
assert_eq!(first("for (var k"), "if (e) {", "{g}");
}
- /// The constants a variant imports are the ones it is given, by name: a merged kernel's lengths, a guard's limit.
+ /// The constants a variant imports are the ones it is given, by name: a guard's limit, the uniform tables'
+ /// lengths. The merged layout has none of its own.
#[test]
fn the_variant_gives_what_it_imports() {
- let v = KernelVariant { merged: Some(caps()), guard: Some(9), ..KernelVariant::new(false, Default::default(), 0) };
- let c = v.constants();
- assert_eq!(c.len(), 6 + 2);
- assert!(c.contains(&("ML_DIRECT_OUT".into(), 64 * 36)) && c.contains(&("LOOP_GUARD_LIMIT".into(), 9)) && c.contains(&("GUARD_WORDS".into(), GUARD_WORDS)));
+ let v = KernelVariant { merged: true, guard: Some(9), ..KernelVariant::new(false, Default::default(), 0) };
+ assert_eq!(v.constants(), vec![("GUARD_WORDS".into(), GUARD_WORDS), ("LOOP_GUARD_LIMIT".into(), 9)]);
+ assert_eq!(KernelVariant { merged: true, ..Default::default() }.constants(), vec![("GUARD_WORDS".into(), GUARD_WORDS)]);
let u = KernelVariant { uniform_tables: true, ..KernelVariant::new(false, Default::default(), 0) }.constants();
assert_eq!(u, vec![("UT_TEX_INFO".into(), 4096), ("UT_OBJECTS".into(), 4096), ("UT_INSTANCES".into(), 409), ("UT_MEDIA".into(), 32)]);
assert!(KernelVariant::default().constants().is_empty());
}
#[test]
- #[should_panic(expected = "ML_REFL")]
+ #[should_panic(expected = "LOOP_GUARD_LIMIT")]
fn a_constant_the_source_imports_must_be_given() {
- let mut c = KernelVariant { merged: Some(caps()), ..KernelVariant::new(false, Default::default(), 0) }.constants();
- c.retain(|(n, _)| n != "ML_REFL");
- crate::gpu::wesl_wgsl(&kernel_template(), &KernelVariant { merged: Some(caps()), ..Default::default() }.flags(), &c);
+ let v = KernelVariant { guard: Some(9), ..KernelVariant::new(false, Default::default(), 0) };
+ let mut c = v.constants();
+ c.retain(|(n, _)| n != "LOOP_GUARD_LIMIT");
+ crate::gpu::wesl_wgsl(&kernel_template(), &v.flags(), &c);
}
}