From b6345fc61d640de07afc9a2f3695039e02ac3201 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 02:56:31 +0100 Subject: [PATCH] Shader packs, clean room 19: GPU time of each pass (developers' aid) HORIZON_SHADER_PACK_TIMING=1 puts timestamps around every pass of a shader pack, one frame in 30, and logs each pass's median every 30 timed frames. The frame after a timed one waits for the GPU before reading them (Metal resolves timestamps without waiting for the passes that write them). Passes overlap on tiled GPUs, so a pass is charged from the later of its beginning and the previous pass's end. This is what attributes a pack's cost to its own programs or to ours when the machine is shared and FPS comparisons are noisy. Clean-room: Horizon's own tooling, no spec section; no other loader's code read. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 1 + crates/horizon-client/src/gfx/pack_post.rs | 11 ++ crates/horizon-client/src/gfx/pack_timing.rs | 147 +++++++++++++++++++ 3 files changed, 159 insertions(+) create mode 100644 crates/horizon-client/src/gfx/pack_timing.rs diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 9a7356d6e..f0987dddd 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -70,6 +70,7 @@ mod lod; mod occlusion; mod pack_atlas; mod pack_post; +mod pack_timing; pub mod pack_uniforms; mod page_runs; pub mod panorama; diff --git a/crates/horizon-client/src/gfx/pack_post.rs b/crates/horizon-client/src/gfx/pack_post.rs index b96da2599..739688784 100644 --- a/crates/horizon-client/src/gfx/pack_post.rs +++ b/crates/horizon-client/src/gfx/pack_post.rs @@ -168,6 +168,8 @@ pub struct PackPost { water: Option, /// A program after translucent terrain reads `depthtex1`: it is copied before water. depth1: bool, + /// `HORIZON_SHADER_PACK_TIMING`: GPU time of each pass, in the log. + timing: Option, /// `shaders.properties`' custom uniforms, after the frame's in `uniforms.values`. custom: horizon_shaders::Custom, atlas: Option, @@ -853,6 +855,7 @@ impl PackPost { terrain, water, depth1, + timing: super::pack_timing::PassTiming::new(device, queue), custom, atlas: world.atlas.as_ref().map(|a| a.0.clone()), lightmap: world.lightmap, @@ -1053,9 +1056,11 @@ impl PackPost { .and_then(|t| attach(&t[usize::from(self.main & 1 << buffer != 0)], load)); } { + let timestamp_writes = self.timing.as_mut().and_then(|t| t.writes(&pass.name)); let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some(&pass.name), color_attachments: &attachments, + timestamp_writes, depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { view: &targets.depth, depth_ops: Some(wgpu::Operations { @@ -1164,6 +1169,9 @@ impl PackPost { terrain: &mut dyn FnMut(&mut wgpu::RenderPass<'_>, bool), ) { self.resize(device, size); + if let Some(t) = &mut self.timing { + t.begin(device, queue); + } self.uniforms.update(frame, inputs, size); self.uniforms.eval_custom(&mut self.custom); let Some(targets) = &self.targets else { return }; @@ -1214,6 +1222,7 @@ impl PackPost { encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Shader pack clear"), color_attachments: &attachments, + timestamp_writes: self.timing.as_mut().and_then(|t| t.writes("clear")), ..Default::default() }); } @@ -1250,6 +1259,7 @@ impl PackPost { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Shader pack world"), color_attachments: &attachments, + timestamp_writes: self.timing.as_mut().and_then(|t| t.writes("world")), depth_stencil_attachment: self.blit_depth.then_some( wgpu::RenderPassDepthStencilAttachment { view: &targets.depth, @@ -1314,6 +1324,7 @@ impl PackPost { let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some(&pass.name), color_attachments: &attachments, + timestamp_writes: self.timing.as_mut().and_then(|t| t.writes(&pass.name)), ..Default::default() }); rp.set_pipeline(&pass.pipeline); diff --git a/crates/horizon-client/src/gfx/pack_timing.rs b/crates/horizon-client/src/gfx/pack_timing.rs new file mode 100644 index 000000000..61ab721e5 --- /dev/null +++ b/crates/horizon-client/src/gfx/pack_timing.rs @@ -0,0 +1,147 @@ +//! Developers' aid: `HORIZON_SHADER_PACK_TIMING=1` times every pass of a shader pack on the +//! GPU, one frame in `EVERY`, and logs each pass's median every `REPORT` timed frames. The +//! frame after a timed one waits for the GPU before reading the timestamps (Metal resolves +//! them without waiting for the passes that write them), so timing slows the game. + +const EVERY: u32 = 30; +const REPORT: usize = 30; +/// Passes timed per frame at most (two timestamps each). +const CAPACITY: u32 = 64; + +pub(super) struct PassTiming { + queries: wgpu::QuerySet, + resolve: wgpu::Buffer, + read: wgpu::Buffer, + period_ns: f32, + frame: u32, + /// The passes timed in the frame being recorded or waiting to be read, in order. + names: Vec, + timed: bool, + samples: Vec<(String, Vec)>, + reports: usize, +} + +impl PassTiming { + pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option { + if std::env::var_os("HORIZON_SHADER_PACK_TIMING").is_none() + || !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) + { + return None; + } + let size = u64::from(CAPACITY) * 2 * 8; + let buffer = |label, usage| { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size, + usage, + mapped_at_creation: false, + }) + }; + Some(Self { + queries: device.create_query_set(&wgpu::QuerySetDescriptor { + label: Some("Shader pack pass timing"), + ty: wgpu::QueryType::Timestamp, + count: CAPACITY * 2, + }), + resolve: buffer( + "Shader pack timing resolve", + wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, + ), + read: buffer( + "Shader pack timing read", + wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + ), + period_ns: queue.get_timestamp_period(), + frame: 0, + names: Vec::new(), + timed: false, + samples: Vec::new(), + reports: 0, + }) + } + + /// At the start of a frame: reads the last timed frame's passes, and decides whether this + /// one is timed. + pub fn begin(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) { + if self.timed && !self.names.is_empty() { + self.collect(device, queue); + } + self.names.clear(); + self.frame += 1; + self.timed = self.frame.is_multiple_of(EVERY); + } + + /// Timestamp writes for the pass `name`, in a timed frame. + pub fn writes(&mut self, name: &str) -> Option> { + let i = self.names.len() as u32; + if !self.timed || i >= CAPACITY { + return None; + } + self.names.push(name.to_owned()); + Some(wgpu::RenderPassTimestampWrites { + query_set: &self.queries, + beginning_of_pass_write_index: Some(2 * i), + end_of_pass_write_index: Some(2 * i + 1), + }) + } + + fn collect(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) { + // The timed frame first, then the resolve, so every timestamp is written. + _ = device.poll(wgpu::PollType::wait_indefinitely()); + let count = self.names.len() as u32 * 2; + let bytes = u64::from(count) * 8; + let mut encoder = device.create_command_encoder(&Default::default()); + encoder.resolve_query_set(&self.queries, 0..count, &self.resolve, 0); + encoder.copy_buffer_to_buffer(&self.resolve, 0, &self.read, 0, bytes); + queue.submit([encoder.finish()]); + let slice = self.read.slice(..bytes); + slice.map_async(wgpu::MapMode::Read, |_| {}); + _ = device.poll(wgpu::PollType::wait_indefinitely()); + let Ok(data) = slice.get_mapped_range() else { + return; + }; + let stamps: Vec = data + .as_chunks::<8>() + .0 + .iter() + .map(|b| u64::from_le_bytes(*b)) + .collect(); + drop(data); + self.read.unmap(); + // Passes overlap on tiled GPUs (a pass begins before the one before it ends): a pass + // costs the time from the later of its beginning and the previous pass's end. + let mut previous_end = 0; + for (name, pair) in self.names.iter().zip(stamps.as_chunks::<2>().0) { + if pair[0] == 0 || pair[1] < pair[0] { + continue; + } + let from = pair[0].max(previous_end).min(pair[1]); + previous_end = pair[1]; + let ms = (pair[1] - from) as f32 * self.period_ns / 1e6; + match self.samples.iter_mut().find(|s| s.0 == *name) { + Some(s) => s.1.push(ms), + None => self.samples.push((name.clone(), vec![ms])), + } + } + self.reports += 1; + if self.reports.is_multiple_of(REPORT) { + self.report(); + } + } + + fn report(&mut self) { + let mut total = 0.0; + let mut parts = Vec::new(); + for (name, v) in &mut self.samples { + v.sort_by(f32::total_cmp); + let median = v[v.len() / 2]; + total += median; + parts.push(format!("{name} {median:.3}")); + v.clear(); + } + log::info!( + "shader pack GPU time per pass (median ms of {REPORT} frames): {} = {total:.3}", + parts.join(", ") + ); + } +}