Skip to main content

sim_logic/platform/desktop/
timing.rs

1//! Bounded asynchronous GPU samples correlated to the logical frame that submitted them.
2
3use sim_engine::{
4    GpuTimingBatch, GpuTimingId, GpuTimingSample, GpuTimingSource, GpuTimingStatistics,
5    WgpuRenderer,
6};
7
8const MAX_PENDING: usize = 16;
9const MAX_COLLECTED: usize = 8;
10
11/// One completed GPU pass with its originating logical frame and device generation.
12///
13/// Composition and retained 3D remain separate sources. This is hardware pass
14/// time, not CPU work, frame latency, acquisition or confirmed monitor scanout.
15#[derive(Debug, Clone, Copy)]
16pub struct DesktopGpuTimingSample {
17    logic_frame: u64,
18    generation: u64,
19    sample: GpuTimingSample,
20}
21
22impl DesktopGpuTimingSample {
23    /// Returns the shared runner frame index that submitted this exact pass.
24    pub const fn logic_frame_index(self) -> u64 {
25        self.logic_frame
26    }
27
28    /// Returns zero for the initial device, incremented after each successful recovery.
29    pub const fn device_generation(self) -> u64 {
30        self.generation
31    }
32
33    /// Returns Engine's original source, opaque report ID and hardware interval.
34    pub const fn sample(self) -> GpuTimingSample {
35        self.sample
36    }
37}
38
39/// Latest bounded GPU diagnostics for the current desktop renderer generation.
40///
41/// No timing is inferred for Disabled/Unavailable devices, skipped sampling,
42/// failed readback or pending work. Statistics preserve Engine's explicit status
43/// and loss counters. At most eight completed samples and sixteen pending
44/// report-to-frame associations are retained; no sample history grows with time.
45/// Late or failed samples can outlive association capacity, in which case they
46/// remain in the raw batch but are never attributed to a guessed logical frame.
47///
48/// Recovery clears old samples, associations and counters. This is diagnostic
49/// state only; collection uses one nonblocking poll without waiting for the GPU.
50#[derive(Debug, Default)]
51pub struct DesktopGpuTimings {
52    generation: u64,
53    statistics: Option<GpuTimingStatistics>,
54    last_batch: Option<GpuTimingBatch>,
55    samples: [Option<DesktopGpuTimingSample>; MAX_COLLECTED],
56    pending: PendingTimings<GpuTimingId>,
57    unmatched_samples: u64,
58    evicted_correlations: u64,
59}
60
61impl DesktopGpuTimings {
62    /// Returns the current device generation, zero before and after initial creation.
63    pub const fn device_generation(&self) -> u64 {
64        self.generation
65    }
66
67    /// Returns Engine's latest current-device counters and explicit availability.
68    /// `None` means no renderer was initialized, not zero measured GPU work.
69    pub const fn statistics(&self) -> Option<GpuTimingStatistics> {
70        self.statistics
71    }
72
73    /// Returns the latest nonempty collection, which can belong to earlier frames.
74    ///
75    /// IDs/source categories remain authoritative; batch order is not frame order.
76    /// A subsequent empty collection preserves this batch. It is cleared during
77    /// device recovery. Engine statistics still include every collection's CPU cost.
78    pub const fn last_batch(&self) -> Option<GpuTimingBatch> {
79        self.last_batch
80    }
81
82    /// Iterates samples in the latest nonempty batch with exact source-and-ID matches.
83    /// An unmatched raw sample is omitted, not paired with the most recent frame.
84    pub fn samples(&self) -> impl Iterator<Item = &DesktopGpuTimingSample> {
85        self.samples.iter().filter_map(Option::as_ref)
86    }
87
88    /// Counts collected samples with no retained matching submission association.
89    /// This is separate from Engine query/readback losses and resets on recovery.
90    pub const fn unmatched_samples(&self) -> u64 {
91        self.unmatched_samples
92    }
93
94    /// Counts associations replaced when the sixteen-entry metadata limit was full.
95    /// Failed readbacks can leave associations that never receive a sample.
96    pub const fn evicted_correlations(&self) -> u64 {
97        self.evicted_correlations
98    }
99
100    pub(super) fn reset(&mut self, generation: u64, statistics: GpuTimingStatistics) {
101        self.reset_generation(generation);
102        self.statistics = Some(statistics);
103    }
104
105    fn reset_generation(&mut self, generation: u64) {
106        *self = Self {
107            generation,
108            ..Self::default()
109        };
110    }
111
112    pub(super) fn submitted(
113        &mut self,
114        logic_frame: u64,
115        source: GpuTimingSource,
116        id: Option<GpuTimingId>,
117    ) {
118        if let Some(id) = id
119            && self.pending.insert(id, source, logic_frame)
120        {
121            self.evicted_correlations = self.evicted_correlations.saturating_add(1);
122        }
123    }
124
125    pub(super) fn collect(&mut self, renderer: &mut WgpuRenderer) {
126        let batch = renderer.collect_gpu_timings();
127        self.statistics = Some(renderer.gpu_timing_statistics());
128        if batch.samples().is_empty() {
129            return;
130        }
131        self.samples.fill(None);
132        for (index, sample) in batch.samples().iter().copied().enumerate() {
133            if let Some(logic_frame) = self.pending.take(sample.id(), sample.source())
134                && let Some(destination) = self.samples.get_mut(index)
135            {
136                *destination = Some(DesktopGpuTimingSample {
137                    logic_frame,
138                    generation: self.generation,
139                    sample,
140                });
141            } else {
142                self.unmatched_samples = self.unmatched_samples.saturating_add(1);
143            }
144        }
145        self.last_batch = Some(batch);
146    }
147}
148
149#[derive(Debug, Clone, Copy)]
150struct PendingTiming<Id> {
151    id: Id,
152    source: GpuTimingSource,
153    logic_frame: u64,
154}
155
156#[derive(Debug)]
157struct PendingTimings<Id> {
158    entries: [Option<PendingTiming<Id>>; MAX_PENDING],
159}
160
161impl<Id: Copy> Default for PendingTimings<Id> {
162    fn default() -> Self {
163        Self {
164            entries: [None; MAX_PENDING],
165        }
166    }
167}
168
169impl<Id: Copy + Ord> PendingTimings<Id> {
170    /// Returns whether a previous association had to be evicted.
171    fn insert(&mut self, id: Id, source: GpuTimingSource, logic_frame: u64) -> bool {
172        if self
173            .entries
174            .iter()
175            .flatten()
176            .any(|entry| entry.id == id && entry.source == source)
177        {
178            return false;
179        }
180        let vacant = self.entries.iter().position(Option::is_none);
181        // Engine IDs are monotonic. Lost readbacks leave old associations;
182        // evict the oldest one only after using the full bounded metadata pool.
183        let index = vacant.or_else(|| {
184            self.entries
185                .iter()
186                .enumerate()
187                .filter_map(|(index, entry)| entry.map(|entry| (index, entry.id)))
188                .min_by_key(|(_, id)| *id)
189                .map(|(index, _)| index)
190        });
191        let Some(index) = index else {
192            return false;
193        };
194        self.entries[index] = Some(PendingTiming {
195            id,
196            source,
197            logic_frame,
198        });
199        vacant.is_none()
200    }
201
202    fn take(&mut self, id: Id, source: GpuTimingSource) -> Option<u64> {
203        self.entries
204            .iter_mut()
205            .find(|entry| entry.is_some_and(|entry| entry.id == id && entry.source == source))?
206            .take()
207            .map(|entry| entry.logic_frame)
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    #[test]
216    fn correlation_requires_both_id_and_source_and_accepts_out_of_order_completion() {
217        let mut pending = PendingTimings::<u64>::default();
218        assert!(!pending.insert(10, GpuTimingSource::Scene3d, 100));
219        assert!(!pending.insert(11, GpuTimingSource::FrameComposer, 100));
220        assert!(!pending.insert(12, GpuTimingSource::Scene3d, 101));
221        assert_eq!(pending.take(10, GpuTimingSource::FrameComposer), None);
222        assert_eq!(pending.take(12, GpuTimingSource::Scene3d), Some(101));
223        assert_eq!(pending.take(10, GpuTimingSource::Scene3d), Some(100));
224        assert_eq!(pending.take(11, GpuTimingSource::FrameComposer), Some(100));
225        assert_eq!(pending.take(10, GpuTimingSource::Scene3d), None);
226    }
227
228    #[test]
229    fn lost_samples_have_bounded_metadata_and_cannot_reuse_an_evicted_frame() {
230        let mut pending = PendingTimings::<u64>::default();
231        for id in 1..=MAX_PENDING as u64 {
232            assert!(!pending.insert(id, GpuTimingSource::Scene3d, id + 100));
233        }
234        assert!(pending.insert(17, GpuTimingSource::Scene3d, 117));
235        assert_eq!(pending.take(1, GpuTimingSource::Scene3d), None);
236        assert_eq!(pending.take(17, GpuTimingSource::Scene3d), Some(117));
237        assert!(!pending.insert(18, GpuTimingSource::Scene3d, 118));
238        assert_eq!(pending.take(2, GpuTimingSource::Scene3d), Some(102));
239    }
240
241    #[test]
242    fn repeated_submission_does_not_reassign_a_timing_id_to_another_frame() {
243        let mut pending = PendingTimings::<u64>::default();
244        assert!(!pending.insert(1, GpuTimingSource::Scene3d, 10));
245        assert!(!pending.insert(1, GpuTimingSource::Scene3d, 11));
246        assert_eq!(pending.take(1, GpuTimingSource::Scene3d), Some(10));
247    }
248
249    #[test]
250    fn uninitialized_diagnostics_have_no_fabricated_gpu_times() {
251        let diagnostics = DesktopGpuTimings::default();
252        assert!(diagnostics.statistics().is_none());
253        assert!(diagnostics.last_batch().is_none());
254        assert_eq!(diagnostics.samples().count(), 0);
255        assert_eq!(diagnostics.unmatched_samples(), 0);
256        assert_eq!(diagnostics.evicted_correlations(), 0);
257    }
258
259    #[test]
260    fn recovery_generation_discards_old_diagnostic_counters() {
261        let mut diagnostics = DesktopGpuTimings {
262            generation: 1,
263            unmatched_samples: 7,
264            evicted_correlations: 9,
265            ..DesktopGpuTimings::default()
266        };
267        diagnostics.reset_generation(2);
268        assert_eq!(diagnostics.device_generation(), 2);
269        assert_eq!(diagnostics.unmatched_samples(), 0);
270        assert_eq!(diagnostics.evicted_correlations(), 0);
271        assert!(diagnostics.last_batch().is_none());
272        assert!(diagnostics.statistics().is_none());
273        assert_eq!(diagnostics.samples().count(), 0);
274    }
275}