Skip to main content

crcbl_render/
cull_stats.rs

1//! The culling statistics, off the GPU and onto a ring of readback slots.
2//!
3//! ```text
4//!  add_copy_pass ─▶ copy pass: cull stats ──▶ a free slot k        (frame f)
5//!                                                  │
6//!  begin_frame ─────── request_readback(slot k) ───┘               (frame f+1)
7//!                                                  │
8//!  begin_frame ─────── poll_readback(slot k) ──────┘               (frame f+2,
9//!                              │                                    and every
10//!                              │                                    frame until
11//!                              │                                    it answers)
12//!                              ▼  latest() ──▶ ForwardRenderer::counters()
13//! ```
14//!
15//! Topic 03 §3.6's culling-stats readback, and
16//! topic 40's eighth missing piece: "the culling stats never
17//! leave the GPU … there is no staging buffer, no copy inside the frame graph,
18//! and no consumer". This is all three.
19//!
20//! # The answer *is* the synchronisation
21//!
22//! A slot is handed back for another copy **when its readback answers**, and not
23//! before. That is the stronger of the two guarantees available: an answered
24//! readback is proof that the copy which filled the slot completed, where a
25//! count of frames is an assumption about how far ahead of the CPU the GPU is
26//! allowed to get. There is no fence here, no `wait_idle` and no poll in a loop
27//! — a slot that has not answered is left alone until the next frame, and a
28//! frame that finds every slot still waiting simply records no copy.
29//!
30//! So the number is a few frames old — two at the very best, because the copy is
31//! recorded on one frame, requested on the next and first polled on the one
32//! after — and it says which frame it is about: [`CullStats::frame`] carries it,
33//! and [`FrameCounters`](crate::counters::FrameCounters) puts it on the panel as
34//! its own row. A latent counter beside live ones without saying so is the whole
35//! reason that row exists.
36//!
37//! # A poll is a question, and on one backend it is asked across a wire
38//!
39//! Every outstanding slot is polled **once per frame**, which is exactly what
40//! [`poll_readback`](Device::poll_readback) permits and what the browser needs.
41//! `crcbl-webgpu` answers a poll by encoding the question onto the command
42//! stream and returning [`ReadbackState::Pending`], because the answer cannot
43//! arrive until that stream has been replayed and its replies drained: the
44//! **first** poll on a handle there is never `Ready`, whatever the map has
45//! already done. This module used to poll a slot once and release it on the next
46//! line whatever it answered, which threw every browser answer away before it
47//! could arrive — [`latest`](CullStatsRing::latest) stayed [`None`] for ever and
48//! the panel showed no culling statistics at all. The native backends can answer
49//! their first poll, which is why nothing else ever noticed.
50//!
51//! A deadline is the other half of that — `POLL_DEADLINE`, private to this
52//! module. A device that has stopped answering must not end up holding every
53//! slot in the ring mapped for the rest of the process, so a request that has
54//! gone unanswered for that many frames is released and its slot reused. It is
55//! not a wait: nothing blocks on it, and every other slot goes on being polled
56//! meanwhile.
57//!
58//! # Three points in the frame, and why the request is not at the copy
59//!
60//! A readback "covers work **already submitted** when
61//! [`request_readback`](Device::request_readback) is called". The copy is
62//! recorded, not submitted, when [`CullStatsRing::add_copy_pass`] returns — the
63//! encoder is still open — so requesting there would be the caller bug the seam
64//! names: "requesting before submitting the copy that fills the buffer … reads
65//! stale bytes". The request therefore happens at the *next*
66//! [`CullStatsRing::begin_frame`], by which point the frame that recorded the
67//! copy has been submitted, because a frame loop submits the graph it executed
68//! before it starts another one.
69//!
70//! And it happens only if the copy pass's body actually ran. A graph that was
71//! built and then dropped — a compile error, a swapchain that went out of date —
72//! recorded nothing, and a request against that slot would return the bytes the
73//! *previous* turn of the ring left in it and report them as this frame's. So
74//! the body stamps the frame number it recorded — from inside
75//! [`execute`](crate::graph::CompiledGraph::execute), through the one piece of
76//! shared state this type has — and a slot nothing stamped is never read.
77//!
78//! # Degrading rather than breaking
79//!
80//! [`CullStatsRing::new`] answers [`None`] if the device will not give it the
81//! buffers, and any seam error afterwards switches the ring off for good — one
82//! log line, and [`latest`](CullStatsRing::latest) is [`None`] from then on. The
83//! panel says `indirect` in that case, which is what it said before this ring
84//! existed. **A zero would be worse than nothing**: it reads as "the cull kept
85//! nothing", which is a scene that vanished rather than a counter that never
86//! arrived.
87//!
88//! # One ring, for the camera's cull only
89//!
90//! A frame runs several culls — the camera's, and one per shadow cascade and
91//! shadowed light — and each is its own [`DrawGen`](crate::draw_gen::DrawGen)
92//! with its own statistics buffer. Only the camera's is read: it is the one
93//! whose survivors are "the culling win", and summing the shadow culls into it
94//! would produce a number larger than the instance count that means nothing at
95//! all. A shadow cull's survivors are a different question about a different
96//! frustum, and the day something asks it, it asks with a ring of its own.
97
98use std::sync::Arc;
99use std::sync::atomic::{AtomicU64, Ordering};
100
101use crcbl_hal::{
102    BufferCopy, BufferDesc, BufferHandle, BufferUsage, Device, MemoryLocation, ReadbackDesc,
103    ReadbackHandle, ReadbackState, ResourceState,
104};
105use crcbl_shaders::cull;
106
107use crate::graph::{BufferId, ImportedBuffer, RenderGraph};
108
109/// Bytes of one slot: the whole statistics buffer, in one copy.
110///
111/// Every counter the frame produces lives in that one buffer — see
112/// [`cull::STATS_WORDS`] — so reading all of it is the same single copy as
113/// reading any of it, and a slot that held a prefix would have to grow the day
114/// something asked for a word it had left behind.
115const SLOT_BYTES: u64 = cull::STATS_WORDS as u64 * 4;
116
117/// Frames a request is given to answer before its slot is taken back.
118///
119/// Long enough that no working device reaches it — a browser answers a poll
120/// across a command stream, which costs a frame's round trip and not two orders
121/// of magnitude of them — and short enough that a device which has *stopped*
122/// answering releases what it holds. There is nothing else to release it: the
123/// ring would otherwise run out of slots, stop recording copies, and hold every
124/// buffer in it mapped until the renderer was destroyed.
125///
126/// The slot is safe to reuse when this expires for the reason the whole module
127/// turns on: the copy that filled it was submitted this many frames ago, which
128/// is far more than the frames the loop keeps in flight.
129const POLL_DEADLINE: u64 = 120;
130
131/// **What the per-cluster cull did, split by which test did it.**
132///
133/// Three numbers rather than one, because a survivor count alone cannot be read:
134/// "27 of 338 survived" is equally consistent with the normal cone rejecting
135/// every one of the other 311 and with it rejecting none of them, and
136/// quarry's charter asks the panel to say which.
137///
138/// **Every cluster the amplification stage *tested* is in exactly one of the
139/// three**, and a cluster it did not test is in none — see
140/// [`tested`](Self::tested), which is the identity that makes them readable.
141#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
142pub struct ClusterCull {
143    /// Clusters both tests kept, which is what the mesh stage was dispatched
144    /// for.
145    pub survivors: u64,
146    /// Clusters whose bounding sphere was entirely outside the frustum.
147    pub frustum_rejects: u64,
148    /// Clusters the frustum kept and the normal cone refused — every triangle
149    /// facing away from the camera.
150    ///
151    /// **The two tests are ordered**, so this is "faced away *and* was on
152    /// screen". A cluster that is both behind the camera and facing away is
153    /// counted in [`frustum_rejects`](Self::frustum_rejects).
154    pub cone_rejects: u64,
155}
156
157impl ClusterCull {
158    /// Clusters the amplification stage put to either test — the size of the
159    /// cut it was handed, in a frame whose instance survived the camera's cull.
160    ///
161    /// The three counters partition that set, so this is their sum and there is
162    /// no fourth bucket. A cluster the DAG descent did not select, or a group
163    /// past the dispatch extents, was never tested and is in none of them: it
164    /// was not rejected by a cull, it was never offered to one.
165    #[must_use]
166    pub const fn tested(&self) -> u64 {
167        self.survivors + self.frustum_rejects + self.cone_rejects
168    }
169}
170
171/// What the camera's occlusion and small-feature culls did — zero on a frame
172/// that ran neither, which is every frame until a caller switches one on.
173#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
174pub struct OcclusionCull {
175    /// Survivors the **first** phase marked hidden against the previous frame's
176    /// pyramid. Every one of them was tested again.
177    pub early_rejects: u64,
178    /// Survivors the **second** phase still found hidden against this frame's
179    /// early depth — the instances the frame did not draw.
180    pub late_rejects: u64,
181    /// Instances dropped as smaller than the threshold, which are not in
182    /// [`CullStats::instances`] at all.
183    pub small_feature_rejects: u64,
184}
185
186impl OcclusionCull {
187    /// Survivors the first phase got wrong and the second drew anyway — a
188    /// disocclusion, a moved occluder or a camera cut.
189    #[must_use]
190    pub const fn rescued(&self) -> u64 {
191        self.early_rejects.saturating_sub(self.late_rejects)
192    }
193}
194
195/// What one frame's culling actually kept.
196#[derive(Clone, Copy, Debug, PartialEq, Eq)]
197pub struct CullStats {
198    /// Instances the camera's cull kept.
199    ///
200    /// The **true** survivor count, which can exceed
201    /// [`DrawGen::visible_capacity`](crate::draw_gen::DrawGen::visible_capacity)
202    /// — the cull counts every survivor and writes the prefix that fits, so a
203    /// number larger than the list is a scene that outgrew it rather than an
204    /// error here.
205    pub instances: u64,
206    /// What the per-cluster cull did — survivors and the two rejection counts —
207    /// or [`None`] where nothing counted them.
208    ///
209    /// [`None`] on the two indirect geometry paths and on a device with
210    /// `Features::MESH_SHADER` and no `Features::TASK_SHADER`: there is no
211    /// amplification stage in those frames, so the words keep the zeroes the
212    /// clearing pass wrote. Reporting those zeroes as counts would say "every
213    /// cluster was rejected" about a frame that drew all of them.
214    ///
215    /// **One [`Option`] over the three and not three [`Option`]s**, because the
216    /// condition is one condition: the same absent stage is what leaves all
217    /// three words untouched, and three separately-unknown numbers would invite
218    /// a caller to add two of them up.
219    pub clusters: Option<ClusterCull>,
220    /// What the occlusion and small-feature culls rejected. The instances drawn
221    /// are [`instances`](Self::instances) less
222    /// [`OcclusionCull::late_rejects`].
223    pub occlusion: OcclusionCull,
224    /// Which frame these came from — a few frames behind the one being
225    /// recorded, and how many is the device's to decide rather than this
226    /// module's. See the module docs.
227    pub frame: u64,
228}
229
230/// What one slot is doing, which is what decides whether a copy may take it.
231///
232/// A slot is [`Idle`](Self::Idle) only when nothing is outstanding on it at all,
233/// so the state is what keeps this frame's copy off a buffer the last frame's
234/// copy is still on its way into or a readback is still mapping.
235#[derive(Debug)]
236enum SlotState {
237    /// Nothing outstanding; the next copy may take it.
238    Idle,
239    /// Handed to this frame's graph by [`CullStatsRing::add_copy_pass`].
240    ///
241    /// The request is made at the *next* [`CullStatsRing::begin_frame`], by
242    /// which point the copy has been submitted — see below for why it cannot be
243    /// made here — and only if the graph actually ran.
244    Recording,
245    /// A request is out for the copy `frame` recorded, made on frame `since`.
246    Polling {
247        /// The frame whose copy the body stamped into this slot.
248        frame: u64,
249        /// The frame [`request_readback`](Device::request_readback) was called
250        /// on, which is what [`POLL_DEADLINE`] is measured from and what keeps
251        /// the first poll off the frame that made the request.
252        since: u64,
253        readback: ReadbackHandle,
254    },
255}
256
257/// One slot: a host-readable buffer, and whatever is outstanding on it.
258#[derive(Debug)]
259struct Slot {
260    /// The [`MemoryLocation::HostReadback`] buffer the copy pass writes into.
261    ///
262    /// One per slot rather than one buffer with per-slot offsets, because a
263    /// readback is a mapping: WebGPU maps a buffer once, so a buffer with a map
264    /// already in flight cannot take a second. A ring is exactly the shape that
265    /// has several in flight.
266    buffer: BufferHandle,
267    /// What the **last frame that used this slot** left the buffer in, and what
268    /// [`CullStatsRing::add_copy_pass`] imports it as.
269    ///
270    /// [`ResourceState::Undefined`] until a copy has been declared into it, and
271    /// [`ResourceState::TransferDst`] thereafter. **This is the field the whole
272    /// cross-frame hazard turns on**: the previous write to this buffer is
273    /// another frame's `copy_buffer_to_buffer`, in another submission, and a
274    /// barrier naming `Undefined` as its source carries no source scope at all —
275    /// `srcStageMask = NONE` — so it would order the two writes against nothing.
276    /// Naming `TransferDst` is what gives the graph's barrier a real prior
277    /// access to depend on.
278    imported: ResourceState,
279    /// Whether this slot is free, recording, or waiting on an answer.
280    state: SlotState,
281}
282
283/// A ring of host-readable buffers, one per frame in flight plus one.
284#[derive(Debug)]
285pub struct CullStatsRing {
286    slots: Vec<Slot>,
287    /// Where [`CullStatsRing::take_slot`] starts looking, so consecutive frames
288    /// land in different slots while free ones remain.
289    ///
290    /// Round robin rather than first-free because the buffer a frame copies into
291    /// is the one the *last* frame on that slot copied into, and spreading the
292    /// copies across the ring is what leaves the readback of the slot before it
293    /// a whole frame to answer in before its buffer is wanted again.
294    next: usize,
295    /// The frame number the copy pass body stamped, or `0` for "nothing was
296    /// recorded". Shared with the body, which runs inside
297    /// [`execute`](crate::graph::CompiledGraph::execute) and therefore cannot
298    /// hold `&mut` to this.
299    recorded: Arc<AtomicU64>,
300    /// Whether an amplification stage counts clusters in this frame at all —
301    /// [`CullStats::clusters`]'s [`None`].
302    counts_clusters: bool,
303    frames: u64,
304    latest: Option<CullStats>,
305    /// Set by the first seam error. The ring reports nothing from then on rather
306    /// than a number it cannot stand behind.
307    off: bool,
308}
309
310impl CullStatsRing {
311    /// Builds the ring, or `None` if the device will not give it its buffers.
312    ///
313    /// `counts_clusters` is whether the caller **built** an amplification stage
314    /// — `ForwardRenderer::culls_clusters`, not a device capability — because
315    /// that is what decides whether the cluster word is a count or the zero the
316    /// clearing pass left.
317    ///
318    /// `None` is not an error: it is [`PassTimers::new`](crate::timing::PassTimers::new)'s
319    /// answer to a device with no timestamps, for the same reason. The caller
320    /// adds no copy pass and the panel says `indirect`.
321    #[must_use]
322    pub fn new(
323        device: &dyn Device,
324        frames_in_flight: usize,
325        counts_clusters: bool,
326    ) -> Option<Self> {
327        // One more than the frames in flight. The depth is how many copies may
328        // be outstanding before a frame has to go without one, and a slot is
329        // busy from the frame its copy is recorded to the frame that answer
330        // lands: three is what keeps a device answering its first poll copying
331        // every frame, with a slot's grace for one that answers a frame later.
332        let count = frames_in_flight.max(1) + 1;
333        let mut slots = Vec::with_capacity(count);
334        for index in 0..count {
335            match device.create_buffer(&BufferDesc {
336                label: Some("cull stats readback"),
337                size: SLOT_BYTES,
338                // `TRANSFER_DST` and nothing else: this is the copy's
339                // destination and it is never bound. The buffer a shader writes
340                // stays device-local — see [`MemoryLocation`], which is where
341                // that rule and the D3D12 device it cost are written down.
342                usage: BufferUsage::TRANSFER_DST,
343                memory: MemoryLocation::HostReadback,
344            }) {
345                Ok(buffer) => slots.push(Slot {
346                    buffer,
347                    // Nothing has written it, which is the one state a barrier
348                    // may name as a source without ordering anything: there is
349                    // nothing to order against yet.
350                    imported: ResourceState::Undefined,
351                    state: SlotState::Idle,
352                }),
353                Err(error) => {
354                    crcbl_core::log::debug!(
355                        "cull stats: readback buffer {index} refused ({error}); the culling \
356                         counters stay on the GPU"
357                    );
358                    for slot in &slots {
359                        device.destroy_buffer(slot.buffer);
360                    }
361                    return None;
362                }
363            }
364        }
365        Some(Self {
366            slots,
367            next: 0,
368            recorded: Arc::new(AtomicU64::new(0)),
369            counts_clusters,
370            frames: 0,
371            latest: None,
372            off: false,
373        })
374    }
375
376    /// The most recent frame whose statistics have actually landed, or [`None`]
377    /// until the first readback has answered.
378    #[must_use]
379    pub const fn latest(&self) -> Option<CullStats> {
380        self.latest
381    }
382
383    /// Starts a frame: requests the readback the last frame's copy earned, then
384    /// polls everything outstanding.
385    ///
386    /// Called once per frame, before [`add_copy_pass`](Self::add_copy_pass), and
387    /// **after the previous frame was submitted** — which is the frame loop's
388    /// own order, since a frame is recorded, submitted and presented before the
389    /// next one starts. See the module docs for why the request cannot happen at
390    /// the copy.
391    pub fn begin_frame(&mut self, device: &dyn Device) {
392        if self.off {
393            return;
394        }
395        self.frames += 1;
396        self.request_recorded(device);
397        self.poll_outstanding(device);
398    }
399
400    /// Requests the readback for the copy the last frame recorded, or hands that
401    /// slot back if the graph holding it never ran.
402    ///
403    /// The copy the recording slot was given last frame has been submitted by
404    /// now, so a request against it covers work that is really on its way. A slot
405    /// nothing stamped is released unread: the graph that would have filled it
406    /// never ran, and what is in it belongs to an older frame.
407    fn request_recorded(&mut self, device: &dyn Device) {
408        let recorded = self.recorded.swap(0, Ordering::Relaxed);
409        let Some(index) = self
410            .slots
411            .iter()
412            .position(|slot| matches!(slot.state, SlotState::Recording))
413        else {
414            return;
415        };
416        if recorded == 0 {
417            self.slots[index].state = SlotState::Idle;
418            return;
419        }
420        let since = self.frames;
421        let request = device.request_readback(&ReadbackDesc {
422            label: Some("cull stats"),
423            buffer: self.slots[index].buffer,
424            offset: 0,
425            size: SLOT_BYTES,
426            // Everything submitted so far, which is exactly the copy above and
427            // nothing this ring has to name a timeline value for.
428            after: None,
429        });
430        match request {
431            Ok(readback) => {
432                self.slots[index].state = SlotState::Polling {
433                    frame: recorded,
434                    since,
435                    readback,
436                };
437            }
438            Err(error) => {
439                self.slots[index].state = SlotState::Idle;
440                self.give_up(device, &format!("request failed ({error})"));
441            }
442        }
443    }
444
445    /// Polls every outstanding slot once, reports what has landed, and releases
446    /// what has run out of time.
447    ///
448    /// **Once per frame per readback, and never on the frame the request was
449    /// made.** Once per frame is what the seam permits and what a backend whose
450    /// polls are themselves asynchronous needs — see the module docs. Not on the
451    /// requesting frame because that poll can only ever say `Pending`: it asks
452    /// about a submission the frame loop has not even reached the end of.
453    ///
454    /// No allocation: the bytes land in one stack buffer reused across the
455    /// slots, which [`poll_readback`](Device::poll_readback) leaves untouched
456    /// unless it answers `Ready`.
457    fn poll_outstanding(&mut self, device: &dyn Device) {
458        let mut bytes = [0u8; SLOT_BYTES as usize];
459        for index in 0..self.slots.len() {
460            let SlotState::Polling {
461                frame,
462                since,
463                readback,
464            } = self.slots[index].state
465            else {
466                continue;
467            };
468            if since >= self.frames {
469                continue;
470            }
471            match device.poll_readback(readback, &mut bytes) {
472                Ok(ReadbackState::Ready) => {
473                    device.destroy_readback(readback);
474                    self.slots[index].state = SlotState::Idle;
475                    self.report(frame, &bytes);
476                }
477                Ok(ReadbackState::Pending) if self.frames - since >= POLL_DEADLINE => {
478                    device.destroy_readback(readback);
479                    self.slots[index].state = SlotState::Idle;
480                    crcbl_core::log::debug!(
481                        "cull stats: frame {frame} was never answered; its slot is back in the ring"
482                    );
483                }
484                Ok(ReadbackState::Pending) => {}
485                Err(error) => {
486                    self.give_up(device, &format!("poll failed ({error})"));
487                    return;
488                }
489            }
490        }
491    }
492
493    /// Files a landed slot's bytes as the report, unless an even later frame has
494    /// already landed.
495    ///
496    /// **The panel's number never goes backwards.** Slots answer in the order
497    /// they were requested on every device seen so far, but nothing in the seam
498    /// promises it: two can land on the same frame, and a device is free to
499    /// answer the newer one first. Reporting whichever spoke last would then walk
500    /// [`CullStats::frame`] back down, which reads as the frame loop having
501    /// stalled.
502    fn report(&mut self, frame: u64, bytes: &[u8; SLOT_BYTES as usize]) {
503        if self.latest.is_some_and(|latest| latest.frame >= frame) {
504            return;
505        }
506        let stats = CullStats {
507            instances: u64::from(word(bytes, cull::INSTANCE_SURVIVOR_WORD)),
508            clusters: self.counts_clusters.then(|| ClusterCull {
509                survivors: u64::from(word(bytes, cull::CLUSTER_SURVIVOR_WORD)),
510                frustum_rejects: u64::from(word(bytes, cull::CLUSTER_FRUSTUM_REJECT_WORD)),
511                cone_rejects: u64::from(word(bytes, cull::CLUSTER_CONE_REJECT_WORD)),
512            }),
513            occlusion: OcclusionCull {
514                early_rejects: u64::from(word(bytes, cull::OCCLUSION_EARLY_REJECT_WORD)),
515                late_rejects: u64::from(word(bytes, cull::OCCLUSION_LATE_REJECT_WORD)),
516                small_feature_rejects: u64::from(word(bytes, cull::SMALL_FEATURE_REJECT_WORD)),
517            },
518            frame,
519        };
520        // At `trace!` and nowhere near `debug!`: this is a line per frame, and
521        // the module's own rule about the failure path — one line, not one a
522        // frame — cuts the same way here. It earns its place because the panel
523        // is the only other place these numbers exist and the panel is *glyphs*:
524        // a browser cannot read them back at all, and the bug this ring shipped
525        // with was precisely that they silently stopped arriving there.
526        crcbl_core::log::trace!(
527            "cull stats: frame {frame} kept {} instances, and its cluster cull did {:?}",
528            stats.instances,
529            stats.clusters,
530        );
531        self.latest = Some(stats);
532    }
533
534    /// The slot this frame's copy goes into, marked as this frame's.
535    ///
536    /// [`None`] when every slot is still waiting on an answer, which is the
537    /// frame that records no copy at all.
538    ///
539    /// A slot found still [`Recording`](SlotState::Recording) is that slot: it
540    /// means two copies were recorded with no [`begin_frame`](Self::begin_frame)
541    /// between them, so nothing ever requested a readback for what is in it and
542    /// the newer copy may simply overwrite it. Taking a fresh slot instead would
543    /// leave that one recording for the life of the ring.
544    fn take_slot(&mut self) -> Option<usize> {
545        let len = self.slots.len();
546        if let Some(index) = self
547            .slots
548            .iter()
549            .position(|slot| matches!(slot.state, SlotState::Recording))
550        {
551            return Some(index);
552        }
553        let index = (0..len)
554            .map(|step| (self.next + step) % len)
555            .find(|&index| matches!(self.slots[index].state, SlotState::Idle))?;
556        self.slots[index].state = SlotState::Recording;
557        self.next = (index + 1) % len;
558        Some(index)
559    }
560
561    /// Adds the copy that takes this frame's statistics off the GPU.
562    ///
563    /// `stats` is the id
564    /// [`GeneratedDraws::visible_count_id`](crate::draw_gen::GeneratedDraws::visible_count_id)
565    /// handed back, so **the graph** moves the buffer into
566    /// [`ResourceState::TransferSrc`] and back out again; there is not a
567    /// hand-written barrier here, which is the whole difference between this and
568    /// `crcbl::screenshot`'s copy.
569    ///
570    /// Declare it **last**, after every pass that writes that buffer: the cull
571    /// dispatch, the amplification stage and the light grid all add to it, and a
572    /// copy scheduled between them reads a total half the frame has not
573    /// contributed to yet.
574    ///
575    /// Nothing is added on a frame that finds every slot still waiting on an
576    /// answer. The alternative is a copy into a buffer a readback is still
577    /// mapping, and a frame's statistics are worth far less than that: the panel
578    /// keeps the number it has, still stamped with the frame it came from, and
579    /// the next frame after an answer lands records a copy again.
580    ///
581    /// # The destination is in the graph too, and it has to be
582    ///
583    /// A slot is written by a copy this frame and was written by a copy some
584    /// frames ago — **two writes, in two submissions, with nothing between
585    /// them**. That is a write-after-write hazard exactly like the one the graph
586    /// already computes for the depth transient across a frame boundary, and it
587    /// is not made safe by the readback's completion point: a timeline gates the
588    /// *host's read*, which is a different edge from the GPU's second write.
589    ///
590    /// So the slot is imported with what the last frame on it left it in —
591    /// `Undefined` the first time and `TransferDst` thereafter — and the copy
592    /// declares [`ResourceState::TransferDst`] on it, which makes the graph emit
593    /// `TransferDst → TransferDst` before the copy: a barrier whose source scope
594    /// covers that earlier submission's transfer write. An earlier version of
595    /// this function left the destination out on the grounds that "nothing else
596    /// in the frame touches it", which is true and beside the point — the
597    /// conflicting access is in *another* frame. CI's validation layer reported
598    /// it as `SYNC-HAZARD-WRITE-AFTER-WRITE … write_barriers: 0`; ours cannot
599    /// see across submissions at all.
600    ///
601    /// The state never changes after that, which is also what D3D12 requires: a
602    /// resource on the `READBACK` heap is created in `COPY_DEST` and pinned
603    /// there for its lifetime, so `TransferDst` is the only state this buffer
604    /// may ever be declared in.
605    pub fn add_copy_pass(&mut self, graph: &mut RenderGraph<'_>, stats: BufferId) {
606        if self.off {
607            return;
608        }
609        let Some(index) = self.take_slot() else {
610            return;
611        };
612        let frame = self.frames;
613        let recorded = Arc::clone(&self.recorded);
614        let slot = &mut self.slots[index];
615        let handle = slot.buffer;
616        let dst = graph.import_buffer(
617            "cull-stats-slot",
618            ImportedBuffer {
619                buffer: handle,
620                initial: slot.imported,
621                final_state: ResourceState::TransferDst,
622            },
623        );
624        // Set here rather than from inside the body, and deliberately: a graph
625        // that is built and dropped leaves the buffer in whatever it was, and
626        // claiming a write that never happened only makes the *next* barrier
627        // wait for something already finished. Claiming `Undefined` after a
628        // write that did happen would drop the source scope, which is the bug
629        // this whole comment is about.
630        slot.imported = ResourceState::TransferDst;
631        graph
632            .add_copy_pass("cull-stats-readback")
633            .use_buffer(stats, ResourceState::TransferSrc)
634            .use_buffer(dst, ResourceState::TransferDst)
635            .execute(move |ctx| {
636                let src = ctx.buffer(stats);
637                let dst = ctx.buffer(dst);
638                ctx.encoder().copy_buffer_to_buffer(&BufferCopy {
639                    src,
640                    src_offset: 0,
641                    dst,
642                    dst_offset: 0,
643                    size: SLOT_BYTES,
644                });
645                // Recorded, so the next `begin_frame` may ask for it. Nothing
646                // stamps this if the graph is dropped rather than executed.
647                recorded.store(frame, Ordering::Relaxed);
648            });
649    }
650
651    /// Switches the ring off after a seam error, releasing what it can.
652    ///
653    /// Once rather than per frame: whatever refused a readback will refuse the
654    /// next one, and a profiler that logs a line per frame forever is one nobody
655    /// reads.
656    fn give_up(&mut self, device: &dyn Device, why: &str) {
657        self.off = true;
658        self.latest = None;
659        crcbl_core::log::warn!("cull stats: {why}; the culling counters are off (said once)");
660        for slot in &mut self.slots {
661            if let SlotState::Polling { readback, .. } = slot.state {
662                device.destroy_readback(readback);
663            }
664            slot.state = SlotState::Idle;
665        }
666    }
667
668    /// Releases the ring. The device must be idle.
669    pub fn destroy(self, device: &dyn Device) {
670        for slot in &self.slots {
671            if let SlotState::Polling { readback, .. } = slot.state {
672                device.destroy_readback(readback);
673            }
674            device.destroy_buffer(slot.buffer);
675        }
676    }
677}
678
679/// One `u32` of the statistics block, little-endian as every backend writes it.
680///
681/// Indexed by word rather than by byte offset so the two counters are named by
682/// `crcbl_shaders`' constants and not by arithmetic repeated at each call site.
683fn word(bytes: &[u8; SLOT_BYTES as usize], index: u32) -> u32 {
684    let start = index as usize * 4;
685    u32::from_le_bytes([
686        bytes[start],
687        bytes[start + 1],
688        bytes[start + 2],
689        bytes[start + 3],
690    ])
691}
692
693// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
694#[cfg(all(test, not(target_arch = "wasm32")))]
695mod tests {
696    use super::*;
697    use crcbl_hal::null::{Command, NullInstance, Recorder};
698    use crcbl_hal::{
699        AdapterId, CommandEncoderDesc, DeviceDesc, Instance, QueueHandle, QueueKind, SubmitInfo,
700    };
701
702    use crate::graph::ImportedBuffer;
703    use crate::transient::TransientPool;
704
705    /// How many frames a caller keeps in flight, and therefore one less than the
706    /// ring's length. Two, as every frame loop in this engine runs.
707    const FRAMES_IN_FLIGHT: usize = 2;
708
709    /// Frames a test runs before deciding the ring has stopped reporting.
710    ///
711    /// Generous rather than exact: which frame an answer lands on is the
712    /// device's to decide — that is what polling until it answers means — so a
713    /// test that pinned the number would be asserting the null backend's
714    /// readback latency and calling it the ring's behaviour.
715    const BOUND: u64 = 16;
716
717    /// A device, a statistics buffer shaped like [`DrawGen`]'s, and a frame that
718    /// runs the ring end to end without a driver.
719    ///
720    /// [`DrawGen`]: crate::draw_gen::DrawGen
721    struct Harness {
722        recorder: Recorder,
723        device: Box<dyn Device>,
724        queue: QueueHandle,
725        stats: BufferHandle,
726        pool: TransientPool,
727    }
728
729    impl Harness {
730        fn open() -> Self {
731            let recorder = Recorder::new();
732            let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
733            let device = instance
734                .create_device(&DeviceDesc::for_adapter(AdapterId(0)))
735                .expect("the gpu_driven preset opens");
736            let queue = device.queue(QueueKind::Graphics).expect("always present");
737            let stats = device
738                .create_buffer(&BufferDesc {
739                    label: Some("cull stats"),
740                    size: SLOT_BYTES,
741                    usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
742                    memory: MemoryLocation::DeviceLocal,
743                })
744                .expect("a device-local counter buffer");
745            Self {
746                recorder,
747                device,
748                queue,
749                stats,
750                pool: TransientPool::new(),
751            }
752        }
753
754        /// One frame: begin, declare the copy, compile, execute, submit — the
755        /// order every caller records in, and the order the request depends on.
756        fn frame(&mut self, ring: &mut CullStatsRing) {
757            let device = self.device.as_ref();
758            ring.begin_frame(device);
759            let mut graph = RenderGraph::new(self.queue);
760            let stats = graph.import_buffer(
761                "cull-count",
762                ImportedBuffer {
763                    buffer: self.stats,
764                    initial: ResourceState::ShaderRead,
765                    final_state: ResourceState::ShaderRead,
766                },
767            );
768            ring.add_copy_pass(&mut graph, stats);
769            let compiled = graph.compile(&self.pool).expect("a legal frame");
770            let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
771                label: Some("cull stats frame"),
772                queue: self.queue,
773            });
774            compiled
775                .execute(device, &mut self.pool, encoder.as_mut(), None)
776                .expect("the graph executed");
777            let commands = encoder.finish().expect("recording succeeded");
778            device
779                .submit(self.queue, &SubmitInfo::new(&[commands]))
780                .expect("submitted");
781            device.destroy_command_buffer(commands);
782        }
783
784        fn ring(&self, counts_clusters: bool) -> CullStatsRing {
785            CullStatsRing::new(self.device.as_ref(), FRAMES_IN_FLIGHT, counts_clusters)
786                .expect("the null backend gives out readback buffers")
787        }
788
789        fn finish(self, ring: CullStatsRing) {
790            ring.destroy(self.device.as_ref());
791            self.device.destroy_buffer(self.stats);
792        }
793    }
794
795    /// **Each counter is read from its own word.** Several counters in one buffer
796    /// is exactly the arrangement where an off-by-one offset reports another
797    /// one's total and looks entirely plausible, so each is given a different
798    /// value and read back by name.
799    #[test]
800    fn a_counter_is_read_from_its_own_word() {
801        let bytes = stats_bytes();
802        assert_eq!(word(&bytes, cull::INSTANCE_SURVIVOR_WORD), 7);
803        assert_eq!(word(&bytes, cull::CLUSTER_SURVIVOR_WORD), 9);
804        assert_eq!(word(&bytes, cull::CLUSTER_FRUSTUM_REJECT_WORD), 13);
805        assert_eq!(word(&bytes, cull::CLUSTER_CONE_REJECT_WORD), 17);
806    }
807
808    /// The statistics buffer with a different number in every word, so a field
809    /// filled from the wrong one is a different number rather than a coincidence.
810    ///
811    /// Word 2 is the light grid's dropped-assignment count — a decoy on purpose:
812    /// it sits *between* the survivor word and the two rejection words, so a
813    /// mapping that walked the buffer in order rather than indexing it by name
814    /// would report it as a cull statistic.
815    fn stats_bytes() -> [u8; SLOT_BYTES as usize] {
816        let mut bytes = [0u8; SLOT_BYTES as usize];
817        for (index, value) in [
818            (cull::INSTANCE_SURVIVOR_WORD, 7u32),
819            (cull::CLUSTER_SURVIVOR_WORD, 9),
820            (crcbl_shaders::light::CLUSTER_OVERFLOW_WORD, 11),
821            (cull::CLUSTER_FRUSTUM_REJECT_WORD, 13),
822            (cull::CLUSTER_CONE_REJECT_WORD, 17),
823            (cull::OCCLUSION_EARLY_REJECT_WORD, 19),
824            (cull::OCCLUSION_LATE_REJECT_WORD, 23),
825            (cull::SMALL_FEATURE_REJECT_WORD, 29),
826        ] {
827            let at = index as usize * 4;
828            bytes[at..at + 4].copy_from_slice(&value.to_le_bytes());
829        }
830        bytes
831    }
832
833    /// **The three cluster counters land in the three fields that name them.**
834    ///
835    /// The word-to-field mapping is the whole of what makes the split real, and
836    /// nothing downstream can catch it being wrong: a frustum count reported as
837    /// survivors is a plausible number in a plausible field, and the three would
838    /// still sum to the size of the cut. So the report is driven directly, with
839    /// a distinct value in every word.
840    #[test]
841    fn each_cluster_counter_reaches_the_field_that_names_it() {
842        let harness = Harness::open();
843        let mut ring = harness.ring(true);
844        ring.report(3, &stats_bytes());
845        assert_eq!(
846            ring.latest(),
847            Some(CullStats {
848                instances: 7,
849                clusters: Some(ClusterCull {
850                    survivors: 9,
851                    frustum_rejects: 13,
852                    cone_rejects: 17,
853                }),
854                // And the occlusion words beside them, on the same terms: a
855                // distinct value in each, so a word read for its neighbour is a
856                // different number here.
857                occlusion: OcclusionCull {
858                    early_rejects: 19,
859                    late_rejects: 23,
860                    small_feature_rejects: 29,
861                },
862                frame: 3,
863            }),
864        );
865        harness.finish(ring);
866    }
867
868    /// **The copy really is in the frame, and it is outside every pass scope.**
869    ///
870    /// The recorded stream is the evidence for both halves: the command is
871    /// there, it names this ring's own buffer as the destination, and the null
872    /// backend — which checks the seam's scope rules — recorded no violation. A
873    /// copy declared as a compute pass records the same command and fails the
874    /// second half.
875    #[test]
876    fn the_copy_is_recorded_and_sits_outside_every_pass() {
877        let mut harness = Harness::open();
878        let mut ring = harness.ring(false);
879        harness.frame(&mut ring);
880
881        let copies: Vec<BufferCopy> = harness
882            .recorder
883            .commands()
884            .into_iter()
885            .filter_map(|command| match command {
886                Command::CopyBufferToBuffer(copy) => Some(copy),
887                _ => None,
888            })
889            .collect();
890        assert_eq!(copies.len(), 1, "one copy per frame, no more and no less");
891        assert_eq!(copies[0].src, harness.stats);
892        assert_eq!(copies[0].size, SLOT_BYTES);
893        assert!(
894            ring.slots.iter().any(|slot| slot.buffer == copies[0].dst),
895            "the copy must land in this ring's own slot",
896        );
897        harness.recorder.assert_valid();
898
899        harness.finish(ring);
900    }
901
902    /// **The barriers around the copy are the graph's, and they put the counter
903    /// buffer back.**
904    ///
905    /// `ShaderRead → TransferSrc` before it, and the graph's final barrier back
906    /// to `ShaderRead` — which is the state the next frame on that slot imports
907    /// it in. A copy pass that declared nothing would record the same copy with
908    /// no transition at all, and the buffer would be read as a shader resource
909    /// while the transfer was still in flight.
910    #[test]
911    fn the_graph_moves_the_counter_buffer_through_transfer_src_and_back() {
912        let mut harness = Harness::open();
913        let mut ring = harness.ring(false);
914        harness.frame(&mut ring);
915
916        let transitions: Vec<(ResourceState, ResourceState)> = harness
917            .recorder
918            .commands()
919            .into_iter()
920            .filter_map(|command| match command {
921                Command::Barrier { buffers, .. } => Some(buffers),
922                _ => None,
923            })
924            .flatten()
925            .filter(|barrier| barrier.buffer == harness.stats)
926            .map(|barrier| (barrier.from, barrier.to))
927            .collect();
928        assert_eq!(
929            transitions,
930            [
931                (ResourceState::ShaderRead, ResourceState::TransferSrc),
932                (ResourceState::TransferSrc, ResourceState::ShaderRead),
933            ],
934        );
935
936        harness.finish(ring);
937    }
938
939    /// **A frame's write to a slot is ordered against the write the last frame
940    /// on that slot made** — the cross-submission hazard, caught with no driver
941    /// in the room.
942    ///
943    /// This is the bug this ring shipped with and CI's validation layer caught:
944    /// `SYNC-HAZARD-WRITE-AFTER-WRITE … write_barriers: 0`, one frame's
945    /// `vkCmdCopyBuffer` into a slot against an earlier frame's copy into the
946    /// same slot, in an earlier submission, with nothing between them. The
947    /// readback's completion point does not help: a timeline gates the *host's*
948    /// read, which is a different edge from the GPU's second write.
949    ///
950    /// It is asserted here, against the null backend, because the layer that
951    /// found it is one this repository cannot run everywhere: local runs report
952    /// `cross-submission=no` and see nothing of this class. That makes a
953    /// device-free assertion the durable half — the same argument
954    /// `crcbl-render`'s `a_second_frame_barriers_against_what_the_first_one_left`
955    /// makes for the depth transient.
956    ///
957    /// Both ends are checked, and the first is what stops the second being
958    /// vacuous: the **first** use of a slot names `Undefined` (there is nothing
959    /// to order against), and the **reusing** frame names `TransferDst` (there
960    /// is). A version that imported `Undefined` every time would emit a barrier
961    /// that passes a "was there a barrier" test and orders nothing at all,
962    /// because `Undefined` as a source expands to `srcStageMask = NONE`.
963    #[test]
964    fn a_reused_slot_barriers_against_the_frame_that_wrote_it_last() {
965        let mut harness = Harness::open();
966        let mut ring = harness.ring(false);
967
968        // The first turn of the ring: this slot has never been written.
969        harness.frame(&mut ring);
970        let slot = recording_slot(&ring);
971        assert_eq!(
972            barrier_before_the_copy_into(&harness.recorder, slot),
973            Some((ResourceState::Undefined, ResourceState::TransferDst)),
974            "a slot nothing has written orders against nothing, and says so",
975        );
976
977        // Round the ring until this same slot comes up again.
978        for _ in 1..ring.slots.len() {
979            harness.recorder.clear();
980            harness.frame(&mut ring);
981            assert_ne!(
982                recording_slot(&ring),
983                slot,
984                "the ring must hand out a different slot until it has turned over",
985            );
986        }
987        harness.recorder.clear();
988        harness.frame(&mut ring);
989        assert_eq!(
990            recording_slot(&ring),
991            slot,
992            "the ring has come round and this frame reuses the first slot",
993        );
994        assert_eq!(
995            barrier_before_the_copy_into(&harness.recorder, slot),
996            Some((ResourceState::TransferDst, ResourceState::TransferDst)),
997            "the copy into a reused slot must be ordered against the copy that wrote it last, \
998             and a source of `Undefined` would carry no scope to order against",
999        );
1000
1001        harness.finish(ring);
1002    }
1003
1004    /// The transition a recorded frame put on `buffer` **before** the copy that
1005    /// writes it, or `None` if there was no such barrier.
1006    ///
1007    /// The ordering is the assertion, not a detail: a barrier recorded *after*
1008    /// the copy orders the frame after next and leaves this one hazardous, and
1009    /// it would satisfy a test that only asked whether a barrier existed.
1010    fn barrier_before_the_copy_into(
1011        recorder: &Recorder,
1012        buffer: BufferHandle,
1013    ) -> Option<(ResourceState, ResourceState)> {
1014        let mut transition = None;
1015        for command in recorder.commands() {
1016            match command {
1017                Command::Barrier { buffers, .. } => {
1018                    if let Some(found) = buffers.iter().find(|barrier| barrier.buffer == buffer) {
1019                        transition = Some((found.from, found.to));
1020                    }
1021                }
1022                Command::CopyBufferToBuffer(copy) if copy.dst == buffer => return transition,
1023                _ => {}
1024            }
1025        }
1026        None
1027    }
1028
1029    /// The buffer the frame just run handed to its graph.
1030    ///
1031    /// Exactly one slot is [`SlotState::Recording`] between a frame's
1032    /// [`CullStatsRing::add_copy_pass`] and the next
1033    /// [`CullStatsRing::begin_frame`], which is where every caller of this looks.
1034    fn recording_slot(ring: &CullStatsRing) -> BufferHandle {
1035        let index = ring
1036            .slots
1037            .iter()
1038            .position(|slot| matches!(slot.state, SlotState::Recording))
1039            .expect("a frame that recorded its copy left exactly one slot recording");
1040        ring.slots[index].buffer
1041    }
1042
1043    /// How many of this ring's copies a recorded frame holds.
1044    ///
1045    /// By size rather than by destination, so it counts a copy into any slot:
1046    /// which slot a frame took is the ring's own business and the question here
1047    /// is only whether a copy was recorded at all.
1048    fn stats_copies(recorder: &Recorder) -> usize {
1049        recorder
1050            .commands()
1051            .iter()
1052            .filter(|command| {
1053                matches!(command, Command::CopyBufferToBuffer(copy) if copy.size == SLOT_BYTES)
1054            })
1055            .count()
1056    }
1057
1058    /// Runs frames until the ring reports something, and fails if `bound` frames
1059    /// go by without one.
1060    ///
1061    /// The bound is what makes this a test rather than a hang: a ring that has
1062    /// stopped reporting has to go red here rather than spin, which is exactly
1063    /// the failure the browser saw.
1064    fn run_until_reported(
1065        harness: &mut Harness,
1066        ring: &mut CullStatsRing,
1067        bound: u64,
1068    ) -> CullStats {
1069        for _ in 0..bound {
1070            harness.frame(ring);
1071            if let Some(stats) = ring.latest() {
1072                return stats;
1073            }
1074        }
1075        panic!("nothing was reported in {bound} frames");
1076    }
1077
1078    /// **Nothing is reported until a readback has actually answered, and the
1079    /// number says which frame it is from.**
1080    ///
1081    /// Three points, in the frames the module documents: the copy is recorded on
1082    /// frame 1, the request for it is made on frame 2 — a readback covers work
1083    /// already *submitted*, and frame 1's submission is what it covers — and the
1084    /// first poll is on frame 3. So a report on frame 1 or 2 would be one
1085    /// invented before any readback was even asked for, and the frame it names
1086    /// must be the frame whose copy it is rather than the frame it landed on.
1087    ///
1088    /// The frame numbers are what has teeth here: a ring that read the slot it
1089    /// had just requested would report frame 2 on frame 2, and one that reported
1090    /// the current frame would say 3.
1091    #[test]
1092    fn nothing_is_reported_until_a_readback_has_answered() {
1093        let mut harness = Harness::open();
1094        let mut ring = harness.ring(false);
1095        assert_eq!(ring.latest(), None, "nothing has been recorded yet");
1096
1097        harness.frame(&mut ring);
1098        assert_eq!(ring.latest(), None, "frame 1 has only recorded its copy");
1099        harness.frame(&mut ring);
1100        assert_eq!(
1101            ring.latest(),
1102            None,
1103            "frame 2 made the request; polling it here would ask about a frame still being \
1104             recorded",
1105        );
1106
1107        harness.frame(&mut ring);
1108        let stats = ring.latest().expect("the first request has answered");
1109        assert_eq!(
1110            stats.frame, 1,
1111            "the report names the frame whose copy it is, not the frame it landed on",
1112        );
1113
1114        harness.frame(&mut ring);
1115        assert_eq!(
1116            ring.latest().expect("and the ring keeps turning").frame,
1117            2,
1118            "each further frame advances the report by one",
1119        );
1120
1121        harness.finish(ring);
1122    }
1123
1124    /// **A device whose first poll answers `Pending` still reports, within a
1125    /// bounded number of frames.**
1126    ///
1127    /// This is the browser, and it is the bug this test exists for: `crcbl-webgpu`
1128    /// answers a `poll_readback` by *encoding* the question onto the command
1129    /// stream, so the first poll on a handle is `Pending` however long the map
1130    /// has been ready, and the answer arrives a frame later. A ring that polled a
1131    /// slot once and released it on the next line — which this one did — threw
1132    /// every answer away unread and reported nothing at all in a browser, for
1133    /// ever, while every native backend went on passing because they can answer
1134    /// their first poll.
1135    ///
1136    /// Red against that ring: [`Recorder::set_readback_latency`] makes N polls
1137    /// answer `Pending` first, which is the one thing no hardware in CI will
1138    /// reproduce. A test that only ran the null backend's instant readback — or a
1139    /// real GPU — cannot fail here, which is why neither caught it.
1140    ///
1141    /// The counts run past the ring's own depth deliberately: three slots and a
1142    /// readback that needs four polls means a frame where every slot is still
1143    /// waiting, and the ring has to record no copy that frame and carry on rather
1144    /// than wedge.
1145    #[test]
1146    fn a_first_poll_that_answers_pending_still_reports() {
1147        for pending_polls in 1..=4u32 {
1148            let mut harness = Harness::open();
1149            harness.recorder.set_readback_latency(pending_polls);
1150            let mut ring = harness.ring(false);
1151
1152            // Two frames to record and request, one poll per frame after that,
1153            // and room for the frames the ring spends with no free slot.
1154            let bound = 2 * (2 + u64::from(pending_polls) + ring.slots.len() as u64);
1155            let first = run_until_reported(&mut harness, &mut ring, bound);
1156            assert_eq!(
1157                first.frame, 1,
1158                "the first frame's copy is the first thing to answer, {pending_polls} pending \
1159                 polls or not",
1160            );
1161
1162            // And it keeps moving: a ring that reported once and stopped —
1163            // because it never freed the slot it read — would pass everything
1164            // above.
1165            let mut later = first;
1166            for _ in 0..bound {
1167                harness.frame(&mut ring);
1168                later = ring.latest().expect("a report never goes back to nothing");
1169                if later.frame > first.frame {
1170                    break;
1171                }
1172            }
1173            assert!(
1174                later.frame > first.frame,
1175                "the ring stopped reporting after its first answer: {later:?}",
1176            );
1177
1178            harness.finish(ring);
1179        }
1180    }
1181
1182    /// **A slot that has not come back reports nothing rather than its bytes.**
1183    ///
1184    /// The null backend's readback latency is the only way to reach this. What is
1185    /// in the buffer belongs to an older frame — nothing has said otherwise —
1186    /// and reporting it would put a stale number on the panel under a fresh
1187    /// frame's label.
1188    #[test]
1189    fn a_readback_that_never_completes_reports_nothing() {
1190        let mut harness = Harness::open();
1191        // More polls than this test will ever make, so every slot stays pending.
1192        harness.recorder.set_readback_latency(1_000);
1193        let mut ring = harness.ring(false);
1194
1195        for _ in 0..(ring.slots.len() * 3) {
1196            harness.frame(&mut ring);
1197            assert_eq!(ring.latest(), None, "a pending slot has nothing to report");
1198        }
1199
1200        harness.finish(ring);
1201    }
1202
1203    /// **A device that stops answering does not grow the ring, and does not wedge
1204    /// it either.**
1205    ///
1206    /// Every slot ends up waiting on an answer that never comes, and from there
1207    /// two things must hold: the ring holds no more than the buffers and requests
1208    /// it already had — one leaked readback per frame is what an unbounded
1209    /// version looks like — and [`POLL_DEADLINE`] eventually hands the slots back
1210    /// so the frame that follows records a copy again.
1211    ///
1212    /// The recorded stream is the observable for the second half: no copy while
1213    /// every slot is out, and a copy again once the deadline has passed.
1214    #[test]
1215    fn a_device_that_stops_answering_neither_leaks_slots_nor_wedges_the_ring() {
1216        let mut harness = Harness::open();
1217        // More polls than any device will ever be asked for, so nothing answers.
1218        harness.recorder.set_readback_latency(u32::MAX);
1219        let mut ring = harness.ring(false);
1220
1221        // Enough frames to put every slot out on a request.
1222        for _ in 0..=ring.slots.len() {
1223            harness.frame(&mut ring);
1224        }
1225        let live = harness.recorder.total_live_objects();
1226
1227        // Well inside the deadline: nothing has been handed back, so no frame
1228        // may copy into a buffer a readback still holds — and the ring must not
1229        // be growing while it waits.
1230        for _ in 0..(POLL_DEADLINE / 2) {
1231            harness.recorder.clear();
1232            harness.frame(&mut ring);
1233            assert_eq!(
1234                stats_copies(&harness.recorder),
1235                0,
1236                "a frame with no free slot must record no copy",
1237            );
1238            assert!(
1239                harness.recorder.total_live_objects() <= live,
1240                "the ring must not accumulate requests a device never answers",
1241            );
1242        }
1243
1244        // And past it: the slots come back and the ring records copies again.
1245        let mut copies = 0;
1246        for _ in 0..(2 * POLL_DEADLINE) {
1247            harness.recorder.clear();
1248            harness.frame(&mut ring);
1249            copies += stats_copies(&harness.recorder);
1250            assert!(
1251                harness.recorder.total_live_objects() <= live,
1252                "the ring must not accumulate requests a device never answers",
1253            );
1254        }
1255        assert!(
1256            copies > 0,
1257            "the deadline must hand the slots back, so the ring records copies again",
1258        );
1259        assert_eq!(
1260            ring.latest(),
1261            None,
1262            "and still reports nothing it never read"
1263        );
1264
1265        harness.finish(ring);
1266    }
1267
1268    /// **A device that refuses the readback reports nothing, not zero.**
1269    ///
1270    /// A zero in the culling row reads as "the cull kept nothing" — a scene that
1271    /// vanished — which is a far worse answer than an honest absence. So the
1272    /// ring gives up for good, and what it reported before the failure goes with
1273    /// it rather than sitting on the panel as a number that stopped moving.
1274    #[test]
1275    fn a_device_that_refuses_the_readback_reports_nothing_rather_than_zero() {
1276        let mut harness = Harness::open();
1277        let mut ring = harness.ring(false);
1278        run_until_reported(&mut harness, &mut ring, BOUND);
1279        assert!(ring.latest().is_some(), "the ring was working");
1280
1281        // The device goes down between frames, so the next request is refused.
1282        // Only `begin_frame` is run from here: a lost device refuses to finish a
1283        // command buffer too, and this test is about the readback rather than
1284        // about the caller's frame.
1285        harness.recorder.lose_device("the test lost the device");
1286        ring.begin_frame(harness.device.as_ref());
1287        assert_eq!(ring.latest(), None, "a refused readback is not a zero");
1288        // And it stays off rather than trying again every frame.
1289        ring.begin_frame(harness.device.as_ref());
1290        assert_eq!(ring.latest(), None);
1291
1292        harness.finish(ring);
1293    }
1294
1295    /// **The cluster word is unknown where nothing counts clusters, not zero.**
1296    ///
1297    /// Both rings read the same bytes out of the same shaped buffer; the one
1298    /// built for a path with no amplification stage reports [`None`] and the one
1299    /// built for a path with one reports the number it read. A ring that always
1300    /// reported the word would say "no clusters survived" about three of the
1301    /// four ways this engine draws.
1302    #[test]
1303    fn the_cluster_word_is_unknown_where_no_stage_counts_it() {
1304        for (counts_clusters, expected) in [(false, None), (true, Some(ClusterCull::default()))] {
1305            let mut harness = Harness::open();
1306            let mut ring = harness.ring(counts_clusters);
1307            let stats = run_until_reported(&mut harness, &mut ring, BOUND);
1308            assert_eq!(stats.clusters, expected);
1309            harness.finish(ring);
1310        }
1311    }
1312
1313    /// **A frame whose graph never ran leaves nothing to read.**
1314    ///
1315    /// The copy is declared, the graph is dropped rather than executed, and the
1316    /// slot must stay empty: requesting a readback against it would return
1317    /// whatever the previous turn of the ring left there and report it under
1318    /// this frame's number. The `recorded` stamp is what tells the two apart,
1319    /// and this is the test that fails without it.
1320    #[test]
1321    fn a_graph_that_was_dropped_rather_than_executed_stamps_nothing() {
1322        let harness = Harness::open();
1323        let mut ring = harness.ring(false);
1324
1325        for _ in 0..BOUND {
1326            ring.begin_frame(harness.device.as_ref());
1327            let mut graph = RenderGraph::new(harness.queue);
1328            let stats = graph.import_buffer(
1329                "cull-count",
1330                ImportedBuffer {
1331                    buffer: harness.stats,
1332                    initial: ResourceState::ShaderRead,
1333                    final_state: ResourceState::ShaderRead,
1334                },
1335            );
1336            ring.add_copy_pass(&mut graph, stats);
1337            drop(graph);
1338            assert_eq!(ring.latest(), None, "no copy ran, so there is nothing back");
1339        }
1340
1341        harness.finish(ring);
1342    }
1343
1344    /// The ring releases every buffer and every outstanding request.
1345    #[test]
1346    fn the_ring_leaks_nothing() {
1347        let mut harness = Harness::open();
1348        let before = harness.recorder.total_live_objects();
1349        let mut ring = harness.ring(false);
1350        assert!(harness.recorder.total_live_objects() > before);
1351        harness.frame(&mut ring);
1352        harness.frame(&mut ring);
1353        ring.destroy(harness.device.as_ref());
1354        assert_eq!(
1355            harness.recorder.total_live_objects(),
1356            before,
1357            "every slot and every live readback must be released",
1358        );
1359        harness.device.destroy_buffer(harness.stats);
1360    }
1361}