Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

LightBench LB1 and LB3a: a Rust + Bevy test renderer (bench/lightbench, docs/lightbench.feature)

shinyobjectzbdd30b7c65ee
diff --git a/Cargo.lock b/Cargo.lock
index c87da896..4780a71c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14707,6 +14707,14 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "raea-lightbench"
+version = "0.1.0"
+dependencies = [
+ "bevy",
+ "bytemuck",
+]
+
[[package]]
name = "raea-modules"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index b9ff57f2..ce5189b6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -169,6 +169,7 @@ members = [
"runtime/cssurls",
"bench/bridge",
"bench/bevy-parity",
+ "bench/lightbench",
"bench/bridge/swatch",
"bench/rerender/ios",
"core/alloc",
diff --git a/bench/lightbench/Cargo.toml b/bench/lightbench/Cargo.toml
new file mode 100644
index 00000000..d4cdbc44
--- /dev/null
+++ b/bench/lightbench/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "raea-lightbench"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "LightBench: a small Rust + Bevy renderer that proves lighting and geometry techniques against its own all-lights reference before they move into raea (docs/lightbench.feature)"
+
+[[bin]]
+name = "lightbench"
+path = "src/main.rs"
+
+[dependencies]
+# bench/bevy-parity's Bevy (engine/render's features, and winit for the window), so it builds against the Bevy raea compiled
+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "default_font", "system_font_discovery", "ghost_nodes", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "jpeg", "tonemapping_luts", "ktx2", "zstd_rust", "smaa_luts", "experimental_pbr_pcss", "area_light_luts", "dfg_lut", "bluenoise_texture", "bevy_gilrs", "bevy_winit", "bevy_scene", "bevy_camera_controller", "free_camera", "pan_camera", "pan_orbit_camera", "bevy_gizmos", "bevy_gizmos_render", "bevy_state", "picking", "mesh_picking", "sprite_picking", "ui_picking", "hdr", "exr", "webp", "bevy_dev_tools", "bevy_ui_widgets", "bevy_feathers", "bevy_audio", "vorbis", "wav", "mp3", "morph_animation", "bevy_input_focus", "custom_cursor", "serialize", "reflect_functions", "pbr_multi_layer_material_textures"] }
+bytemuck = { version = "1.25", features = ["derive"] }
diff --git a/bench/lightbench/src/bvh.rs b/bench/lightbench/src/bvh.rs
new file mode 100644
index 00000000..3c0d33bc
--- /dev/null
+++ b/bench/lightbench/src/bvh.rs
@@ -0,0 +1,271 @@
+//! The scene's triangles in one BVH, built once on the CPU (binned SAH) and flattened depth-first for the GPU's shadow
+//! rays: an inner node's left child is the next node and its right child is at `a`; a leaf holds `count` triangles
+//! from `a`. Every triangle is in it, the ones off screen too, so a caster the camera can't see still casts.
+
+use bevy::math::Vec3;
+use bytemuck::{Pod, Zeroable};
+
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable, Default, Debug)]
+pub struct Node {
+ pub min: [f32; 3],
+ pub a: u32,
+ pub max: [f32; 3],
+ pub count: u32,
+}
+
+/// A triangle as the GPU tests it: v0, v1 - v0 and v2 - v0, each padded to a vec4.
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable, Default, Debug)]
+pub struct Tri {
+ pub v0: [f32; 4],
+ pub e1: [f32; 4],
+ pub e2: [f32; 4],
+}
+
+pub struct Bvh {
+ pub nodes: Vec<Node>,
+ pub tris: Vec<Tri>,
+}
+
+const LEAF: usize = 4;
+const BINS: usize = 16;
+
+#[derive(Clone, Copy)]
+struct Aabb {
+ min: Vec3,
+ max: Vec3,
+}
+
+impl Aabb {
+ const EMPTY: Self = Self { min: Vec3::INFINITY, max: Vec3::NEG_INFINITY };
+ fn grow(&mut self, p: Vec3) {
+ self.min = self.min.min(p);
+ self.max = self.max.max(p);
+ }
+ fn join(&mut self, b: &Aabb) {
+ self.min = self.min.min(b.min);
+ self.max = self.max.max(b.max);
+ }
+ fn area(&self) -> f32 {
+ let d = (self.max - self.min).max(Vec3::ZERO);
+ 2.0 * (d.x * d.y + d.y * d.z + d.z * d.x)
+ }
+}
+
+pub fn build(tris: &[[Vec3; 3]]) -> Bvh {
+ let boxes: Vec<Aabb> = tris
+ .iter()
+ .map(|t| {
+ let mut b = Aabb::EMPTY;
+ t.iter().for_each(|p| b.grow(*p));
+ b
+ })
+ .collect();
+ let cents: Vec<Vec3> = boxes.iter().map(|b| (b.min + b.max) * 0.5).collect();
+ let mut idx: Vec<u32> = (0..tris.len() as u32).collect();
+ let mut nodes = Vec::with_capacity(tris.len() / 2 + 1);
+ split(&boxes, &cents, &mut idx, 0, tris.len(), &mut nodes);
+ let tris = idx
+ .iter()
+ .map(|&i| {
+ let [a, b, c] = tris[i as usize];
+ Tri { v0: a.extend(0.0).into(), e1: (b - a).extend(0.0).into(), e2: (c - a).extend(0.0).into() }
+ })
+ .collect();
+ Bvh { nodes, tris }
+}
+
+/// Builds the node for idx[lo..hi] and its subtree; returns its index.
+fn split(boxes: &[Aabb], cents: &[Vec3], idx: &mut [u32], lo: usize, hi: usize, nodes: &mut Vec<Node>) -> usize {
+ let me = nodes.len();
+ nodes.push(Node::default());
+ let (mut bounds, mut cb) = (Aabb::EMPTY, Aabb::EMPTY);
+ for &i in &idx[lo..hi] {
+ bounds.join(&boxes[i as usize]);
+ cb.grow(cents[i as usize]);
+ }
+ nodes[me].min = bounds.min.into();
+ nodes[me].max = bounds.max.into();
+ let n = hi - lo;
+ let leaf = |nodes: &mut Vec<Node>| {
+ nodes[me].a = lo as u32;
+ nodes[me].count = n as u32;
+ me
+ };
+ if n <= LEAF {
+ return leaf(nodes);
+ }
+ // the cheapest of BINS-1 planes on each axis by the surface area heuristic
+ let ext = cb.max - cb.min;
+ let mut best = (f32::INFINITY, 0usize, 0usize);
+ for axis in 0..3 {
+ if ext[axis] <= 1e-9 {
+ continue;
+ }
+ let bin_of = |c: Vec3| (((c[axis] - cb.min[axis]) / ext[axis] * BINS as f32) as usize).min(BINS - 1);
+ let mut bins = [(Aabb::EMPTY, 0usize); BINS];
+ for &i in &idx[lo..hi] {
+ let b = &mut bins[bin_of(cents[i as usize])];
+ b.0.join(&boxes[i as usize]);
+ b.1 += 1;
+ }
+ let mut right = [(0.0f32, 0usize); BINS];
+ let (mut acc, mut cnt) = (Aabb::EMPTY, 0);
+ for s in (1..BINS).rev() {
+ acc.join(&bins[s].0);
+ cnt += bins[s].1;
+ right[s] = (acc.area(), cnt);
+ }
+ let (mut acc, mut cnt) = (Aabb::EMPTY, 0);
+ for s in 1..BINS {
+ acc.join(&bins[s - 1].0);
+ cnt += bins[s - 1].1;
+ if cnt == 0 || right[s].1 == 0 {
+ continue;
+ }
+ let cost = acc.area() * cnt as f32 + right[s].0 * right[s].1 as f32;
+ if cost < best.0 {
+ best = (cost, axis, s);
+ }
+ }
+ }
+ let mut mid = lo;
+ if best.0.is_finite() {
+ let (axis, s) = (best.1, best.2);
+ let bin_of = |c: Vec3| (((c[axis] - cb.min[axis]) / ext[axis] * BINS as f32) as usize).min(BINS - 1);
+ for k in lo..hi {
+ if bin_of(cents[idx[k] as usize]) < s {
+ idx.swap(k, mid);
+ mid += 1;
+ }
+ }
+ }
+ if mid == lo || mid == hi {
+ // centroids all in one place: halve by index
+ mid = lo + n / 2;
+ }
+ split(boxes, cents, idx, lo, mid, nodes);
+ let right = split(boxes, cents, idx, mid, hi, nodes);
+ nodes[me].a = right as u32;
+ nodes[me].count = 0;
+ me
+}
+
+impl Bvh {
+ /// Whether anything lies on the ray from `o` along unit `d` before `tmax`: the shader's `occluded`, on the CPU.
+ pub fn occluded(&self, o: Vec3, d: Vec3, tmax: f32) -> bool {
+ let inv = Vec3::ONE / d.map(|c| if c.abs() < 1e-12 { 1e-12 } else { c });
+ let mut stack = Vec::with_capacity(64);
+ let mut i = 0usize;
+ loop {
+ let n = &self.nodes[i];
+ if hit_box(o, inv, n.min.into(), n.max.into(), tmax) {
+ if n.count > 0 {
+ let t = &self.tris[n.a as usize..(n.a + n.count) as usize];
+ if t.iter().any(|t| hit_tri(o, d, t, tmax)) {
+ return true;
+ }
+ } else {
+ stack.push(n.a as usize);
+ i += 1;
+ continue;
+ }
+ }
+ match stack.pop() {
+ Some(j) => i = j,
+ None => return false,
+ }
+ }
+ }
+
+ /// The deepest leaf's depth: the GPU's traversal stack must hold it.
+ pub fn depth(&self) -> usize {
+ fn go(b: &Bvh, i: usize) -> usize {
+ let n = &b.nodes[i];
+ if n.count > 0 { 1 } else { 1 + go(b, i + 1).max(go(b, n.a as usize)) }
+ }
+ go(self, 0)
+ }
+}
+
+fn hit_box(o: Vec3, inv: Vec3, min: Vec3, max: Vec3, tmax: f32) -> bool {
+ let (t0, t1) = ((min - o) * inv, (max - o) * inv);
+ let near = t0.min(t1).max_element().max(0.0);
+ let far = t0.max(t1).min_element().min(tmax);
+ near <= far
+}
+
+/// Möller-Trumbore, both sides.
+pub fn hit_tri(o: Vec3, d: Vec3, t: &Tri, tmax: f32) -> bool {
+ let (v0, e1, e2) = (Vec3::from_slice(&t.v0), Vec3::from_slice(&t.e1), Vec3::from_slice(&t.e2));
+ let pv = d.cross(e2);
+ let det = e1.dot(pv);
+ if det.abs() < 1e-12 {
+ return false;
+ }
+ let inv = 1.0 / det;
+ let tv = o - v0;
+ let u = tv.dot(pv) * inv;
+ if !(0.0..=1.0).contains(&u) {
+ return false;
+ }
+ let qv = tv.cross(e1);
+ let v = d.dot(qv) * inv;
+ if v < 0.0 || u + v > 1.0 {
+ return false;
+ }
+ let t = e2.dot(qv) * inv;
+ t > 0.0 && t < tmax
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ struct Lcg(u64);
+ impl Lcg {
+ fn f(&mut self) -> f32 {
+ self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ (self.0 >> 40) as f32 / (1u64 << 24) as f32
+ }
+ fn v(&mut self, s: f32) -> Vec3 {
+ Vec3::new(self.f(), self.f(), self.f()) * 2.0 * s - s
+ }
+ }
+
+ #[test]
+ fn the_bvh_answers_as_every_triangle_does() {
+ let mut r = Lcg(7);
+ let soup: Vec<[Vec3; 3]> = (0..3000)
+ .map(|_| {
+ let c = r.v(5.0);
+ [c + r.v(0.4), c + r.v(0.4), c + r.v(0.4)]
+ })
+ .collect();
+ let bvh = build(&soup);
+ let all: Vec<Tri> = build(&soup).tris;
+ assert_eq!(all.len(), soup.len());
+ let (mut hits, mut n) = (0, 0);
+ for _ in 0..20000 {
+ let o = r.v(6.0);
+ let d = r.v(1.0).normalize_or(Vec3::X);
+ let tmax = r.f() * 12.0;
+ let brute = all.iter().any(|t| hit_tri(o, d, t, tmax));
+ assert_eq!(bvh.occluded(o, d, tmax), brute, "ray {o} {d} {tmax}");
+ hits += brute as u32;
+ n += 1;
+ }
+ // both answers turn up, so the test means something
+ assert!(hits > n / 10 && hits < n * 9 / 10, "{hits} of {n} rays hit");
+ assert!(bvh.depth() < 48, "depth {}", bvh.depth());
+ }
+
+ #[test]
+ fn coincident_triangles_still_split() {
+ let t = [Vec3::ZERO, Vec3::X, Vec3::Y];
+ let bvh = build(&vec![t; 100]);
+ assert!(bvh.occluded(Vec3::new(0.2, 0.2, 1.0), Vec3::NEG_Z, 2.0));
+ assert!(!bvh.occluded(Vec3::new(0.8, 0.8, 1.0), Vec3::NEG_Z, 2.0));
+ }
+}
diff --git a/bench/lightbench/src/light.wgsl b/bench/lightbench/src/light.wgsl
new file mode 100644
index 00000000..861647f1
--- /dev/null
+++ b/bench/lightbench/src/light.wgsl
@@ -0,0 +1,243 @@
+// LightBench's lighting (docs/lightbench.feature LB1, LB3): each pixel of Bevy's G-buffer (the depth prepass and the
+// deferred prepass's albedo and normal) lit by point lights, every light (the reference) or K of them chosen at random,
+// each through one shadow ray in LightBench's own BVH. Both use `unshadowed` and `visible`, so they differ only in
+// which lights they look at. The result goes into the camera's HDR main texture, before Bevy's tonemapping.
+
+struct Params {
+ world_from_clip: mat4x4<f32>,
+ // xyz: the camera, w: exposure
+ eye: vec4<f32>,
+ // width, height, lights, frame
+ size: vec4<u32>,
+ // mode (0 every light, 1 uniform, 2 weighted), K, view (0 lit, 1 normal, 2 albedo, 3 depth, 4 rays), brute force
+ mode: vec4<u32>,
+}
+
+struct Node { mn: vec3<f32>, a: u32, mx: vec3<f32>, count: u32 }
+struct Light { pos: vec3<f32>, range: f32, power: vec3<f32>, radius: f32 }
+
+@group(0) @binding(0) var<uniform> p: Params;
+@group(0) @binding(1) var depth_tex: texture_depth_2d;
+@group(0) @binding(2) var gbuf: texture_2d<u32>;
+@group(0) @binding(3) var<storage, read> nodes: array<Node>;
+// three a triangle: v0, v1 - v0, v2 - v0
+@group(0) @binding(4) var<storage, read> tris: array<vec4<f32>>;
+@group(0) @binding(5) var<storage, read> lights: array<Light>;
+@group(0) @binding(6) var out: texture_storage_2d<rgba16float, write>;
+
+const PI: f32 = 3.14159265;
+const MAX_K: u32 = 16u;
+const STACK: u32 = 48u;
+
+var<private> seed: u32;
+var<private> rays: u32;
+
+fn pcg(v: u32) -> u32 {
+ let s = v * 747796405u + 2891336453u;
+ let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
+ return (w >> 22u) ^ w;
+}
+
+fn rnd() -> f32 {
+ seed = pcg(seed);
+ return f32(seed >> 8u) / 16777216.0;
+}
+
+// Bevy's octahedral_decode (bevy_render utils), for the deferred prepass's normal
+fn oct_decode(v: vec2<f32>) -> vec3<f32> {
+ let f = v * 2.0 - 1.0;
+ var n = vec3(f.xy, 1.0 - abs(f.x) - abs(f.y));
+ let t = saturate(-n.z);
+ let w = select(vec2(t), vec2(-t), n.xy >= vec2(0.0));
+ n = vec3(n.xy + w, n.z);
+ return normalize(n);
+}
+
+fn hit_box(o: vec3<f32>, inv: vec3<f32>, mn: vec3<f32>, mx: vec3<f32>, tmax: f32) -> bool {
+ let t0 = (mn - o) * inv;
+ let t1 = (mx - o) * inv;
+ let lo = min(t0, t1);
+ let hi = max(t0, t1);
+ let near = max(max(lo.x, lo.y), max(lo.z, 0.0));
+ let far = min(min(hi.x, hi.y), min(hi.z, tmax));
+ return near <= far;
+}
+
+// Möller-Trumbore, both sides
+fn hit_tri(o: vec3<f32>, d: vec3<f32>, i: u32, tmax: f32) -> bool {
+ let v0 = tris[3u * i].xyz;
+ let e1 = tris[3u * i + 1u].xyz;
+ let e2 = tris[3u * i + 2u].xyz;
+ let pv = cross(d, e2);
+ let det = dot(e1, pv);
+ if abs(det) < 1e-12 {
+ return false;
+ }
+ let inv = 1.0 / det;
+ let tv = o - v0;
+ let u = dot(tv, pv) * inv;
+ if u < 0.0 || u > 1.0 {
+ return false;
+ }
+ let qv = cross(tv, e1);
+ let v = dot(d, qv) * inv;
+ if v < 0.0 || u + v > 1.0 {
+ return false;
+ }
+ let t = dot(e2, qv) * inv;
+ return t > 0.0 && t < tmax;
+}
+
+// whether anything lies on the ray before tmax: the BVH, or every triangle when brute force is asked for
+fn occluded(o: vec3<f32>, d: vec3<f32>, tmax: f32) -> bool {
+ rays += 1u;
+ if p.mode.w != 0u {
+ let n = arrayLength(&tris) / 3u;
+ for (var i = 0u; i < n; i++) {
+ if hit_tri(o, d, i, tmax) {
+ return true;
+ }
+ }
+ return false;
+ }
+ let inv = 1.0 / select(d, vec3(1e-12), abs(d) < vec3(1e-12));
+ var stack: array<u32, STACK>;
+ var sp = 0u;
+ var i = 0u;
+ loop {
+ let n = nodes[i];
+ if hit_box(o, inv, n.mn, n.mx, tmax) {
+ if n.count > 0u {
+ for (var t = n.a; t < n.a + n.count; t++) {
+ if hit_tri(o, d, t, tmax) {
+ return true;
+ }
+ }
+ } else if sp < STACK {
+ stack[sp] = n.a;
+ sp++;
+ i++;
+ continue;
+ }
+ }
+ if sp == 0u {
+ break;
+ }
+ sp--;
+ i = stack[sp];
+ }
+ return false;
+}
+
+// a light's light at a point before its shadow: its power times the cosine and the falloff (an inverse square that
+// stops growing inside its radius and fades to nothing at its range); all zero where it can't reach
+fn unshadowed(l: Light, pos: vec3<f32>, n: vec3<f32>) -> vec3<f32> {
+ let v = l.pos - pos;
+ let d2 = max(dot(v, v), 1e-8);
+ let d = sqrt(d2);
+ let ndl = dot(n, v / d);
+ if ndl <= 0.0 || d >= l.range {
+ return vec3(0.0);
+ }
+ let x = d / l.range;
+ let win = saturate(1.0 - x * x * x * x);
+ return l.power * (ndl * win * win / max(d2, l.radius * l.radius));
+}
+
+fn visible(o: vec3<f32>, l: Light) -> f32 {
+ let v = l.pos - o;
+ let d = length(v);
+ return select(1.0, 0.0, occluded(o, v / d, d - 1e-3));
+}
+
+fn lum(c: vec3<f32>) -> f32 {
+ return dot(c, vec3(0.2126, 0.7152, 0.0722));
+}
+
+@compute @workgroup_size(8, 8, 1)
+fn main(@builtin(global_invocation_id) id: vec3<u32>) {
+ if id.x >= p.size.x || id.y >= p.size.y {
+ return;
+ }
+ let px = vec2<i32>(id.xy);
+ let depth = textureLoad(depth_tex, px, 0);
+ // the sky (reverse Z: far is 0) keeps Bevy's clear colour
+ if depth <= 0.0 {
+ return;
+ }
+ let g = textureLoad(gbuf, px, 0);
+ let albedo = pow(unpack4x8unorm(g.r).rgb, vec3(2.2));
+ let n = oct_decode(vec2(f32(g.a & 0xFFFu), f32((g.a >> 12u) & 0xFFFu)) / 4095.0);
+ let uv = (vec2<f32>(id.xy) + 0.5) / vec2<f32>(p.size.xy);
+ let w = p.world_from_clip * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);
+ let pos = w.xyz / w.w;
+ let dist = length(pos - p.eye.xyz);
+ let view = p.mode.z;
+ if view == 1u {
+ textureStore(out, px, vec4(n * 0.5 + 0.5, 1.0));
+ return;
+ }
+ if view == 2u {
+ textureStore(out, px, vec4(albedo, 1.0));
+ return;
+ }
+ if view == 3u {
+ textureStore(out, px, vec4(vec3(dist / 20.0), 1.0));
+ return;
+ }
+ seed = pcg(id.x + id.y * p.size.x + p.size.w * p.size.x * p.size.y);
+ rays = 0u;
+ // off the surface along its normal, more the farther it is (depth precision)
+ let o = pos + n * (2e-3 + 5e-4 * dist);
+ let nl = p.size.z;
+ let k = clamp(p.mode.y, 1u, MAX_K);
+ var c = vec3(0.0);
+ if p.mode.x == 0u {
+ for (var i = 0u; i < nl; i++) {
+ let u = unshadowed(lights[i], pos, n);
+ if lum(u) > 0.0 {
+ c += u * visible(o, lights[i]);
+ }
+ }
+ } else if p.mode.x == 1u {
+ // uniform: each light 1 / N
+ for (var s = 0u; s < k; s++) {
+ let i = min(u32(rnd() * f32(nl)), nl - 1u);
+ let u = unshadowed(lights[i], pos, n);
+ if lum(u) > 0.0 {
+ c += u * visible(o, lights[i]) * f32(nl);
+ }
+ }
+ c /= f32(k);
+ } else {
+ // weighted: K reservoirs over every light by its unshadowed light, so any light that adds light can be chosen
+ var pick: array<u32, MAX_K>;
+ var pw: array<f32, MAX_K>;
+ var wsum = 0.0;
+ for (var i = 0u; i < nl; i++) {
+ let wi = lum(unshadowed(lights[i], pos, n));
+ if wi <= 0.0 {
+ continue;
+ }
+ wsum += wi;
+ for (var s = 0u; s < k; s++) {
+ if rnd() * wsum < wi {
+ pick[s] = i;
+ pw[s] = wi;
+ }
+ }
+ }
+ if wsum > 0.0 {
+ for (var s = 0u; s < k; s++) {
+ let l = lights[pick[s]];
+ c += unshadowed(l, pos, n) * visible(o, l) * (wsum / pw[s]);
+ }
+ c /= f32(k);
+ }
+ }
+ if view == 4u {
+ textureStore(out, px, vec4(vec3(f32(rays) / 16.0), 1.0));
+ return;
+ }
+ textureStore(out, px, vec4(c * albedo / PI * p.eye.w, 1.0));
+}
diff --git a/bench/lightbench/src/main.rs b/bench/lightbench/src/main.rs
new file mode 100644
index 00000000..a6c4087f
--- /dev/null
+++ b/bench/lightbench/src/main.rs
@@ -0,0 +1,181 @@
+//! LightBench (docs/lightbench.feature): a small Rust + Bevy renderer that proves lighting and geometry techniques
+//! against its own all-lights reference before they move into raea. `lightbench --help` lists the switches; with
+//! `--shot FILE` it draws headless, saves frame `--frames` as a PNG and exits, so every claim is a repeatable run.
+
+mod bvh;
+mod pass;
+mod scene;
+
+use bevy::{
+ camera::{CameraMainTextureUsages, Hdr, RenderTarget},
+ core_pipeline::prepass::{DeferredPrepass, DepthPrepass},
+ pbr::DefaultOpaqueRendererMethod,
+ prelude::*,
+ render::{
+ render_resource::{TextureFormat, TextureUsages},
+ view::screenshot::{Screenshot, ScreenshotCaptured},
+ },
+ window::ExitCondition,
+};
+
+const HELP: &str = "lightbench [switches]
+ --mode all|uniform|weighted every light (the reference), or K chosen uniformly or by their light (all)
+ --k K light samples a pixel, 1 to 16 (4)
+ --lights N point lights, the pillar's first (16)
+ --view lit|normal|albedo|depth|rays what to show (lit)
+ --brute test every triangle for each shadow ray instead of the BVH
+ --detail N the knot's segments; its triangles are N * N / 16 (2048)
+ --size WxH pixels (1280x720)
+ --t SECONDS hold the lights where they are at this time (they move otherwise)
+ --exposure X linear exposure (1)
+ --shot FILE draw headless, save frame --frames as a PNG, exit
+ --frames N the lit frame --shot saves (4)
+ --bench N with --shot: time N more lit frames first and print the mean (frame time, its own run)
+ --no-pillar leave out the pillar outside the view (its shadow should go with it)";
+
+#[derive(Resource, Clone)]
+pub struct Opts {
+ pub mode: u32,
+ pub k: u32,
+ pub lights: u32,
+ pub view: u32,
+ pub brute: bool,
+ pub detail: u32,
+ pub size: UVec2,
+ pub t: Option<f32>,
+ pub exposure: f32,
+ pub shot: Option<String>,
+ pub frames: u32,
+ pub bench: u32,
+ pub pillar: bool,
+}
+
+fn opts() -> Result<Opts, String> {
+ let mut o = Opts { mode: 0, k: 4, lights: 16, view: 0, brute: false, detail: 2048, size: UVec2::new(1280, 720), t: None, exposure: 1.0, shot: None, frames: 4, bench: 0, pillar: true };
+ let mut args = std::env::args().skip(1);
+ while let Some(a) = args.next() {
+ let mut val = || args.next().ok_or(format!("{a} needs a value"));
+ let num = |v: String| v.parse::<f32>().map_err(|_| format!("{a}: {v} isn't a number"));
+ match a.as_str() {
+ "--mode" => {
+ let v = val()?;
+ o.mode = ["all", "uniform", "weighted"].iter().position(|m| *m == v).ok_or("--mode: all, uniform or weighted")? as u32;
+ }
+ "--view" => {
+ let v = val()?;
+ o.view = ["lit", "normal", "albedo", "depth", "rays"].iter().position(|m| *m == v).ok_or("--view: lit, normal, albedo, depth or rays")? as u32;
+ }
+ "--k" => o.k = (num(val()?)? as u32).clamp(1, 16),
+ "--lights" => o.lights = (num(val()?)? as u32).max(1),
+ "--brute" => o.brute = true,
+ "--detail" => o.detail = (num(val()?)? as u32).max(64),
+ "--size" => {
+ let v = val()?;
+ let (w, h) = v.split_once('x').ok_or("--size: WxH")?;
+ o.size = UVec2::new(num(w.into())? as u32, num(h.into())? as u32);
+ }
+ "--t" => o.t = Some(num(val()?)?),
+ "--exposure" => o.exposure = num(val()?)?,
+ "--shot" => o.shot = Some(val()?),
+ "--frames" => o.frames = (num(val()?)? as u32).max(1),
+ "--bench" => o.bench = num(val()?)? as u32,
+ "--no-pillar" => o.pillar = false,
+ "--help" | "-h" => return Err(HELP.into()),
+ _ => return Err(format!("unknown switch {a}\n{HELP}")),
+ }
+ }
+ Ok(o)
+}
+
+/// Whether this run times its frames (--bench), read before the app is built.
+pub fn timing() -> bool {
+ std::env::args().any(|a| a == "--bench")
+}
+
+/// The image a headless run draws into.
+#[derive(Resource)]
+struct Target(Handle<Image>);
+
+fn main() {
+ let o = match opts() {
+ Ok(o) => o,
+ Err(e) => {
+ eprintln!("{e}");
+ std::process::exit(if e == HELP { 0 } else { 2 });
+ }
+ };
+ let mut app = App::new();
+ if o.shot.is_some() {
+ app.add_plugins(
+ DefaultPlugins
+ .set(WindowPlugin { primary_window: None, exit_condition: ExitCondition::DontExit, ..default() })
+ .disable::<bevy::winit::WinitPlugin>(),
+ )
+ .add_plugins(bevy::app::ScheduleRunnerPlugin::run_loop(std::time::Duration::ZERO));
+ } else {
+ let window = Window { title: "LightBench".into(), resolution: (o.size.x, o.size.y).into(), ..default() };
+ app.add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(window), ..default() }));
+ }
+ app.insert_resource(o)
+ .insert_resource(DefaultOpaqueRendererMethod::deferred())
+ .insert_resource(ClearColor(Color::srgb(0.02, 0.025, 0.035)))
+ .add_plugins(pass::LightPass)
+ .add_systems(Startup, (scene::spawn, camera))
+ .add_systems(Update, (tick, shoot))
+ .run();
+}
+
+fn camera(mut commands: Commands, o: Res<Opts>, mut images: ResMut<Assets<Image>>) {
+ let usages = TextureUsages::RENDER_ATTACHMENT | TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_SRC | TextureUsages::STORAGE_BINDING;
+ let mut cam = commands.spawn((
+ Camera3d::default(),
+ Hdr,
+ Msaa::Off,
+ DepthPrepass,
+ DeferredPrepass,
+ CameraMainTextureUsages(usages),
+ Projection::Perspective(PerspectiveProjection { fov: 45f32.to_radians(), ..default() }),
+ Transform::from_xyz(0.0, 2.2, 7.0).looking_at(Vec3::new(0.0, 1.3, 0.0), Vec3::Y),
+ ));
+ if o.shot.is_some() {
+ let mut image = Image::new_target_texture(o.size.x, o.size.y, TextureFormat::Rgba8UnormSrgb, None);
+ image.texture_descriptor.usage |= TextureUsages::COPY_SRC;
+ let handle = images.add(image);
+ cam.insert(RenderTarget::Image(handle.clone().into()));
+ commands.insert_resource(Target(handle));
+ }
+}
+
+/// The lights where they are this frame, and the switches, for the render world.
+fn tick(o: Res<Opts>, time: Res<Time>, mut frame: ResMut<pass::Frame>) {
+ let t = o.t.unwrap_or(time.elapsed_secs());
+ *frame = pass::Frame { lights: scene::lights(o.lights, t), mode: o.mode, k: o.k, view: o.view, frame: frame.frame.wrapping_add(1), exposure: o.exposure, brute: o.brute };
+}
+
+fn shoot(mut commands: Commands, o: Res<Opts>, target: Option<Res<Target>>, mut done: Local<bool>, mut clock: Local<Option<(std::time::Instant, u32)>>) {
+ let (Some(path), Some(target)) = (o.shot.clone(), target) else { return };
+ // counted from the lighting pass's first frame, not from startup (its pipeline compiles meanwhile)
+ let drawn = pass::DRAWN.load(std::sync::atomic::Ordering::Relaxed);
+ if *done || drawn < o.frames + o.bench {
+ if drawn >= o.frames && clock.is_none() {
+ *clock = Some((std::time::Instant::now(), drawn));
+ }
+ return;
+ }
+ *done = true;
+ if o.bench > 0 {
+ let (t0, d0) = clock.unwrap();
+ let ms = t0.elapsed().as_secs_f64() * 1000.0 / (drawn - d0).max(1) as f64;
+ println!("FRAME {ms:.2} ms, the GPU waited for ({} frames, {}x{}, {} lights, mode {} k {})", drawn - d0, o.size.x, o.size.y, o.lights, ["all", "uniform", "weighted"][o.mode as usize], o.k);
+ }
+ commands.spawn(Screenshot::image(target.0.clone())).observe(move |shot: On<ScreenshotCaptured>, mut exit: MessageWriter<AppExit>| {
+ match shot.image.clone().try_into_dynamic() {
+ Ok(img) => match img.to_rgb8().save(&path) {
+ Ok(()) => println!("SHOT {path}"),
+ Err(e) => eprintln!("lightbench: saving {path}: {e}"),
+ },
+ Err(e) => eprintln!("lightbench: the frame: {e:?}"),
+ }
+ exit.write(AppExit::Success);
+ });
+}
diff --git a/bench/lightbench/src/pass.rs b/bench/lightbench/src/pass.rs
new file mode 100644
index 00000000..30f2b635
--- /dev/null
+++ b/bench/lightbench/src/pass.rs
@@ -0,0 +1,162 @@
+//! The lighting pass (light.wgsl) in Bevy's render world: after Bevy's opaque pass has filled the depth and deferred
+//! prepasses, a compute pass lights every pixel into the camera's HDR main texture, which Bevy then tonemaps. The
+//! BVH's buffers are made once; the lights and the parameters each frame.
+
+use crate::scene::{GpuLight, SceneGpu};
+use bevy::{
+ core_pipeline::{
+ core_3d::{main_opaque_pass_3d, main_transparent_pass_3d},
+ prepass::ViewPrepassTextures,
+ schedule::Core3d,
+ Core3dSystems,
+ },
+ prelude::*,
+ render::{
+ extract_resource::{ExtractResource, ExtractResourcePlugin},
+ render_resource::{
+ binding_types::{storage_buffer_read_only_sized, texture_2d, texture_depth_2d, texture_storage_2d, uniform_buffer},
+ *,
+ },
+ renderer::{RenderContext, RenderDevice, RenderQueue, ViewQuery},
+ view::{ExtractedView, ViewTarget},
+ RenderApp, RenderStartup,
+ },
+};
+use std::sync::{atomic::{AtomicU32, Ordering}, Arc};
+
+/// Frames the lighting pass has drawn, so a headless shot waits for its pipeline rather than for a number of frames.
+pub static DRAWN: AtomicU32 = AtomicU32::new(0);
+
+/// What this frame draws: the lights where they are now, and the switches.
+#[derive(Resource, Clone, Default, ExtractResource)]
+#[extract_app(RenderApp)]
+pub struct Frame {
+ pub lights: Vec<GpuLight>,
+ /// 0 every light, 1 uniform, 2 weighted
+ pub mode: u32,
+ pub k: u32,
+ /// 0 lit, 1 normal, 2 albedo, 3 depth, 4 rays
+ pub view: u32,
+ pub frame: u32,
+ pub exposure: f32,
+ pub brute: bool,
+}
+
+pub struct LightPass;
+
+impl Plugin for LightPass {
+ fn build(&self, app: &mut App) {
+ bevy::asset::embedded_asset!(app, "light.wgsl");
+ app.init_resource::<Frame>().add_plugins((ExtractResourcePlugin::<Frame>::default(), ExtractResourcePlugin::<SceneGpu>::default()));
+ let Some(render) = app.get_sub_app_mut(RenderApp) else { return };
+ // timing a run (--bench): each frame waits for the GPU, so the frame time counts the GPU's work too
+ if crate::timing() {
+ render.add_systems(bevy::render::Render, wait.in_set(bevy::render::RenderSystems::Cleanup));
+ }
+ render.init_resource::<Buffers>().add_systems(RenderStartup, init).add_systems(
+ Core3d,
+ light.in_set(Core3dSystems::MainPass).after(main_opaque_pass_3d).before(main_transparent_pass_3d),
+ );
+ }
+}
+
+#[derive(ShaderType, Clone, Copy)]
+struct Params {
+ world_from_clip: Mat4,
+ eye: Vec4,
+ size: UVec4,
+ mode: UVec4,
+}
+
+#[derive(Resource)]
+struct Pipeline {
+ layout: BindGroupLayoutDescriptor,
+ id: CachedComputePipelineId,
+}
+
+/// The BVH on the GPU, made from the SceneGpu it came from (by its pointer).
+#[derive(Resource, Default)]
+struct Buffers {
+ from: Option<(usize, Buffer, Buffer)>,
+}
+
+fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCache>) {
+ let read = |n: u64| storage_buffer_read_only_sized(false, std::num::NonZeroU64::new(n));
+ let layout = BindGroupLayoutDescriptor::new(
+ "lightbench_light",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ uniform_buffer::<Params>(false),
+ texture_depth_2d(),
+ texture_2d(TextureSampleType::Uint),
+ read(32),
+ read(48),
+ read(32),
+ texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),
+ ),
+ ),
+ );
+ let id = cache.queue_compute_pipeline(ComputePipelineDescriptor {
+ label: Some("lightbench_light".into()),
+ layout: vec![layout.clone()],
+ shader: assets.load("embedded://lightbench/light.wgsl"),
+ entry_point: Some("main".into()),
+ ..default()
+ });
+ commands.insert_resource(Pipeline { layout, id });
+}
+
+#[allow(clippy::too_many_arguments)]
+fn light(
+ view: ViewQuery<(&ExtractedView, &ViewTarget, Option<&ViewPrepassTextures>)>,
+ p: Option<Res<Pipeline>>,
+ scene: Option<Res<SceneGpu>>,
+ frame: Res<Frame>,
+ mut bufs: ResMut<Buffers>,
+ cache: Res<PipelineCache>,
+ queue: Res<RenderQueue>,
+ mut ctx: RenderContext,
+) {
+ let (Some(p), Some(scene)) = (p, scene) else { return };
+ let (extracted, target, prepass) = view.into_inner();
+ let Some(pipeline) = cache.get_compute_pipeline(p.id) else { return };
+ let Some(prepass) = prepass else { return };
+ let (Some(depth), Some(gbuf)) = (prepass.depth_only_view(), prepass.deferred_view()) else { return };
+ if target.main_texture_format() != TextureFormat::Rgba16Float || frame.lights.is_empty() {
+ return;
+ }
+ let device: RenderDevice = ctx.render_device().clone();
+ let key = Arc::as_ptr(&scene.tris) as usize;
+ if bufs.from.as_ref().map(|b| b.0) != Some(key) {
+ let make = |label: &str, bytes: &[u8]| device.create_buffer_with_data(&BufferInitDescriptor { label: Some(label), contents: bytes, usage: BufferUsages::STORAGE });
+ let nodes = make("lightbench_nodes", bytemuck::cast_slice(&scene.nodes));
+ let tris = make("lightbench_tris", bytemuck::cast_slice(&scene.tris));
+ bufs.from = Some((key, nodes, tris));
+ }
+ let (_, nodes, tris) = bufs.from.as_ref().unwrap();
+ let lights = device.create_buffer_with_data(&BufferInitDescriptor { label: Some("lightbench_lights"), contents: bytemuck::cast_slice(&frame.lights), usage: BufferUsages::STORAGE });
+ let size = target.main_texture().size();
+ let world_from_clip = extracted.world_from_view.to_matrix() * extracted.clip_from_view.inverse();
+ let mut params = UniformBuffer::from(Params {
+ world_from_clip,
+ eye: extracted.world_from_view.translation().extend(frame.exposure),
+ size: UVec4::new(size.width, size.height, frame.lights.len() as u32, frame.frame),
+ mode: UVec4::new(frame.mode, frame.k, frame.view, frame.brute as u32),
+ });
+ params.write_buffer(&device, &queue);
+ let group = device.create_bind_group(
+ "lightbench_light",
+ &cache.get_bind_group_layout(&p.layout),
+ &BindGroupEntries::sequential((params.binding().unwrap(), depth, gbuf, nodes.as_entire_binding(), tris.as_entire_binding(), lights.as_entire_binding(), target.main_texture_view())),
+ );
+ let mut pass = ctx.command_encoder().begin_compute_pass(&ComputePassDescriptor { label: Some("lightbench_light"), timestamp_writes: None });
+ pass.set_pipeline(pipeline);
+ pass.set_bind_group(0, &group, &[]);
+ pass.dispatch_workgroups(size.width.div_ceil(8), size.height.div_ceil(8), 1);
+ DRAWN.fetch_add(1, Ordering::Relaxed);
+}
+
+fn wait(device: Res<RenderDevice>) {
+ let _ = device.poll(PollType::wait_indefinitely());
+}
diff --git a/bench/lightbench/src/scene.rs b/bench/lightbench/src/scene.rs
new file mode 100644
index 00000000..377fdee3
--- /dev/null
+++ b/bench/lightbench/src/scene.rs
@@ -0,0 +1,112 @@
+//! LightBench's procedural scene (docs/lightbench.feature, Background): a ground, a detailed torus knot, a wall that
+//! occludes it from some lights, and a pillar outside the view with a light behind it, so its shadow falls into the
+//! frame from a caster the camera can't see. Every triangle goes into the BVH; the meshes are drawn by Bevy.
+
+use crate::{bvh, Opts};
+use bevy::{
+ asset::RenderAssetUsages,
+ mesh::{Indices, PrimitiveTopology, VertexAttributeValues},
+ prelude::*,
+ render::{extract_resource::ExtractResource, RenderApp},
+};
+use bytemuck::{Pod, Zeroable};
+use std::sync::Arc;
+
+/// A light as the shader reads it: where, the distance past which it adds nothing, its colour times its power, and
+/// the radius inside which its falloff stops growing.
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable, Default, Debug)]
+pub struct GpuLight {
+ pub pos: [f32; 3],
+ pub range: f32,
+ pub power: [f32; 3],
+ pub radius: f32,
+}
+
+/// The BVH, made once at startup and handed to the render world.
+#[derive(Resource, Clone, ExtractResource)]
+#[extract_app(RenderApp)]
+pub struct SceneGpu {
+ pub nodes: Arc<Vec<bvh::Node>>,
+ pub tris: Arc<Vec<bvh::Tri>>,
+}
+
+/// Where the off-screen pillar stands and the light behind it.
+pub const PILLAR: Vec3 = Vec3::new(4.6, 2.0, 3.0);
+const PILLAR_LIGHT: Vec3 = Vec3::new(6.2, 2.4, 4.4);
+
+pub fn spawn(mut commands: Commands, opts: Res<Opts>, mut meshes: ResMut<Assets<Mesh>>, mut mats: ResMut<Assets<StandardMaterial>>) {
+ let mut tris: Vec<[Vec3; 3]> = Vec::new();
+ let mut put = |mesh: Mesh, at: Transform, color: Color, tris: &mut Vec<[Vec3; 3]>| {
+ tris.extend(triangles(&mesh, &at));
+ let material = mats.add(StandardMaterial { base_color: color, perceptual_roughness: 0.6, ..default() });
+ commands.spawn((Mesh3d(meshes.add(mesh)), MeshMaterial3d(material), at));
+ };
+ put(Plane3d::default().mesh().size(30.0, 30.0).build(), Transform::IDENTITY, Color::srgb(0.62, 0.62, 0.6), &mut tris);
+ put(knot(2, 3, opts.detail, opts.detail / 32, 0.33), Transform::from_xyz(0.0, 1.75, 0.0).with_scale(Vec3::splat(0.5)), Color::srgb(0.85, 0.42, 0.18), &mut tris);
+ put(Cuboid::new(0.2, 2.5, 3.0).mesh().build(), Transform::from_xyz(-2.5, 1.25, 0.0), Color::srgb(0.35, 0.42, 0.55), &mut tris);
+ if opts.pillar {
+ put(Cuboid::new(0.4, 4.0, 0.4).mesh().build(), Transform::from_translation(PILLAR), Color::srgb(0.9, 0.9, 0.88), &mut tris);
+ }
+ let t0 = std::time::Instant::now();
+ let built = bvh::build(&tris);
+ info!("lightbench: {} triangles, {} BVH nodes, depth {}, built in {:.0} ms", tris.len(), built.nodes.len(), built.depth(), t0.elapsed().as_secs_f64() * 1000.0);
+ commands.insert_resource(SceneGpu { nodes: Arc::new(built.nodes), tris: Arc::new(built.tris) });
+}
+
+/// The lights at time `t` (seconds): the pillar's light first, then `n - 1` on a ring that turns, each a different
+/// colour, their power split so the frame's brightness doesn't change with how many there are.
+pub fn lights(n: u32, t: f32) -> Vec<GpuLight> {
+ let mut out = vec![GpuLight { pos: PILLAR_LIGHT.into(), range: 14.0, power: [30.0, 28.0, 24.0], radius: 0.05 }];
+ let ring = n.saturating_sub(1).max(1);
+ for i in 0..n.saturating_sub(1) {
+ let f = i as f32 / ring as f32;
+ let a = f * std::f32::consts::TAU + t * 0.3;
+ let h = 1.3 + 1.6 * (0.5 + 0.5 * (f * 17.0 + t * 0.7).sin());
+ let c = Color::hsl(f * 360.0, 0.7, 0.6).to_linear();
+ let lum = 0.2126 * c.red + 0.7152 * c.green + 0.0722 * c.blue;
+ let p = 60.0 / ring as f32 / lum.max(1e-3);
+ out.push(GpuLight { pos: [3.6 * a.cos(), h, 3.6 * a.sin()], range: 9.0, power: [c.red * p, c.green * p, c.blue * p], radius: 0.05 });
+ }
+ out
+}
+
+/// A (p, q) torus knot `seg` segments long and `ring` around, its tube `r` thick, in the xy plane.
+fn knot(p: u32, q: u32, seg: u32, ring: u32, r: f32) -> Mesh {
+ let (p, q) = (p as f32, q as f32);
+ let c = |t: f32| Vec3::new((2.0 + (q * t).cos()) * (p * t).cos(), (2.0 + (q * t).cos()) * (p * t).sin(), -(q * t).sin());
+ let (mut pos, mut nor, mut idx) = (Vec::new(), Vec::new(), Vec::new());
+ let e = 1e-3;
+ for i in 0..seg {
+ let t = i as f32 / seg as f32 * std::f32::consts::TAU;
+ let (c0, cp, cm) = (c(t), c(t + e), c(t - e));
+ let tan = (cp - cm).normalize();
+ let b = (cp - cm).cross(cp - 2.0 * c0 + cm).normalize();
+ let n = b.cross(tan);
+ for j in 0..ring {
+ let a = j as f32 / ring as f32 * std::f32::consts::TAU;
+ let dir = n * a.cos() + b * a.sin();
+ pos.push(c0 + dir * r);
+ nor.push(dir);
+ let (i1, j1) = ((i + 1) % seg, (j + 1) % ring);
+ let (v00, v10, v01, v11) = (i * ring + j, i1 * ring + j, i * ring + j1, i1 * ring + j1);
+ idx.extend([v00, v10, v11, v00, v11, v01]);
+ }
+ }
+ Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::default())
+ .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, pos)
+ .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, nor)
+ .with_inserted_indices(Indices::U32(idx))
+}
+
+/// A mesh's triangles in world space.
+fn triangles(mesh: &Mesh, at: &Transform) -> Vec<[Vec3; 3]> {
+ let Some(VertexAttributeValues::Float32x3(p)) = mesh.attribute(Mesh::ATTRIBUTE_POSITION) else { return vec![] };
+ let m = at.to_matrix();
+ let w: Vec<Vec3> = p.iter().map(|v| m.transform_point3(Vec3::from(*v))).collect();
+ let idx: Vec<usize> = match mesh.indices() {
+ Some(i) => i.iter().collect(),
+ None => (0..w.len()).collect(),
+ };
+ idx.chunks_exact(3).map(|t| [w[t[0]], w[t[1]], w[t[2]]]).collect()
+}
diff --git a/docs/lightbench.feature b/docs/lightbench.feature
new file mode 100644
index 00000000..9866b5fe
--- /dev/null
+++ b/docs/lightbench.feature
@@ -0,0 +1,50 @@
+@spec
+Feature: LightBench: a small Rust + Bevy renderer that proves raea's lighting and geometry techniques before they ship
+ Shane, 2026-11-18 (the goal): "use LightBench to validate the techniques in a runnable Rust + Bevy renderer inspired
+ by Nanite and MegaLights", started from five real photos rebuilt in raea (Raea/lightbench), whose biggest mismatches
+ rank what LightBench works on. Native desktop, one perspective camera, static opaque geometry and dynamic point
+ lights; Bevy for the ECS, the window, assets and render integration, with LightBench's own passes in WGSL on Bevy's
+ wgpu. No Bevy fork and no hardware ray tracing: its shadow rays go through its own triangle BVH, so it is also the
+ path for GPUs without ray queries. A technique proven here moves into raea Light (docs/realism.feature).
+
+ The crate is bench/lightbench (`lightbench --help`). Every claim below is a run of it, at a fixed resolution and seed,
+ whose numbers are written down beside the scenario.
+
+ Background:
+ Given the procedural scene: a ground, a detailed torus knot, a wall that occludes it, a pillar outside the view
+ And N point lights that move, each with a range past which it adds nothing
+
+ # LB1: the reference path
+ Scenario: LB1a the G-buffer holds depth, world-space normals and albedo
+ When LightBench draws the scene with --view normal, --view albedo and --view depth
+ Then each shows the scene's own normals, colours and distances (Bevy's deferred prepass, decoded by LightBench)
+
+ Scenario: LB1b the all-lights reference
+ When LightBench draws --mode all
+ Then every pixel sums every light, each times one shadow ray through the BVH, with the same equations the sampled
+ path uses
+ And the BVH's answers match a brute-force test of every triangle (unit tests, and --brute on the GPU)
+
+ Scenario: LB1c casters outside the view still cast
+ Then the pillar outside the frame throws its shadow into it
+
+ # LB2: adaptive geometry
+ Scenario: LB2a culling and discrete LODs, then a cluster hierarchy chosen by projected error
+ Then a cluster's projected error is focal_px * error / depth (with the instance's scale and the camera inside its
+ bounds counted), 1 px by default; a parent or its children are drawn, never both, and shared edges don't crack
+ And farther is coarser, a narrower field of view at the same distance is finer, and --lod colour shows it
+
+ Scenario: LB2b selection on the GPU with indirect draws, the CPU path kept; then hierarchical depth occlusion
+
+ # LB3: sampled lighting
+ Scenario: LB3a K light samples a pixel (4 by default), uniform then weighted
+ When LightBench draws --mode uniform or --mode weighted with --k K
+ Then each pixel traces K shadow rays whatever the number of lights, and every light that adds light can be chosen
+ And the raw average converges to --mode all as samples grow (RMSE against it, written down per K)
+
+ Scenario: LB3b temporal accumulation, reprojected, rejected on depth and normal, reset on a camera cut; --raw drops it
+
+ # LB4: instrumentation and acceptance
+ Scenario: LB4 sweeps
+ Then camera and light-count sweeps at a fixed resolution print triangles drawn, rays a pixel and pass timings
+ And frame time is measured on its own, on documented hardware, toward 60+ fps