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 LB5: diffuse bounces through the BVH, each hit lit by the pixel's own light sampling; an f32 history

shinyobjectz56ff2a703171
diff --git a/bench/lightbench/src/bvh.rs b/bench/lightbench/src/bvh.rs
index 3c0d33bc..ac891c31 100644
--- a/bench/lightbench/src/bvh.rs
+++ b/bench/lightbench/src/bvh.rs
@@ -14,7 +14,8 @@ pub struct Node {
pub count: u32,
}
-/// A triangle as the GPU tests it: v0, v1 - v0 and v2 - v0, each padded to a vec4.
+/// A triangle as the GPU tests it: v0, v1 - v0 and v2 - v0, each padded to a vec4 whose w holds the triangle's
+/// albedo (linear r, g, b), so a bounce ray knows the colour of what it hits.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable, Default, Debug)]
pub struct Tri {
@@ -53,7 +54,8 @@ impl Aabb {
}
}
-pub fn build(tris: &[[Vec3; 3]]) -> Bvh {
+/// The BVH over `tris`, each with its albedo (`albedo` one a triangle, or empty for black).
+pub fn build(tris: &[[Vec3; 3]], albedo: &[Vec3]) -> Bvh {
let boxes: Vec<Aabb> = tris
.iter()
.map(|t| {
@@ -70,7 +72,8 @@ pub fn build(tris: &[[Vec3; 3]]) -> Bvh {
.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() }
+ let k = albedo.get(i as usize).copied().unwrap_or(Vec3::ZERO);
+ Tri { v0: a.extend(k.x).into(), e1: (b - a).extend(k.y).into(), e2: (c - a).extend(k.z).into() }
})
.collect();
Bvh { nodes, tris }
@@ -179,6 +182,35 @@ impl Bvh {
}
}
+ /// The nearest triangle on the ray before `tmax`, and how far: the shader's `closest`, on the CPU.
+ pub fn closest(&self, o: Vec3, d: Vec3, tmax: f32) -> Option<(f32, usize)> {
+ 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 best, mut i) = (None, 0usize);
+ let mut far = tmax;
+ loop {
+ let n = &self.nodes[i];
+ if hit_box(o, inv, n.min.into(), n.max.into(), far) {
+ if n.count > 0 {
+ for k in n.a as usize..(n.a + n.count) as usize {
+ let t = tri_t(o, d, &self.tris[k]);
+ if t < far {
+ (far, best) = (t, Some((t, k)));
+ }
+ }
+ } else {
+ stack.push(n.a as usize);
+ i += 1;
+ continue;
+ }
+ }
+ match stack.pop() {
+ Some(j) => i = j,
+ None => return best,
+ }
+ }
+ }
+
/// 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 {
@@ -196,27 +228,31 @@ fn hit_box(o: Vec3, inv: Vec3, min: Vec3, max: Vec3, tmax: f32) -> bool {
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));
+ tri_t(o, d, t) < tmax
+}
+
+/// Möller-Trumbore, both sides: how far along the ray the triangle is, infinity if it isn't on it.
+pub fn tri_t(o: Vec3, d: Vec3, t: &Tri) -> f32 {
+ let (v0, e1, e2) = (Vec3::from_slice(&t.v0[..3]), Vec3::from_slice(&t.e1[..3]), Vec3::from_slice(&t.e2[..3]));
let pv = d.cross(e2);
let det = e1.dot(pv);
if det.abs() < 1e-12 {
- return false;
+ return f32::INFINITY;
}
let inv = 1.0 / det;
let tv = o - v0;
let u = tv.dot(pv) * inv;
if !(0.0..=1.0).contains(&u) {
- return false;
+ return f32::INFINITY;
}
let qv = tv.cross(e1);
let v = d.dot(qv) * inv;
if v < 0.0 || u + v > 1.0 {
- return false;
+ return f32::INFINITY;
}
let t = e2.dot(qv) * inv;
- t > 0.0 && t < tmax
+ if t > 0.0 { t } else { f32::INFINITY }
}
#[cfg(test)]
@@ -243,8 +279,8 @@ mod tests {
[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;
+ 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 {
@@ -253,6 +289,9 @@ mod tests {
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}");
+ // the nearest hit too, as LB5's bounce rays find it
+ let near = all.iter().enumerate().map(|(k, t)| (tri_t(o, d, t), k)).filter(|h| h.0 < tmax).min_by(|a, b| a.0.total_cmp(&b.0));
+ assert_eq!(bvh.closest(o, d, tmax).map(|h| h.1), near.map(|h| h.1), "nearest on ray {o} {d} {tmax}");
hits += brute as u32;
n += 1;
}
@@ -264,7 +303,7 @@ mod tests {
#[test]
fn coincident_triangles_still_split() {
let t = [Vec3::ZERO, Vec3::X, Vec3::Y];
- let bvh = build(&vec![t; 100]);
+ 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/field.rs b/bench/lightbench/src/field.rs
index 03f4ee44..9e19e373 100644
--- a/bench/lightbench/src/field.rs
+++ b/bench/lightbench/src/field.rs
@@ -30,6 +30,9 @@ pub struct Knot {
drawn: Vec<usize>,
}
+/// The knots' colour.
+pub const COLOUR: Color = Color::srgb(0.85, 0.42, 0.18);
+
const LEVEL_COLOURS: [[f32; 3]; 8] = [[1.0, 1.0, 1.0], [0.3, 0.9, 0.3], [0.95, 0.9, 0.2], [1.0, 0.55, 0.1], [0.95, 0.2, 0.2], [0.85, 0.3, 0.9], [0.3, 0.5, 1.0], [0.2, 0.9, 0.9]];
/// The knots' places: rows from 3 m to about 60 m away, each a little different in size and turn.
@@ -62,7 +65,7 @@ pub fn spawn(commands: &mut Commands, opts: &Opts, meshes: &mut Assets<Mesh>, ma
});
let center = (lo + hi) * 0.5;
let radius = pos.iter().map(|p| p.distance(center)).fold(0.0, f32::max);
- let material = mats.add(StandardMaterial { base_color: Color::srgb(0.85, 0.42, 0.18), perceptual_roughness: 0.6, ..default() });
+ let material = mats.add(StandardMaterial { base_color: COLOUR, perceptual_roughness: 0.6, ..default() });
let lod_material = mats.add(StandardMaterial { base_color: Color::WHITE, perceptual_roughness: 0.6, ..default() });
for at in places(opts.rows) {
let m = at.to_matrix();
diff --git a/bench/lightbench/src/light.wgsl b/bench/lightbench/src/light.wgsl
index 688c5fa8..7d05f520 100644
--- a/bench/lightbench/src/light.wgsl
+++ b/bench/lightbench/src/light.wgsl
@@ -1,7 +1,10 @@
// 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.
+// which lights they look at. With --bounce (LB5) each pixel also follows a cosine-chosen ray through the BVH to the
+// nearest surface and lights that point the same way (one light sample in the sampled modes, every light in the
+// reference), so the reference and the sampled path still differ only in the 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>,
@@ -9,7 +12,8 @@ struct Params {
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, 5 history),
+ // mode (0 every light, 1 uniform, 2 weighted), K, view (0 lit, 1 normal, 2 albedo, 3 depth, 4 rays, 5 history,
+ // 6 lod, 7 bounce: the bounced light alone),
// brute force
mode: vec4<u32>,
// the previous frame's camera, to find where a point was
@@ -21,6 +25,8 @@ 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
+ gi: vec4<u32>,
}
struct Node { mn: vec3<f32>, a: u32, mx: vec3<f32>, count: u32 }
@@ -30,7 +36,7 @@ struct Light { pos: vec3<f32>, range: f32, power: vec3<f32>, radius: f32 }
@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
+// three a triangle: v0, v1 - v0, v2 - v0; their w the triangle's albedo (linear r, g, b), for the bounce
@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>;
@@ -38,7 +44,8 @@ struct Light { pos: vec3<f32>, range: f32, power: vec3<f32>, radius: f32 }
// (its normal, and its distance from that frame's camera); last frame's to read, this frame's to write
@group(0) @binding(7) var hist_in: texture_2d<f32>;
@group(0) @binding(8) var geo_in: texture_2d<f32>;
-@group(0) @binding(9) var hist_out: texture_storage_2d<rgba16float, write>;
+// (in f32: a long history's 1 / n steps are below an f16's resolution, and its mean stops moving)
+@group(0) @binding(9) var hist_out: texture_storage_2d<rgba32float, write>;
@group(0) @binding(10) var geo_out: texture_storage_2d<rgba16float, write>;
// 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>;
@@ -89,29 +96,35 @@ fn hit_box(o: vec3<f32>, inv: vec3<f32>, mn: vec3<f32>, mx: vec3<f32>, tmax: f32
return near <= far;
}
-// Möller-Trumbore, both sides
-fn hit_tri(o: vec3<f32>, d: vec3<f32>, i: u32, tmax: f32) -> bool {
+const MISS: f32 = 3.4e38;
+
+// Möller-Trumbore, both sides: how far along the ray triangle i is, MISS if it isn't on it
+fn tri_t(o: vec3<f32>, d: vec3<f32>, i: u32) -> f32 {
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;
+ return MISS;
}
let inv = 1.0 / det;
let tv = o - v0;
let u = dot(tv, pv) * inv;
if u < 0.0 || u > 1.0 {
- return false;
+ return MISS;
}
let qv = cross(tv, e1);
let v = dot(d, qv) * inv;
if v < 0.0 || u + v > 1.0 {
- return false;
+ return MISS;
}
let t = dot(e2, qv) * inv;
- return t > 0.0 && t < tmax;
+ return select(MISS, t, t > 0.0);
+}
+
+fn hit_tri(o: vec3<f32>, d: vec3<f32>, i: u32, tmax: f32) -> bool {
+ return tri_t(o, d, i) < tmax;
}
// whether anything lies on the ray before tmax: the BVH, or every triangle when brute force is asked for
@@ -155,6 +168,53 @@ fn occluded(o: vec3<f32>, d: vec3<f32>, tmax: f32) -> bool {
return false;
}
+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
+fn closest(o: vec3<f32>, d: vec3<f32>, tmax: f32) -> Hit {
+ rays += 1u;
+ var best = Hit(tmax, 0xFFFFFFFFu);
+ if p.mode.w != 0u {
+ let n = arrayLength(&tris) / 3u;
+ for (var i = 0u; i < n; i++) {
+ let t = tri_t(o, d, i);
+ if t < best.t {
+ best = Hit(t, i);
+ }
+ }
+ return best;
+ }
+ 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, 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);
+ }
+ }
+ } else if sp < STACK {
+ stack[sp] = n.a;
+ sp++;
+ i++;
+ continue;
+ }
+ }
+ if sp == 0u {
+ break;
+ }
+ sp--;
+ i = stack[sp];
+ }
+ return best;
+}
+
// 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> {
@@ -199,45 +259,10 @@ fn lum(c: vec3<f32>) -> f32 {
return dot(c, vec3(0.2126, 0.7152, 0.0722));
}
-// one pixel: its light, its history; (shadow rays traced, 1 if it is a lit pixel)
-fn shade(id: vec3<u32>) -> vec2<u32> {
- if id.x >= p.size.x || id.y >= p.size.y {
- return vec2(0u);
- }
- 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, and holds no history
- if depth <= 0.0 {
- textureStore(hist_out, px, vec4(0.0));
- textureStore(geo_out, px, vec4(0.0, 0.0, 0.0, -1.0));
- return vec2(0u);
- }
- 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 vec2(0u);
- }
- if view == 2u || view == 6u {
- textureStore(out, px, vec4(albedo, 1.0));
- return vec2(0u);
- }
- if view == 3u {
- textureStore(out, px, vec4(vec3(dist / 20.0), 1.0));
- return vec2(0u);
- }
- 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);
+// the light reaching a point (pos, its normal n, o just off it) from the lights: every light with its shadow ray, or
+// k shadow rays to lights chosen uniformly or by their light from the point's cell
+fn lit_at(pos: vec3<f32>, n: vec3<f32>, o: vec3<f32>, k: u32) -> vec3<f32> {
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++) {
@@ -288,6 +313,98 @@ fn shade(id: vec3<u32>) -> vec2<u32> {
c /= f32(k);
}
}
+ return c;
+}
+
+// a direction about n, chosen in proportion to its cosine (Duff et al.'s basis)
+fn cosine_dir(n: vec3<f32>) -> vec3<f32> {
+ let phi = 2.0 * PI * rnd();
+ let r2 = rnd();
+ let r = sqrt(r2);
+ let s = select(-1.0, 1.0, n.z >= 0.0);
+ let a = -1.0 / (s + n.z);
+ let b = n.x * n.y * a;
+ let t = vec3(1.0 + s * n.x * n.x * a, s * b, -s * n.x);
+ let bt = vec3(b, s + n.y * n.y * a, -n.y);
+ return normalize(t * (r * cos(phi)) + bt * (r * sin(phi)) + n * sqrt(max(0.0, 1.0 - r2)));
+}
+
+// the light reaching a point by way of other surfaces, p.gi.x bounces deep: from the point a cosine-chosen ray to the
+// nearest triangle, that point lit as a pixel is (one light sample, or every light in the reference), and on from
+// there. A cosine-chosen ray's pdf cancels the cosine and the 1 / PI of the hit's diffuse light, so each bounce adds
+// the albedos so far times the light at the hit. Rays that leave the scene bring nothing (it has no sky).
+fn bounced(n0: vec3<f32>, o0: vec3<f32>) -> vec3<f32> {
+ var e = vec3(0.0);
+ var through = vec3(1.0);
+ var n = n0;
+ var o = o0;
+ for (var b = 0u; b < p.gi.x; b++) {
+ let d = cosine_dir(n);
+ let h = closest(o, d, 1e4);
+ if h.i == 0xFFFFFFFFu {
+ break;
+ }
+ let v0 = tris[3u * h.i];
+ let e1 = tris[3u * h.i + 1u];
+ let e2 = tris[3u * h.i + 2u];
+ var nh = normalize(cross(e1.xyz, e2.xyz));
+ if dot(nh, d) > 0.0 {
+ nh = -nh;
+ }
+ let hp = o + d * h.t;
+ let oh = hp + nh * (2e-3 + 5e-4 * length(hp - p.eye.xyz));
+ through *= vec3(v0.w, e1.w, e2.w);
+ e += through * lit_at(hp, nh, oh, 1u);
+ n = nh;
+ o = oh;
+ }
+ return e;
+}
+
+// one pixel: its light, its history; (shadow rays traced, 1 if it is a lit pixel)
+fn shade(id: vec3<u32>) -> vec2<u32> {
+ if id.x >= p.size.x || id.y >= p.size.y {
+ return vec2(0u);
+ }
+ 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, and holds no history
+ if depth <= 0.0 {
+ textureStore(hist_out, px, vec4(0.0));
+ textureStore(geo_out, px, vec4(0.0, 0.0, 0.0, -1.0));
+ return vec2(0u);
+ }
+ 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 vec2(0u);
+ }
+ if view == 2u || view == 6u {
+ textureStore(out, px, vec4(albedo, 1.0));
+ return vec2(0u);
+ }
+ if view == 3u {
+ textureStore(out, px, vec4(vec3(dist / 20.0), 1.0));
+ return vec2(0u);
+ }
+ 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);
+ var c = vec3(0.0);
+ if view != 7u {
+ c = lit_at(pos, n, o, clamp(p.mode.y, 1u, MAX_K));
+ }
+ 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
var held = 0.0;
var acc = c;
diff --git a/bench/lightbench/src/main.rs b/bench/lightbench/src/main.rs
index c81d0cf3..89aba96e 100644
--- a/bench/lightbench/src/main.rs
+++ b/bench/lightbench/src/main.rs
@@ -26,6 +26,9 @@ const HELP: &str = "lightbench [switches]
--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)
+ --bounce N diffuse bounces each pixel follows through the BVH, each hit lit by the same light
+ sampling as the pixel (one sample; every light with --mode all) (0)
+ --view bounce the bounced light alone
--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; the field's knots 512)
--size WxH pixels (1280x720)
@@ -75,10 +78,11 @@ pub struct Opts {
pub tau: f32,
pub fov: f32,
pub grid: bool,
+ pub bounces: u32,
}
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 };
+ 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 };
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"));
@@ -90,7 +94,7 @@ fn opts() -> Result<Opts, String> {
}
"--view" => {
let v = val()?;
- o.view = ["lit", "normal", "albedo", "depth", "rays", "history", "lod"].iter().position(|m| *m == v).ok_or("--view: lit, normal, albedo, depth, rays, history or lod")? as u32;
+ o.view = ["lit", "normal", "albedo", "depth", "rays", "history", "lod", "bounce"].iter().position(|m| *m == v).ok_or("--view: lit, normal, albedo, depth, rays, history, lod or bounce")? as u32;
}
"--k" => o.k = (num(val()?)? as u32).clamp(1, 16),
"--lights" => o.lights = (num(val()?)? as u32).max(1),
@@ -111,6 +115,7 @@ fn opts() -> Result<Opts, String> {
"--tau" => o.tau = num(val()?)?.max(0.0),
"--fov" => o.fov = num(val()?)?.clamp(1.0, 170.0),
"--grid" => o.grid = val()? != "off",
+ "--bounce" => o.bounces = (num(val()?)? as u32).min(8),
"--size" => {
let v = val()?;
let (w, h) = v.split_once('x').ok_or("--size: WxH")?;
@@ -249,6 +254,7 @@ fn tick(o: Res<Opts>, time: Res<Time>, mut frame: ResMut<pass::Frame>, mut cam:
raw: o.raw,
cut,
history: o.history,
+ bounces: o.bounces,
};
}
@@ -278,7 +284,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 {})", drawn - d0, o.size.x, o.size.y, o.lights, ["all", "uniform", "weighted"][o.mode as usize], o.k);
+ 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);
}
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 dad0a7a4..9517d4ec 100644
--- a/bench/lightbench/src/pass.rs
+++ b/bench/lightbench/src/pass.rs
@@ -42,7 +42,7 @@ pub struct Frame {
/// 0 every light, 1 uniform, 2 weighted
pub mode: u32,
pub k: u32,
- /// 0 lit, 1 normal, 2 albedo, 3 depth, 4 rays
+ /// 0 lit, 1 normal, 2 albedo, 3 depth, 4 rays, 5 history, 6 lod, 7 bounce
pub view: u32,
pub frame: u32,
pub exposure: f32,
@@ -58,6 +58,8 @@ pub struct Frame {
pub grid_dims: UVec4,
pub grid_start: Vec<u32>,
pub grid_idx: Vec<u32>,
+ /// diffuse bounces a pixel follows (LB5)
+ pub bounces: u32,
}
pub struct LightPass;
@@ -89,6 +91,7 @@ struct Params {
temporal: UVec4,
grid_min: Vec4,
grid_dims: UVec4,
+ gi: UVec4,
}
#[derive(Resource)]
@@ -126,7 +129,7 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCac
texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),
texture_2d(TextureSampleType::Float { filterable: false }),
texture_2d(TextureSampleType::Float { filterable: false }),
- texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),
+ texture_storage_2d(TextureFormat::Rgba32Float, StorageTextureAccess::WriteOnly),
texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),
storage_buffer_sized(false, std::num::NonZeroU64::new(16)),
read(4),
@@ -185,7 +188,8 @@ fn light(
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
- format: TextureFormat::Rgba16Float,
+ // the light in f32 (a long history's 1 / n steps vanish in f16), the surface in f16
+ format: if i % 2 == 0 { TextureFormat::Rgba32Float } else { TextureFormat::Rgba16Float },
usage: TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
@@ -228,6 +232,7 @@ 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),
});
params.write_buffer(&device, &queue);
let group = device.create_bind_group(
diff --git a/bench/lightbench/src/scene.rs b/bench/lightbench/src/scene.rs
index d1f33bcd..dd3fea0a 100644
--- a/bench/lightbench/src/scene.rs
+++ b/bench/lightbench/src/scene.rs
@@ -37,10 +37,15 @@ 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();
+ // where each mesh's triangles start and its albedo, for the bounce
+ let mut from: Vec<(usize, Vec3)> = Vec::new();
+ let linear = |c: Color| { let l = c.to_linear(); Vec3::new(l.red, l.green, l.blue) };
if opts.scene == 1 {
+ from.push((0, linear(crate::field::COLOUR)));
crate::field::spawn(&mut commands, &opts, &mut meshes, &mut mats, &mut tris);
}
let mut put = |mesh: Mesh, at: Transform, color: Color, tris: &mut Vec<[Vec3; 3]>| {
+ from.push((tris.len(), linear(color)));
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));
@@ -54,7 +59,8 @@ pub fn spawn(mut commands: Commands, opts: Res<Opts>, mut meshes: ResMut<Assets<
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);
+ let albedo: Vec<Vec3> = (0..tris.len()).map(|i| from.iter().rev().find(|f| f.0 <= i).map_or(Vec3::ZERO, |f| f.1)).collect();
+ let built = bvh::build(&tris, &albedo);
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) });
}
diff --git a/bench/lightbench/sweep.sh b/bench/lightbench/sweep.sh
index 1c363325..7fb46494 100755
--- a/bench/lightbench/sweep.sh
+++ b/bench/lightbench/sweep.sh
@@ -8,7 +8,7 @@ mkdir -p "$out"
root="$(cd "$(dirname "$0")/../.." && pwd)"
lb="$root/target/release/lightbench"
[ -x "$lb" ] || { echo "no $lb: cargo build --release -p raea-lightbench" >&2; exit 1; }
-run() { "$lb" --t 0 --size 1280x720 "$@" 2>/dev/null | grep -E '^(FRAME|LOD)' || { echo "FAILED: $*" >&2; return 1; }; }
+run() { "$lb" --t 0 --size 1280x720 "$@" 2>/dev/null | grep -E '^(FRAME|LOD|RAYS|GPU)' || { echo "FAILED: $*" >&2; return 1; }; }
echo "# frame time (the GPU waited for each frame) by light count and mode"
for n in 16 64 256; do
@@ -16,6 +16,9 @@ for n in 16 64 256; do
for m in uniform weighted; do run --lights "$n" --mode "$m" --k 4 --bench 30 --raw --shot "$out/$m-$n.png"; done
done
+echo "# bounces (LB5): rays a pixel and the lighting pass's time, 0 to 2 bounces"
+for b in 0 1 2; do run --lights 64 --mode weighted --k 4 --bounce "$b" --bench 30 --shot "$out/bounce-$b.png"; done
+
echo "# detail: full against adaptive, then the field of view"
run --scene field --detail full --view lod --shot "$out/field-full.png"
for fov in 45 20 8; do run --scene field --fov "$fov" --view lod --shot "$out/field-fov$fov.png"; done
diff --git a/docs/lightbench.feature b/docs/lightbench.feature
index 9866b5fe..761493e7 100644
--- a/docs/lightbench.feature
+++ b/docs/lightbench.feature
@@ -44,6 +44,15 @@ Feature: LightBench: a small Rust + Bevy renderer that proves raea's lighting an
Scenario: LB3b temporal accumulation, reprojected, rejected on depth and normal, reset on a camera cut; --raw drops it
+ # LB5: bounce light
+ Scenario: LB5 diffuse bounces through the BVH, lit by the same light sampling, against the every-light reference
+ When LightBench draws with --bounce N
+ Then each pixel follows N cosine-chosen rays to the nearest triangle, and lights each hit as it lights a pixel
+ (one light sample, or every light with --mode all), so the reference and the sampled path differ only in which
+ lights they look at
+ And the sampled bounce converges to the reference as frames grow (RMSE against it, written down) with no bias
+ And a sampled pixel traces at most K + 2N rays whatever the number of lights
+
# 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