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 LB7: a world radiance cache, the nearer child first, and the bounce at half resolution

shinyobjectz94dae14946f4
diff --git a/bench/lightbench/src/bvh.rs b/bench/lightbench/src/bvh.rs
index ac891c31..59289ac1 100644
--- a/bench/lightbench/src/bvh.rs
+++ b/bench/lightbench/src/bvh.rs
@@ -44,6 +44,10 @@ impl Aabb {
self.min = self.min.min(p);
self.max = self.max.max(p);
}
+ /// The bin of BINS a centre falls in along an axis of this box (the centres' box)
+ fn bin(&self, c: Vec3, axis: usize) -> usize {
+ (((c[axis] - self.min[axis]) / (self.max[axis] - self.min[axis]) * BINS as f32) as usize).min(BINS - 1)
+ }
fn join(&mut self, b: &Aabb) {
self.min = self.min.min(b.min);
self.max = self.max.max(b.max);
@@ -106,10 +110,9 @@ fn split(boxes: &[Aabb], cents: &[Vec3], idx: &mut [u32], lo: usize, hi: usize,
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])];
+ let b = &mut bins[cb.bin(cents[i as usize], axis)];
b.0.join(&boxes[i as usize]);
b.1 += 1;
}
@@ -136,9 +139,8 @@ fn split(boxes: &[Aabb], cents: &[Vec3], idx: &mut [u32], lo: usize, hi: usize,
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 {
+ if cb.bin(cents[idx[k] as usize], axis) < s {
idx.swap(k, mid);
mid += 1;
}
diff --git a/bench/lightbench/src/cache.wgsl b/bench/lightbench/src/cache.wgsl
new file mode 100644
index 00000000..624d5e71
--- /dev/null
+++ b/bench/lightbench/src/cache.wgsl
@@ -0,0 +1,133 @@
+// LightBench's world radiance cache (LB7, joined after light.wgsl and trace.wgsl): a hash table of cells over the
+// scene's surfaces, each the size of its distance from the camera (base size at 1 m, doubling with each doubling of
+// distance) and one of six normal directions, holding the irradiance there. A pixel's bounce ray reads the cell it
+// hits instead of tracing on, and adds a fresh sample to it: that point's direct light plus one more ray, which brings
+// the next surface's cell; so each frame the cache carries light one bounce further, and a pixel gets every bounce
+// for the price of two rays. After the pixels, `resolve` folds each cell's samples into its light and frees cells no
+// ray has touched for a while. The idea of NVIDIA's SHaRC and Bevy Solari's world cache.
+
+// a cell is six words: its key (0 empty), the last frame a ray touched it, then this frame's summed light (r, g, b, in
+// 1/FIX steps) and how many samples
+@group(0) @binding(14) var<storage, read_write> cells: array<atomic<u32>>;
+// each cell's light: irradiance (rgb) and how many samples it holds (w)
+@group(0) @binding(15) var<storage, read_write> cell_light: array<vec4<f32>>;
+
+const CELLS: u32 = 262144u;
+const WORDS: u32 = 6u;
+const FIX: f32 = 256.0;
+// a sample brighter than this is clipped as it goes in (a light right against a surface), so a sum can't overflow
+const CELL_MAX: f32 = 64.0;
+// frames a cell lives without a ray touching it
+const CELL_LIFE: u32 = 120u;
+
+// the cell at a point: (where its probe starts, its key; never 0)
+fn cell_key(pos: vec3<f32>, n: vec3<f32>) -> vec2<u32> {
+ let level = u32(clamp(ceil(log2(max(length(pos - p.eye.xyz), 1.0))), 0.0, 15.0));
+ let q = bitcast<vec3<u32>>(vec3<i32>(floor(pos / (p.cache.x * exp2(f32(level))))));
+ let a = abs(n);
+ let axis = select(select(2u, 1u, a.y >= a.z), 0u, a.x >= a.y && a.x >= a.z);
+ let dir = axis * 2u + select(0u, 1u, n[axis] < 0.0);
+ let at = pcg(q.x ^ pcg(q.y ^ pcg(q.z ^ pcg(level * 8u + dir))));
+ let key = pcg(level * 8u + dir + pcg(q.z + pcg(q.y + pcg(q.x + 0x2545f491u)))) | 1u;
+ return vec2(at, key);
+}
+
+// the cell's slot, made if `make` and there's room along its probe; CELLS if it has none
+fn cell(pos: vec3<f32>, n: vec3<f32>, make: bool) -> u32 {
+ let h = cell_key(pos, n);
+ for (var k = 0u; k < 8u; k++) {
+ let i = (h.x + k) % CELLS;
+ var key = atomicLoad(&cells[i * WORDS]);
+ if key == 0u {
+ if !make {
+ return CELLS;
+ }
+ let r = atomicCompareExchangeWeak(&cells[i * WORDS], 0u, h.y);
+ // a weak exchange can fail with the slot still empty: try again next frame rather than probe past it
+ key = select(r.old_value, h.y, r.exchanged);
+ if key == 0u {
+ return CELLS;
+ }
+ }
+ if key == h.y {
+ atomicMax(&cells[i * WORDS + 1u], p.size.w);
+ return i;
+ }
+ }
+ return CELLS;
+}
+
+fn cell_add(i: u32, e: vec3<f32>) {
+ let v = vec3<u32>(min(e, vec3(CELL_MAX)) * FIX + 0.5);
+ atomicAdd(&cells[i * WORDS + 2u], v.x);
+ atomicAdd(&cells[i * WORDS + 3u], v.y);
+ atomicAdd(&cells[i * WORDS + 4u], v.z);
+ atomicAdd(&cells[i * WORDS + 5u], 1u);
+}
+
+// the nearest surface along d from o: its point, its normal facing the ray, its albedo; w of the first 0 on a miss
+struct Surface { pos: vec4<f32>, n: vec3<f32>, albedo: vec3<f32> }
+
+fn surface(o: vec3<f32>, d: vec3<f32>) -> Surface {
+ let h = closest(o, d, 1e4);
+ if h.i == 0xFFFFFFFFu {
+ return Surface(vec4(0.0), vec3(0.0), vec3(0.0));
+ }
+ let v0 = tris[3u * h.i];
+ let e1 = tris[3u * h.i + 1u];
+ let e2 = tris[3u * h.i + 2u];
+ var n = normalize(cross(e1.xyz, e2.xyz));
+ n = select(n, -n, dot(n, d) > 0.0);
+ return Surface(vec4(o + d * h.t, 1.0), n, vec3(v0.w, e1.w, e2.w));
+}
+
+// a pixel's bounced light by way of the cache: one ray to the nearest surface, whose cell's light it takes (or the
+// fresh sample, until the cell holds any); the fresh sample goes into the cell
+fn cached(n0: vec3<f32>, o0: vec3<f32>) -> vec3<f32> {
+ let s1 = surface(o0, cosine_dir(n0));
+ if s1.pos.w == 0.0 {
+ return PI * p.sky.rgb;
+ }
+ let o1 = s1.pos.xyz + s1.n * (2e-3 + 5e-4 * length(s1.pos.xyz - p.eye.xyz));
+ var e = lit_at(s1.pos.xyz, s1.n, o1, 1u);
+ let s2 = surface(o1, cosine_dir(s1.n));
+ if s2.pos.w == 0.0 {
+ e += PI * p.sky.rgb;
+ } else {
+ let j = cell(s2.pos.xyz, s2.n, false);
+ if j < CELLS {
+ e += s2.albedo * cell_light[j].rgb;
+ }
+ }
+ let i = cell(s1.pos.xyz, s1.n, true);
+ if i == CELLS {
+ return s1.albedo * e;
+ }
+ cell_add(i, e);
+ let held = cell_light[i];
+ return s1.albedo * select(e, held.rgb, held.w > 0.0);
+}
+
+// after the pixels: each cell's samples folded into its light (a running mean over at most p.cache.y samples), and a
+// cell no ray has touched in CELL_LIFE frames freed
+@compute @workgroup_size(64, 1, 1)
+fn resolve(@builtin(global_invocation_id) id: vec3<u32>) {
+ let i = id.x;
+ if i >= CELLS || atomicLoad(&cells[i * WORDS]) == 0u {
+ return;
+ }
+ let b = i * WORDS;
+ let n = atomicLoad(&cells[b + 5u]);
+ if p.size.w - atomicLoad(&cells[b + 1u]) > CELL_LIFE {
+ atomicStore(&cells[b], 0u);
+ cell_light[i] = vec4(0.0);
+ } else if n > 0u {
+ let mean = vec3(f32(atomicLoad(&cells[b + 2u])), f32(atomicLoad(&cells[b + 3u])), f32(atomicLoad(&cells[b + 4u]))) / (FIX * f32(n));
+ let was = cell_light[i];
+ let held = min(was.w, p.cache.y);
+ cell_light[i] = vec4(mix(was.rgb, mean, f32(n) / (f32(n) + held)), held + f32(n));
+ }
+ for (var k = 2u; k < WORDS; k++) {
+ atomicStore(&cells[b + k], 0u);
+ }
+}
diff --git a/bench/lightbench/src/field.rs b/bench/lightbench/src/field.rs
index 9e19e373..2b96123c 100644
--- a/bench/lightbench/src/field.rs
+++ b/bench/lightbench/src/field.rs
@@ -81,7 +81,7 @@ pub fn spawn(commands: &mut Commands, opts: &Opts, meshes: &mut Assets<Mesh>, ma
fn build(pos: &[Vec3], nor: &[Vec3], dag: &[lod::Cluster], drawn: &[usize], coloured: bool) -> Mesh {
let mesh = Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::default());
if !coloured {
- let idx: Vec<u32> = drawn.iter().flat_map(|&c| dag[c].indices.iter().copied()).collect();
+ let idx = lod::indices_of(dag, drawn);
return mesh.with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, pos.to_vec()).with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, nor.to_vec()).with_inserted_indices(Indices::U32(idx));
}
let (mut p, mut n, mut c) = (Vec::new(), Vec::new(), Vec::new());
@@ -141,7 +141,7 @@ pub fn choose(
}
*vis = Visibility::Inherited;
let drawn: Vec<usize> = if opts.full {
- (0..f.dag.len()).filter(|&k| f.dag[k].level == 0).collect()
+ f.dag.iter().enumerate().filter(|(_, c)| c.level == 0).map(|(k, _)| k).collect()
} else {
let to_obj = xf.to_matrix().inverse();
let eye_obj = to_obj.transform_point3(at);
diff --git a/bench/lightbench/src/half.wgsl b/bench/lightbench/src/half.wgsl
new file mode 100644
index 00000000..05794cf0
--- /dev/null
+++ b/bench/lightbench/src/half.wgsl
@@ -0,0 +1,84 @@
+// LightBench's half-resolution bounce (LB7, joined after the other three): `trace_half` traces the bounce for one
+// pixel of each 2 x 2 block, a different one each frame so four frames cover them all, into `bounce_half`; the lighting pass
+// then takes each pixel's bounce from the four nearest blocks' samples, weighted by distance and by how near each
+// sample's surface is to the pixel's (its normal, and the pixel's plane), as Lumen and MegaLights upsample theirs.
+
+// each block's bounced light (rgb) and 1 where it holds a surface's
+@group(0) @binding(13) var<storage, read_write> bounce_half: array<vec4<f32>>;
+
+// a G-buffer pixel's surface: its point, its normal, and w of the point 0 for the sky
+struct Pixel { pos: vec4<f32>, n: vec3<f32> }
+
+fn pixel_at(px: vec2<i32>) -> Pixel {
+ let depth = textureLoad(depth_tex, px, 0);
+ if depth <= 0.0 {
+ return Pixel(vec4(0.0), vec3(0.0));
+ }
+ let g = textureLoad(gbuf, px, 0);
+ let n = oct_decode(vec2(f32(g.a & 0xFFFu), f32((g.a >> 12u) & 0xFFFu)) / 4095.0);
+ let uv = (vec2<f32>(px) + 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);
+ return Pixel(vec4(w.xyz / w.w, 1.0), n);
+}
+
+fn half_size() -> vec2<u32> {
+ return (p.size.xy + 1u) / 2u;
+}
+
+// the pixel block b samples this frame
+fn half_pixel(b: vec2<u32>) -> vec2<i32> {
+ let o = array(vec2(0u, 0u), vec2(1u, 1u), vec2(1u, 0u), vec2(0u, 1u))[p.size.w % 4u];
+ return vec2<i32>(min(b * 2u + o, p.size.xy - 1u));
+}
+
+@compute @workgroup_size(8, 8, 1)
+fn trace_half(@builtin(global_invocation_id) id: vec3<u32>) {
+ let hs = half_size();
+ if id.x >= hs.x || id.y >= hs.y {
+ return;
+ }
+ let b = id.y * hs.x + id.x;
+ let px = half_pixel(id.xy);
+ let s = pixel_at(px);
+ if s.pos.w == 0.0 {
+ bounce_half[b] = vec4(0.0);
+ return;
+ }
+ seed = pcg(u32(px.x) + u32(px.y) * p.size.x + p.size.w * p.size.x * p.size.y + 0x68e31da4u);
+ rays = 0u;
+ let o = s.pos.xyz + s.n * (2e-3 + 5e-4 * length(s.pos.xyz - p.eye.xyz));
+ var e = vec3(0.0);
+ if p.gi.y != 0u {
+ e = cached(s.n, o);
+ } else {
+ e = bounced(s.n, o);
+ }
+ bounce_half[b] = vec4(e, 1.0);
+ if rays > 0u {
+ atomicAdd(&stats[0], rays);
+ }
+}
+
+// a pixel's bounced light from the four blocks around it
+fn upsampled(px: vec2<i32>, pos: vec3<f32>, n: vec3<f32>, dist: f32) -> vec3<f32> {
+ let hs = vec2<i32>(half_size());
+ let b0 = (px - 1) / 2;
+ var sum = vec3(0.0);
+ var wsum = 0.0;
+ for (var k = 0; k < 4; k++) {
+ let b = clamp(b0 + vec2(k & 1, k >> 1), vec2(0), hs - 1);
+ let v = bounce_half[u32(b.y * hs.x + b.x)];
+ if v.w == 0.0 {
+ continue;
+ }
+ let spx = half_pixel(vec2<u32>(b));
+ let s = pixel_at(spx);
+ let near = max(0.0, 1.0 - length(vec2<f32>(spx - px)) / 3.0);
+ let facing = pow(max(dot(n, s.n), 0.0), 8.0);
+ let plane = exp(-abs(dot(n, s.pos.xyz - pos)) / (0.01 * dist + 0.005));
+ let w = (near + 1e-3) * facing * plane;
+ sum += v.rgb * w;
+ wsum += w;
+ }
+ return select(vec3(0.0), sum / wsum, wsum > 1e-6);
+}
diff --git a/bench/lightbench/src/light.wgsl b/bench/lightbench/src/light.wgsl
index 58fd8650..f4281710 100644
--- a/bench/lightbench/src/light.wgsl
+++ b/bench/lightbench/src/light.wgsl
@@ -25,13 +25,16 @@ struct Params {
// the light grid: its corner (xyz) and cell size (w); its cells along x, y, z, and whether the sampled modes use it
grid_min: vec4<f32>,
grid_dims: vec4<u32>,
- // diffuse bounces a pixel follows (0 none), 0, 0, 0
+ // diffuse bounces a pixel follows (0 none), whether its bounce reads the radiance cache instead (cache.wgsl),
+ // whether the bounce is traced at half resolution and upsampled (half.wgsl), 0
gi: vec4<u32>,
// the sun (LB6): xyz the unit direction toward it, w its angular radius in radians; its irradiance (rgb, 0 off)
sun: vec4<f32>,
sun_e: vec4<f32>,
// the sky's radiance (rgb): what a bounce ray that leaves the scene brings back
sky: vec4<f32>,
+ // the radiance cache: a cell's size at 1 m from the camera, the samples a cell holds at most, 0, 0
+ cache: vec4<f32>,
}
struct Node { mn: vec3<f32>, a: u32, mx: vec3<f32>, count: u32 }
@@ -55,9 +58,9 @@ struct Light { pos: vec3<f32>, range: f32, power: vec3<f32>, radius: f32 }
// this frame's shadow rays, lit pixels and the most rays any pixel traced (LB4's rays a pixel)
@group(0) @binding(11) var<storage, read_write> stats: array<atomic<u32>, 4>;
-// cell c's lights are grid_idx[grid_start[c]..grid_start[c + 1]]
-@group(0) @binding(12) var<storage, read> grid_start: array<u32>;
-@group(0) @binding(13) var<storage, read> grid_idx: array<u32>;
+// the light grid's two lists in one: cell c's lights are grid[grid[c]..grid[c + 1]] (its starts count from the buffer's
+// beginning, the lights' indices following the starts)
+@group(0) @binding(12) var<storage, read> grid: array<u32>;
var<workgroup> wg_rays: atomic<u32>;
var<workgroup> wg_px: atomic<u32>;
@@ -113,11 +116,11 @@ fn candidates(pos: vec3<f32>) -> vec2<u32> {
return vec2(0u, 0u);
}
let cell = u32((c.z * d.y + c.y) * d.x + c.x);
- return vec2(grid_start[cell], grid_start[cell + 1u] - grid_start[cell]);
+ return vec2(grid[cell], grid[cell + 1u] - grid[cell]);
}
fn candidate(range: vec2<u32>, j: u32) -> u32 {
- return select(grid_idx[range.x + j], j, range.x == 0xFFFFFFFFu);
+ return select(grid[range.x + j], j, range.x == 0xFFFFFFFFu);
}
fn lum(c: vec3<f32>) -> f32 {
@@ -261,7 +264,11 @@ fn shade(id: vec3<u32>) -> vec2<u32> {
if view != 7u {
c = lit_at(pos, n, o, clamp(p.mode.y, 1u, MAX_K));
}
- if p.gi.x > 0u {
+ if p.gi.z != 0u {
+ c += upsampled(px, pos, n, dist);
+ } else if p.gi.y != 0u {
+ c += cached(n, o);
+ } else if p.gi.x > 0u {
c += bounced(n, o);
}
// the history: where this point was last frame, kept only if the same surface was there
diff --git a/bench/lightbench/src/lod.rs b/bench/lightbench/src/lod.rs
index c6f352aa..6bf8a4e1 100644
--- a/bench/lightbench/src/lod.rs
+++ b/bench/lightbench/src/lod.rs
@@ -84,7 +84,12 @@ pub struct Cluster {
fn clusters_of(pos: &[Vec3], idx: &[u32]) -> Vec<Vec<u32>> {
let m = meshopt::build_meshlets(idx, &adapter(pos), 128, 128, 0.0);
- m.iter().map(|c| c.triangles.iter().map(|&t| c.vertices[t as usize]).collect()).collect()
+ m.iter().map(|c| c.triangles.iter().map(|&t| c.vertices[usize::from(t)]).collect()).collect()
+}
+
+/// The named clusters' triangles as one index list.
+pub fn indices_of(all: &[Cluster], which: &[usize]) -> Vec<u32> {
+ which.iter().flat_map(|&c| all[c].indices.iter().copied()).collect()
}
/// The cluster hierarchy of a closed mesh.
@@ -103,13 +108,13 @@ pub fn dag(pos: &[Vec3], idx: &[u32]) -> Vec<Cluster> {
}
// groups of about four clusters that share vertices
let counts: Vec<u32> = level.iter().map(|&c| all[c].indices.len() as u32).collect();
- let flat: Vec<u32> = level.iter().flat_map(|&c| all[c].indices.iter().copied()).collect();
+ let flat = indices_of(&all, &level);
let mut part = vec![0u32; level.len()];
let groups = meshopt::partition_clusters(&mut part, &flat, &counts, pos.len(), 4);
let mut next = Vec::new();
for g in 0..groups {
let members: Vec<usize> = level.iter().zip(&part).filter(|(_, p)| **p as usize == g).map(|(c, _)| *c).collect();
- let merged: Vec<u32> = members.iter().flat_map(|&c| all[c].indices.iter().copied()).collect();
+ let merged = indices_of(&all, &members);
let mut err = 0.0;
let simple = meshopt::simplify(&merged, &a, merged.len() / 2, f32::MAX, SimplifyOptions::LockBorder | SimplifyOptions::ErrorAbsolute, Some(&mut err));
// a group that won't halve stays as it is: its clusters are roots
diff --git a/bench/lightbench/src/main.rs b/bench/lightbench/src/main.rs
index 0c4e5a58..515a18c2 100644
--- a/bench/lightbench/src/main.rs
+++ b/bench/lightbench/src/main.rs
@@ -48,6 +48,11 @@ const HELP: &str = "lightbench [switches]
0.25, --bounce 2 unless given) (knot)
--sun on|off a low sun from the left, one shadow ray to a point on its disc a pixel (off)
--sun-size DEG the sun's angular diameter: larger, softer shadows (0.53)
+ --cache on|off the bounce reads a world radiance cache at its first hit instead of tracing on, and
+ feeds it: every bounce for two rays a pixel (off)
+ --bounce-res full|half the bounce traced at every pixel, or at one of each 2 x 2 block (a different one each
+ frame) and upsampled by depth and normal (full)
+ --cell M the cache's cell size at 1 m from the camera, doubling with each doubling (0.1)
--sky X the sky's radiance (a blue-white), brought by bounce rays that leave the scene (0)
--rows N the field's rows (6)
--detail full|adaptive every finest triangle, or the clusters each knot's distance asks for (adaptive)
@@ -87,10 +92,13 @@ pub struct Opts {
pub sun: bool,
pub sun_size: f32,
pub sky: f32,
+ pub cache: bool,
+ pub cell: f32,
+ pub half: bool,
}
fn opts() -> Result<Opts, String> {
- let mut o = Opts { mode: 0, k: 4, lights: 16, view: 0, brute: false, detail: 0, size: UVec2::new(1280, 720), t: None, exposure: 1.0, shot: None, frames: 4, bench: 0, pillar: true, raw: false, history: 32, camera: 0, cut_at: 8, scene: 0, rows: 6, full: false, tau: 1.0, fov: 45.0, grid: true, bounces: 0, sun: false, sun_size: 0.53, sky: 0.0 };
+ let mut o = Opts { mode: 0, k: 4, lights: 16, view: 0, brute: false, detail: 0, size: UVec2::new(1280, 720), t: None, exposure: 1.0, shot: None, frames: 4, bench: 0, pillar: true, raw: false, history: 32, camera: 0, cut_at: 8, scene: 0, rows: 6, full: false, tau: 1.0, fov: 45.0, grid: true, bounces: 0, sun: false, sun_size: 0.53, sky: 0.0, cache: false, cell: 0.1, half: false };
// what --scene room turns on, unless the switches say otherwise
let (mut sun, mut sky, mut bounces) = (None, None, None);
let mut args = std::env::args().skip(1);
@@ -129,6 +137,9 @@ fn opts() -> Result<Opts, String> {
"--sun" => sun = Some(val()? != "off"),
"--sun-size" => o.sun_size = num(val()?)?.clamp(0.0, 30.0),
"--sky" => sky = Some(num(val()?)?.max(0.0)),
+ "--cache" => o.cache = val()? != "off",
+ "--cell" => o.cell = num(val()?)?.clamp(0.01, 10.0),
+ "--bounce-res" => o.half = val()? == "half",
"--size" => {
let v = val()?;
let (w, h) = v.split_once('x').ok_or("--size: WxH")?;
@@ -265,8 +276,8 @@ fn tick(o: Res<Opts>, time: Res<Time>, mut frame: ResMut<pass::Frame>, mut cam:
*frame = pass::Frame {
grid_min: g.min.extend(g.cell),
grid_dims: g.dims.extend(o.grid as u32),
- grid_start: g.start,
- grid_idx: g.idx,
+ // the starts count from the buffer's beginning, the indices following them
+ grid: g.start.iter().map(|s| s + g.start.len() as u32).chain(g.idx.iter().copied()).collect(),
lights,
mode: o.mode,
k: o.k,
@@ -281,6 +292,9 @@ fn tick(o: Res<Opts>, time: Res<Time>, mut frame: ResMut<pass::Frame>, mut cam:
sun: SUN_TO.normalize().extend((o.sun_size * 0.5).to_radians()),
sun_e: if o.sun { SUN_E.extend(0.0) } else { Vec4::ZERO },
sky: (SKY * o.sky).extend(0.0),
+ cache: o.cache,
+ cell: o.cell,
+ half: o.half,
};
}
@@ -310,7 +324,7 @@ fn shoot(mut commands: Commands, o: Res<Opts>, counts: Res<field::Counts>, targe
if n > n0 {
println!("GPU lighting pass {:.2} ms ({} frames timed)", (ns - ns0) as f64 / 1e6 / (n - n0) as f64, n - n0);
}
- println!("FRAME {ms:.2} ms, the GPU waited for ({} frames, {}x{}, {} lights, mode {} k {}, bounces {})", drawn - d0, o.size.x, o.size.y, o.lights, ["all", "uniform", "weighted"][o.mode as usize], o.k, o.bounces);
+ println!("FRAME {ms:.2} ms, the GPU waited for ({} frames, {}x{}, {} lights, mode {} k {}, bounces {}{}{})", drawn - d0, o.size.x, o.size.y, o.lights, ["all", "uniform", "weighted"][o.mode as usize], o.k, o.bounces, if o.cache { ", cache" } else { "" }, if o.half { ", half-res" } else { "" });
}
commands.spawn(Screenshot::image(target.0.clone())).observe(move |shot: On<ScreenshotCaptured>, mut exit: MessageWriter<AppExit>| {
match shot.image.clone().try_into_dynamic() {
diff --git a/bench/lightbench/src/pass.rs b/bench/lightbench/src/pass.rs
index 8a1732e8..bb9776f4 100644
--- a/bench/lightbench/src/pass.rs
+++ b/bench/lightbench/src/pass.rs
@@ -56,8 +56,8 @@ pub struct Frame {
/// the light grid (grid.rs): its corner and cell size, its cells along each axis and whether to use it, its lists
pub grid_min: Vec4,
pub grid_dims: UVec4,
- pub grid_start: Vec<u32>,
- pub grid_idx: Vec<u32>,
+ /// the grid's lists in one: the cells' starts (counted from the buffer's beginning), then the lights' indices
+ pub grid: Vec<u32>,
/// diffuse bounces a pixel follows (LB5)
pub bounces: u32,
/// the sun (LB6): the unit direction toward it and its angular radius; its irradiance (zero: none); the sky's
@@ -65,6 +65,11 @@ pub struct Frame {
pub sun: Vec4,
pub sun_e: Vec4,
pub sky: Vec4,
+ /// the bounce reads the radiance cache (LB7); a cell's size at 1 m from the camera
+ pub cache: bool,
+ pub cell: f32,
+ /// the bounce traced for one pixel of each 2 x 2 block and upsampled (LB7)
+ pub half: bool,
}
pub struct LightPass;
@@ -99,12 +104,17 @@ struct Params {
sun: Vec4,
sun_e: Vec4,
sky: Vec4,
+ cache: Vec4,
}
#[derive(Resource)]
struct Pipeline {
layout: BindGroupLayoutDescriptor,
id: CachedComputePipelineId,
+ /// the radiance cache's resolve, after the pixels
+ resolve: CachedComputePipelineId,
+ /// the half-resolution bounce, before them
+ half: CachedComputePipelineId,
}
/// The BVH on the GPU, made from the SceneGpu it came from (by its pointer); the history's two pairs of textures
@@ -118,8 +128,15 @@ struct Buffers {
stats: Option<(Buffer, Buffer)>,
/// the pass's start and end timestamps, resolved, read back; nanoseconds a tick
timer: Option<(wgpu::QuerySet, wgpu::Buffer, wgpu::Buffer, f64)>,
+ /// the radiance cache (cache.wgsl): its cells and their light
+ cache: Option<(Buffer, Buffer)>,
+ /// the half-resolution bounce (half.wgsl), one vec4 a 2 x 2 block
+ half: Option<Buffer>,
}
+/// The radiance cache's slots (cache.wgsl's CELLS) and the words each takes.
+const CELLS: u64 = 262144;
+
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(
@@ -140,22 +157,27 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCac
texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),
storage_buffer_sized(false, std::num::NonZeroU64::new(16)),
read(4),
- read(4),
+ storage_buffer_sized(false, std::num::NonZeroU64::new(16)),
+ storage_buffer_sized(false, std::num::NonZeroU64::new(24)),
+ storage_buffer_sized(false, std::num::NonZeroU64::new(16)),
),
),
);
- let id = cache.queue_compute_pipeline(ComputePipelineDescriptor {
- label: Some("lightbench_light".into()),
- layout: vec![layout.clone()],
- // the lighting and the rays it traces, one module
- shader: assets.add(bevy::shader::Shader::from_wgsl(concat!(include_str!("light.wgsl"), "\n", include_str!("trace.wgsl")), "lightbench/light.wgsl")),
- entry_point: Some("main".into()),
- ..default()
- });
- commands.insert_resource(Pipeline { layout, id });
+ // the lighting, the rays it traces and the radiance cache, one module
+ let shader = assets.add(bevy::shader::Shader::from_wgsl(concat!(include_str!("light.wgsl"), "\n", include_str!("trace.wgsl"), "\n", include_str!("cache.wgsl"), "\n", include_str!("half.wgsl")), "lightbench/light.wgsl"));
+ // three entry points of one module, on one layout
+ let base = ComputePipelineDescriptor { layout: vec![layout.clone()], shader, ..default() };
+ let queue = |entry: &'static str| cache.queue_compute_pipeline(ComputePipelineDescriptor { label: Some(format!("lightbench_{entry}").into()), entry_point: Some(entry.into()), ..base.clone() });
+ let (id, resolve, half) = (queue("main"), queue("resolve"), queue("trace_half"));
+ commands.insert_resource(Pipeline { layout, id, resolve, half });
}
#[allow(clippy::too_many_arguments)]
+/// A 16-byte buffer: the ray counts and the timer's resolve and read-back.
+fn small(d: &wgpu::Device, label: &str, usage: wgpu::BufferUsages) -> wgpu::Buffer {
+ d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: 16, usage, mapped_at_creation: false })
+}
+
fn light(
view: ViewQuery<(&ExtractedView, &ViewTarget, Option<&ViewPrepassTextures>)>,
p: Option<Res<Pipeline>>,
@@ -168,7 +190,7 @@ fn light(
) {
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(pipeline), Some(resolve), Some(half)) = (cache.get_compute_pipeline(p.id), cache.get_compute_pipeline(p.resolve), cache.get_compute_pipeline(p.half)) 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() {
@@ -184,7 +206,7 @@ fn light(
}
let lights = device.create_buffer_with_data(&BufferInitDescriptor { label: Some("lightbench_lights"), contents: bytemuck::cast_slice(&frame.lights), usage: BufferUsages::STORAGE });
let list = |label: &str, v: &[u32]| device.create_buffer_with_data(&BufferInitDescriptor { label: Some(label), contents: bytemuck::cast_slice(if v.is_empty() { &[0u32][..] } else { v }), usage: BufferUsages::STORAGE });
- let (grid_start, grid_idx) = (list("lightbench_grid_start", &frame.grid_start), list("lightbench_grid_idx", &frame.grid_idx));
+ let grid = list("lightbench_grid", &frame.grid);
let size = target.main_texture().size();
let want = UVec2::new(size.width, size.height);
let fresh = bufs.history.as_ref().map(|h| h.0) != Some(want);
@@ -205,6 +227,9 @@ fn light(
(t, v)
};
bufs.history = Some((want, [make(0), make(1), make(2), make(3)]));
+ // a block's bounce, a 2 x 2 block a vec4
+ let blocks = (want.x.div_ceil(2) * want.y.div_ceil(2)) as u64;
+ bufs.half = Some(device.create_buffer(&BufferDescriptor { label: Some("lightbench_bounce_half"), size: blocks * 16, usage: BufferUsages::STORAGE, mapped_at_creation: false }));
}
let world_from_clip = extracted.world_from_view.to_matrix() * extracted.clip_from_view.inverse();
let clip_from_world = extracted.clip_from_view * extracted.world_from_view.to_matrix().inverse();
@@ -213,17 +238,22 @@ fn light(
let reset = fresh || frame.cut || bufs.prev.is_none();
bufs.prev = Some((clip_from_world, eye));
if bufs.stats.is_none() {
- let make = |label: &str, usage: BufferUsages| device.create_buffer(&BufferDescriptor { label: Some(label), size: 16, usage, mapped_at_creation: false });
+ let make = |label: &str, usage: BufferUsages| Buffer::from(small(device.wgpu_device(), label, usage));
bufs.stats = Some((make("lightbench_stats", BufferUsages::STORAGE | BufferUsages::COPY_DST | BufferUsages::COPY_SRC), make("lightbench_stats_read", BufferUsages::MAP_READ | BufferUsages::COPY_DST)));
}
if bufs.timer.is_none() && crate::timing() && device.features().contains(WgpuFeatures::TIMESTAMP_QUERY) {
let d = device.wgpu_device();
let set = d.create_query_set(&wgpu::QuerySetDescriptor { label: Some("lightbench_timer"), ty: wgpu::QueryType::Timestamp, count: 2 });
- let buf = |label: &str, usage: wgpu::BufferUsages| d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: 16, usage, mapped_at_creation: false });
- let resolve = buf("lightbench_timer_resolve", wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC);
- let read = buf("lightbench_timer_read", wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ);
+ let resolve = small(d, "lightbench_timer_resolve", wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC);
+ let read = small(d, "lightbench_timer_read", wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ);
bufs.timer = Some((set, resolve, read, queue.get_timestamp_period() as f64));
}
+ if bufs.cache.is_none() {
+ let make = |label: &str, size: u64| device.create_buffer(&BufferDescriptor { label: Some(label), size, usage: BufferUsages::STORAGE, mapped_at_creation: false });
+ bufs.cache = Some((make("lightbench_cells", CELLS * 6 * 4), make("lightbench_cell_light", CELLS * 16)));
+ }
+ let (cells, cell_light) = bufs.cache.as_ref().unwrap();
+ let half_res = frame.half && (frame.cache || frame.bounces > 0);
let (stats, readback) = bufs.stats.as_ref().unwrap();
queue.write_buffer(stats, 0, &[0u8; 16]);
let (_, nodes, tris) = bufs.from.as_ref().unwrap();
@@ -240,25 +270,36 @@ fn light(
temporal: UVec4::new(frame.raw as u32, reset as u32, frame.history.max(1), 0),
grid_min: frame.grid_min,
grid_dims: frame.grid_dims,
- gi: UVec4::new(frame.bounces, 0, 0, 0),
+ gi: UVec4::new(frame.bounces, frame.cache as u32, half_res as u32, 0),
sun: frame.sun,
sun_e: frame.sun_e,
sky: frame.sky,
+ cache: Vec4::new(frame.cell, 4096.0, 0.0, 0.0),
});
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(), &h[r].1, &h[r + 1].1, &h[w].1, &h[w + 1].1, stats.as_entire_binding(), grid_start.as_entire_binding(), grid_idx.as_entire_binding())),
+ &BindGroupEntries::sequential((params.binding().unwrap(), depth, gbuf, nodes.as_entire_binding(), tris.as_entire_binding(), lights.as_entire_binding(), target.main_texture_view(), &h[r].1, &h[r + 1].1, &h[w].1, &h[w + 1].1, stats.as_entire_binding(), grid.as_entire_binding(), bufs.half.as_ref().unwrap().as_entire_binding(), cells.as_entire_binding(), cell_light.as_entire_binding())),
);
let encoder = ctx.command_encoder();
// timed at the pass's own start and end: Apple's GPUs take timestamps there, not inside passes or between them
let timer = bufs.timer.as_ref();
- let writes = timer.map(|t| wgpu::ComputePassTimestampWrites { query_set: &t.0, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: Some(1) });
+ let writes = timer.map(|(set, ..)| wgpu::ComputePassTimestampWrites { query_set: set, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: Some(1) });
let mut pass = encoder.begin_compute_pass(&ComputePassDescriptor { label: Some("lightbench_light"), timestamp_writes: writes });
- pass.set_pipeline(pipeline);
pass.set_bind_group(0, &group, &[]);
+ // the bounce at half resolution first, so the pixels can take it up
+ if half_res {
+ pass.set_pipeline(half);
+ pass.dispatch_workgroups(size.width.div_ceil(2).div_ceil(8), size.height.div_ceil(2).div_ceil(8), 1);
+ }
+ pass.set_pipeline(pipeline);
pass.dispatch_workgroups(size.width.div_ceil(8), size.height.div_ceil(8), 1);
+ // a dispatch is its own usage scope, so the resolve sees every pixel's samples
+ if frame.cache {
+ pass.set_pipeline(resolve);
+ pass.dispatch_workgroups((CELLS / 64) as u32, 1, 1);
+ }
drop(pass);
encoder.copy_buffer_to_buffer(stats, 0, readback, 0, 16);
if let Some(t) = timer {
diff --git a/bench/lightbench/src/scene.rs b/bench/lightbench/src/scene.rs
index 5d32253e..fd60a2fd 100644
--- a/bench/lightbench/src/scene.rs
+++ b/bench/lightbench/src/scene.rs
@@ -157,7 +157,7 @@ pub fn knot_data(p: u32, q: u32, seg: u32, ring: u32, r: f32) -> (Vec<Vec3>, Vec
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 w: Vec<Vec3> = p.iter().map(|&v| m.transform_point3(v.into())).collect();
let idx: Vec<usize> = match mesh.indices() {
Some(i) => i.iter().collect(),
None => (0..w.len()).collect(),
diff --git a/bench/lightbench/src/trace.wgsl b/bench/lightbench/src/trace.wgsl
index 413c49bb..fb35ba41 100644
--- a/bench/lightbench/src/trace.wgsl
+++ b/bench/lightbench/src/trace.wgsl
@@ -96,8 +96,20 @@ fn occluded(o: vec3<f32>, d: vec3<f32>, tmax: f32) -> bool {
struct Hit { t: f32, i: u32 }
-// the nearest triangle on the ray before tmax (i 0xFFFFFFFF if none): the BVH walked as `occluded` walks it, the
-// ray shortening at each hit so farther boxes drop out; every triangle with brute force
+// where the ray enters a box (0 if it starts inside), MISS if it doesn't before tmax
+fn box_t(o: vec3<f32>, inv: vec3<f32>, mn: vec3<f32>, mx: vec3<f32>, tmax: f32) -> f32 {
+ 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 select(MISS, near, near <= far);
+}
+
+// the nearest triangle on the ray before tmax (i 0xFFFFFFFF if none): at each inner node the nearer child first and
+// the farther kept with where the ray enters it, so once a hit is nearer than a kept box that box is skipped; every
+// triangle with brute force
fn closest(o: vec3<f32>, d: vec3<f32>, tmax: f32) -> Hit {
rays += 1u;
var best = Hit(tmax, 0xFFFFFFFFu);
@@ -112,31 +124,51 @@ fn closest(o: vec3<f32>, d: vec3<f32>, tmax: f32) -> Hit {
return best;
}
let inv = 1.0 / select(d, vec3(1e-12), abs(d) < vec3(1e-12));
+ if box_t(o, inv, nodes[0].mn, nodes[0].mx, best.t) == MISS {
+ return best;
+ }
var stack: array<u32, STACK>;
+ var enter: array<f32, STACK>;
var sp = 0u;
var i = 0u;
loop {
let n = nodes[i];
- if hit_box(o, inv, n.mn, n.mx, best.t) {
- if n.count > 0u {
- for (var t = n.a; t < n.a + n.count; t++) {
- let h = tri_t(o, d, t);
- if h < best.t {
- best = Hit(h, t);
- }
+ var next = 0xFFFFFFFFu;
+ if n.count > 0u {
+ for (var t = n.a; t < n.a + n.count; t++) {
+ let h = tri_t(o, d, t);
+ if h < best.t {
+ best = Hit(h, t);
}
- } else if sp < STACK {
- stack[sp] = n.a;
- sp++;
- i++;
- continue;
+ }
+ } else {
+ let tl = box_t(o, inv, nodes[i + 1u].mn, nodes[i + 1u].mx, best.t);
+ let tr = box_t(o, inv, nodes[n.a].mn, nodes[n.a].mx, best.t);
+ if tl < MISS && tr < MISS {
+ let left_first = tl <= tr;
+ next = select(n.a, i + 1u, left_first);
+ if sp < STACK {
+ stack[sp] = select(i + 1u, n.a, left_first);
+ enter[sp] = max(tl, tr);
+ sp++;
+ }
+ } else if tl < MISS {
+ next = i + 1u;
+ } else if tr < MISS {
+ next = n.a;
}
}
- if sp == 0u {
+ // nothing to go down into: the nearest kept box the ray still reaches before its best hit
+ while next == 0xFFFFFFFFu && sp > 0u {
+ sp--;
+ if enter[sp] < best.t {
+ next = stack[sp];
+ }
+ }
+ if next == 0xFFFFFFFFu {
break;
}
- sp--;
- i = stack[sp];
+ i = next;
}
return best;
}
diff --git a/docs/lightbench.feature b/docs/lightbench.feature
index 9a2fdc56..c9b12887 100644
--- a/docs/lightbench.feature
+++ b/docs/lightbench.feature
@@ -60,6 +60,13 @@ Feature: LightBench: a small Rust + Bevy renderer that proves raea's lighting an
And in the room the bounce lights what the sun patch and the window don't, and converges to the reference
And a sampled pixel traces at most K + 1 + 3N rays
+ Scenario: LB7 a world radiance cache and a half-resolution bounce, toward 60 fps
+ When LightBench draws with --cache on, and --bounce-res half
+ Then a bounce ray reads the hashed cell it hits and feeds it a fresh sample, so a pixel gets every bounce for two
+ rays, converging to a many-bounce reference with a small bias (written down by cell size)
+ And at half resolution one pixel of each 2 x 2 block traces the bounce and the rest take it up by depth and normal
+ And the room's frame time is measured on its own at 1280x720, toward 60+ fps
+
# 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
diff --git a/tools/layers.toml b/tools/layers.toml
index 5a620b86..95bc9422 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -76,6 +76,7 @@ raea-sys-footage = "systems"
raea-perceive = "tools"
raea-bridge-bench = "tools"
raea-bevy-parity = "tools" # Bevy's own examples with the parity probe (docs/control.feature FC0a)
+raea-lightbench = "tools" # LightBench (bench/lightbench): a test renderer on Bevy alone, proving lighting before it moves into raea
raea-rerender-ios = "tools" # RR0's film on the iPhone (bench/rerender/ios): a static library the bench app calls
raea-sys-parity = "systems" # the parity probe, in raea's App and the examples'
raea-bench-swatch = "systems" # a Blitz widget fixture (bench/bridge/swatch) the plugin catalog declares: a leaf on vendored crates, so a runtime crate may build it in