Skip to main content

crcbl_frame/
counters.rs

1//! What one frame's passes actually recorded: draws, instances, triangles.
2//!
3//! Topic 40's seventh missing piece — "Counters are
4//! piecemeal. `SceneStats`, `visible_count` and each sample's own rows exist;
5//! there is no one place a frame's draw count, instance count, cluster count or
6//! triangle count is reported." This is that one place, and it lives beside
7//! [`crate::timing`] for the reason `FrameTimings` does: the overlay is not
8//! allowed to know a render pass exists, so the module is contributed by the
9//! system it reports on.
10//!
11//! Every renderer says what it recorded —
12//! [`UiRenderer::counters`](crate::ui_pass::UiRenderer::counters) here, and
13//! `crcbl_render`'s `SpriteRenderer::counters` and `ForwardRenderer::counters`
14//! — and a caller [`plus`](FrameCounters::plus)es them into one, exactly as it
15//! sums their `MAX_PASSES` for [`PassTimers`](crate::timing::PassTimers). A
16//! number is produced once, by whichever renderer wrote the draw.
17//!
18//! # A counter is either a number the frame has or nothing at all
19//!
20//! Three of the five are [`Option`], and that is the whole design. A pass that
21//! draws **indirectly** — every pass a `ForwardRenderer`
22//! adds — has its instance count and its index count in a buffer
23//! `draw_gen.slang` wrote on the GPU; the CPU records the call and does not know
24//! what it covers. So those counters report [`None`] and the row says
25//! `indirect`, rather than a zero that reads as "nothing was drawn" or a product
26//! of a cluster count and a nominal triangles-per-cluster that reads as
27//! authoritative and is not.
28//!
29//! [`FrameCounters::plus`] propagates that: a frame holding one indirect pass
30//! has no honest total for either counter, so the sum is `None` however many
31//! direct passes it also holds. A counter that silently dropped the indirect
32//! pass's share would be topic 40's "counters that lie by
33//! omission" written down.
34//!
35//! # Instances drawn comes back off the GPU, a few frames late
36//!
37//! [`drawn`](FrameCounters::drawn) is a number on the GPU-driven path now, and
38//! it is the plan's culling win: `cull.slang`'s survivor count, copied out of
39//! `DrawGen::visible_count` by a pass
40//! the render graph schedules and read off `crcbl_render::cull_stats`'s delayed ring.
41//! **It is about an older frame than everything beside it**, and
42//! [`cull_frame`](FrameCounters::cull_frame) is how a reader can tell: it is the
43//! frame the readback came from, and it is [`None`] on a frame whose counters
44//! are all the CPU's own.
45//!
46//! So the section reads as two lags rather than one, deliberately stated rather
47//! than smoothed over:
48//!
49//! - `draws recorded`, `instances submitted` and `triangles drawn` are the
50//!   previous frame's, uniformly — see below.
51//! - `instances drawn` and `clusters drawn` carry the GPU's answer from the
52//!   frame named in `cull frame`, which is a few frames older again — how many
53//!   is the device's to decide, since `crcbl_render::cull_stats` reports a readback
54//!   when it answers rather than on a fixed schedule, and `cull frame` is what
55//!   says which frame it really was.
56//!
57//! A frame that mixes an indirect pass with direct ones has a `drawn` total
58//! whose GPU-sourced part is that old and whose CPU-sourced part is not.
59//! `cull frame` names the oldest frame in the total, so the row can be read as
60//! "no part of this is older than that" rather than as one instant.
61//!
62//! # The row is one frame behind, all of it
63//!
64//! The engine's loop gathers the debug panel *before* it hands the frame to the
65//! GPU — `Loop::frame_body` draws the overlay and then calls `GameGpu::frame`,
66//! which is where every renderer's `begin_frame` and `add_passes` run. So the
67//! counters a panel shows are the previous frame's, uniformly — and the two
68//! rows above are older still, which is what `cull frame` exists to say out
69//! loud. That is the arrangement [`crate::timing`]'s ring and
70//! `crcbl_ui::budget`'s two windows have to be careful about.
71//! `apps/horde`'s `Gpu::scene_stats` already documents the same lag for the same
72//! reason.
73
74use crcbl_ui::debug::{DebugModule, DebugSection};
75
76/// Draw calls, instances and triangles one frame recorded.
77///
78/// Built by [`plus`](Self::plus)ing each renderer's contribution onto
79/// [`FrameCounters::default`]; see the [module docs](self) for what the two
80/// [`Option`]s mean and when they are [`None`].
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub struct FrameCounters {
83    /// Draw calls the frame's passes recorded.
84    ///
85    /// Always known, on every geometry path: an indirect call is still a call
86    /// the CPU wrote into the command buffer. On the GPU-driven path this is
87    /// the number topic 03 §3.3 is about — one
88    /// per bucket, independent of what the scene holds.
89    pub draws: u64,
90    /// Instances the frame submitted to be drawn or culled.
91    ///
92    /// Also always known: a sprite pass uploads its instances and a
93    /// `ForwardRenderer` knows how many live
94    /// instances its pool holds, which is what the cull dispatch is given.
95    pub instances: u64,
96    /// Instances the recorded draws actually cover, or [`None`] where nothing
97    /// counted them.
98    ///
99    /// The pair with [`instances`](Self::instances) is the plan's "instances
100    /// submitted vs drawn". Where a pass culls nothing the two are equal and
101    /// deliberately so — that is the true answer, not a placeholder.
102    ///
103    /// On the GPU-driven path this is what the cull kept, off
104    /// `crcbl_render::cull_stats`'s ring, and therefore a number about the frame
105    /// [`cull_frame`](Self::cull_frame) names. [`None`] there means the ring has
106    /// not come round yet, or the device would not give one — see the module
107    /// docs.
108    pub drawn: Option<u64>,
109    /// Triangles those draws cover, or [`None`] where a pass draws indirectly.
110    ///
111    /// Exact where it is `Some`: a sprite is six vertices of a triangle list and
112    /// the UI pass draws an index count it wrote itself. Nothing here is a
113    /// per-mesh average, and nothing derives one from a cluster count.
114    pub triangles: Option<u64>,
115    /// Clusters the amplification stage kept, or [`None`] where nothing counted
116    /// them.
117    ///
118    /// [`None`] on the two indirect geometry paths and on a device with
119    /// `Features::MESH_SHADER` and no `Features::TASK_SHADER`: those frames have
120    /// no amplification stage, so nothing rejects a cluster and nothing counts
121    /// one. The row says [`UNKNOWN`] there, which is a different claim from the
122    /// zero that word would otherwise be — "every cluster was rejected" about a
123    /// frame that drew all of them.
124    ///
125    /// `Some(0)` for a frame of sprites and UI, which really did draw no
126    /// clusters. That is what makes [`Default`] the identity of
127    /// [`plus`](Self::plus) here as it is for the others.
128    pub clusters: Option<u64>,
129    /// Which frame [`drawn`](Self::drawn) and [`clusters`](Self::clusters) came
130    /// back from, where either came off the GPU.
131    ///
132    /// [`None`] on a frame whose counters are entirely the CPU's own, which is
133    /// every frame with no `ForwardRenderer` in it —
134    /// there is no second lag to declare, so there is no row.
135    pub cull_frame: Option<u64>,
136}
137
138/// A frame that recorded nothing — **and knows it did**.
139///
140/// Hand-written rather than derived, because a derived `Default` would leave the
141/// two [`Option`]s at [`None`], which is this type's word for "the GPU knows and
142/// the CPU does not". Those are opposite claims, and the accumulator has to
143/// start from the first one: this value is the identity of
144/// [`plus`](FrameCounters::plus), so summing a frame's renderers onto it reports
145/// exactly what they recorded.
146impl Default for FrameCounters {
147    fn default() -> Self {
148        Self {
149            draws: 0,
150            instances: 0,
151            drawn: Some(0),
152            triangles: Some(0),
153            clusters: Some(0),
154            // Nothing here came off the GPU, so there is no second lag to
155            // declare — and `plus` keeps whichever side does have one.
156            cull_frame: None,
157        }
158    }
159}
160
161impl FrameCounters {
162    /// These and another pass's contribution, added.
163    ///
164    /// The two totals sum. The two [`Option`]s sum **only when both sides know**
165    /// — one unknown makes the total unknown, because a sum that dropped the
166    /// unknown side's share would be a smaller number wearing a total's name.
167    #[must_use]
168    pub const fn plus(self, other: Self) -> Self {
169        Self {
170            draws: self.draws + other.draws,
171            instances: self.instances + other.instances,
172            drawn: match (self.drawn, other.drawn) {
173                (Some(mine), Some(theirs)) => Some(mine + theirs),
174                _ => None,
175            },
176            triangles: match (self.triangles, other.triangles) {
177                (Some(mine), Some(theirs)) => Some(mine + theirs),
178                _ => None,
179            },
180            clusters: match (self.clusters, other.clusters) {
181                (Some(mine), Some(theirs)) => Some(mine + theirs),
182                _ => None,
183            },
184            // **The oldest frame either side drew on**, so the row is read as
185            // "no part of this total is older than that". A sum of a latent
186            // counter and a live one is genuinely two ages; naming the newer of
187            // them would be the half that is not stale claiming the whole.
188            cull_frame: match (self.cull_frame, other.cull_frame) {
189                (Some(mine), Some(theirs)) if theirs < mine => Some(theirs),
190                (Some(mine), _) => Some(mine),
191                (None, theirs) => theirs,
192            },
193        }
194    }
195}
196
197/// How a counter with no honest number spells itself.
198///
199/// One place, so the row and the assertion that reads it back cannot drift, and
200/// deliberately a word rather than a zero or a dash: `indirect` says *why* there
201/// is no number.
202pub const INDIRECT: &str = "indirect";
203
204/// How the cluster counter with no number spells itself.
205///
206/// A different word from [`INDIRECT`] because it is a different claim. `indirect`
207/// says the draw carried its counts in a buffer; this says **nothing in the
208/// frame counted the thing at all** — there is no amplification stage on three
209/// of the four geometry paths, so no cluster was ever accepted or rejected.
210pub const UNKNOWN: &str = "unknown";
211
212/// The panel row.
213///
214/// Labels are long enough to be unique across the whole panel: `DebugModule`
215/// labels share one namespace and nothing detects a collision, so a bare `drawn`
216/// here would be the same label `apps/horde`'s scene section already uses, and a
217/// test searching the draw list by label text would read whichever came first.
218///
219/// The last row is the frame stamp, and it appears only when something in the
220/// section came off the GPU — see the [module docs](self) on the two lags this
221/// section carries and why the newer one is not allowed to speak for both.
222impl DebugModule for FrameCounters {
223    fn debug_section(&self, out: &mut DebugSection) {
224        out.set_title("counters");
225        out.row("draws recorded", format_args!("{}", self.draws));
226        out.row("instances submitted", format_args!("{}", self.instances));
227        write_known(out, "instances drawn", self.drawn, INDIRECT);
228        write_known(out, "triangles drawn", self.triangles, INDIRECT);
229        write_known(out, "clusters drawn", self.clusters, UNKNOWN);
230        if let Some(frame) = self.cull_frame {
231            out.row("cull frame", format_args!("{frame}"));
232        }
233    }
234}
235
236/// One row that is either a number or the word that says why it is not.
237fn write_known(out: &mut DebugSection, label: &str, value: Option<u64>, absent: &str) {
238    match value {
239        Some(value) => out.row(label, format_args!("{value}")),
240        None => out.row_str(label, absent),
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    /// A section's rows as `(label, value)`, written the way the panel writes
249    /// one — cleared before every `debug_section`.
250    fn rows(counters: &FrameCounters) -> Vec<(String, String)> {
251        let mut section = DebugSection::default();
252        counters.debug_section(&mut section);
253        assert_eq!(section.title(), "counters");
254        section
255            .rows()
256            .iter()
257            .map(|row| (row.label.clone(), row.value.clone()))
258            .collect()
259    }
260
261    /// A pass that knows everything it drew: a sprite or UI pass, which draws
262    /// directly and counts no clusters because it has none.
263    fn known(draws: u64, instances: u64, triangles: u64) -> FrameCounters {
264        FrameCounters {
265            draws,
266            instances,
267            drawn: Some(instances),
268            triangles: Some(triangles),
269            clusters: Some(0),
270            cull_frame: None,
271        }
272    }
273
274    /// **The row renders the numbers it was given, and a different frame renders
275    /// different text.** A row wired to a constant passes a test that only
276    /// checks the row is there.
277    #[test]
278    fn the_row_renders_the_counters_it_was_given() {
279        assert_eq!(
280            rows(&known(3, 412, 824)),
281            vec![
282                ("draws recorded".to_owned(), "3".to_owned()),
283                ("instances submitted".to_owned(), "412".to_owned()),
284                ("instances drawn".to_owned(), "412".to_owned()),
285                ("triangles drawn".to_owned(), "824".to_owned()),
286                ("clusters drawn".to_owned(), "0".to_owned()),
287            ]
288        );
289        assert_eq!(
290            rows(&known(5, 9, 18)),
291            vec![
292                ("draws recorded".to_owned(), "5".to_owned()),
293                ("instances submitted".to_owned(), "9".to_owned()),
294                ("instances drawn".to_owned(), "9".to_owned()),
295                ("triangles drawn".to_owned(), "18".to_owned()),
296                ("clusters drawn".to_owned(), "0".to_owned()),
297            ]
298        );
299    }
300
301    /// **The frame stamp is a row of its own, and only when there is something
302    /// to stamp.** A GPU-sourced counter beside CPU-sourced ones with no way to
303    /// tell them apart is the lie this row exists to prevent — and a frame with
304    /// no such counter must not grow an empty row saying so.
305    #[test]
306    fn the_cull_frame_row_appears_only_when_a_counter_came_off_the_gpu() {
307        let labels: Vec<String> = rows(&known(3, 412, 824))
308            .into_iter()
309            .map(|(label, _)| label)
310            .collect();
311        assert!(
312            !labels.contains(&"cull frame".to_owned()),
313            "nothing here came off the GPU: {labels:?}",
314        );
315
316        let latent = FrameCounters {
317            draws: 15,
318            instances: 4097,
319            drawn: Some(2043),
320            triangles: None,
321            clusters: Some(881),
322            cull_frame: Some(37),
323        };
324        assert_eq!(
325            rows(&latent),
326            vec![
327                ("draws recorded".to_owned(), "15".to_owned()),
328                ("instances submitted".to_owned(), "4097".to_owned()),
329                ("instances drawn".to_owned(), "2043".to_owned()),
330                ("triangles drawn".to_owned(), INDIRECT.to_owned()),
331                ("clusters drawn".to_owned(), "881".to_owned()),
332                ("cull frame".to_owned(), "37".to_owned()),
333            ]
334        );
335    }
336
337    /// **A total mixing two ages names the older one.** A latent culling count
338    /// summed with a live sprite count is genuinely two frames' worth, and the
339    /// stamp has to be the stale half or it understates how old the row is.
340    #[test]
341    fn adding_keeps_the_oldest_frame_either_side_drew_on() {
342        let sprites = known(2, 30, 60);
343        let latent = FrameCounters {
344            cull_frame: Some(37),
345            ..known(1, 5, 10)
346        };
347        let older = FrameCounters {
348            cull_frame: Some(31),
349            ..known(1, 5, 10)
350        };
351        assert_eq!(sprites.plus(latent).cull_frame, Some(37));
352        assert_eq!(latent.plus(sprites).cull_frame, Some(37));
353        assert_eq!(latent.plus(older).cull_frame, Some(31));
354        assert_eq!(older.plus(latent).cull_frame, Some(31));
355    }
356
357    /// **An unknown counter says `indirect`, never `0`.** A zero in either of
358    /// these rows means "the frame drew nothing", and a frame drawing a
359    /// GPU-driven scene has drawn plenty.
360    #[test]
361    fn an_unknown_counter_is_a_word_and_not_a_zero() {
362        let indirect = FrameCounters {
363            draws: 4,
364            instances: 7,
365            drawn: None,
366            triangles: None,
367            clusters: None,
368            cull_frame: None,
369        };
370        assert_eq!(
371            rows(&indirect),
372            vec![
373                ("draws recorded".to_owned(), "4".to_owned()),
374                ("instances submitted".to_owned(), "7".to_owned()),
375                ("instances drawn".to_owned(), INDIRECT.to_owned()),
376                ("triangles drawn".to_owned(), INDIRECT.to_owned()),
377                ("clusters drawn".to_owned(), UNKNOWN.to_owned()),
378            ]
379        );
380        assert_ne!(
381            INDIRECT, UNKNOWN,
382            "the two absences are different claims and must read differently",
383        );
384        // And a genuine zero is still a zero, so the two are told apart.
385        assert_eq!(
386            rows(&known(0, 0, 0))[2],
387            ("instances drawn".to_owned(), "0".to_owned())
388        );
389    }
390
391    /// **Submitted and drawn are separate rows off separate fields.** A version
392    /// that rendered one field twice, or swapped the pair, agrees with itself on
393    /// a frame that culls nothing — so the frame here culls something.
394    #[test]
395    fn submitted_and_drawn_are_not_the_same_field() {
396        let culled = FrameCounters {
397            draws: 1,
398            instances: 900,
399            drawn: Some(120),
400            triangles: Some(240),
401            clusters: None,
402            cull_frame: Some(9),
403        };
404        let rendered = rows(&culled);
405        assert_eq!(
406            rendered[1],
407            ("instances submitted".to_owned(), "900".to_owned())
408        );
409        assert_eq!(
410            rendered[2],
411            ("instances drawn".to_owned(), "120".to_owned())
412        );
413    }
414
415    /// The totals sum, and one unknown side makes the whole total unknown.
416    #[test]
417    fn adding_sums_what_is_known_and_gives_up_on_what_is_not() {
418        let sprites = known(3, 400, 800);
419        let ui = known(1, 1, 26);
420        assert_eq!(
421            sprites.plus(ui),
422            FrameCounters {
423                draws: 4,
424                instances: 401,
425                drawn: Some(401),
426                triangles: Some(826),
427                clusters: Some(0),
428                cull_frame: None,
429            }
430        );
431        // Order does not matter.
432        assert_eq!(sprites.plus(ui), ui.plus(sprites));
433
434        let indirect = FrameCounters {
435            draws: 15,
436            instances: 6,
437            drawn: None,
438            triangles: None,
439            clusters: None,
440            cull_frame: None,
441        };
442        let total = sprites.plus(indirect);
443        assert_eq!(
444            total.draws, 18,
445            "the draws are still known: the CPU records them"
446        );
447        assert_eq!(total.instances, 406);
448        assert_eq!(
449            total.drawn, None,
450            "400 of an unknown number is not a total of instances drawn"
451        );
452        assert_eq!(total.triangles, None);
453        assert_eq!(total.clusters, None);
454    }
455
456    /// **The accumulator starts from "nothing, and I know it"**, not from
457    /// "nothing, and I have no idea" — a `Default` at `None` would make every
458    /// sum unknown for ever, whatever the renderers reported.
459    #[test]
460    fn the_empty_value_is_zero_and_known_and_is_the_identity_of_plus() {
461        let nothing = FrameCounters::default();
462        assert_eq!(nothing.draws, 0);
463        assert_eq!(nothing.instances, 0);
464        assert_eq!(nothing.drawn, Some(0));
465        assert_eq!(nothing.triangles, Some(0));
466        assert_eq!(nothing.clusters, Some(0));
467        assert_eq!(nothing.cull_frame, None);
468        assert_eq!(nothing.plus(nothing), nothing);
469
470        let sprites = known(2, 30, 60);
471        assert_eq!(nothing.plus(sprites), sprites);
472        assert_eq!(sprites.plus(nothing), sprites);
473    }
474
475    /// Every label this section writes, so a rename is visible and a collision
476    /// with another module's row is something a reader can check against this
477    /// list.
478    #[test]
479    fn the_sections_labels_are_its_own() {
480        let labels: Vec<String> = rows(&FrameCounters {
481            cull_frame: Some(1),
482            ..FrameCounters::default()
483        })
484        .into_iter()
485        .map(|(label, _)| label)
486        .collect();
487        assert_eq!(
488            labels,
489            [
490                "draws recorded",
491                "instances submitted",
492                "instances drawn",
493                "triangles drawn",
494                "clusters drawn",
495                "cull frame",
496            ]
497        );
498    }
499}