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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
LightBench LB3c: a light grid, so a pixel weighs only the lights whose range reaches its cell
shinyobjectz88ff2b696789
diff --git a/bench/lightbench/src/grid.rs b/bench/lightbench/src/grid.rsnew file mode 100644index 00000000..9ae88652--- /dev/null+++ b/bench/lightbench/src/grid.rs@@ -0,0 +1,101 @@+//! The light grid (docs/lightbench.feature LB3c): world cells over everything the lights reach, each listing the lights+//! whose range touches it, so a pixel weighs only its cell's lights rather than all of them. A light that doesn't touch+//! a cell can't reach any point in it, so choosing among the cell's lights is still unbiased; outside the grid no light+//! reaches at all. Built on the CPU each frame as the lights move (a count, then the lists, cell by cell).++use crate::scene::GpuLight;+use bevy::math::{UVec3, Vec3};++pub struct Grid {+ pub min: Vec3,+ pub cell: f32,+ pub dims: UVec3,+ /// cell c's lights are idx[start[c]..start[c + 1]]+ pub start: Vec<u32>,+ pub idx: Vec<u32>,+}++/// At most this many cells along an axis; the cell grows past `cell` to keep to it.+const MAX_DIM: f32 = 96.0;++pub fn build(lights: &[GpuLight], cell: f32) -> Grid {+ let (mut lo, mut hi) = (Vec3::INFINITY, Vec3::NEG_INFINITY);+ for l in lights {+ let p = Vec3::from(l.pos);+ lo = lo.min(p - l.range);+ hi = hi.max(p + l.range);+ }+ if lights.is_empty() {+ (lo, hi) = (Vec3::ZERO, Vec3::ONE);+ }+ let cell = cell.max((hi - lo).max_element() / MAX_DIM);+ let dims = ((hi - lo) / cell).ceil().max(Vec3::ONE).as_uvec3();+ let n = (dims.x * dims.y * dims.z) as usize;+ let at = |x: u32, y: u32, z: u32| ((z * dims.y + y) * dims.x + x) as usize;+ // each light's cells: those its range sphere touches+ let mut pairs: Vec<(u32, u32)> = Vec::new();+ for (i, l) in lights.iter().enumerate() {+ let p = Vec3::from(l.pos);+ let a = ((p - l.range - lo) / cell).floor().max(Vec3::ZERO).as_uvec3().min(dims - 1);+ let b = ((p + l.range - lo) / cell).floor().max(Vec3::ZERO).as_uvec3().min(dims - 1);+ for z in a.z..=b.z {+ for y in a.y..=b.y {+ for x in a.x..=b.x {+ let c0 = lo + Vec3::new(x as f32, y as f32, z as f32) * cell;+ let near = p.clamp(c0, c0 + cell);+ if near.distance_squared(p) <= l.range * l.range {+ pairs.push((at(x, y, z) as u32, i as u32));+ }+ }+ }+ }+ }+ let mut start = vec![0u32; n + 1];+ pairs.iter().for_each(|(c, _)| start[*c as usize + 1] += 1);+ for c in 0..n {+ start[c + 1] += start[c];+ }+ let mut fill = start.clone();+ let mut idx = vec![0u32; pairs.len().max(1)];+ for (c, i) in pairs {+ idx[fill[c as usize] as usize] = i;+ fill[c as usize] += 1;+ }+ Grid { min: lo, cell, dims, start, idx }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn every_light_that_reaches_a_point_is_in_its_cell() {+ let lights: Vec<GpuLight> = (0..300)+ .map(|i| {+ let f = i as f32;+ GpuLight { pos: [(f * 7.3).sin() * 20.0, 1.0 + (f * 1.1).cos(), (f * 3.7).cos() * 30.0 - 20.0], range: 2.0 + (f * 0.37).sin().abs() * 5.0, power: [1.0; 3], radius: 0.05 }+ })+ .collect();+ let g = build(&lights, 2.0);+ let mut checked = 0;+ for k in 0..20000 {+ let f = k as f32;+ let p = Vec3::new((f * 0.731).sin() * 24.0, (f * 0.217).cos() * 3.0 + 1.0, (f * 0.393).cos() * 36.0 - 20.0);+ let c = ((p - g.min) / g.cell).floor();+ let inside = c.cmpge(Vec3::ZERO).all() && c.cmplt(g.dims.as_vec3()).all();+ for (i, l) in lights.iter().enumerate() {+ if Vec3::from(l.pos).distance(p) < l.range {+ assert!(inside, "{p} is reached by light {i} but is outside the grid");+ let c = c.as_uvec3();+ let cell = ((c.z * g.dims.y + c.y) * g.dims.x + c.x) as usize;+ assert!(g.idx[g.start[cell] as usize..g.start[cell + 1] as usize].contains(&(i as u32)), "light {i} reaches {p} but isn't in its cell");+ checked += 1;+ }+ }+ }+ assert!(checked > 1000, "{checked}");+ // and the lists are far shorter than all the lights+ let mean = g.idx.len() as f32 / (g.start.len() - 1) as f32;+ assert!(mean < 30.0, "{mean} lights a cell");+ }+}diff --git a/bench/lightbench/src/light.wgsl b/bench/lightbench/src/light.wgslindex 224838a4..688c5fa8 100644--- a/bench/lightbench/src/light.wgsl+++ b/bench/lightbench/src/light.wgsl@@ -18,6 +18,9 @@ struct Params {prev_eye: vec4<f32>,// raw (no history), reset (a camera cut, or the first frame), the history's length in frames, 0temporal: vec4<u32>,+ // 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>,}struct Node { mn: vec3<f32>, a: u32, mx: vec3<f32>, count: u32 }@@ -40,6 +43,10 @@ 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>;+var<workgroup> wg_rays: atomic<u32>;var<workgroup> wg_px: atomic<u32>;var<workgroup> wg_max: atomic<u32>;@@ -169,6 +176,25 @@ fn visible(o: vec3<f32>, l: Light) -> f32 {return select(1.0, 0.0, occluded(o, v / d, d - 1e-3));}+// the candidate lights at a point: (first, count) into grid_idx, or with the grid off every light (count with first+// = 0xFFFFFFFF); outside the grid no light reaches+fn candidates(pos: vec3<f32>) -> vec2<u32> {+ if p.grid_dims.w == 0u {+ return vec2(0xFFFFFFFFu, p.size.z);+ }+ let c = vec3<i32>(floor((pos - p.grid_min.xyz) / p.grid_min.w));+ let d = vec3<i32>(p.grid_dims.xyz);+ if any(c < vec3(0)) || any(c >= d) {+ 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]);+}++fn candidate(range: vec2<u32>, j: u32) -> u32 {+ return select(grid_idx[range.x + j], j, range.x == 0xFFFFFFFFu);+}+fn lum(c: vec3<f32>) -> f32 {return dot(c, vec3(0.2126, 0.7152, 0.0722));}@@ -221,21 +247,27 @@ fn shade(id: vec3<u32>) -> vec2<u32> {}}} 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);+ // uniform: each candidate 1 / their number+ let cand = candidates(pos);+ let m = cand.y;+ if m > 0u {+ for (var s = 0u; s < k; s++) {+ let i = candidate(cand, min(u32(rnd() * f32(m)), m - 1u));+ let u = unshadowed(lights[i], pos, n);+ if lum(u) > 0.0 {+ c += u * visible(o, lights[i]) * f32(m);+ }}+ c /= f32(k);}- c /= f32(k);} else {// weighted: K reservoirs over every light by its unshadowed light, so any light that adds light can be chosenvar pick: array<u32, MAX_K>;var pw: array<f32, MAX_K>;var wsum = 0.0;- for (var i = 0u; i < nl; i++) {+ let cand = candidates(pos);+ for (var j = 0u; j < cand.y; j++) {+ let i = candidate(cand, j);let wi = lum(unshadowed(lights[i], pos, n));if wi <= 0.0 {continue;diff --git a/bench/lightbench/src/main.rs b/bench/lightbench/src/main.rsindex ff980e35..c81d0cf3 100644--- a/bench/lightbench/src/main.rs+++ b/bench/lightbench/src/main.rs@@ -4,6 +4,7 @@mod bvh;mod field;+mod grid;mod lod;mod pass;mod scene;@@ -44,7 +45,8 @@ const HELP: &str = "lightbench [switches]--detail full|adaptive every finest triangle, or the clusters each knot's distance asks for (adaptive)--tau PX the error in pixels a cluster may show (1)--fov DEG the vertical field of view (45)- --view lod each cluster coloured by its level (white the finest), unlit";+ --view lod each cluster coloured by its level (white the finest), unlit+ --grid on|off the sampled modes weigh only the lights whose range reaches the pixel's cell (on)";#[derive(Resource, Clone)]pub struct Opts {@@ -72,10 +74,11 @@ pub struct Opts {pub full: bool,pub tau: f32,pub fov: f32,+ pub grid: 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 };+ 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 args = std::env::args().skip(1);while let Some(a) = args.next() {let mut val = || args.next().ok_or(format!("{a} needs a value"));@@ -107,6 +110,7 @@ fn opts() -> Result<Opts, String> {"--rows" => o.rows = (num(val()?)? as u32).max(1),"--tau" => o.tau = num(val()?)?.max(0.0),"--fov" => o.fov = num(val()?)?.clamp(1.0, 170.0),+ "--grid" => o.grid = val()? != "off","--size" => {let v = val()?;let (w, h) = v.split_once('x').ok_or("--size: WxH")?;@@ -228,8 +232,14 @@ fn tick(o: Res<Opts>, time: Res<Time>, mut frame: ResMut<pass::Frame>, mut cam:cut = at.translation.distance(to.translation) > 1.0 || at.rotation.angle_between(to.rotation) > 20f32.to_radians();*at = to;}+ let lights = scene::lights(o.lights, t, o.scene == 1);+ let g = grid::build(&lights, 2.0);*frame = pass::Frame {- lights: scene::lights(o.lights, t),+ grid_min: g.min.extend(g.cell),+ grid_dims: g.dims.extend(o.grid as u32),+ grid_start: g.start,+ grid_idx: g.idx,+ lights,mode: o.mode,k: o.k,view: o.view,diff --git a/bench/lightbench/src/pass.rs b/bench/lightbench/src/pass.rsindex c3568c1e..dad0a7a4 100644--- a/bench/lightbench/src/pass.rs+++ b/bench/lightbench/src/pass.rs@@ -53,6 +53,11 @@ pub struct Frame {pub cut: bool,/// the history's length in framespub history: u32,+ /// 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>,}pub struct LightPass;@@ -82,6 +87,8 @@ struct Params {prev_clip_from_world: Mat4,prev_eye: Vec4,temporal: UVec4,+ grid_min: Vec4,+ grid_dims: UVec4,}#[derive(Resource)]@@ -122,6 +129,8 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCactexture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),storage_buffer_sized(false, std::num::NonZeroU64::new(16)),+ read(4),+ read(4),),),);@@ -163,6 +172,8 @@ fn light(bufs.from = Some((key, nodes, tris));}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 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);@@ -215,12 +226,14 @@ fn light(prev_clip_from_world,prev_eye: prev_eye.extend(0.0),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,});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())),+ &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())),);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 themdiff --git a/bench/lightbench/src/scene.rs b/bench/lightbench/src/scene.rsindex 38357f6b..d1f33bcd 100644--- a/bench/lightbench/src/scene.rs+++ b/bench/lightbench/src/scene.rs@@ -61,7 +61,10 @@ pub fn spawn(mut commands: Commands, opts: Res<Opts>, mut meshes: ResMut<Assets</// 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> {+pub fn lights(n: u32, t: f32, field: bool) -> Vec<GpuLight> {+ if field {+ return field_lights(n, t);+ }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) {@@ -76,6 +79,21 @@ pub fn lights(n: u32, t: f32) -> Vec<GpuLight> {out}+/// The field's lights: scattered over it from 4 m in front of the camera to 56 m behind, each reaching 6 m and as+/// bright as the next, so more lights light more of the field (the many-small-lights case a light grid is for).+fn field_lights(n: u32, t: f32) -> Vec<GpuLight> {+ (0..n)+ .map(|i| {+ let h = |k: f32| ((i as f32 * 12.9898 + k * 78.233).sin() * 43758.547).fract().abs();+ let c = Color::hsl(h(1.0) * 360.0, 0.75, 0.6).to_linear();+ let lum = 0.2126 * c.red + 0.7152 * c.green + 0.0722 * c.blue;+ let p = 6.0 / lum.max(1e-3);+ let y = 0.4 + 2.6 * (0.5 + 0.5 * (h(2.0) * 6.28 + t * 0.7).sin());+ GpuLight { pos: [h(3.0) * 36.0 - 18.0, y, 4.0 - h(4.0) * 60.0], range: 6.0, power: [c.red * p, c.green * p, c.blue * p], radius: 0.05 }+ })+ .collect()+}+/// 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 (pos, nor, idx) = knot_data(p, q, seg, ring, r);