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 LB3b: temporal accumulation, reprojected, kept only on the same surface, reset on a camera cut; --raw
shinyobjectz0a77ecb65ed2
diff --git a/bench/lightbench/src/light.wgsl b/bench/lightbench/src/light.wgslindex 861647f1..cc31eb4f 100644--- a/bench/lightbench/src/light.wgsl+++ b/bench/lightbench/src/light.wgsl@@ -9,8 +9,15 @@ struct Params {eye: vec4<f32>,// width, height, lights, framesize: 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 (0 every light, 1 uniform, 2 weighted), K, view (0 lit, 1 normal, 2 albedo, 3 depth, 4 rays, 5 history),+ // brute forcemode: vec4<u32>,+ // the previous frame's camera, to find where a point was+ prev_clip_from_world: mat4x4<f32>,+ // xyz: the previous camera+ prev_eye: vec4<f32>,+ // raw (no history), reset (a camera cut, or the first frame), the history's length in frames, 0+ temporal: vec4<u32>,}struct Node { mn: vec3<f32>, a: u32, mx: vec3<f32>, count: u32 }@@ -24,6 +31,12 @@ struct Light { pos: vec3<f32>, range: f32, power: vec3<f32>, radius: f32 }@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>;+// the light so far at each pixel (rgb, before albedo) and how many frames it holds (a); the surface it was for+// (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>;+@group(0) @binding(10) var geo_out: texture_storage_2d<rgba16float, write>;const PI: f32 = 3.14159265;const MAX_K: u32 = 16u;@@ -161,8 +174,10 @@ fn main(@builtin(global_invocation_id) id: vec3<u32>) {}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+ // the sky (reverse Z: far is 0) keeps Bevy's clear colour, and holds no historyif depth <= 0.0 {+ textureStore(hist_out, px, vec4(0.0));+ textureStore(geo_out, px, vec4(0.0, 0.0, 0.0, -1.0));return;}let g = textureLoad(gbuf, px, 0);@@ -235,9 +250,32 @@ fn main(@builtin(global_invocation_id) id: vec3<u32>) {c /= f32(k);}}+ // the history: where this point was last frame, kept only if the same surface was there+ var held = 0.0;+ var acc = c;+ if p.temporal.x == 0u && p.temporal.y == 0u {+ let was = p.prev_clip_from_world * vec4(pos, 1.0);+ let ndc = was.xy / was.w;+ let at = vec2<i32>(floor(vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * vec2<f32>(p.size.xy)));+ if was.w > 0.0 && all(at >= vec2(0)) && all(at < vec2<i32>(p.size.xy)) {+ let geo = textureLoad(geo_in, at, 0);+ let expect = length(pos - p.prev_eye.xyz);+ if geo.w > 0.0 && abs(geo.w - expect) < 0.02 * expect + 0.01 && dot(geo.xyz, n) > 0.9 {+ let h = textureLoad(hist_in, at, 0);+ held = min(h.a, f32(p.temporal.z) - 1.0);+ acc = mix(h.rgb, c, 1.0 / (held + 1.0));+ }+ }+ }+ textureStore(hist_out, px, vec4(acc, held + 1.0));+ textureStore(geo_out, px, vec4(n, dist));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));+ if view == 5u {+ textureStore(out, px, vec4(vec3((held + 1.0) / f32(p.temporal.z)), 1.0));+ return;+ }+ textureStore(out, px, vec4(acc * albedo / PI * p.eye.w, 1.0));}diff --git a/bench/lightbench/src/main.rs b/bench/lightbench/src/main.rsindex a6c4087f..5becd035 100644--- a/bench/lightbench/src/main.rs+++ b/bench/lightbench/src/main.rs@@ -31,7 +31,12 @@ const HELP: &str = "lightbench [switches]--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)";+ --no-pillar leave out the pillar outside the view (its shadow should go with it)+ --raw no temporal accumulation: each frame's samples alone+ --history N frames the history holds at most (32)+ --camera still|orbit|cut the camera holds, circles slowly, or jumps to a second view at lit frame --cut-at (still)+ --cut-at N the lit frame --camera cut jumps on (8)+ --view history frames of history at each pixel, white when full";#[derive(Resource, Clone)]pub struct Opts {@@ -48,10 +53,15 @@ pub struct Opts {pub frames: u32,pub bench: u32,pub pillar: bool,+ pub raw: bool,+ pub history: u32,+ /// 0 still, 1 orbit, 2 cut+ pub camera: u32,+ pub cut_at: u32,}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 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, raw: false, history: 32, camera: 0, cut_at: 8 };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"));@@ -63,7 +73,7 @@ fn opts() -> Result<Opts, String> {}"--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;+ o.view = ["lit", "normal", "albedo", "depth", "rays", "history"].iter().position(|m| *m == v).ok_or("--view: lit, normal, albedo, depth, rays or history")? as u32;}"--k" => o.k = (num(val()?)? as u32).clamp(1, 16),"--lights" => o.lights = (num(val()?)? as u32).max(1),@@ -80,6 +90,13 @@ fn opts() -> Result<Opts, String> {"--frames" => o.frames = (num(val()?)? as u32).max(1),"--bench" => o.bench = num(val()?)? as u32,"--no-pillar" => o.pillar = false,+ "--raw" => o.raw = true,+ "--history" => o.history = (num(val()?)? as u32).max(1),+ "--cut-at" => o.cut_at = num(val()?)? as u32,+ "--camera" => {+ let v = val()?;+ o.camera = ["still", "orbit", "cut"].iter().position(|m| *m == v).ok_or("--camera: still, orbit or cut")? as u32;+ }"--help" | "-h" => return Err(HELP.into()),_ => return Err(format!("unknown switch {a}\n{HELP}")),}@@ -135,7 +152,7 @@ fn camera(mut commands: Commands, o: Res<Opts>, mut images: ResMut<Assets<Image>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),+ eye(&o, 0),));if o.shot.is_some() {let mut image = Image::new_target_texture(o.size.x, o.size.y, TextureFormat::Rgba8UnormSrgb, None);@@ -146,10 +163,44 @@ fn camera(mut commands: Commands, o: Res<Opts>, mut images: ResMut<Assets<Image>}}-/// 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>) {+const EYE: Vec3 = Vec3::new(0.0, 2.2, 7.0);+const LOOK: Vec3 = Vec3::new(0.0, 1.3, 0.0);++/// Where the camera is on lit frame `n`: held, circling slowly, or cut to a second view at --cut-at.+fn eye(o: &Opts, n: u32) -> Transform {+ match o.camera {+ 1 => {+ let a = n as f32 * 0.004;+ Transform::from_translation(LOOK + Quat::from_rotation_y(a) * (EYE - LOOK)).looking_at(LOOK, Vec3::Y)+ }+ 2 if n >= o.cut_at => Transform::from_xyz(4.5, 3.2, 4.5).looking_at(LOOK, Vec3::Y),+ _ => Transform::from_translation(EYE).looking_at(LOOK, Vec3::Y),+ }+}++/// The camera and the lights where they are this frame, and the switches, for the render world. A cut is a jump of+/// more than a metre or 20 degrees in one frame: the history starts again.+fn tick(o: Res<Opts>, time: Res<Time>, mut frame: ResMut<pass::Frame>, mut cam: Query<&mut Transform, With<Camera3d>>) {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 };+ let n = pass::DRAWN.load(std::sync::atomic::Ordering::Relaxed);+ let mut cut = false;+ if let Ok(mut at) = cam.single_mut() {+ let to = eye(&o, n);+ cut = at.translation.distance(to.translation) > 1.0 || at.rotation.angle_between(to.rotation) > 20f32.to_radians();+ *at = to;+ }+ *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,+ raw: o.raw,+ cut,+ history: o.history,+ };}fn shoot(mut commands: Commands, o: Res<Opts>, target: Option<Res<Target>>, mut done: Local<bool>, mut clock: Local<Option<(std::time::Instant, u32)>>) {diff --git a/bench/lightbench/src/pass.rs b/bench/lightbench/src/pass.rsindex 30f2b635..0a64ac75 100644--- a/bench/lightbench/src/pass.rs+++ b/bench/lightbench/src/pass.rs@@ -40,6 +40,12 @@ pub struct Frame {pub frame: u32,pub exposure: f32,pub brute: bool,+ /// no history (--raw)+ pub raw: bool,+ /// the camera cut this frame: the history starts again+ pub cut: bool,+ /// the history's length in frames+ pub history: u32,}pub struct LightPass;@@ -66,6 +72,9 @@ struct Params {eye: Vec4,size: UVec4,mode: UVec4,+ prev_clip_from_world: Mat4,+ prev_eye: Vec4,+ temporal: UVec4,}#[derive(Resource)]@@ -74,10 +83,13 @@ struct Pipeline {id: CachedComputePipelineId,}-/// The BVH on the GPU, made from the SceneGpu it came from (by its pointer).+/// The BVH on the GPU, made from the SceneGpu it came from (by its pointer); the history's two pairs of textures+/// (light, surface), read one frame and written the next; and the last frame's camera.#[derive(Resource, Default)]struct Buffers {from: Option<(usize, Buffer, Buffer)>,+ history: Option<(UVec2, [(Texture, TextureView); 4])>,+ prev: Option<(Mat4, Vec3)>,}fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCache>) {@@ -94,6 +106,10 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCacread(48),read(32),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::Rgba16Float, StorageTextureAccess::WriteOnly),),),);@@ -134,21 +150,51 @@ fn light(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 want = UVec2::new(size.width, size.height);+ let fresh = bufs.history.as_ref().map(|h| h.0) != Some(want);+ if fresh {+ let make = |i: usize| {+ let t = device.create_texture(&TextureDescriptor {+ label: Some(["lightbench_hist_a", "lightbench_geo_a", "lightbench_hist_b", "lightbench_geo_b"][i]),+ size: Extent3d { width: want.x, height: want.y, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: TextureDimension::D2,+ format: TextureFormat::Rgba16Float,+ usage: TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING,+ view_formats: &[],+ });+ let v = t.create_view(&TextureViewDescriptor::default());+ (t, v)+ };+ bufs.history = Some((want, [make(0), make(1), make(2), make(3)]));+ }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();+ let eye = extracted.world_from_view.translation();+ let (prev_clip_from_world, prev_eye) = bufs.prev.unwrap_or((clip_from_world, eye));+ let reset = fresh || frame.cut || bufs.prev.is_none();+ bufs.prev = Some((clip_from_world, eye));+ let (_, nodes, tris) = bufs.from.as_ref().unwrap();+ // even frames read pair a and write pair b, odd frames the other way+ let h = &bufs.history.as_ref().unwrap().1;+ let (r, w) = if frame.frame % 2 == 0 { (0, 2) } else { (2, 0) };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),+ 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),});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())),+ &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)),);let mut pass = ctx.command_encoder().begin_compute_pass(&ComputePassDescriptor { label: Some("lightbench_light"), timestamp_writes: None });pass.set_pipeline(pipeline);