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 LB4: rays a lit pixel counted on the GPU and the lighting pass timed by its own timestamps
shinyobjectze70878301303
diff --git a/Cargo.lock b/Cargo.lockindex 32da2157..e23681f0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14714,6 +14714,7 @@ dependencies = ["bevy","bytemuck","meshopt",+ "wgpu",][[package]]diff --git a/bench/lightbench/Cargo.toml b/bench/lightbench/Cargo.tomlindex 451f6902..07bbd5c0 100644--- a/bench/lightbench/Cargo.toml+++ b/bench/lightbench/Cargo.toml@@ -16,3 +16,5 @@ bevy = { version = "=0.20.0", default-features = false, features = ["std", "defabytemuck = { version = "1.25", features = ["derive"] }# meshoptimizer (MIT): the simplifier and clusterizer behind the LODs and the cluster hierarchymeshopt = "0.6.2"+# Bevy's wgpu, for the lighting pass's timestamp queries+wgpu = "=30.0.1"diff --git a/bench/lightbench/src/light.wgsl b/bench/lightbench/src/light.wgslindex 6ff18e53..224838a4 100644--- a/bench/lightbench/src/light.wgsl+++ b/bench/lightbench/src/light.wgsl@@ -37,6 +37,12 @@ struct Light { pos: vec3<f32>, range: f32, power: vec3<f32>, radius: 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>;+// 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>;++var<workgroup> wg_rays: atomic<u32>;+var<workgroup> wg_px: atomic<u32>;+var<workgroup> wg_max: atomic<u32>;const PI: f32 = 3.14159265;const MAX_K: u32 = 16u;@@ -167,10 +173,10 @@ fn lum(c: vec3<f32>) -> f32 {return dot(c, vec3(0.2126, 0.7152, 0.0722));}-@compute @workgroup_size(8, 8, 1)-fn main(@builtin(global_invocation_id) id: vec3<u32>) {+// 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;+ return vec2(0u);}let px = vec2<i32>(id.xy);let depth = textureLoad(depth_tex, px, 0);@@ -178,7 +184,7 @@ fn main(@builtin(global_invocation_id) id: vec3<u32>) {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;+ return vec2(0u);}let g = textureLoad(gbuf, px, 0);let albedo = pow(unpack4x8unorm(g.r).rgb, vec3(2.2));@@ -190,15 +196,15 @@ fn main(@builtin(global_invocation_id) id: vec3<u32>) {let view = p.mode.z;if view == 1u {textureStore(out, px, vec4(n * 0.5 + 0.5, 1.0));- return;+ return vec2(0u);}if view == 2u || view == 6u {textureStore(out, px, vec4(albedo, 1.0));- return;+ return vec2(0u);}if view == 3u {textureStore(out, px, vec4(vec3(dist / 20.0), 1.0));- return;+ return vec2(0u);}seed = pcg(id.x + id.y * p.size.x + p.size.w * p.size.x * p.size.y);rays = 0u;@@ -271,11 +277,26 @@ fn main(@builtin(global_invocation_id) id: vec3<u32>) {textureStore(geo_out, px, vec4(n, dist));if view == 4u {textureStore(out, px, vec4(vec3(f32(rays) / 16.0), 1.0));- return;+ return vec2(rays, 1u);}if view == 5u {textureStore(out, px, vec4(vec3((held + 1.0) / f32(p.temporal.z)), 1.0));- return;+ return vec2(rays, 1u);}textureStore(out, px, vec4(acc * albedo / PI * p.eye.w, 1.0));+ return vec2(rays, 1u);+}++@compute @workgroup_size(8, 8, 1)+fn main(@builtin(global_invocation_id) id: vec3<u32>, @builtin(local_invocation_index) li: u32) {+ let r = shade(id);+ atomicAdd(&wg_rays, r.x);+ atomicAdd(&wg_px, r.y);+ atomicMax(&wg_max, r.x);+ workgroupBarrier();+ if li == 0u {+ atomicAdd(&stats[0], atomicLoad(&wg_rays));+ atomicAdd(&stats[1], atomicLoad(&wg_px));+ atomicMax(&stats[2], atomicLoad(&wg_max));+ }}diff --git a/bench/lightbench/src/main.rs b/bench/lightbench/src/main.rsindex 90fefaec..ff980e35 100644--- a/bench/lightbench/src/main.rs+++ b/bench/lightbench/src/main.rs@@ -153,16 +153,23 @@ fn main() {}};let mut app = App::new();+ // timing runs ask the GPU for timestamps at a pass's start and end (Apple's GPUs have no others), for its time+ let mut wgpu = bevy::render::settings::WgpuSettings::default();+ if timing() {+ wgpu.features |= bevy::render::settings::WgpuFeatures::TIMESTAMP_QUERY;+ }+ let render = bevy::render::RenderPlugin { render_creation: bevy::render::settings::RenderCreation::Automatic(Box::new(wgpu)), ..default() };if o.shot.is_some() {app.add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: None, exit_condition: ExitCondition::DontExit, ..default() })+ .set(render).disable::<bevy::winit::WinitPlugin>(),).add_plugins(bevy::app::ScheduleRunnerPlugin::run_loop(std::time::Duration::ZERO));} else {let window = Window { title: "LightBench".into(), resolution: (o.size.x, o.size.y).into(), ..default() };- app.add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(window), ..default() }));+ app.add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(window), ..default() }).set(render));}app.insert_resource(o).insert_resource(DefaultOpaqueRendererMethod::deferred())@@ -235,13 +242,14 @@ fn tick(o: Res<Opts>, time: Res<Time>, mut frame: ResMut<pass::Frame>, mut cam:};}-fn shoot(mut commands: Commands, o: Res<Opts>, counts: Res<field::Counts>, target: Option<Res<Target>>, mut done: Local<bool>, mut clock: Local<Option<(std::time::Instant, u32)>>) {+fn shoot(mut commands: Commands, o: Res<Opts>, counts: Res<field::Counts>, target: Option<Res<Target>>, mut done: Local<bool>, mut clock: Local<Option<(std::time::Instant, u32)>>, mut gpu0: Local<Option<(u64, u32)>>) {let (Some(path), Some(target)) = (o.shot.clone(), target) else { return };// counted from the lighting pass's first frame, not from startup (its pipeline compiles meanwhile)let drawn = pass::DRAWN.load(std::sync::atomic::Ordering::Relaxed);if *done || drawn < o.frames + o.bench {if drawn >= o.frames && clock.is_none() {*clock = Some((std::time::Instant::now(), drawn));+ *gpu0 = Some((pass::GPU_NS.load(std::sync::atomic::Ordering::Relaxed), pass::GPU_FRAMES.load(std::sync::atomic::Ordering::Relaxed)));}return;}@@ -253,6 +261,13 @@ fn shoot(mut commands: Commands, o: Res<Opts>, counts: Res<field::Counts>, targeif o.bench > 0 {let (t0, d0) = clock.unwrap();let ms = t0.elapsed().as_secs_f64() * 1000.0 / (drawn - d0).max(1) as f64;+ let r = |k: usize| pass::RAYS[k].load(std::sync::atomic::Ordering::Relaxed);+ println!("RAYS {:.2} a lit pixel (most {}), {} lit pixels", r(0) as f64 / r(1).max(1) as f64, r(2), r(1));+ let (ns, n) = (pass::GPU_NS.load(std::sync::atomic::Ordering::Relaxed), pass::GPU_FRAMES.load(std::sync::atomic::Ordering::Relaxed));+ let (ns0, n0) = gpu0.unwrap_or((0, 0));+ 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);}commands.spawn(Screenshot::image(target.0.clone())).observe(move |shot: On<ScreenshotCaptured>, mut exit: MessageWriter<AppExit>| {diff --git a/bench/lightbench/src/pass.rs b/bench/lightbench/src/pass.rsindex 0a64ac75..c3568c1e 100644--- a/bench/lightbench/src/pass.rs+++ b/bench/lightbench/src/pass.rs@@ -14,7 +14,7 @@ use bevy::{render::{extract_resource::{ExtractResource, ExtractResourcePlugin},render_resource::{- binding_types::{storage_buffer_read_only_sized, texture_2d, texture_depth_2d, texture_storage_2d, uniform_buffer},+ binding_types::{storage_buffer_read_only_sized, storage_buffer_sized, texture_2d, texture_depth_2d, texture_storage_2d, uniform_buffer},*,},renderer::{RenderContext, RenderDevice, RenderQueue, ViewQuery},@@ -27,6 +27,13 @@ use std::sync::{atomic::{AtomicU32, Ordering}, Arc};/// Frames the lighting pass has drawn, so a headless shot waits for its pipeline rather than for a number of frames.pub static DRAWN: AtomicU32 = AtomicU32::new(0);+/// The last frame read back (timing runs only): shadow rays, lit pixels, the most rays one pixel traced.+pub static RAYS: [AtomicU32; 3] = [AtomicU32::new(0), AtomicU32::new(0), AtomicU32::new(0)];++/// The lighting pass's GPU time (timing runs, where the GPU has timestamps): nanoseconds summed, and frames timed.+pub static GPU_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+pub static GPU_FRAMES: AtomicU32 = AtomicU32::new(0);+/// What this frame draws: the lights where they are now, and the switches.#[derive(Resource, Clone, Default, ExtractResource)]#[extract_app(RenderApp)]@@ -90,6 +97,10 @@ struct Buffers {from: Option<(usize, Buffer, Buffer)>,history: Option<(UVec2, [(Texture, TextureView); 4])>,prev: Option<(Mat4, Vec3)>,+ /// the ray counts the shader adds to, and where a timing run reads them back+ 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)>,}fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCache>) {@@ -110,6 +121,7 @@ fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCactexture_2d(TextureSampleType::Float { filterable: false }),texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),+ storage_buffer_sized(false, std::num::NonZeroU64::new(16)),),),);@@ -177,6 +189,20 @@ fn light(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));+ 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 });+ 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);+ bufs.timer = Some((set, resolve, read, queue.get_timestamp_period() as f64));+ }+ let (stats, readback) = bufs.stats.as_ref().unwrap();+ queue.write_buffer(stats, 0, &[0u8; 16]);let (_, nodes, tris) = bufs.from.as_ref().unwrap();// even frames read pair a and write pair b, odd frames the other waylet h = &bufs.history.as_ref().unwrap().1;@@ -194,15 +220,51 @@ fn light(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)),+ &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())),);- let mut pass = ctx.command_encoder().begin_compute_pass(&ComputePassDescriptor { label: Some("lightbench_light"), timestamp_writes: None });+ 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 mut pass = encoder.begin_compute_pass(&ComputePassDescriptor { label: Some("lightbench_light"), timestamp_writes: writes });pass.set_pipeline(pipeline);pass.set_bind_group(0, &group, &[]);pass.dispatch_workgroups(size.width.div_ceil(8), size.height.div_ceil(8), 1);+ drop(pass);+ encoder.copy_buffer_to_buffer(stats, 0, readback, 0, 16);+ if let Some(t) = timer {+ encoder.resolve_query_set(&t.0, 0..2, &t.1, 0);+ encoder.copy_buffer_to_buffer(&t.1, 0, &t.2, 0, 16);+ }DRAWN.fetch_add(1, Ordering::Relaxed);}-fn wait(device: Res<RenderDevice>) {+fn wait(device: Res<RenderDevice>, bufs: Res<Buffers>) {+ let _ = device.poll(PollType::wait_indefinitely());+ // the frame is done: read its ray counts back+ let Some((_, readback)) = bufs.stats.as_ref() else { return };+ let slice = readback.slice(..);+ slice.map_async(MapMode::Read, |_| {});let _ = device.poll(PollType::wait_indefinitely());+ {+ let Ok(data) = slice.get_mapped_range() else { return };+ let v: &[u32] = bytemuck::cast_slice(&data);+ for (k, n) in RAYS.iter().enumerate() {+ n.store(v[k], Ordering::Relaxed);+ }+ }+ readback.unmap();+ let Some((_, _, read, period)) = bufs.timer.as_ref() else { return };+ let slice = read.slice(..);+ slice.map_async(wgpu::MapMode::Read, |_| {});+ let _ = device.poll(PollType::wait_indefinitely());+ {+ let Ok(data) = slice.get_mapped_range() else { return };+ let t: &[u64] = bytemuck::cast_slice(&data);+ if t[1] > t[0] {+ GPU_NS.fetch_add(((t[1] - t[0]) as f64 * period) as u64, Ordering::Relaxed);+ GPU_FRAMES.fetch_add(1, Ordering::Relaxed);+ }+ }+ read.unmap();}