Skip to main content

wde_wgpu/passes/
timestamps.rs

1//! GPU timestamps written between the commands of a command buffer, read back without blocking.
2use std::{
3    collections::VecDeque,
4    sync::mpsc::{self, TryRecvError}
5};
6
7use crate::{command_buffer::CommandBuffer, instance::RenderInstanceData, memory::GpuAllocation};
8
9/// Resolved frames waiting to be read back, beyond which new frames are dropped.
10const MAX_PENDING: usize = 4;
11
12/// Device features needed by [`GpuTimestamps`].
13pub fn timestamp_features() -> wgpu::Features {
14    wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS
15}
16
17/// Timestamps written into a command buffer with [`GpuTimestamps::write`], resolved at the end of each frame with
18/// [`GpuTimestamps::resolve`] and read back a few frames later with [`GpuTimestamps::collect`]. Each frame carries
19/// a `T` describing what its timestamps measure.
20pub struct GpuTimestamps<T> {
21    query_set: wgpu::QuerySet,
22    resolve_buffer: wgpu::Buffer,
23    _resolve_memory: GpuAllocation,
24    capacity: u32,
25    /// Timestamps written in the current frame.
26    count: u32,
27    /// Nanoseconds per tick.
28    period: f64,
29    free: Vec<(wgpu::Buffer, GpuAllocation)>,
30    pending: VecDeque<PendingFrame<T>>
31}
32
33struct PendingFrame<T> {
34    buffer: wgpu::Buffer,
35    memory: GpuAllocation,
36    count: u32,
37    data: T,
38    /// Set once the buffer mapping is requested.
39    mapped: Option<mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>>
40}
41
42impl<T> GpuTimestamps<T> {
43    /// `None` if the device lacks the [`timestamp_features`].
44    pub fn new(instance: &RenderInstanceData, label: &str, capacity: u32) -> Option<Self> {
45        if !instance.device.features().contains(timestamp_features()) || capacity == 0 {
46            return None;
47        }
48        let query_set = instance.device.create_query_set(&wgpu::QuerySetDescriptor {
49            label: Some(label),
50            ty: wgpu::QueryType::Timestamp,
51            count: capacity
52        });
53        let resolve_buffer = instance.device.create_buffer(&wgpu::BufferDescriptor {
54            label: Some(&format!("{label}-resolve")),
55            size: Self::size(capacity),
56            usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
57            mapped_at_creation: false
58        });
59        Some(Self {
60            query_set,
61            _resolve_memory: GpuAllocation::buffer(&format!("{label}-resolve"), &resolve_buffer),
62            resolve_buffer,
63            capacity,
64            count: 0,
65            period: instance.queue.get_timestamp_period() as f64,
66            free: vec![],
67            pending: VecDeque::new()
68        })
69    }
70
71    fn size(count: u32) -> u64 {
72        count as u64 * wgpu::QUERY_SIZE as u64
73    }
74
75    /// Writes a timestamp once the previous commands are done. Returns its index in the frame, or `None` once the
76    /// capacity is reached.
77    pub fn write(&mut self, command_buffer: &mut CommandBuffer) -> Option<u32> {
78        if self.count >= self.capacity {
79            return None;
80        }
81        command_buffer
82            .encoder()
83            .write_timestamp(&self.query_set, self.count);
84        self.count += 1;
85        Some(self.count - 1)
86    }
87
88    /// Copies the timestamps of the frame to be read back, with its `data`. Call [`GpuTimestamps::map`] once the
89    /// command buffer is submitted.
90    pub fn resolve(
91        &mut self,
92        instance: &RenderInstanceData,
93        command_buffer: &mut CommandBuffer,
94        data: T
95    ) {
96        let count = std::mem::take(&mut self.count);
97        if count == 0 || self.pending.len() >= MAX_PENDING {
98            return;
99        }
100        let (buffer, memory) = self.free.pop().unwrap_or_else(|| {
101            let buffer = instance.device.create_buffer(&wgpu::BufferDescriptor {
102                label: Some("timestamps-readback"),
103                size: Self::size(self.capacity),
104                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
105                mapped_at_creation: false
106            });
107            let memory = GpuAllocation::buffer("timestamps-readback", &buffer);
108            (buffer, memory)
109        });
110        let encoder = command_buffer.encoder();
111        encoder.resolve_query_set(&self.query_set, 0..count, &self.resolve_buffer, 0);
112        encoder.copy_buffer_to_buffer(&self.resolve_buffer, 0, &buffer, 0, Self::size(count));
113        self.pending.push_back(PendingFrame {
114            buffer,
115            memory,
116            count,
117            data,
118            mapped: None
119        });
120    }
121
122    /// Starts reading back the resolved frames. Call it after submitting their command buffer.
123    pub fn map(&mut self) {
124        for frame in self.pending.iter_mut().filter(|f| f.mapped.is_none()) {
125            let (sender, receiver) = mpsc::channel();
126            frame.buffer.slice(..Self::size(frame.count)).map_async(
127                wgpu::MapMode::Read,
128                move |result| {
129                    let _ = sender.send(result);
130                }
131            );
132            frame.mapped = Some(receiver);
133        }
134    }
135
136    /// Frames read back since the last call, oldest first, with their timestamps in nanoseconds. Polls the device
137    /// without blocking.
138    pub fn collect(&mut self, instance: &RenderInstanceData) -> Vec<(T, Vec<u64>)> {
139        instance.poll_non_blocking();
140        let mut frames = vec![];
141        while let Some(result) = self
142            .pending
143            .front()
144            .and_then(|f| f.mapped.as_ref())
145            .map(|r| r.try_recv())
146        {
147            if result == Err(TryRecvError::Empty) {
148                break;
149            }
150            let frame = self.pending.pop_front().unwrap();
151            if result != Ok(Ok(())) {
152                continue;
153            }
154            let slice = frame.buffer.slice(..Self::size(frame.count));
155            let timestamps = slice
156                .get_mapped_range()
157                .expect("Mapped range out of bounds")
158                .as_chunks::<{ wgpu::QUERY_SIZE as usize }>()
159                .0
160                .iter()
161                .map(|t| (u64::from_ne_bytes(*t) as f64 * self.period) as u64)
162                .collect();
163            frame.buffer.unmap();
164            frames.push((frame.data, timestamps));
165            self.free.push((frame.buffer, frame.memory));
166        }
167        frames
168    }
169}