1use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
10use std::sync::{Arc, Mutex};
11
12const SAMPLE_EVERY: u64 = 8;
14const RING: usize = 4;
16const RESOLVED_BYTES: u64 = 3 * 8;
17
18#[derive(Clone, Copy, Debug, Default, PartialEq)]
20pub struct FrameGpuTimes {
21 pub render_ms: f64,
23 pub pack_ms: f64,
25 pub sampled_frames: u64,
27 pub flat_frames: u64,
30 pub timed_frames: u64,
32 pub unread_frames: u64,
34}
35
36impl FrameGpuTimes {
37 #[must_use]
39 #[allow(clippy::cast_precision_loss, reason = "a frame count far below 2^52")]
40 pub fn render_ms_per_frame(&self) -> Option<f64> {
41 (self.sampled_frames > 0).then(|| self.render_ms / self.sampled_frames as f64)
42 }
43
44 #[must_use]
46 #[allow(clippy::cast_precision_loss, reason = "a frame count far below 2^52")]
47 pub fn pack_ms_per_frame(&self) -> Option<f64> {
48 (self.sampled_frames > 0).then(|| self.pack_ms / self.sampled_frames as f64)
49 }
50}
51
52#[derive(Debug)]
53struct Slot {
54 resolve: wgpu::Buffer,
55 readback: wgpu::Buffer,
56 pending: AtomicBool,
57 mapped: Arc<AtomicU8>,
59}
60
61const MAP_WAITING: u8 = 0;
62const MAP_DONE: u8 = 1;
63const MAP_FAILED: u8 = 2;
64
65#[derive(Debug)]
66pub(crate) struct FrameGpuTimer {
67 queries: wgpu::QuerySet,
68 slots: Vec<Slot>,
69 frames: AtomicU64,
70 timed_since_take: AtomicU64,
71 period: f32,
73 totals: Mutex<FrameGpuTimes>,
74}
75
76pub(crate) struct FrameSample<'a> {
77 timer: &'a FrameGpuTimer,
78 slot: usize,
79}
80
81impl FrameGpuTimer {
82 pub(crate) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
84 let queries = device.create_query_set(&wgpu::QuerySetDescriptor {
85 label: Some("alpha2 frame GPU time"),
86 ty: wgpu::QueryType::Timestamp,
87 count: 3,
88 });
89 let slots = (0..RING)
90 .map(|_| Slot {
91 resolve: device.create_buffer(&wgpu::BufferDescriptor {
92 label: Some("alpha2 frame GPU time resolve"),
93 size: RESOLVED_BYTES,
94 usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
95 mapped_at_creation: false,
96 }),
97 readback: device.create_buffer(&wgpu::BufferDescriptor {
98 label: Some("alpha2 frame GPU time readback"),
99 size: RESOLVED_BYTES,
100 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
101 mapped_at_creation: false,
102 }),
103 pending: AtomicBool::new(false),
104 mapped: Arc::new(AtomicU8::new(MAP_WAITING)),
105 })
106 .collect();
107 Self {
108 queries,
109 slots,
110 frames: AtomicU64::new(0),
111 timed_since_take: AtomicU64::new(0),
112 period: queue.get_timestamp_period(),
113 totals: Mutex::default(),
114 }
115 }
116
117 #[allow(
118 clippy::cast_precision_loss,
119 reason = "a frame's span in timestamp ticks, far below 2^52"
120 )]
121 fn collect(&self) {
122 let mut totals = self
123 .totals
124 .lock()
125 .unwrap_or_else(std::sync::PoisonError::into_inner);
126 for slot in &self.slots {
127 if !slot.pending.load(Ordering::Acquire) {
128 continue;
129 }
130 match slot.mapped.load(Ordering::Acquire) {
131 MAP_WAITING => continue,
132 MAP_FAILED => {
134 slot.mapped.store(MAP_WAITING, Ordering::Release);
135 slot.pending.store(false, Ordering::Release);
136 continue;
137 }
138 _ => {}
139 }
140 if let Ok(bytes) = slot.readback.slice(..).get_mapped_range() {
141 let tick = |at: usize| {
142 let mut word = [0; 8];
143 word.copy_from_slice(&bytes[at * 8..at * 8 + 8]);
144 u64::from_le_bytes(word)
145 };
146 let (start, graph_end, pack_end) = (tick(0), tick(1), tick(2));
147 if start == pack_end {
149 totals.flat_frames += 1;
150 } else if start <= graph_end && graph_end <= pack_end {
151 let milliseconds =
152 |ticks: u64| ticks as f64 * f64::from(self.period) / 1_000_000.0;
153 totals.render_ms += milliseconds(graph_end - start);
154 totals.pack_ms += milliseconds(pack_end - graph_end);
155 totals.sampled_frames += 1;
156 }
157 }
158 slot.readback.unmap();
159 slot.mapped.store(MAP_WAITING, Ordering::Release);
160 slot.pending.store(false, Ordering::Release);
161 }
162 }
163
164 pub(crate) fn begin(&self) -> Option<FrameSample<'_>> {
166 let frame = self.frames.fetch_add(1, Ordering::Relaxed);
167 self.timed_since_take.fetch_add(1, Ordering::Relaxed);
168 if !frame.is_multiple_of(SAMPLE_EVERY) {
169 return None;
170 }
171 self.collect();
172 let slot = self
173 .slots
174 .iter()
175 .position(|slot| !slot.pending.load(Ordering::Acquire))?;
176 Some(FrameSample { timer: self, slot })
177 }
178
179 pub(crate) fn take(&self) -> FrameGpuTimes {
181 self.collect();
182 let mut times = std::mem::take(
183 &mut *self
184 .totals
185 .lock()
186 .unwrap_or_else(std::sync::PoisonError::into_inner),
187 );
188 times.timed_frames = self.timed_since_take.swap(0, Ordering::Relaxed);
189 let unread = self
190 .slots
191 .iter()
192 .filter(|slot| slot.pending.load(Ordering::Acquire))
193 .count();
194 times.unread_frames = u64::try_from(unread).unwrap_or(u64::MAX);
195 times
196 }
197}
198
199impl FrameSample<'_> {
200 fn mark(&self, encoder: &mut wgpu::CommandEncoder, index: u32) {
203 let writes = if index == 0 {
204 wgpu::ComputePassTimestampWrites {
205 query_set: &self.timer.queries,
206 beginning_of_pass_write_index: None,
207 end_of_pass_write_index: Some(index),
208 }
209 } else {
210 wgpu::ComputePassTimestampWrites {
211 query_set: &self.timer.queries,
212 beginning_of_pass_write_index: Some(index),
213 end_of_pass_write_index: None,
214 }
215 };
216 drop(encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
217 label: Some("alpha2 frame GPU time mark"),
218 timestamp_writes: Some(writes),
219 }));
220 }
221
222 pub(crate) fn graph_start(&self, encoder: &mut wgpu::CommandEncoder) {
223 self.mark(encoder, 0);
224 }
225
226 pub(crate) fn graph_end(&self, encoder: &mut wgpu::CommandEncoder) {
227 self.mark(encoder, 1);
228 }
229
230 pub(crate) fn pack_end(&self, encoder: &mut wgpu::CommandEncoder) {
232 self.mark(encoder, 2);
233 let slot = &self.timer.slots[self.slot];
234 encoder.resolve_query_set(&self.timer.queries, 0..3, &slot.resolve, 0);
235 encoder.copy_buffer_to_buffer(&slot.resolve, 0, &slot.readback, 0, RESOLVED_BYTES);
236 }
237
238 pub(crate) fn submitted(self, gpu: &alpha2_gpu::GpuContext) {
240 let slot = &self.timer.slots[self.slot];
241 slot.pending.store(true, Ordering::Release);
242 let mapped = Arc::clone(&slot.mapped);
243 gpu.map_async(
244 &slot.readback.slice(..),
245 wgpu::MapMode::Read,
246 move |result| {
247 mapped.store(
248 if result.is_ok() { MAP_DONE } else { MAP_FAILED },
249 Ordering::Release,
250 );
251 },
252 );
253 }
254}