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.

Shaders: shared declarations once; the kernel's layouts in one place, held to the source (#91)

Yujia2521d608f004
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index b20a366..13af16b 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2391,6 +2391,16 @@ placeholder there), so the count of bindings is as it was.
is byte-identical to one main's binary gave; four confirming runs under-read a test whose output holds for a
process.
+**Shared declarations once; the kernel's layouts held to its source (2026-11-15, after it).** `TriAttr` was
+declared in three shaders, `Pixel` and the light tiles' constants in two; the particle passes got the object table's
+stride by gpu.rs rewriting a line of their text; the kernel's bind group layouts were written by hand beside the
+shader's declarations, with no test between them. Now `records.wgsl` declares what is shared and is part of each
+shader that uses it; the stride is a pipeline constant, as in the kernel; the layouts' entries are one function
+(gpu.rs `kernel_layout_entries`), and a test holds them to what every variant of the kernel declares, kind and
+access (it fails on a wrong entry: tried). The kernels' code is the same: render-identity against main 0 of 194
+changed in four layouts, bench-window's shots as main's, the trace equal (Bistro 8.65 / 8.64 ms, lamp-rooms 3.71 /
+3.72), `tools/web-hello.ts` in Chrome passes.
+
## 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 7f36d1c..b8f6e59 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1044,8 +1044,9 @@ to it.
(`a_top_tree_is_kept_while_units_only_move`); the random edits above run through the same rule;
- what a ray reads, counted (`units_cost.rs`, measurements, not tests: `units_cost` over a bundle's scene with units
and flattened; `units_pile`, pieces of debris thrown onto a scene);
-- the sources handed to wgpu for every scene without units: the hashes main has
- (`the_default_sources_are_untouched`); the guarded, merged kernel with units is valid WGSL in 8 storage buffers;
+- the sources handed to wgpu for every scene without units: the hashes main had then (a test of that step, since
+ removed; `every_kernel_variant_is_valid` prints the default variants' hashes); the guarded, merged kernel with
+ units is valid WGSL in 8 storage buffers;
- an offline render of a scene with instances: no unit, no `F_UNITS`, and the triangle and node bytes the flattened
scene has, unless `THREERT_UNITS=1` (`an_offline_render_has_no_units_unless_told`);
- the guard's default: a kernel with units has it at 65,536 with nothing set and none at `THREERT_LOOP_GUARD=0`, a
@@ -1234,8 +1235,8 @@ units under software traversal; hello world natively and in Chrome (every check,
## The kernel's source
-The path-tracing kernel is one WESL module: `pathtrace.wgsl`, then `trace_units.wgsl`, `trace_hw.wgsl` and
-`translucent.wgsl` (gpu.rs `KERNEL_FILES`), every device's and scene's variant in it under WESL's conditional
+The path-tracing kernel is one WESL module: `pathtrace.wgsl`, then `records.wgsl`, `sample.wgsl`,
+`trace_units.wgsl`, `trace_hw.wgsl` and `translucent.wgsl` (gpu.rs `KERNEL_FILES`), every device's and scene's variant in it under WESL's conditional
translation (`@if(flag)` on a declaration or a statement, `@if(flag) { .. } @else { .. }` on a block of
declarations). wesl-rs (WESL's compiler in Rust, natively and in a browser alike) makes a kernel's WGSL from a
variant (gpu.rs `KernelVariant`, `kernel_wgsl`): the traversal (`hwrt`), a device's switches (`strict`,
@@ -1250,6 +1251,12 @@ too is an override, from F_TINT).
`cache_acc_add`, `refl_store`, ...), declared once in each layout's block, so a layout is its declarations and
nothing else of the kernel knows which it is in.
- The loop guard's count goes into every loop by a pass over the variant's syntax tree (gpu.rs `guard_loops`).
+- What more than one shader reads or writes is declared once, in `records.wgsl`: a triangle's attributes
+ (`TriAttr`), a sample of the trace (`Pixel`), the light tiles' constants. The file is part of the kernel, of the
+ particle passes and of the live passes (build.rs reads it with live.wgsl). The particle passes take the object
+ table's stride as a pipeline constant, as the kernel does (until 2026-11-15 gpu.rs rewrote a line of their text).
+- The kernel's bind group layouts are written in one place (gpu.rs `kernel_layout_entries`), and a test holds them
+ to what every variant's source declares, kind and access (`the_kernels_layouts_are_its_declarations`).
- Still as text: a scene's material, volume and geometry functions, between their markers in pathtrace.wgsl.
- Until 2026-11-14 the variants were patches of the source at anchors, whole lines of code found and replaced (gpu.rs
`kernel_base`, `kernel_switches`, `kernel_source`). For every combination of the flags, 2,304, the Metal source naga
@@ -1378,8 +1385,7 @@ On Qualcomm's Adreno 740 (Snapdragon 8 Gen 2, Android 13; an AYN Thor handheld)
draw correctly: a model's textures came out as another table's numbers, emissive objects lit nothing, Light Room was
black. What follows is what fixed it there, on this engine's current source, and it has run on the device ("Checked
on the device" below). All of it is off on every other platform unless asked for: with nothing set the device, its
-layout and its kernels' source are what they were (`gpu.rs` `the_options_default_to_the_device_as_written`,
-`the_default_sources_are_untouched`).
+layout and its kernels' source are what they were (`gpu.rs` `the_options_default_to_the_device_as_written`).
**The figures in the two tables are the original author's, measured on that handheld with the engine at `b646a20`,**
on scenes that are not all at hand. What was measured again on this source, on the same handheld, is under "Checked
diff --git a/renderer/build.rs b/renderer/build.rs
index 952bca8..0168ab6 100644
--- a/renderer/build.rs
+++ b/renderer/build.rs
@@ -1,4 +1,5 @@
-//! The live passes' bindings as `shaders/live.wgsl` declares them, read with naga (the compiler wgpu uses) when the
+//! The live passes' bindings as `shaders/live.wgsl` declares them (after `shaders/records.wgsl`, what it shares with
+//! the kernel: live/targets.rs `live_source`), read with naga (the compiler wgpu uses) when the
//! crate is built, into `$OUT_DIR/live_layout.rs` (`src/live/layout.rs` includes it): each binding's name, number,
//! kind and element stride, and the bindings each entry point uses. The shader is the one place they are written;
//! what it cannot say (a buffer's size, a pass's grid) is `src/live/layout.rs`'s table. At build time, not at run
@@ -8,10 +9,12 @@ use naga::{AddressSpace, ImageClass, ImageDimension, ScalarKind, StorageAccess,
use std::fmt::Write;
fn main() {
- let path = "shaders/live.wgsl";
- println!("cargo:rerun-if-changed={path}");
+ let files = ["shaders/records.wgsl", "shaders/live.wgsl"];
+ for path in files {
+ println!("cargo:rerun-if-changed={path}");
+ }
println!("cargo:rerun-if-changed=build.rs");
- let src = std::fs::read_to_string(path).expect("shaders/live.wgsl");
+ let src: String = files.iter().map(|path| std::fs::read_to_string(path).unwrap_or_else(|e| panic!("{path}: {e}"))).collect();
let module = 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(&module)
diff --git a/renderer/shaders/gpu_particles.wgsl b/renderer/shaders/gpu_particles.wgsl
index e30ee48..01909a7 100644
--- a/renderer/shaders/gpu_particles.wgsl
+++ b/renderer/shaders/gpu_particles.wgsl
@@ -55,8 +55,7 @@ struct PP {
// friction, -); e: (first spawn, spawned count, frame number, -); p: parameters.
struct System { a: vec4<u32>, b: vec4<u32>, c: vec4<f32>, d: vec4<f32>, e: vec4<u32>, p: array<vec4<f32>, 8> };
-// scene.rs GpuTriAttr: normals (w: uv parts), uv parts + material, tangent + bitangent sign, (texel density, object).
-struct TriAttr { n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, uv: vec4<f32>, t: vec4<f32>, x: vec4<f32> };
+// (`TriAttr`: records.wgsl.)
@group(0) @binding(0) var<uniform> PPS: PP;
@group(0) @binding(1) var<storage, read> systems: array<System>;
@@ -73,7 +72,8 @@ struct TriAttr { n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, uv: vec4<f32>, t:
@group(0) @binding(9) var<storage, read> spawns: array<vec4<f32>>;
@group(0) @binding(10) var<storage, read> grid: array<u32>;
-const OBJECT_STRIDE: u32 = 3u; // scene.rs `object_stride`: gpu.rs writes 4 here in a scene with instance colours
+// vec4s an object in `objects` (scene.rs `object_stride`: 4 in a scene with instance colours), the pipeline's constant.
+override OBJECT_STRIDE: u32 = 3u;
fn pcg(v: u32) -> u32 {
let s = v * 747796405u + 2891336453u;
diff --git a/renderer/shaders/live.wgsl b/renderer/shaders/live.wgsl
index 3ce284f..f69bcb3 100644
--- a/renderer/shaders/live.wgsl
+++ b/renderer/shaders/live.wgsl
@@ -34,9 +34,7 @@ struct LiveParams {
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), -, 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).
-struct Pixel { color: vec4<f32>, albedo: vec4<f32>, normal: vec4<f32>, emit: vec4<f32>, spec: vec4<f32> };
+// (`Pixel`, a sample of the trace: records.wgsl, a part of this module. normal.w: `medium_tr`, `medium_share`.)
@group(0) @binding(0) var<uniform> L: LiveParams;
@group(0) @binding(1) var<storage, read> sample_px: array<Pixel>; // color.w = first-hit distance (0 = sky)
@@ -249,8 +247,7 @@ const RESOLVE_N: u32 = 8u;
// ---- The light tiles: each 8 x 8 tile's pixels' reports made its list (pathtrace.wgsl "Light tiles": the lights
// reported, each once: index, reports; ascending; the 64th vec4 holds their number, 63 at most). A workgroup is a
// tile: the grid is the traced one shifted by L.lt.xy, another offset each frame, so tile borders do not stay put.
-// (Float values, not integers' bits: pathtrace.wgsl LT_NONE says why.)
-const LT_NONE: u32 = 16777216u;
+// (LT_LIST, LT_NONE: records.wgsl. A list is as long as a tile has pixels.)
var<workgroup> lt_keys: array<u32, 64>;
var<workgroup> lt_first: array<u32, 64>;
@@ -283,10 +280,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 = (wg.y * L.lt.w + wg.x) * 64u;
+ let list = (wg.y * L.lt.w + wg.x) * LT_LIST;
let at = less.x + less.y + less.z + less.w;
- 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); }
+ if (first && at < LT_LIST - 1u) { 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 + LT_LIST - 1u] = vec4<f32>(f32(min(all.x + all.y + all.z + all.w, LT_LIST - 1u)), 0.0, 0.0, 0.0); }
}
@compute @workgroup_size(8, 8, 1)
diff --git a/renderer/shaders/particles.wgsl b/renderer/shaders/particles.wgsl
index 8c2e10d..3995fec 100644
--- a/renderer/shaders/particles.wgsl
+++ b/renderer/shaders/particles.wgsl
@@ -39,8 +39,7 @@ struct PP {
env: vec4<f32>, // rain, wetness, first run (1: no last frame, motion vectors 0), -
};
-// scene.rs GpuTriAttr: normals (w: uv parts), uv parts + material, tangent + bitangent sign, (texel density, object).
-struct TriAttr { n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, uv: vec4<f32>, t: vec4<f32>, x: vec4<f32> };
+// (`TriAttr`: records.wgsl.)
// a: (first triangle in the GPU order, count, first object, function); b: (seed, first dynamic triangle, translucent
// (1: its triangles are the translucency pass's, `tblas` from the first translucent triangle), first translucent
@@ -60,7 +59,8 @@ struct System { a: vec4<u32>, b: vec4<u32>, c: vec4<f32>, p: array<vec4<f32>, 8>
// The translucent particles' BLAS input (gpu.rs `Translucent`).
@group(0) @binding(8) var<storage, read_write> tblas: array<f32>;
-const OBJECT_STRIDE: u32 = 3u; // scene.rs `object_stride`: gpu.rs writes 4 here in a scene with instance colours
+// vec4s an object in `objects` (scene.rs `object_stride`: 4 in a scene with instance colours), the pipeline's constant.
+override OBJECT_STRIDE: u32 = 3u;
fn pcg(v: u32) -> u32 {
let s = v * 747796405u + 2891336453u;
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 2487106..b507b8a 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -5,7 +5,7 @@
// wetness / puddles / ripples / grime, procedural facade windows, emissive animation, RIS many-light sampling, height
// fog with volumetric single scattering. Each is compiled out when the scene does not use it (FEAT).
//
-// The kernel is this file and sample.wgsl, trace_units.wgsl, trace_hw.wgsl and translucent.wgsl after it (gpu.rs `KERNEL_FILES`),
+// The kernel is this file and records.wgsl, sample.wgsl, trace_units.wgsl, trace_hw.wgsl and translucent.wgsl after it (gpu.rs `KERNEL_FILES`),
// compiled for a device and a scene by WESL's conditional translation (`@if`, gpu.rs `kernel_wgsl`): a declaration
// or a statement under `@if(x)` is there only where x holds. The flags:
// hwrt hardware traversal (ray queries) in the software BVH walk's place, and the translucency pass
@@ -115,7 +115,7 @@ struct Params {
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> };
+// (`TriAttr`, a triangle's attributes, and `Pixel`, a sample in `accum`: records.wgsl.)
struct Node { bmin: vec3<f32>, left_or_first: u32, bmax: vec3<f32>, count: u32 };
// See scene::GpuMaterial for the field layout.
struct Material {
@@ -124,11 +124,6 @@ struct Material {
};
// See scene::GpuLight (x = volumetric scattering scale, specular scale, rect barn-door cosine, -).
struct Light { pos: vec4<f32>, dir: vec4<f32>, color: vec4<f32>, ext: vec4<f32>, x: vec4<f32> };
-// Live: color = diffuse lighting at the first hit (+ first-hit distance), emit = what the camera ray sees directly
-// (emission, sky; kept out of the denoiser) + first-hit roughness, spec = specular lighting at the first hit +
-// distance to what the first specular bounce hit (reprojection of reflections), normal.w = the media before the first
-// hit (`media_composite`: 0.5 = none). Offline: color / albedo / normal sums.
-struct Pixel { color: vec4<f32>, albedo: vec4<f32>, normal: vec4<f32>, emit: vec4<f32>, spec: vec4<f32> };
@group(0) @binding(0) var<uniform> P: Params;
@group(0) @binding(1) var<storage, read> tri_verts: array<vec4<f32>>;
@@ -1728,12 +1723,8 @@ fn local_light(li: Light, x: vec3<f32>, u: vec2<f32>) -> LS {
// 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
// is the same sum, so one gone stale (the table reordered, a surface newly in view) costs noise, not light.
-// Compiled in for scenes whose shadow-casting local lights are resampled (F_LISTS).
-const LT_TILE: u32 = 8u;
-const LT_LIST: u32 = 64u;
-// (Indices and counts are stored as float values, not as their bits: a small integer's bits are a denormal float,
-// which a driver may flush to zero. So a light-table index stays below LT_NONE, 2^24.)
-const LT_NONE: u32 = 16777216u;
+// Compiled in for scenes whose shadow-casting local lights are resampled (F_LISTS). (LT_TILE, LT_LIST, LT_NONE:
+// records.wgsl.)
var<private> lt_list: u32;
var<private> lt_list_n: u32;
var<private> lt_fb: u32;
diff --git a/renderer/shaders/records.wgsl b/renderer/shaders/records.wgsl
new file mode 100644
index 0000000..84643d6
--- /dev/null
+++ b/renderer/shaders/records.wgsl
@@ -0,0 +1,22 @@
+// What more than one shader reads or writes, declared once. This file is part of the kernel (gpu.rs `KERNEL_FILES`),
+// of the particle passes (`particle_source`, `gpu_particle_source`) and of the live passes (live/targets.rs
+// `live_source`, build.rs).
+
+// A triangle's shading attributes (scene.rs GpuTriAttr): normals (w: uv parts), uv parts (w: material index, bits),
+// tangent (w: bitangent sign), x: (texel density, object (bits), a particle's area, light-tree path code).
+struct TriAttr { n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, uv: vec4<f32>, t: vec4<f32>, x: vec4<f32> };
+
+// A sample the kernel leaves in `accum`. Live: color = diffuse lighting at the first hit (w: first-hit distance, 0 =
+// sky), emit = what the camera ray sees directly (emission, sky; kept out of the denoiser; w: first-hit roughness),
+// spec = specular lighting at the first hit (w: distance to what the first specular bounce hit, for the reflections'
+// reprojection), normal.w = the media before the first hit (`media_composite`: 0.5 = none). Offline: color / albedo /
+// normal sums.
+struct Pixel { color: vec4<f32>, albedo: vec4<f32>, normal: vec4<f32>, emit: vec4<f32>, spec: vec4<f32> };
+
+// The light tiles (pathtrace.wgsl "Light tiles", live.wgsl `light_tiles`): a tile's side in traced pixels, the vec4s
+// of its list (the last holds how many lights it lists), and the report of a pixel that found no light. (Indices and
+// counts are stored as float values, not as their bits: a small integer's bits are a denormal float, which a driver
+// may flush to zero. So a light-table index stays below LT_NONE, 2^24.)
+const LT_TILE: u32 = 8u;
+const LT_LIST: u32 = 64u;
+const LT_NONE: u32 = 16777216u;
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index e4dd27e..5fa6b1e 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -193,6 +193,84 @@ pub struct PendingProc {
/// The acceleration structure's binding in the scene's group (trace_hw.wgsl `acc`): the last, after every buffer.
const ACC_BINDING: u32 = 19;
+/// What the kernel's bind group layouts follow: the device's traversal and binding layout, and whether group 1 has
+/// the loop guard's count (`guard_room`).
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct LayoutShape {
+ pub hwrt: bool,
+ pub merged: bool,
+ pub uniform_tables: bool,
+ pub guard: bool,
+}
+
+fn layout_entry(binding: u32, ty: wgpu::BindingType) -> wgpu::BindGroupLayoutEntry {
+ wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None }
+}
+fn storage_buffer(read_only: bool) -> wgpu::BindingType {
+ wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None }
+}
+const UNIFORM_BUFFER: wgpu::BindingType = wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None };
+fn float_texture(view_dimension: wgpu::TextureViewDimension) -> wgpu::BindingType {
+ wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension, multisampled: false }
+}
+const ACCELERATION_STRUCTURE: wgpu::BindingType = wgpu::BindingType::AccelerationStructure { vertex_return: false };
+
+/// The entries of the kernel's bind group layouts, the one place they are written: group 0 (the scene), group 1
+/// (what the kernel writes), group 2 (the translucency pass's; hardware traversal). A test holds them to what every
+/// variant of the kernel's source declares (`the_kernels_layouts_are_its_declarations`).
+pub(crate) fn kernel_layout_entries(shape: LayoutShape) -> [Vec<wgpu::BindGroupLayoutEntry>; 3] {
+ use crate::merged::{GUARD_BINDING, LISTS_BINDING, LIVE_BINDING, TABLE_VIEWS, UNIFORM_TABLES};
+ let LayoutShape { hwrt, merged, uniform_tables, guard } = shape;
+ let (read, write) = (storage_buffer(true), storage_buffer(false));
+ // Group 0: the parameters; triangles and their attributes; 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.
+ let mut scene = vec![
+ layout_entry(0, UNIFORM_BUFFER),
+ layout_entry(1, read),
+ layout_entry(2, read),
+ layout_entry(4, read),
+ layout_entry(5, read),
+ layout_entry(6, read),
+ layout_entry(7, float_texture(wgpu::TextureViewDimension::D2Array)),
+ layout_entry(8, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)),
+ layout_entry(9, float_texture(wgpu::TextureViewDimension::D2)),
+ layout_entry(10, float_texture(wgpu::TextureViewDimension::D3)),
+ layout_entry(11, write),
+ ];
+ // Software traversal's trees.
+ if !hwrt {
+ scene.push(layout_entry(3, read));
+ }
+ // The tables the kernel reads at every hit or light, bound again as typed views of their sections (the merged
+ // layout has no binding for them), four of them uniform copies where a driver needs it.
+ if !merged {
+ let copied = |b: u32| uniform_tables && UNIFORM_TABLES.iter().any(|t| t.binding == b);
+ scene.extend(TABLE_VIEWS.iter().map(|&(_, b)| layout_entry(b, if copied(b) { UNIFORM_BUFFER } else { read })));
+ }
+ if hwrt {
+ scene.push(layout_entry(ACC_BINDING, ACCELERATION_STRUCTURE));
+ }
+ // Group 1: the raster pass's visibility; then, merged, the one buffer (`heap::Live`, the loop guard's count in
+ // it); as written, the radiance cache's three, the light tiles' lists, the specular rays, the motion vectors, the
+ // direct light, and the loop guard's count where a kernel of this device may have the guard (one without it does
+ // not name the binding).
+ let mut live = vec![layout_entry(0, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Uint, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false })];
+ if merged {
+ live.push(layout_entry(LIVE_BINDING, write));
+ } else {
+ live.extend([1, 2, 3, 5, 6, 7].map(|b| layout_entry(b, write)));
+ live.push(layout_entry(LISTS_BINDING, read));
+ if guard {
+ live.push(layout_entry(GUARD_BINDING, write));
+ }
+ }
+ // Group 2: the translucent particles' acceleration structure, the pass's parameters, its image, the volume
+ // training points and their count, the image at reduced scale.
+ let translucent = if hwrt { vec![layout_entry(0, ACCELERATION_STRUCTURE), layout_entry(1, UNIFORM_BUFFER), layout_entry(2, write), layout_entry(3, write), layout_entry(4, write), layout_entry(5, write)] } else { vec![] };
+ [scene, live, translucent]
+}
+
/// A note for each uniform table that a scene has more entries of (`used`, merged.rs `UNIFORM_TABLES`' order) than
/// its array holds: the kernel reads the last entry for the rest.
pub(crate) fn uniform_overflow(used: [u64; 4]) -> Vec<String> {
@@ -555,10 +633,7 @@ pub struct GpuParticlesGpu {
/// gpu_particles.wgsl with the scene's particle programs (`fn pe_` / `pu_<name>`) and their dispatch.
fn gpu_particle_source(scene: &Scene) -> String {
- let stride = "const OBJECT_STRIDE: u32 = 3u;";
let base = include_str!("../shaders/gpu_particles.wgsl");
- assert_eq!(base.matches(stride).count(), 1, "gpu_particles.wgsl: {stride}");
- let base = if scene.tinted { base.replace(stride, "const OBJECT_STRIDE: u32 = 4u;") } else { base.to_string() };
let mut f = String::new();
let mut seen = std::collections::HashSet::new();
for (_, _, _, helpers) in &scene.particle_programs {
@@ -585,16 +660,12 @@ fn gpu_particle_source(scene: &Scene) -> String {
f.push_str(" default { return s; }\n }\n}\n");
let (head, rest) = base.split_once("// @particle-programs-begin").unwrap();
let (_, tail) = rest.split_once("// @particle-programs-end").unwrap();
- format!("{head}{f}{tail}")
+ format!("{RECORDS}{head}{f}{tail}")
}
-/// particles.wgsl with the scene's particle functions (`fn pf_<name>`) and their dispatch (object entries of 4 vec4s
-/// with instance colours: `scene::object_stride`).
+/// particles.wgsl with the scene's particle functions (`fn pf_<name>`) and their dispatch.
fn particle_source(scene: &Scene) -> String {
- let stride = "const OBJECT_STRIDE: u32 = 3u;";
let base = include_str!("../shaders/particles.wgsl");
- assert_eq!(base.matches(stride).count(), 1, "particles.wgsl: {stride}");
- let base = if scene.tinted { base.replace(stride, "const OBJECT_STRIDE: u32 = 4u;") } else { base.to_string() };
let mut functions = String::new();
let mut seen = std::collections::HashSet::new();
for (_, _, helpers) in &scene.particle_fns {
@@ -614,7 +685,7 @@ fn particle_source(scene: &Scene) -> String {
functions.push_str(" default { return POut(i.pivot, vec3<f32>(0.0), vec3<f32>(0.0), false, vec4<f32>(0.0)); }\n }\n}\n");
let (head, rest) = base.split_once("// @particle-functions-begin").unwrap();
let (_, tail) = rest.split_once("// @particle-functions-end").unwrap();
- format!("{head}{functions}{tail}")
+ format!("{RECORDS}{head}{functions}{tail}")
}
/// Hardware acceleration structures: one BLAS per non-empty traversal group, one TLAS over them.
@@ -749,8 +820,14 @@ pub fn instance_mask(cast_shadow: bool, hidden: bool) -> u8 {
}
/// The kernel's files, one module in this order (pathtrace.wgsl's head says what each holds and names the `@if` flags).
-const KERNEL_FILES: [&str; 5] = [
+/// What more than one shader reads or writes, declared once: a file of the kernel, of the particle passes and of
+/// the live passes (live/targets.rs `live_source`).
+const RECORDS: &str = include_str!("../shaders/records.wgsl");
+
+/// (pathtrace.wgsl first: a module's imports and directives come before its declarations.)
+const KERNEL_FILES: [&str; 6] = [
include_str!("../shaders/pathtrace.wgsl"),
+ RECORDS,
include_str!("../shaders/sample.wgsl"),
include_str!("../shaders/trace_units.wgsl"),
include_str!("../shaders/trace_hw.wgsl"),
@@ -1607,78 +1684,8 @@ impl Gpu {
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,
- ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None },
- count: None,
- };
- let uniform = |binding: u32| wgpu::BindGroupLayoutEntry {
- binding,
- visibility: wgpu::ShaderStages::COMPUTE,
- ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
- count: None,
- };
- let texture = |binding: u32, view_dimension: wgpu::TextureViewDimension| wgpu::BindGroupLayoutEntry {
- binding,
- visibility: wgpu::ShaderStages::COMPUTE,
- 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, 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(4, true),
- storage(5, true),
- storage(6, true),
- texture(7, wgpu::TextureViewDimension::D2Array),
- wgpu::BindGroupLayoutEntry { binding: 8, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None },
- texture(9, wgpu::TextureViewDimension::D2),
- 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`).
- if !merged {
- let copied = |b: u32| uniform_tables && crate::merged::UNIFORM_TABLES.iter().any(|t| t.binding == b);
- entries.extend(crate::merged::TABLE_VIEWS.iter().map(|&(_, b)| if copied(b) { uniform(b) } else { storage(b, true) }));
- }
- if hwrt {
- entries.push(wgpu::BindGroupLayoutEntry { binding: ACC_BINDING, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::AccelerationStructure { vertex_return: false }, count: None });
- }
+ let [entries, vis_entries, tl_entries] = kernel_layout_entries(LayoutShape { hwrt, merged, uniform_tables, guard: guard_room(hwrt) });
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &entries });
- 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(crate::merged::LISTS_BINDING, true),
- storage(5, false),
- storage(6, false),
- storage(7, false),
- ];
- // 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 {
- vis_entries.truncate(2);
- } else if guard_room(hwrt) {
- vis_entries.push(storage(crate::merged::GUARD_BINDING, false));
- }
let vis_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("vis"), entries: &vis_entries });
let one = device.create_texture(&wgpu::TextureDescriptor {
label: Some("no vis"),
@@ -1695,31 +1702,20 @@ impl Gpu {
let grid_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("grid sim"),
entries: &[
- uniform(0),
+ layout_entry(0, UNIFORM_BUFFER),
wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D3, multisampled: false }, count: None },
wgpu::BindGroupLayoutEntry { binding: 2, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D3, multisampled: false }, count: None },
wgpu::BindGroupLayoutEntry { binding: 3, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None },
wgpu::BindGroupLayoutEntry { binding: 4, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::WriteOnly, format: GRID_FORMAT, view_dimension: wgpu::TextureViewDimension::D3 }, count: None },
wgpu::BindGroupLayoutEntry { binding: 5, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::WriteOnly, format: GRID_FORMAT, view_dimension: wgpu::TextureViewDimension::D3 }, count: None },
- storage(6, true),
+ layout_entry(6, storage_buffer(true)),
],
});
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 {
- 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 };
- let l = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: Some("translucent"),
- entries: &[
- wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::AccelerationStructure { vertex_return: false }, count: None },
- wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, count: None },
- st(2),
- st(3),
- st(4),
- st(5),
- ],
- });
+ let l = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("translucent"), entries: &tl_entries });
let tpl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("translucent"), bind_group_layouts: &[Some(&layout), Some(&vis_layout), Some(&l)], immediate_size: 0 });
(Some(l), Some(tpl))
} else {
@@ -2294,11 +2290,13 @@ impl Gpu {
}
_ => None,
};
+ // (The particle passes' pipeline constant: vec4s an object entry, 4 with instance colours.)
+ let object_stride = [("OBJECT_STRIDE", scene.object_stride() as f64)];
// Particle systems (hardware RT: the pass writes the dynamic BLASes' input).
let particles = match &accel {
Some(a) if !scene.particles.is_empty() => {
let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("particles"), source: wgpu::ShaderSource::Wgsl(particle_source(scene).into()) });
- let pipeline = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("particles"), layout: None, module: &module, entry_point: Some("particles"), compilation_options: Default::default(), cache: self.cache() });
+ let pipeline = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("particles"), layout: None, module: &module, entry_point: Some("particles"), compilation_options: wgpu::PipelineCompilationOptions { constants: &object_stride, ..Default::default() }, cache: self.cache() });
let sm = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("stamp"), source: wgpu::ShaderSource::Wgsl(STAMP_WGSL.into()) });
let sp = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("stamp"), layout: None, module: &sm, entry_point: Some("stamp"), compilation_options: Default::default(), cache: self.cache() });
// The stamps depend on what is rebuilt last: the translucent TLAS when there is one.
@@ -2337,7 +2335,7 @@ impl Gpu {
let gpu_particles = match &accel {
Some(a) if !scene.gpu_particles.is_empty() => {
let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("gpu particles"), source: wgpu::ShaderSource::Wgsl(gpu_particle_source(scene).into()) });
- let pipeline = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("gpu particles"), layout: None, module: &module, entry_point: Some("gpu_particles"), compilation_options: Default::default(), cache: self.cache() });
+ let pipeline = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("gpu particles"), layout: None, module: &module, entry_point: Some("gpu_particles"), compilation_options: wgpu::PipelineCompilationOptions { constants: &object_stride, ..Default::default() }, cache: self.cache() });
let systems: Vec<GpuParticleSystemGpu> = scene
.gpu_particles
.iter()
@@ -3356,6 +3354,70 @@ mod tests {
naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all()).validate(&m).unwrap_or_else(|e| panic!("{}", e.emit_to_string(src)));
}
+ /// The kernel's bind group layouts are what its source declares, in every layout and traversal: a variant's
+ /// bindings are the layout's, each of its kind (a storage buffer's access too), but for the loop guard's count,
+ /// which a layout as written has room for and a kernel without the guard does not name.
+ #[test]
+ fn the_kernels_layouts_are_its_declarations() {
+ use naga::{AddressSpace, ImageClass, ImageDimension as Dim, ScalarKind, StorageAccess, TypeInner};
+ use wgpu::TextureViewDimension as View;
+ type Entry = (u32, u32, wgpu::BindingType);
+ let declared = |v: &KernelVariant| -> Vec<Entry> {
+ let src = kernel_wgsl(&kernel_template(), v);
+ let m = naga::front::wgsl::parse_str(&src).unwrap_or_else(|e| panic!("{}", e.emit_to_string(&src)));
+ let mut out: Vec<Entry> = m
+ .global_variables
+ .iter()
+ .filter_map(|(_, g)| {
+ let b = g.binding.as_ref()?;
+ let name = g.name.as_deref().unwrap_or("");
+ let ty = match (g.space, &m.types[g.ty].inner) {
+ (AddressSpace::Uniform, _) => UNIFORM_BUFFER,
+ (AddressSpace::Storage { access }, _) => storage_buffer(!access.contains(StorageAccess::STORE)),
+ (AddressSpace::Handle, TypeInner::Image { dim: Dim::D2, arrayed: false, class: ImageClass::Sampled { kind: ScalarKind::Uint, multi: false } }) => {
+ wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Uint, view_dimension: View::D2, multisampled: false }
+ }
+ (AddressSpace::Handle, TypeInner::Image { dim, arrayed, class: ImageClass::Sampled { kind: ScalarKind::Float, multi: false } }) => float_texture(match (dim, arrayed) {
+ (Dim::D2, true) => View::D2Array,
+ (Dim::D2, false) => View::D2,
+ (Dim::D3, false) => View::D3,
+ other => panic!("{name}: a {other:?} texture"),
+ }),
+ (AddressSpace::Handle, TypeInner::Sampler { comparison: false }) => wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ (AddressSpace::Handle, TypeInner::AccelerationStructure { .. }) => ACCELERATION_STRUCTURE,
+ (space, _) => panic!("{name}: a {space:?} binding the layouts do not know"),
+ };
+ Some((b.group, b.binding, ty))
+ })
+ .collect();
+ out.sort_by_key(|e| (e.0, e.1));
+ out
+ };
+ let mut checked = 0;
+ for (hwrt, merged, uniform_tables) in [(true, false, false), (true, false, true), (false, false, false), (false, false, true), (false, true, false)] {
+ for room in [false, true] {
+ let mut layout: Vec<Entry> = kernel_layout_entries(LayoutShape { hwrt, merged, uniform_tables, guard: room }).iter().enumerate().flat_map(|(g, es)| es.iter().map(move |e| (g as u32, e.binding, e.ty))).collect();
+ layout.sort_by_key(|e| (e.0, e.1));
+ for guard in [None, Some(1 << 16)] {
+ // (As written, a kernel with the guard needs the room.)
+ if guard.is_some() && !room && !merged {
+ continue;
+ }
+ for features in if hwrt { vec![0] } else { vec![0, F_UNITS] } {
+ let mut want = layout.clone();
+ if guard.is_none() && !merged {
+ want.retain(|e| (e.0, e.1) != (1, crate::merged::GUARD_BINDING));
+ }
+ let v = KernelVariant { merged, uniform_tables, guard, ..KernelVariant::new(hwrt, KernelSwitches::default(), features) };
+ assert_eq!(declared(&v), want, "{v:?} in a layout {} room for the guard", if room { "with" } else { "without" });
+ checked += 1;
+ }
+ }
+ }
+ }
+ assert_eq!(checked, 2 * 3 + 2 * 6 + 8);
+ }
+
/// The native default has no loop guard, and the live passes are their file. Every variant the kernel's flags
/// make is valid WGSL (naga, wgpu's front end): each traversal with no switch, each alone and all of them, by no
/// scene feature, each alone and all of them (units are software traversal's), with the uniform tables, and with
@@ -3368,7 +3430,7 @@ mod tests {
}
assert_eq!(loop_guard(), None);
let sha = |s: &str| Sha256::digest(s.as_bytes()).iter().map(|b| format!("{b:02x}")).collect::<String>();
- assert_eq!(crate::live::live_source(), include_str!("../shaders/live.wgsl"));
+ assert_eq!(crate::live::live_source(), [RECORDS, include_str!("../shaders/live.wgsl")].concat());
let template = kernel_template();
let all = KernelSwitches { strict: true, cutout_lite: 2, last_direct: true, last_sun: false, light_pick: true };
let switches = [
@@ -3440,8 +3502,8 @@ mod tests {
}
/// With nothing set, every platform but Android opens the device as it was before the options existed: no
- /// uniform tables, no pipeline cache, the kernel's source the files (`the_default_sources_are_untouched` has its
- /// hashes). Android's defaults are the uniform tables and the switches its GPUs needed; the environment overrides
+ /// uniform tables, no pipeline cache, the kernel's source the files (`every_kernel_variant_is_valid` prints the
+ /// default variants' hashes). Android's defaults are the uniform tables and the switches its GPUs needed; the environment overrides
/// either way, and the merged layout never has the uniform tables.
#[test]
fn the_options_default_to_the_device_as_written() {
@@ -3478,9 +3540,10 @@ mod tests {
/// compile in a browser until 2026-11-14. (The kernel's files: `every_kernel_variant_is_valid`.)
#[test]
fn the_other_shaders_are_wgsl_as_the_specification_writes_it() {
- for src in [include_str!("../shaders/live.wgsl"), include_str!("../shaders/particles.wgsl"), include_str!("../shaders/gpu_particles.wgsl"), include_str!("../shaders/grid_sim.wgsl")] {
- wesl_wgsl(src, &[], &[]);
+ for src in [include_str!("../shaders/live.wgsl"), include_str!("../shaders/particles.wgsl"), include_str!("../shaders/gpu_particles.wgsl")] {
+ wesl_wgsl(&[RECORDS, src].concat(), &[], &[]);
}
+ wesl_wgsl(include_str!("../shaders/grid_sim.wgsl"), &[], &[]);
}
/// Each switch changes what it says, under both traversals (that every combination is valid WGSL:
diff --git a/renderer/src/live/targets.rs b/renderer/src/live/targets.rs
index 8f4f3bf..1f184d4 100644
--- a/renderer/src/live/targets.rs
+++ b/renderer/src/live/targets.rs
@@ -47,10 +47,10 @@ pub(super) fn tonemap_lut(p: &crate::desc::PostPreset) -> Vec<u16> {
out
}
-/// The live passes' source: live.wgsl, natively and in a browser alike (each pass binds at most a browser's storage
-/// buffers: `layout`).
+/// The live passes' source: records.wgsl (what they share with the kernel) and live.wgsl, natively and in a browser
+/// alike (each pass binds at most a browser's storage buffers: `layout`). build.rs reads the same two.
pub(crate) fn live_source() -> &'static str {
- include_str!("../../shaders/live.wgsl")
+ concat!(include_str!("../../shaders/records.wgsl"), include_str!("../../shaders/live.wgsl"))
}
pub(super) struct Passes {