use core::fmt::Write as _;
use crcbl_hal::{
CommandEncoder, Device, Features, PassTimestampWrites, QueryKind, QuerySetDesc, QuerySetHandle,
};
use crcbl_ui::debug::{DebugModule, DebugSection};
use crate::graph::{CompiledPass, PassKind};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PassTiming {
pub label: String,
pub gpu_nanos: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FrameTimings {
pub passes: Vec<PassTiming>,
pub frame: u64,
pub elapsed_nanos: Option<u64>,
}
impl FrameTimings {
#[must_use]
pub fn total_nanos(&self) -> u64 {
self.passes.iter().map(|pass| pass.gpu_nanos).sum()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.passes.is_empty()
}
#[must_use]
pub fn report(&self) -> String {
if self.passes.is_empty() {
return "frame timing: no GPU timestamps (the device has none)\n".to_string();
}
let mut out = String::new();
let total = self.total_nanos();
let _ = writeln!(
out,
"frame timing (frame {}): {} pass(es), {:.3} ms sum of pass spans",
self.frame,
self.passes.len(),
total as f64 / 1.0e6
);
if let Some(elapsed) = self.elapsed_nanos {
let _ = writeln!(
out,
" measured GPU elapsed: {:.3} ms",
elapsed as f64 / 1.0e6
);
}
for pass in &self.passes {
let share = if total == 0 {
0.0
} else {
pass.gpu_nanos as f64 * 100.0 / total as f64
};
let _ = writeln!(
out,
" {:<24} {:>9.3} ms {:>5.1}%",
pass.label,
pass.gpu_nanos as f64 / 1.0e6,
share
);
}
out
}
}
impl DebugModule for FrameTimings {
fn debug_section(&self, out: &mut DebugSection) {
out.set_title("gpu");
if self.passes.is_empty() {
out.row_str("timings", "pending");
return;
}
for pass in &self.passes {
out.row(
&pass.label,
format_args!("{:.3} ms", pass.gpu_nanos as f64 / 1.0e6),
);
}
out.row(
"span sum",
format_args!("{:.3} ms", self.total_nanos() as f64 / 1.0e6),
);
if let Some(elapsed) = self.elapsed_nanos {
out.row("elapsed", format_args!("{:.3} ms", elapsed as f64 / 1.0e6));
}
out.row("frame", format_args!("{}", self.frame));
}
}
#[derive(Debug)]
struct Slot {
set: QuerySetHandle,
labels: Vec<String>,
frame: u64,
}
#[derive(Debug)]
pub struct PassTimers {
slots: Vec<Slot>,
current: usize,
pairs: Vec<Option<u32>>,
capacity: u32,
frames: u64,
latest: FrameTimings,
warned: bool,
}
impl PassTimers {
#[must_use]
pub fn new(device: &dyn Device, frames_in_flight: usize, max_passes: u32) -> Option<Self> {
if !device.caps().features.contains(Features::TIMESTAMP_QUERY) {
crcbl_core::log::debug!(
"graph: no TIMESTAMP_QUERY on this device; per-pass timing is off"
);
return None;
}
let Some(query_count) = max_passes.checked_mul(2) else {
crcbl_core::log::debug!(
"graph: {max_passes} passes needs {} timestamp queries, more than a u32 index \
holds; per-pass timing is off",
u64::from(max_passes) * 2
);
return None;
};
let count = frames_in_flight + 1;
let mut slots = Vec::with_capacity(count);
for index in 0..count {
match device.create_query_set(&QuerySetDesc {
label: Some("graph pass timers"),
kind: QueryKind::Timestamp,
count: query_count,
}) {
Ok(set) => slots.push(Slot {
set,
labels: Vec::new(),
frame: 0,
}),
Err(error) => {
crcbl_core::log::debug!(
"graph: timestamp set {index} refused ({error}); timing is off"
);
for slot in &slots {
device.destroy_query_set(slot.set);
}
return None;
}
}
}
Some(Self {
slots,
current: 0,
pairs: Vec::new(),
capacity: max_passes,
frames: 0,
latest: FrameTimings::default(),
warned: false,
})
}
#[must_use]
pub fn latest(&self) -> &FrameTimings {
&self.latest
}
#[must_use]
pub const fn capacity(&self) -> u32 {
self.capacity
}
pub(crate) fn begin_frame(
&mut self,
device: &dyn Device,
encoder: &mut dyn CommandEncoder,
passes: &[CompiledPass<'_>],
) {
self.frames += 1;
self.current = (self.current + 1) % self.slots.len();
self.resolve(device);
let timeable = passes
.iter()
.filter(|pass| pass.kind() != PassKind::Copy)
.count();
let used = timeable.min(self.capacity as usize);
if timeable > used && !self.warned {
self.warned = true;
crcbl_core::log::warn!(
"graph: {timeable} timed passes but timers hold {}; the last {} are untimed (said \
once)",
self.capacity,
timeable - used
);
}
let slot = &mut self.slots[self.current];
slot.labels.clear();
self.pairs.clear();
for pass in passes {
let pair = if pass.kind() == PassKind::Copy {
None
} else {
let next = u32::try_from(slot.labels.len()).unwrap_or(u32::MAX);
(next < self.capacity).then(|| {
slot.labels.push(pass.label().to_string());
next
})
};
self.pairs.push(pair);
}
slot.frame = self.frames;
encoder.reset_query_set(slot.set, 0..self.capacity.saturating_mul(2));
}
pub(crate) fn pass_writes(&self, index: usize) -> Option<PassTimestampWrites> {
let pair = *self.pairs.get(index)?;
pair.map(|pair| PassTimestampWrites {
set: self.slots[self.current].set,
beginning_of_pass: pair * 2,
end_of_pass: pair * 2 + 1,
})
}
fn resolve(&mut self, device: &dyn Device) {
let slot = &self.slots[self.current];
if slot.labels.is_empty() {
return;
}
let mut nanos = vec![0u64; slot.labels.len() * 2];
if let Err(error) = device.query_results(slot.set, 0, &mut nanos) {
crcbl_core::log::debug!(
"graph: timestamp read failed ({error}); dropping this frame's timing"
);
return;
}
let passes = slot
.labels
.iter()
.enumerate()
.map(|(index, label)| {
PassTiming {
label: label.clone(),
gpu_nanos: nanos[index * 2 + 1].saturating_sub(nanos[index * 2]),
}
})
.collect();
self.latest = FrameTimings {
passes,
frame: slot.frame,
elapsed_nanos: measured_span(&nanos),
};
}
pub fn destroy(&mut self, device: &dyn Device) {
for slot in &self.slots {
device.destroy_query_set(slot.set);
}
self.slots.clear();
}
}
fn measured_span(nanos: &[u64]) -> Option<u64> {
if nanos.is_empty() || !nanos.len().is_multiple_of(2) {
return None;
}
let mut first = u64::MAX;
let mut last = 0;
for pair in nanos.as_chunks::<2>().0 {
let (start, end) = (pair[0], pair[1]);
if start == 0 || end < start {
return None;
}
first = first.min(start);
last = last.max(end);
}
Some(last - first)
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
#[test]
fn overlapping_passes_measure_the_outer_interval_not_their_sum() {
assert_eq!(measured_span(&[100, 500, 200, 900]), Some(800));
assert_eq!(measured_span(&[100, 200, 400, 700]), Some(600));
assert_eq!(measured_span(&[500, 500]), Some(0));
}
#[test]
fn a_missing_or_backwards_timestamp_cannot_supply_a_budget() {
for values in [
&[][..],
&[100][..],
&[0, 200][..],
&[100, 0][..],
&[200, 100][..],
] {
assert_eq!(measured_span(values), None);
}
assert_eq!(measured_span(&[100, 200, 0, 400]), None);
}
#[test]
fn an_empty_report_says_so_rather_than_printing_nothing() {
let timings = FrameTimings::default();
assert!(timings.is_empty());
assert_eq!(timings.total_nanos(), 0);
assert!(timings.report().contains("no GPU timestamps"));
}
#[test]
fn the_report_lists_every_pass_with_its_share() {
let timings = FrameTimings {
elapsed_nanos: None,
frame: 42,
passes: vec![
PassTiming {
label: "forward".to_string(),
gpu_nanos: 3_000_000,
},
PassTiming {
label: "tonemap".to_string(),
gpu_nanos: 1_000_000,
},
],
};
assert_eq!(timings.total_nanos(), 4_000_000);
let report = timings.report();
assert!(report.contains("frame 42"), "{report}");
assert!(report.contains("forward"), "{report}");
assert!(report.contains("tonemap"), "{report}");
assert!(report.contains("4.000 ms"), "{report}");
assert!(
report.contains("75.0%"),
"the shares must be there: {report}"
);
assert!(report.contains("25.0%"), "{report}");
}
#[test]
fn a_zero_length_frame_reports_zero_shares_rather_than_nan() {
let timings = FrameTimings {
elapsed_nanos: None,
frame: 1,
passes: vec![PassTiming {
label: "clear".to_string(),
gpu_nanos: 0,
}],
};
let report = timings.report();
assert!(!report.contains("NaN"), "{report}");
assert!(report.contains("0.0%"), "{report}");
}
#[test]
fn the_debug_section_carries_the_passes_the_renderer_reported() {
use crcbl_ui::debug::{DebugOverlay, DebugRow};
use crcbl_ui::draw_list::{DrawCommand, DrawList};
use crcbl_ui::text::FontAtlas;
use glam::Vec2;
let timings = FrameTimings {
elapsed_nanos: None,
frame: 7,
passes: vec![
PassTiming {
label: "sprites".to_string(),
gpu_nanos: 2_500_000,
},
PassTiming {
label: "ui".to_string(),
gpu_nanos: 250_000,
},
],
};
let mut section = DebugSection::default();
timings.debug_section(&mut section);
assert_eq!(section.title(), "gpu");
let rows: Vec<(&str, &str)> = section
.rows()
.iter()
.map(|DebugRow { label, value }| (label.as_str(), value.as_str()))
.collect();
assert_eq!(
rows,
[
("sprites", "2.500 ms"),
("ui", "0.250 ms"),
("span sum", "2.750 ms"),
("frame", "7"),
],
);
let mut overlay = DebugOverlay::with_visible(true);
overlay.record(core::time::Duration::from_millis(16));
overlay.begin_frame();
overlay.add(&timings);
let mut dl = DrawList::new();
overlay.render(&mut dl, Vec2::new(1280.0, 720.0), &FontAtlas::built_in());
let drawn: Vec<&str> = dl
.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Text { text, .. } => Some(text.as_str()),
_ => None,
})
.collect();
assert_eq!(drawn.first(), Some(&"frame"), "{drawn:?}");
let gpu = drawn
.iter()
.position(|text| *text == "gpu")
.expect("the gpu section is drawn");
assert_eq!(
&drawn[gpu..],
[
"gpu", "sprites", "2.500 ms", "ui", "0.250 ms", "span sum", "2.750 ms", "frame",
"7",
],
);
}
#[test]
fn a_latent_report_renders_as_pending_rather_than_zero() {
let mut section = DebugSection::default();
FrameTimings::default().debug_section(&mut section);
assert_eq!(section.title(), "gpu");
assert_eq!(section.rows().len(), 1);
assert_eq!(section.rows()[0].value, "pending");
}
#[test]
fn a_device_without_timestamps_gets_no_timers_and_no_error() {
use crcbl_hal::null::NullInstance;
use crcbl_hal::{DeviceDesc, Instance};
let instance = NullInstance::portable();
let adapter = instance.adapters().remove(0);
let device = instance
.create_device(&DeviceDesc {
label: None,
adapter: adapter.id,
required_features: Features::empty(),
optional_features: Features::empty(),
compatible_surface: None,
})
.expect("the null backend always opens");
assert!(
!device.caps().features.contains(Features::TIMESTAMP_QUERY),
"this test is only meaningful against a device that has none"
);
assert!(
PassTimers::new(device.as_ref(), 2, 8).is_none(),
"timers must decline rather than fail"
);
}
}