Skip to main content

crcbl_render/
instance_pool.rs

1//! The instance array: one storage-buffer element per drawable object, written
2//! by **delta upload** — the changed elements only, coalesced into runs.
3//!
4//! ```text
5//!  set(handle, instance) ──▶ mirror[index] rewritten
6//!                            └─▶ index marked dirty in every frame's range set
7//!
8//!  begin_frame(device) ──▶ rotate to the next frame's buffer
9//!                          └─▶ one write_buffer per dirty run, then clear
10//!                              └─▶ nothing dirty ⇒ nothing written at all
11//! ```
12//!
13//! Topic 03 §3.2: "`GpuInstance` array (SSBO):
14//! transform, mesh id, material id, flags. Written by delta upload each frame
15//! (**changed instances only — dirty ranges, not full re-upload**)." The
16//! emphasis is the whole reason this type exists rather than a `Vec` re-uploaded
17//! every frame, which is what [`crate::sprite_pass`] does and what §3.2 is
18//! written against.
19//!
20//! The record itself — and which of its fields are reserved rather than working
21//! — is [`crcbl_shaders::mesh::GpuInstance`], because the layout is a contract
22//! with `mesh.slang` and belongs in the crate that owns that source.
23//!
24//! # Dirty runs, and the case they exist for
25//!
26//! The pool holds a sorted list of half-open runs that never touch and
27//! never overlap. Marking an index that **abuts** a run extends it; marking one
28//! that closes the gap between two runs merges them; marking one that is already
29//! inside a run does nothing. So writing instances 3, 4 and 5 produces one
30//! upload of three elements and writing 3 and 900 produces two uploads of one —
31//! whatever order the marks arrive in.
32//!
33//! Nothing merges across a gap, however small: two runs one element apart stay
34//! two. A gap-tolerant merge trades bytes for calls, and choosing where that
35//! trade sits needs a real scene to measure — §3.3's, which is also the first
36//! thing that will move more than one instance per frame.
37//!
38//! # A ring, because the previous frame is still reading
39//!
40//! There is one buffer **per frame in flight**, for the reason
41//! [`crate::forward`]'s uniform ring gives: an instance the CPU rewrites while
42//! the GPU is still drawing last frame is a read-after-write hazard across
43//! submissions, which is stage 2's headline risk for
44//! that stage.
45//!
46//! The consequence is that a write is dirty in **every** slot's range set, not
47//! one: each slot is a separate copy of the same logical array and each has to
48//! be caught up before it is drawn from. So one changed instance costs one small
49//! upload per frame for the next `frames_in_flight` frames, and then nothing.
50//! That is still delta upload — the cost is the size of what changed, not the
51//! size of the array — and [`InstancePool::begin_frame`] writes nothing at all
52//! once every slot has caught up.
53//!
54//! # Where each instance was last frame
55//!
56//! [`GpuInstance::previous_transform`] is the pool's field, not the caller's,
57//! the way the liveness bit is. [`InstancePool::set`] fills it from what the
58//! record already holds, [`InstancePool::insert`] fills it from the new
59//! transform — a spawn did not travel from anywhere — and
60//! [`InstancePool::rotate`] puts back at rest whatever moved a frame ago and
61//! has not moved again. [`InstancePool::set_bases`] is the one write that is
62//! **not** a move: it rewrites a record's two base vertices and leaves this
63//! field and the carry-forward enrolment exactly as they stand, because the
64//! per-frame re-point a skinned object goes through is not a caller saying the
65//! object travelled.
66//!
67//! That last step is what makes the field mean *last frame* rather than *the
68//! last time anyone wrote this*. An instance that moves for a while and then
69//! stands still is written on the frames it moves and not after; without the
70//! carry-forward its record would go on naming the transform it left, and every
71//! temporal consumer would go on smearing it along a journey that finished.
72//!
73//! It is the frame *before* the one being assembled that settles, because a
74//! caller writes a frame's instances and then calls
75//! [`InstancePool::begin_frame`] — so the moves of the frame about to be drawn
76//! have already happened by the time the rotate runs, and settling those would
77//! erase each one before it was ever drawn.
78//!
79//! The cost is one comparison per element per frame after the last write to it,
80//! and one extra upload of that element on the first frame it stands still.
81//! Nothing reads the field yet — topic 43 §9 is why
82//! it is here before its readers are.
83//!
84//! # The pool never grows
85//!
86//! Capacity is fixed by [`InstancePoolDesc`] and [`InstancePool::insert`] fails
87//! by name when it runs out. Same reason [`crate::mesh_pool`] gives: growing a
88//! device buffer means allocating a larger one, copying, and re-pointing every
89//! bind group that names the old one, in the middle of a frame.
90//!
91//! Unlike the geometry pools there is no fragmentation to report, because every
92//! instance is the same size: a slot that comes back fits whatever asks for it
93//! next. [`InstancePoolError::PoolFull`] therefore names one number where
94//! [`crate::mesh_pool::MeshPoolError::PoolExhausted`] names three.
95//!
96//! # What a removed instance leaves behind, and the one bit that says so
97//!
98//! [`InstancePool::remove`] frees the slot and retires the handle, and it
99//! rewrites **one field** of the element: it clears
100//! [`GpuInstance::LIVE`] from the record's flags and marks
101//! the slot dirty, so the next [`InstancePool::begin_frame`] carries the
102//! removal to the GPU. Everything else the removed instance held — its
103//! transform, its mesh id — stays exactly as it was.
104//!
105//! That is the whole contract, and it is what §3.3's cull pass needs: the pass
106//! walks the array from element zero, so a freed slot has to be able to say it
107//! is one. `cull.slang` asks the bit before it reads anything else in the
108//! record, and [`crate::cull::visible_instances`] — the CPU oracle — does the
109//! same.
110//!
111//! **The bit is the pool's, not the caller's.** [`InstancePool::insert`] and
112//! [`InstancePool::set`] set it whatever the caller passed, so an instance
113//! cannot arrive dead by omission, and a caller cannot clear it without going
114//! through `remove`. The other bits of the word are the caller's and are left
115//! alone.
116//!
117//! ## Why the record is not zeroed
118//!
119//! [`crate::mesh_pool::MeshPool::free`] clears its table entry to all zeroes,
120//! and the analogous move here would be to zero the whole instance. It is the
121//! wrong one. What the mesh table is doing is *writing the empty value of the
122//! field that answers the question* — `index_count` — and the fields it clears
123//! with it are ones a stale entry would otherwise be misread through; the
124//! parallel here is clearing the liveness bit, which is that same write.
125//!
126//! Zeroing the rest would make it worse rather than tidier. A zeroed transform
127//! is a degenerate box at the origin and a zeroed mesh id names table entry 0,
128//! which is an ordinary resident mesh — so a consumer that skipped the liveness
129//! check would see a removed instance as *visible whenever the origin is*,
130//! where leaving the record alone at least leaves it wherever it was. The
131//! failure a shortcut produces should not be the one that looks plausible.
132
133use core::ops::Range;
134
135use crcbl_core::{Handle, Pool};
136use crcbl_hal::{BufferDesc, BufferHandle, BufferUsage, Device, HalError, MemoryLocation};
137use crcbl_shaders::mesh::{GpuInstance, INSTANCE_STRIDE};
138
139/// Marker type for [`InstanceHandle`]. Uninhabited.
140#[derive(Debug)]
141pub enum Instance {}
142
143/// An instance in an [`InstancePool`]. Generational, so a removed instance's
144/// handle stops resolving rather than naming whatever took its slot.
145pub type InstanceHandle = Handle<Instance>;
146
147/// What an [`InstancePool`] refuses to do.
148#[derive(Debug, thiserror::Error)]
149pub enum InstancePoolError {
150    /// Every slot is in use.
151    ///
152    /// `in_use` is normally the number of live instances. It can exceed that
153    /// only through generation exhaustion — see [`Pool`]'s docs on retired
154    /// slots, which needs about 4.3 billion removals of one slot — and the two
155    /// are reported together so that case is legible rather than baffling.
156    #[error("the instance pool holds {capacity} instances and {in_use} of them are in use")]
157    PoolFull {
158        /// The pool's fixed capacity.
159        capacity: u32,
160        /// Slots that cannot be handed out.
161        in_use: u32,
162    },
163    /// A box handed over for an instance to be culled by has a non-finite
164    /// corner, or a `min` past its `max` on some axis.
165    ///
166    /// Refused rather than written, because the culls would test it as given:
167    /// an inverted box reaches no frustum and a `NaN` lane fails every plane
168    /// test, so either would drop the object from every view without a word.
169    /// See [`SkinnedInstanceDesc::bounds`](crate::SkinnedInstanceDesc::bounds).
170    #[error(
171        "an instance box must be finite with min <= max on every axis, and this one has min \
172         {min:?} and max {max:?}"
173    )]
174    InvalidBounds {
175        /// The box's lowest corner, as given.
176        min: [f32; 3],
177        /// Its highest corner, as given.
178        max: [f32; 3],
179    },
180    /// Anything the seam refused.
181    #[error(transparent)]
182    Hal(#[from] HalError),
183}
184
185/// Flattens a pool error into the seam's, for callers whose constructors are
186/// already `Result<_, HalError>`.
187///
188/// Same shape and same reason as [`crate::mesh_pool::MeshPoolError`]'s: the seam
189/// has no vocabulary for "this pool is full", so everything that is not already
190/// a [`HalError`] arrives as [`Backend`](HalError::Backend), which renders
191/// verbatim and keeps the numbers.
192impl From<InstancePoolError> for HalError {
193    fn from(error: InstancePoolError) -> Self {
194        match error {
195            InstancePoolError::Hal(hal) => hal,
196            other => Self::Backend(other.to_string()),
197        }
198    }
199}
200
201/// How large an [`InstancePool`] is, and what to call it.
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub struct InstancePoolDesc<'a> {
204    /// Debug name; each frame's buffer is named after it.
205    pub label: Option<&'a str>,
206    /// Instances the pool can hold. Fixed — see the [module docs](self).
207    pub capacity: u32,
208    /// How many buffers to keep, one per frame in flight. Must be at least one.
209    pub frames_in_flight: usize,
210}
211
212/// One `GpuInstance` array, mirrored on the host and uploaded by delta.
213///
214/// See the [module docs](self) for the coalescing rule, the ring, and what a
215/// removal leaves behind — all three are decisions rather than accidents.
216#[derive(Debug)]
217pub struct InstancePool {
218    /// One per frame in flight; `frame` says which is current.
219    buffers: Vec<BufferHandle>,
220    /// What has changed and not yet reached each buffer. Same length as
221    /// `buffers`, and indexed the same way.
222    dirty: Vec<DirtyRanges>,
223    /// The slot `begin_frame` last rotated to.
224    frame: usize,
225
226    /// The array exactly as a buffer holds it, so a dirty run is one contiguous
227    /// slice and there is no second copy of an instance to drift from this one.
228    mirror: Vec<u8>,
229    /// Generational slot allocation, and nothing else: the values live in
230    /// `mirror`. Reusing the crate's pool rather than writing a second
231    /// allocator that gets the generation-retirement rule subtly different.
232    slots: Pool<()>,
233    /// Elements a caller has written since the last [`InstancePool::rotate`],
234    /// which is what the frame being assembled now moves.
235    written_this_frame: Vec<u32>,
236    /// `written_this_frame` as it stood at the last [`InstancePool::rotate`]:
237    /// what the frame already drawn moved, and so what the next rotate has to
238    /// put back at rest. See the [module docs](self) on the previous transform.
239    written_last_frame: Vec<u32>,
240    /// Whether each element is already in `written_this_frame`, so a caller
241    /// that writes one instance repeatedly in a frame enrols it once. Indexed
242    /// by element, `capacity` long.
243    moved_mark: Vec<bool>,
244    capacity: u32,
245    /// One past the highest element [`InstancePool::insert`] has ever handed
246    /// out — what [`InstancePool::slot_count`] reports.
247    high_water: u32,
248    /// How many times the mirror has been written — [`InstancePool::revision`].
249    revision: u64,
250    /// Elements written since the last [`InstancePool::take_written`], each
251    /// once, in the order they were first written.
252    written_since_taken: Vec<u32>,
253    /// Whether each element is already in `written_since_taken`. Indexed by
254    /// element, `capacity` long.
255    written_since_taken_mark: Vec<bool>,
256}
257
258impl InstancePool {
259    /// Creates the ring, with every buffer **cleared**.
260    ///
261    /// Cleared rather than left as the driver handed it over, and for
262    /// [`crate::mesh_pool::MeshPool`]'s reason rather than for tidiness: a slot
263    /// nothing has written is read by anything that walks the array, and "a
264    /// zeroed element is a dead instance" is only a contract if it holds for
265    /// the slots no one has touched as well as for the ones
266    /// [`InstancePool::remove`] clears. A driver's leftovers are not zeroes,
267    /// and a leftover with [`GpuInstance::LIVE`] set is an instance the cull
268    /// pass keeps, at a transform nobody chose.
269    ///
270    /// This is why it was not always so: until the flags word had a defined
271    /// bit, zeroing bought nothing an element written before it is addressed
272    /// did not already have.
273    ///
274    /// The device buffers are created **before** the host mirror, so a capacity
275    /// no device could hold arrives as a [`HalError`] naming the buffer rather
276    /// than as an aborting host allocation of the same size.
277    ///
278    /// # Errors
279    ///
280    /// [`InstancePoolError::Hal`] from any seam call. A failure part-way through
281    /// releases whatever was already created.
282    ///
283    /// # Panics
284    ///
285    /// If `frames_in_flight` is zero: a ring with no buffers has nothing to
286    /// bind, and every later index into it would be the real failure.
287    pub fn new(
288        device: &dyn Device,
289        desc: &InstancePoolDesc<'_>,
290    ) -> Result<Self, InstancePoolError> {
291        assert!(
292            desc.frames_in_flight > 0,
293            "an instance pool needs at least one buffer to bind"
294        );
295        let stem = desc.label.unwrap_or("instance pool");
296        let size = u64::from(desc.capacity) * INSTANCE_STRIDE as u64;
297        let cleared = vec![0u8; desc.capacity as usize * INSTANCE_STRIDE];
298        let mut buffers = Vec::with_capacity(desc.frames_in_flight);
299        for frame in 0..desc.frames_in_flight {
300            let created = device
301                .create_buffer(&BufferDesc {
302                    label: Some(&format!("{stem} instances {frame}")),
303                    size,
304                    // Host-visible, so a delta is a `write_buffer` rather than a
305                    // staging copy needing a barrier inside a frame.
306                    // `crate::graph` is the only thing allowed to record a
307                    // barrier during a frame, and a per-frame transfer submit is
308                    // what §3.1's start-up upload path deliberately is not.
309                    usage: BufferUsage::STORAGE,
310                    memory: MemoryLocation::HostUpload,
311                })
312                // A buffer created and not cleared is one the failure path below
313                // has to release, so the clear happens here rather than in a
314                // second loop over the finished ring.
315                .and_then(|buffer| match device.write_buffer(buffer, 0, &cleared) {
316                    Ok(()) => Ok(buffer),
317                    Err(error) => {
318                        device.destroy_buffer(buffer);
319                        Err(error)
320                    }
321                });
322            match created {
323                Ok(buffer) => buffers.push(buffer),
324                Err(error) => {
325                    for buffer in buffers {
326                        device.destroy_buffer(buffer);
327                    }
328                    return Err(error.into());
329                }
330            }
331        }
332        Ok(Self {
333            buffers,
334            dirty: vec![DirtyRanges::default(); desc.frames_in_flight],
335            frame: 0,
336            mirror: vec![0; desc.capacity as usize * INSTANCE_STRIDE],
337            slots: Pool::new(),
338            written_this_frame: Vec::new(),
339            written_last_frame: Vec::new(),
340            moved_mark: vec![false; desc.capacity as usize],
341            capacity: desc.capacity,
342            high_water: 0,
343            revision: 0,
344            written_since_taken: Vec::new(),
345            written_since_taken_mark: vec![false; desc.capacity as usize],
346        })
347    }
348
349    /// The buffers, one per frame in flight, in slot order.
350    ///
351    /// A caller builds one bind group per slot naming the buffer at that slot,
352    /// and draws frame `n` with the group whose slot [`InstancePool::begin_frame`]
353    /// returned.
354    #[must_use]
355    pub fn buffers(&self) -> &[BufferHandle] {
356        &self.buffers
357    }
358
359    /// How many instances the pool can hold.
360    #[must_use]
361    pub const fn capacity(&self) -> u32 {
362        self.capacity
363    }
364
365    /// How many instances are live.
366    #[must_use]
367    pub const fn len(&self) -> usize {
368        self.slots.len()
369    }
370
371    /// Whether no instance is live.
372    #[must_use]
373    pub const fn is_empty(&self) -> bool {
374        self.slots.is_empty()
375    }
376
377    /// Array elements anything walking the pool has to cover: one past the
378    /// highest slot ever handed out.
379    ///
380    /// **Not [`InstancePool::len`]**, which counts live instances and so shrinks
381    /// when one is removed while the slots above it stay occupied. A cull
382    /// dispatch sized by `len` would silently stop testing the instances past
383    /// the gap, which reads as "those were culled".
384    ///
385    /// It never shrinks, because a slot handed out once may be handed out again
386    /// and nothing compacts the array. Every element below it is either a live
387    /// instance or a dead record — [`InstancePool::remove`] leaves one, and
388    /// [`InstancePool::new`] clears the buffers so an untouched slot is one too
389    /// — which is what makes walking the whole range safe.
390    /// How many times any element of the array has been written, over the
391    /// pool's whole life.
392    ///
393    /// **A number to compare with an older reading of itself, not to interpret**
394    /// — two readings that differ say the instances a pass draws are not the
395    /// ones it drew last time it looked, and two that agree say they are. What
396    /// wants that is a consumer whose output is a function of the array and can
397    /// be kept instead of recomputed. `ForwardRenderer`'s shadow atlas was the
398    /// one there was, and it now asks [`take_written`](Self::take_written)
399    /// instead, which says which elements moved rather than that one did.
400    ///
401    /// It moves on **every** write, including ones no draw could see: a rewrite
402    /// with identical bytes (which [`set`](Self::set) deliberately does not
403    /// filter), a re-point of a skinned object's bases, and the settling of a
404    /// `previous_transform` the frame after a move stopped. Reading it as "the
405    /// scene changed" is therefore conservative in the safe direction — it says
406    /// *changed* more often than a byte comparison would, and never says
407    /// *unchanged* when a byte moved.
408    ///
409    /// It counts writes rather than hashing the array because the array is the
410    /// pool's own capacity in bytes and this is read once a frame.
411    #[must_use]
412    pub const fn revision(&self) -> u64 {
413        self.revision
414    }
415
416    /// Appends every element written since the last call to `into`, each once
417    /// and in the order it was first written, and forgets them here.
418    ///
419    /// [`revision`](Self::revision) says *that* the array changed; this says
420    /// **which elements** did, on the same terms — every write counts,
421    /// including a rewrite with identical bytes, a re-point of a skinned
422    /// object's bases and the settling of a `previous_transform`, so an element
423    /// is left out only when nothing wrote it. What wants that is a consumer
424    /// that can tell which of its outputs an element could reach:
425    /// `ForwardRenderer`'s shadow atlas tests each written element's bounds,
426    /// before and after, against each shadow group's cull, so one moving
427    /// instance redraws the maps it can be seen in rather than every map.
428    ///
429    /// The log is bounded by [`capacity`](Self::capacity), because an element
430    /// already in it is not added again — a pool nobody drains costs at most
431    /// one entry per element.
432    pub fn take_written(&mut self, into: &mut Vec<u32>) {
433        for index in self.written_since_taken.drain(..) {
434            self.written_since_taken_mark[index as usize] = false;
435            into.push(index);
436        }
437    }
438
439    /// What element `index` holds, live or not, decoded from the host mirror,
440    /// or [`None`] at or past [`slot_count`](Self::slot_count).
441    ///
442    /// By element rather than by handle, for a caller that learned the index
443    /// from [`take_written`](Self::take_written): a removed instance's element
444    /// still holds its last transform and mesh with
445    /// [`GpuInstance::LIVE`] cleared, which is what says it draws nothing now.
446    #[must_use]
447    pub fn record(&self, index: u32) -> Option<GpuInstance> {
448        (index < self.high_water).then(|| self.read(index))
449    }
450
451    #[must_use]
452    pub const fn slot_count(&self) -> u32 {
453        self.high_water
454    }
455
456    /// Takes a slot, writes `instance` into it **live**, and marks it dirty
457    /// everywhere.
458    ///
459    /// [`GpuInstance::LIVE`] is set whatever `instance.flags` carried — see the
460    /// [module docs](self) on why the bit is the pool's rather than the
461    /// caller's.
462    ///
463    /// # Errors
464    ///
465    /// [`InstancePoolError::PoolFull`] when every slot is in use. The pool never
466    /// grows — see the [module docs](self).
467    pub fn insert(&mut self, instance: &GpuInstance) -> Result<InstanceHandle, InstancePoolError> {
468        // `Pool` hands out a fresh index only when it has no vacant slot, so
469        // "live plus permanently retired" is exactly the highest index it could
470        // be about to create. Checking before inserting rather than after keeps
471        // a refused insert from burning a generation.
472        let in_use = self.in_use();
473        if in_use >= self.capacity {
474            return Err(InstancePoolError::PoolFull {
475                capacity: self.capacity,
476                in_use,
477            });
478        }
479        let handle: InstanceHandle = self.slots.insert(()).cast();
480        self.high_water = self.high_water.max(handle.index() + 1);
481        // **A spawn did not travel from anywhere**, so the record is created
482        // already at rest: whatever the slot held before belonged to another
483        // instance, and carrying it forward would give the new one a motion
484        // vector across the gap between them.
485        self.write_live(handle.index(), instance, instance.transform);
486        Ok(handle)
487    }
488
489    /// Rewrites `handle`'s instance and marks it dirty everywhere.
490    ///
491    /// Returns whether the handle named a live instance; a stale one writes
492    /// nothing rather than overwriting whatever took its slot.
493    ///
494    /// [`GpuInstance::LIVE`] is set, exactly as [`InstancePool::insert`] sets
495    /// it: a live instance cannot be made dead by rewriting it, only by
496    /// [`InstancePool::remove`].
497    ///
498    /// A rewrite with the same bytes still marks the slot dirty. Filtering that
499    /// would trade a comparison per write for an upload that mostly does not
500    /// happen, and it would make "what got uploaded" depend on the old value —
501    /// which is exactly the kind of thing a caller cannot reason about. Callers
502    /// that know a value did not change do not call this.
503    pub fn set(&mut self, handle: InstanceHandle, instance: &GpuInstance) -> bool {
504        if !self.slots.contains(handle.cast()) {
505            return false;
506        }
507        // Where it was is what the record already holds, which is why the
508        // caller does not pass it — see [`GpuInstance::previous_transform`].
509        let previous = self.read(handle.index()).transform;
510        self.write_live(handle.index(), instance, previous);
511        true
512    }
513
514    /// Rewrites `handle`'s two base vertices and **nothing else** — the
515    /// previous transform the record already holds included.
516    ///
517    /// Returns whether the handle named a live instance; a stale one writes
518    /// nothing, on [`InstancePool::set`]'s terms. The record keeps
519    /// [`GpuInstance::LIVE`], because every path that puts one in the mirror is
520    /// a path that set the bit.
521    ///
522    /// **It exists because a re-point is not a move.**
523    /// [`ForwardRenderer::point_skinned_instances`](crate::forward::ForwardRenderer)
524    /// rewrites every skinned object's pair of bases once a frame, between the
525    /// [`rotate`](Self::rotate) and the upload, and doing that through
526    /// [`set`](Self::set) made it a *transform* write: `set` takes the previous
527    /// transform from the record it overwrites, and by then that record already
528    /// carries this frame's transform, so `previous_transform` came out equal to
529    /// `transform` for every skinned instance on every frame. A character that
530    /// walked contributed nothing to the motion target from the walk.
531    ///
532    /// It also leaves the element out of the next [`rotate`](Self::rotate)'s
533    /// carry-forward, which is the same reason from the other side: a call that
534    /// runs for every skinned object every frame would keep each of them
535    /// permanently written-this-frame, nothing would ever be put back at rest,
536    /// and one move would be reported for ever. What enrols an element is a
537    /// caller's own write — [`insert`](Self::insert) and [`set`](Self::set).
538    pub fn set_bases(
539        &mut self,
540        handle: InstanceHandle,
541        base_vertex: u32,
542        previous_base_vertex: u32,
543    ) -> bool {
544        if !self.slots.contains(handle.cast()) {
545            return false;
546        }
547        let index = handle.index();
548        let mut record = self.read(index);
549        record.base_vertex = base_vertex;
550        record.previous_base_vertex = previous_base_vertex;
551        self.write(index, &record);
552        true
553    }
554
555    /// Rewrites `handle`'s flags word and **nothing else**, on
556    /// [`set_bases`](Self::set_bases)' terms: a flag is not a move, so the
557    /// transform history is left as it is and the element is not enrolled in the
558    /// next [`rotate`](Self::rotate)'s carry-forward.
559    ///
560    /// [`GpuInstance::LIVE`] is kept set whatever `flags` says, because the pool
561    /// owns that bit. Returns whether the handle named a live instance; a stale
562    /// one writes nothing.
563    pub fn set_flags(&mut self, handle: InstanceHandle, flags: u32) -> bool {
564        if !self.slots.contains(handle.cast()) {
565            return false;
566        }
567        let index = handle.index();
568        let mut record = self.read(index);
569        record.flags = flags | GpuInstance::LIVE;
570        self.write(index, &record);
571        true
572    }
573
574    /// Rewrites `handle`'s own box and the
575    /// [`GpuInstance::OWNS_BOUNDS`] bit that says the culls read it, and
576    /// **nothing else**, on [`set_bases`](Self::set_bases)' terms: a box is not
577    /// a move, so the transform history is left as it is and the element is
578    /// not enrolled in the next [`rotate`](Self::rotate)'s carry-forward.
579    ///
580    /// `owns` is the bit or zero; any other bit in it is ignored. Returns
581    /// whether the handle named a live instance; a stale one writes nothing.
582    pub fn set_bounds(
583        &mut self,
584        handle: InstanceHandle,
585        owns: u32,
586        bounds_min: [f32; 3],
587        bounds_max: [f32; 3],
588    ) -> bool {
589        if !self.slots.contains(handle.cast()) {
590            return false;
591        }
592        let index = handle.index();
593        let mut record = self.read(index);
594        record.flags =
595            (record.flags & !GpuInstance::OWNS_BOUNDS) | (owns & GpuInstance::OWNS_BOUNDS);
596        record.bounds_min = bounds_min;
597        record.bounds_max = bounds_max;
598        self.write(index, &record);
599        true
600    }
601
602    /// Clears `bits` from the flags of every live instance that carries any of
603    /// them, and writes only those.
604    ///
605    /// A walk over every slot ever handed out, for a change that is rare by
606    /// nature — a view being released, whose bit every record has to stop
607    /// carrying. [`GpuInstance::LIVE`] is never cleared here, whatever `bits`
608    /// holds.
609    pub fn clear_flags(&mut self, bits: u32) {
610        let bits = bits & !GpuInstance::LIVE;
611        for index in 0..self.high_water {
612            let mut record = self.read(index);
613            if record.flags & GpuInstance::LIVE == 0 || record.flags & bits == 0 {
614                continue;
615            }
616            record.flags &= !bits;
617            self.write(index, &record);
618        }
619    }
620
621    /// What `handle`'s slot currently holds, decoded from the host mirror, or
622    /// `None` if the handle is stale.
623    ///
624    /// The record carries [`GpuInstance::LIVE`], because the pool put it there:
625    /// this is what the buffer holds, not what the caller passed.
626    #[must_use]
627    pub fn get(&self, handle: InstanceHandle) -> Option<GpuInstance> {
628        self.slots
629            .contains(handle.cast())
630            .then(|| self.read(handle.index()))
631    }
632
633    /// Every live element of the array, in slot order.
634    ///
635    /// **The records the device would draw**, decoded from the same mirror the
636    /// buffers are filled from — including
637    /// [`GpuInstance::LIVE`](crcbl_shaders::mesh::GpuInstance::LIVE), which the
638    /// pool sets, so a caller filters on the bit rather than on a second list
639    /// it kept. Slots nothing has written are cleared, and a cleared record has
640    /// the bit off.
641    ///
642    /// Added for `crate::probe_visibility`, which needs the scene as it stands
643    /// rather than as it was described: a probe's visibility map is about where
644    /// the walls *are*, and the walls arrive through
645    /// [`InstancePool::insert`] rather than through the description.
646    #[must_use]
647    pub fn live(&self) -> Vec<GpuInstance> {
648        (0..self.high_water)
649            .map(|index| self.read(index))
650            .filter(|record| record.flags & GpuInstance::LIVE != 0)
651            .collect()
652    }
653
654    /// Every element the pool has handed out, in slot order, dead ones included
655    /// — the array [`slot_count`](Self::slot_count) elements long that a cull
656    /// dispatch walks, decoded from the host mirror.
657    ///
658    /// For `crate::cull`'s oracle, which indexes it the way the shader does:
659    /// [`live`](Self::live) drops the dead slots and with them the indices.
660    #[must_use]
661    pub fn records(&self) -> Vec<GpuInstance> {
662        (0..self.high_water).map(|index| self.read(index)).collect()
663    }
664
665    /// Which element of the array `handle` is, or `None` if the handle is stale.
666    ///
667    /// This is the number a shader indexes with, which is why it is public: a
668    /// draw has to be able to say which instance it draws.
669    #[must_use]
670    pub fn index(&self, handle: InstanceHandle) -> Option<u32> {
671        self.slots.contains(handle.cast()).then(|| handle.index())
672    }
673
674    /// Frees `handle`'s slot for reuse, retires the handle, and clears the
675    /// element's [`GpuInstance::LIVE`] bit.
676    ///
677    /// Returns whether the handle named a live instance. The rest of the
678    /// element's bytes are left as they are — see the [module docs](self) on
679    /// why clearing the bit is the whole of what a removal owes the GPU, and why
680    /// zeroing the record would be worse than leaving it.
681    ///
682    /// The clear reaches the device the way every other write does, through
683    /// [`InstancePool::begin_frame`]: the slot is marked dirty in every buffer's
684    /// range set, so a removal costs the same one small upload per frame in
685    /// flight that a rewrite does.
686    pub fn remove(&mut self, handle: InstanceHandle) -> bool {
687        if self.slots.remove(handle.cast()).is_none() {
688            return false;
689        }
690        let index = handle.index();
691        let mut removed = self.read(index);
692        removed.flags &= !GpuInstance::LIVE;
693        self.write(index, &removed);
694        true
695    }
696
697    /// Rotates to the next frame's buffer and writes that buffer's outstanding
698    /// changes into it, returning the slot it rotated to.
699    ///
700    /// **A frame in which nothing was written performs no seam call at all.**
701    /// That is §3.2's claim about this design, and it is the thing to check when
702    /// wondering whether delta upload is really happening.
703    ///
704    /// # Errors
705    ///
706    /// [`HalError`] if a write failed. The runs it had already written stay
707    /// written and the rest stay dirty, so a later frame retries them — a
708    /// half-uploaded array that forgot the rest would be the worse failure.
709    pub fn begin_frame(&mut self, device: &dyn Device) -> Result<usize, HalError> {
710        let slot = self.rotate();
711        self.flush(device)?;
712        Ok(slot)
713    }
714
715    /// Rotates to the next frame's buffer **without uploading anything**, and
716    /// returns the slot it rotated to.
717    ///
718    /// The half of [`begin_frame`](Self::begin_frame) that decides which buffer
719    /// this frame writes, split out for the one caller that has an instance to
720    /// write which *depends* on the slot:
721    /// [`ForwardRenderer::begin_skinned_frame`](crate::forward::ForwardRenderer::begin_skinned_frame)
722    /// points every skinned instance at the half of its region this frame's
723    /// dispatch will fill, and the parity it reads comes from a
724    /// [`Skinning`](crate::skinning::Skinning) that has to be handed this slot
725    /// first. Rotating and uploading in one call would leave that write for the
726    /// *next* frame's upload, which is a character posed one frame late.
727    ///
728    /// [`flush`](Self::flush) must follow it, or this frame draws whatever the
729    /// frame before last left in this buffer.
730    ///
731    /// **This is also the frame boundary the previous transform is measured
732    /// against**: an element the frame before last wrote and this one did not
733    /// is put back at rest here, so an instance that stopped moving stops
734    /// reporting a move. See [`GpuInstance::previous_transform`] and the
735    /// [module docs](self).
736    pub fn rotate(&mut self) -> usize {
737        self.carry_forward();
738        self.frame = (self.frame + 1) % self.buffers.len();
739        self.frame
740    }
741
742    /// Writes the current slot's outstanding changes into its buffer.
743    ///
744    /// The other half of [`begin_frame`](Self::begin_frame). Idempotent: a
745    /// second call with nothing newly written performs no seam call at all.
746    ///
747    /// # Errors
748    ///
749    /// [`HalError`] if a write failed, on [`begin_frame`](Self::begin_frame)'s
750    /// terms — the runs already written stay written and the rest stay dirty.
751    pub fn flush(&mut self, device: &dyn Device) -> Result<(), HalError> {
752        let slot = self.frame;
753        let buffer = self.buffers[slot];
754        // Detached so the mirror can be borrowed while the runs are walked.
755        let mut runs = core::mem::take(&mut self.dirty[slot].runs);
756        for (done, run) in runs.iter().enumerate() {
757            let at = run.start as usize * INSTANCE_STRIDE;
758            let end = run.end as usize * INSTANCE_STRIDE;
759            if let Err(error) = device.write_buffer(buffer, at as u64, &self.mirror[at..end]) {
760                runs.drain(..done);
761                self.dirty[slot].runs = runs;
762                return Err(error);
763            }
764        }
765        runs.clear();
766        self.dirty[slot].runs = runs;
767        Ok(())
768    }
769
770    #[cfg(all(test, not(target_arch = "wasm32")))]
771    pub(super) fn replace_test_buffer(
772        &mut self,
773        slot: usize,
774        replacement: BufferHandle,
775    ) -> BufferHandle {
776        core::mem::replace(&mut self.buffers[slot], replacement)
777    }
778
779    /// The elements [`take_written`](Self::take_written) would hand out now,
780    /// without taking them: a test that checks a write is pending must leave it
781    /// for the frame that reads it.
782    #[cfg(all(test, not(target_arch = "wasm32")))]
783    pub(super) fn pending_written(&self) -> &[u32] {
784        &self.written_since_taken
785    }
786
787    /// Releases every buffer. The device must be idle.
788    pub fn destroy(self, device: &dyn Device) {
789        for buffer in self.buffers {
790            device.destroy_buffer(buffer);
791        }
792    }
793
794    /// Slots that cannot be handed out: live ones, plus any permanently
795    /// withdrawn by generation exhaustion.
796    fn in_use(&self) -> u32 {
797        let used = self.slots.len() + self.slots.retired_slots();
798        u32::try_from(used).unwrap_or(u32::MAX)
799    }
800
801    /// What the mirror holds at `index`, live or not.
802    ///
803    /// Decoded rather than kept beside the bytes, for the reason the mirror is
804    /// bytes at all: a second copy of an instance is a second thing to drift
805    /// from the one the buffer gets.
806    fn read(&self, index: u32) -> GpuInstance {
807        let at = index as usize * INSTANCE_STRIDE;
808        let bytes: &[u8; INSTANCE_STRIDE] = self.mirror[at..at + INSTANCE_STRIDE]
809            .try_into()
810            .unwrap_or_else(|_| unreachable!("the mirror is capacity × INSTANCE_STRIDE"));
811        GpuInstance::from_bytes(bytes)
812    }
813
814    /// [`InstancePool::write`] with [`GpuInstance::LIVE`] forced on and
815    /// `previous_transform` set to `previous`, which is what every
816    /// caller-supplied record goes through.
817    ///
818    /// Both fields are the pool's rather than the caller's, for the same
819    /// reason: the pool is what knows the answer — that the record is live, and
820    /// what it held a moment ago — and a caller asked for either would be
821    /// keeping a second copy of what this one already has.
822    ///
823    /// It also enrols the element in the carry-forward the next
824    /// [`InstancePool::rotate`] performs, which is what stops a moving instance
825    /// that stopped from reporting the move it made forever.
826    fn write_live(&mut self, index: u32, instance: &GpuInstance, previous: [f32; 16]) {
827        self.write(
828            index,
829            &GpuInstance {
830                flags: instance.flags | GpuInstance::LIVE,
831                previous_transform: previous,
832                ..*instance
833            },
834        );
835        if !self.moved_mark[index as usize] {
836            self.moved_mark[index as usize] = true;
837            self.written_this_frame.push(index);
838        }
839    }
840
841    /// Puts every element a caller wrote last frame at rest: its
842    /// `previous_transform` becomes its `transform`, so a frame in which it is
843    /// not written again reports no motion.
844    ///
845    /// **This is the half that makes the field mean "last frame" rather than
846    /// "the last time anyone touched it".** Without it, an instance that moved
847    /// once and then stood still would go on carrying the transform it moved
848    /// from, and every temporal consumer would go on smearing it along a
849    /// journey that finished.
850    ///
851    /// **It carries forward the frame *before* the one being assembled**, and
852    /// that is the whole subtlety. A caller writes the instances for frame `n`
853    /// and *then* calls [`InstancePool::begin_frame`], so by the time this runs
854    /// the moves of frame `n` have already happened and each already carries
855    /// where it came from — putting those at rest would erase the move before
856    /// it was ever drawn. What is left to settle is frame `n - 1`'s writes that
857    /// frame `n` did not repeat, which is exactly "it moved, and then it
858    /// stopped".
859    ///
860    /// A record already at rest is skipped, so the cost of standing still is
861    /// one comparison in the frame after the last move and nothing after that.
862    /// The write goes through [`InstancePool::write`] rather than
863    /// [`InstancePool::write_live`]: it must not enrol the element again, or a
864    /// pool that had ever moved anything would re-examine it every frame
865    /// forever.
866    fn carry_forward(&mut self) {
867        for at in 0..self.written_last_frame.len() {
868            let index = self.written_last_frame[at];
869            if self.moved_mark[index as usize] {
870                // Written again for the frame about to be drawn, so it is
871                // moving rather than stopping and its own write said where
872                // from.
873                continue;
874            }
875            let mut record = self.read(index);
876            if record.previous_transform == record.transform {
877                continue;
878            }
879            record.previous_transform = record.transform;
880            self.write(index, &record);
881        }
882        self.written_last_frame.clear();
883        core::mem::swap(&mut self.written_last_frame, &mut self.written_this_frame);
884        for index in &self.written_last_frame {
885            self.moved_mark[*index as usize] = false;
886        }
887    }
888
889    /// Puts `instance` into the mirror at `index` and marks it dirty in every
890    /// slot's range set.
891    ///
892    /// **The only thing that ever changes the mirror**, which is what makes
893    /// [`revision`](Self::revision) and [`take_written`](Self::take_written)
894    /// total answers rather than counts of the paths somebody remembered to
895    /// instrument.
896    fn write(&mut self, index: u32, instance: &GpuInstance) {
897        let at = index as usize * INSTANCE_STRIDE;
898        self.mirror[at..at + INSTANCE_STRIDE].copy_from_slice(&instance.to_bytes());
899        self.revision = self.revision.wrapping_add(1);
900        if !self.written_since_taken_mark[index as usize] {
901            self.written_since_taken_mark[index as usize] = true;
902            self.written_since_taken.push(index);
903        }
904        for dirty in &mut self.dirty {
905            dirty.mark(index);
906        }
907    }
908}
909
910/// A sorted set of half-open element runs that never overlap and never touch.
911///
912/// "Never touch" is the load-bearing half: it is what makes marking 3, 4 and 5
913/// one run rather than three, and it is maintained by [`DirtyRanges::mark`]
914/// extending and merging rather than appending. A list that only appended would
915/// produce one `write_buffer` per changed element, which is the cost §3.2's
916/// delta upload exists to avoid — it would still be correct, and it would still
917/// pass any test that only checked the bytes.
918#[derive(Clone, Debug, Default, PartialEq, Eq)]
919struct DirtyRanges {
920    runs: Vec<Range<u32>>,
921}
922
923impl DirtyRanges {
924    /// Marks one element dirty, extending or merging the runs around it.
925    ///
926    /// Idempotent: marking an element already inside a run changes nothing, so
927    /// a value written twice between uploads is uploaded once.
928    ///
929    /// `index` must be below `u32::MAX`, which an [`InstancePool`] index is:
930    /// it is below a capacity that is itself a `u32`.
931    fn mark(&mut self, index: u32) {
932        // The first run that could contain or abut `index` from the left.
933        // Everything before it ends strictly below `index`, so nothing there
934        // can touch what this leaves behind.
935        let at = self.runs.partition_point(|run| run.end < index);
936        // Inside the run, or exactly one past its end.
937        if self.runs.get(at).is_some_and(|run| run.start <= index) {
938            if self.runs[at].end == index {
939                self.runs[at].end = index + 1;
940                // Extending may have closed the gap to the next run, which is
941                // the case that turns "3 and 5, then 4" into one run.
942                if self
943                    .runs
944                    .get(at + 1)
945                    .is_some_and(|next| next.start == index + 1)
946                {
947                    let end = self.runs.remove(at + 1).end;
948                    self.runs[at].end = end;
949                }
950            }
951            return;
952        }
953        // Exactly one before the run. It cannot now touch the run before it:
954        // that one ends strictly below `index`.
955        if self.runs.get(at).is_some_and(|run| run.start == index + 1) {
956            self.runs[at].start = index;
957            return;
958        }
959        // A gap on both sides, or past the last run.
960        self.runs.insert(at, index..index + 1);
961    }
962}
963
964// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
965#[cfg(all(test, not(target_arch = "wasm32")))]
966mod tests {
967    use super::*;
968    use crcbl_hal::null::{Event, NullInstance, Recorder};
969    use crcbl_hal::{DeviceDesc, Instance};
970
971    const FRAMES: usize = 2;
972
973    fn open() -> (Recorder, Box<dyn Device>) {
974        let recorder = Recorder::new();
975        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
976        let adapter = instance.adapters().remove(0);
977        let device = instance
978            .create_device(&DeviceDesc::for_adapter(adapter.id))
979            .expect("the null backend always opens");
980        (recorder, device)
981    }
982
983    fn pool(device: &dyn Device, capacity: u32) -> InstancePool {
984        InstancePool::new(
985            device,
986            &InstancePoolDesc {
987                label: Some("test"),
988                capacity,
989                frames_in_flight: FRAMES,
990            },
991        )
992        .expect("the null backend accepts every descriptor")
993    }
994
995    /// An instance whose transform is distinguishable from every other `n`, as
996    /// a **caller** hands it over.
997    ///
998    /// Its flags do not carry [`GpuInstance::LIVE`] for the `n` the tests below
999    /// use, which is what makes [`stored`] a different value and the pool's
1000    /// forcing of the bit observable.
1001    fn instance(n: u32) -> GpuInstance {
1002        GpuInstance {
1003            transform: [n as f32; 16],
1004            // The pool overwrites this, and a value here that the pool would
1005            // also have chosen could not tell that apart from it being passed
1006            // through. Every `n` the tests use is non-zero, so this is a
1007            // transform no caller record carries.
1008            previous_transform: [0.0; 16],
1009            mesh: n,
1010            material: n + 1,
1011            sector: n + 2,
1012            flags: n + 3,
1013            base_vertex: n + 4,
1014            previous_base_vertex: n + 5,
1015            bounds_min: [n as f32 + 6.0; 3],
1016            bounds_max: [n as f32 + 7.0; 3],
1017        }
1018    }
1019
1020    /// [`instance`] as the pool stores it when it is **inserted**: the
1021    /// caller's record, live, and at rest.
1022    ///
1023    /// Refuses an `n` whose flags happen to carry the bit already, because a
1024    /// comparison against such a record would pass whether or not the pool set
1025    /// it — which is the one way an assertion about the bit can be vacuous. The
1026    /// same refusal covers the previous transform: `n` is non-zero for every
1027    /// caller this module builds, so `instance(n)`'s zeroed one is a value the
1028    /// pool has to have replaced.
1029    fn stored(n: u32) -> GpuInstance {
1030        let caller = instance(n);
1031        assert_eq!(
1032            caller.flags & GpuInstance::LIVE,
1033            0,
1034            "instance({n}) already carries the live bit; pick another n"
1035        );
1036        assert_ne!(
1037            n, 0,
1038            "instance(0)'s transform is its own zeroed previous one"
1039        );
1040        GpuInstance {
1041            flags: caller.flags | GpuInstance::LIVE,
1042            previous_transform: caller.transform,
1043            ..caller
1044        }
1045    }
1046
1047    /// [`stored`] as the pool holds it after a **rewrite** from `was`: live,
1048    /// and carrying where it came from.
1049    fn stored_after(n: u32, was: u32) -> GpuInstance {
1050        GpuInstance {
1051            previous_transform: instance(was).transform,
1052            ..stored(n)
1053        }
1054    }
1055
1056    /// Element `index` of the buffer at `slot`, decoded from the bytes that
1057    /// actually reached the device.
1058    ///
1059    /// Read back rather than taken from the pool's mirror, so an assertion is
1060    /// evidence about what a shader would read and not about the pool's
1061    /// bookkeeping agreeing with itself.
1062    fn on_device(recorder: &Recorder, pool: &InstancePool, slot: usize, index: u32) -> GpuInstance {
1063        let bytes = recorder
1064            .buffer_bytes(pool.buffers()[slot])
1065            .expect("the buffer is live");
1066        let at = index as usize * INSTANCE_STRIDE;
1067        GpuInstance::from_bytes(
1068            bytes[at..at + INSTANCE_STRIDE]
1069                .try_into()
1070                .expect("one element"),
1071        )
1072    }
1073
1074    /// Every `BufferWritten` this recorder saw, as `(offset, len)`.
1075    fn writes(recorder: &Recorder) -> Vec<(u64, usize)> {
1076        recorder
1077            .events()
1078            .into_iter()
1079            .filter_map(|event| match event {
1080                Event::BufferWritten { offset, len, .. } => Some((offset, len)),
1081                _ => None,
1082            })
1083            .collect()
1084    }
1085
1086    /// Drives `frames` uploads, discarding what they wrote — used to reach the
1087    /// steady state where every slot has caught up.
1088    fn settle(pool: &mut InstancePool, device: &dyn Device) {
1089        for _ in 0..FRAMES {
1090            pool.begin_frame(device).expect("the null device writes");
1091        }
1092    }
1093
1094    /// A dirty set's runs as `(start, end)` pairs, which is what the assertions
1095    /// below compare — a bare `Range` literal in an array reads as a range the
1096    /// author meant to iterate, and `clippy` says so.
1097    fn runs(dirty: &DirtyRanges) -> Vec<(u32, u32)> {
1098        dirty.runs.iter().map(|run| (run.start, run.end)).collect()
1099    }
1100
1101    mod scratch;
1102
1103    // --- the coalescing, which is pure logic ---
1104
1105    /// **The headline claim.** Adjacent marks are one run; separated marks are
1106    /// two. A list that appended would report three runs for the first case,
1107    /// which is one `write_buffer` per instance and the whole thing this design
1108    /// exists to avoid.
1109    #[test]
1110    fn adjacent_marks_coalesce_and_separated_ones_do_not() {
1111        let mut dirty = DirtyRanges::default();
1112        for index in [3u32, 4, 5] {
1113            dirty.mark(index);
1114        }
1115        assert_eq!(runs(&dirty), [(3, 6)], "3, 4 and 5 are one run of three");
1116
1117        let mut dirty = DirtyRanges::default();
1118        dirty.mark(3);
1119        dirty.mark(900);
1120        assert_eq!(runs(&dirty), [(3, 4), (900, 901)], "a gap stays a gap");
1121    }
1122
1123    /// The exact boundary, in both directions: two marks that **touch** are one
1124    /// run, two marks one element apart are two. Off by one either way and the
1125    /// first case fragments or the second merges across a gap it must not.
1126    #[test]
1127    fn the_boundary_between_touching_and_separated_is_one_element() {
1128        // `4` touches: 3..4 and 4..5 share an endpoint. `5` leaves one clear
1129        // element between them.
1130        for (second, expected) in [(4u32, &[(3, 5)][..]), (5, &[(3, 4), (5, 6)][..])] {
1131            let mut dirty = DirtyRanges::default();
1132            dirty.mark(3);
1133            dirty.mark(second);
1134            assert_eq!(runs(&dirty), expected, "marking 3 then {second}");
1135        }
1136        // And from the other side, because extending a run backwards is a
1137        // different branch of `mark` than extending it forwards.
1138        for (first, expected) in [(4u32, &[(3, 5)][..]), (5, &[(3, 4), (5, 6)][..])] {
1139            let mut dirty = DirtyRanges::default();
1140            dirty.mark(first);
1141            dirty.mark(3);
1142            assert_eq!(runs(&dirty), expected, "marking {first} then 3");
1143        }
1144    }
1145
1146    /// Marking the element between two runs merges all three. Without the merge
1147    /// after an extend, this stays two runs that touch — which breaks the
1148    /// invariant everything else assumes and costs an upload forever after.
1149    #[test]
1150    fn closing_the_gap_between_two_runs_merges_them() {
1151        let mut dirty = DirtyRanges::default();
1152        dirty.mark(3);
1153        dirty.mark(5);
1154        assert_eq!(runs(&dirty), [(3, 4), (5, 6)]);
1155        dirty.mark(4);
1156        assert_eq!(runs(&dirty), [(3, 6)], "one run of three, not two touching");
1157    }
1158
1159    /// Order does not matter: every permutation of the same marks produces the
1160    /// same runs. Coalescing that only worked left-to-right would pass the
1161    /// tests above and fail the moment a caller wrote its instances in any
1162    /// other order.
1163    #[test]
1164    fn coalescing_does_not_depend_on_the_order_marks_arrive_in() {
1165        let marks = [7u32, 3, 5, 4, 900, 6];
1166        let mut permuted = marks;
1167        // Every rotation is enough to move each element through every position.
1168        for shift in 0..marks.len() {
1169            permuted.rotate_left(shift.min(1));
1170            let mut dirty = DirtyRanges::default();
1171            for index in permuted {
1172                dirty.mark(index);
1173            }
1174            assert_eq!(
1175                runs(&dirty),
1176                [(3, 8), (900, 901)],
1177                "the order {permuted:?} produced different runs"
1178            );
1179        }
1180    }
1181
1182    /// Marking the same element twice is one run of one, so a value rewritten
1183    /// between uploads is uploaded once.
1184    #[test]
1185    fn marking_the_same_element_twice_changes_nothing() {
1186        let mut dirty = DirtyRanges::default();
1187        dirty.mark(3);
1188        dirty.mark(3);
1189        assert_eq!(runs(&dirty), [(3, 4)]);
1190        // And re-marking inside an existing run leaves it alone.
1191        dirty.mark(4);
1192        dirty.mark(5);
1193        dirty.mark(4);
1194        assert_eq!(runs(&dirty), [(3, 6)]);
1195    }
1196
1197    // --- the pool ---
1198
1199    /// **The other headline claim: an unchanged frame uploads nothing.**
1200    ///
1201    /// Asserted on the recorded seam calls rather than on a "dirty" flag,
1202    /// because a flag is a claim about the pool's bookkeeping and this is a
1203    /// claim about what reached the device.
1204    #[test]
1205    fn a_frame_with_no_writes_uploads_nothing() {
1206        let (recorder, device) = open();
1207        let mut pool = pool(device.as_ref(), 16);
1208        pool.insert(&instance(1)).expect("room");
1209        settle(&mut pool, device.as_ref());
1210
1211        let before = writes(&recorder).len();
1212        assert!(before > 0, "the insert must have reached the device at all");
1213        for _ in 0..FRAMES * 3 {
1214            pool.begin_frame(device.as_ref()).expect("writes");
1215        }
1216        assert_eq!(
1217            writes(&recorder).len(),
1218            before,
1219            "six frames with nothing written must perform no seam call"
1220        );
1221
1222        pool.destroy(device.as_ref());
1223        recorder.assert_valid();
1224    }
1225
1226    /// **Every path that changes an instance moves the revision, and a frame
1227    /// that changed nothing leaves it alone.**
1228    ///
1229    /// [`InstancePool::revision`]'s whole contract, and the thing a consumer
1230    /// keeping something derived from the array — `ForwardRenderer`'s shadow
1231    /// atlas — bets a frame's correctness on. The list is deliberately every
1232    /// mutator this type has rather than a sample: a path that changed the
1233    /// mirror without moving the number would be a caster that moved under a
1234    /// shadow map nothing redrew.
1235    #[test]
1236    fn every_write_moves_the_revision_and_a_still_frame_does_not() {
1237        let (recorder, device) = open();
1238        let device = device.as_ref();
1239        let mut pool = pool(device, 16);
1240        let start = pool.revision();
1241
1242        let first = pool.insert(&instance(1)).expect("room");
1243        let inserted = pool.revision();
1244        assert!(inserted > start, "an insert did not move the revision");
1245
1246        assert!(pool.set(first, &instance(2)), "the handle is live");
1247        let written = pool.revision();
1248        assert!(written > inserted, "a rewrite did not move the revision");
1249
1250        assert!(
1251            pool.set(first, &instance(2)),
1252            "a rewrite with the same bytes is still a write — see `InstancePool::set`"
1253        );
1254        let repeated = pool.revision();
1255        assert!(
1256            repeated > written,
1257            "a rewrite the pool does not filter must not be filtered here either"
1258        );
1259
1260        assert!(pool.set_bases(first, 4, 8), "the handle is live");
1261        let repointed = pool.revision();
1262        assert!(repointed > repeated, "a re-point did not move the revision");
1263
1264        // A move to somewhere the record was not, so the settle below has a
1265        // `previous_transform` to put back: rewriting an instance with the
1266        // bytes it already holds leaves the two equal, and the carry-forward
1267        // skips a record already at rest.
1268        assert!(pool.set(first, &instance(3)), "the handle is live");
1269        let moved = pool.revision();
1270        assert!(moved > repointed, "a move did not move the revision");
1271
1272        // The frame after a move settles the record's `previous_transform`,
1273        // which is a write and so a change this number reports. Conservative in
1274        // the safe direction, and the reason the doc says so.
1275        settle(&mut pool, device);
1276        let settled = pool.revision();
1277        assert!(
1278            settled > moved,
1279            "the carry-forward wrote the mirror without saying so"
1280        );
1281
1282        // And now the pool is quiet: nothing was written, so nothing moves,
1283        // however many frames go by.
1284        for _ in 0..FRAMES * 3 {
1285            pool.begin_frame(device).expect("the null device writes");
1286        }
1287        assert_eq!(
1288            pool.revision(),
1289            settled,
1290            "a run of frames nobody wrote in moved the revision, so nothing derived from this \
1291             array could ever be kept"
1292        );
1293
1294        assert!(pool.remove(first), "the handle is live");
1295        assert!(
1296            pool.revision() > settled,
1297            "a removal did not move the revision, so an instance that left the scene would go \
1298             on casting a shadow"
1299        );
1300
1301        pool.destroy(device);
1302        recorder.assert_valid();
1303    }
1304
1305    /// **Every path that changes an element puts it in the written log, once,
1306    /// and a still frame puts nothing there.**
1307    ///
1308    /// [`InstancePool::take_written`]'s contract, which `ForwardRenderer`'s
1309    /// shadow atlas now bets a frame's correctness on in place of the revision:
1310    /// an element missing from the log is a caster that moved under a map
1311    /// nothing redrew. Every mutator this type has, as the revision's test
1312    /// above lists them.
1313    #[test]
1314    fn every_write_names_its_element_once_and_a_still_frame_names_none() {
1315        let (recorder, device) = open();
1316        let device = device.as_ref();
1317        let mut pool = pool(device, 16);
1318        let taken = |pool: &mut InstancePool| {
1319            let mut into = Vec::new();
1320            pool.take_written(&mut into);
1321            into
1322        };
1323
1324        let first = pool.insert(&instance(1)).expect("room");
1325        let second = pool.insert(&instance(2)).expect("room");
1326        assert!(pool.set(first, &instance(3)), "the handle is live");
1327        assert_eq!(
1328            taken(&mut pool),
1329            [0, 1],
1330            "two inserts and a rewrite of the first name each element once, first write first"
1331        );
1332        assert!(taken(&mut pool).is_empty(), "a taken log is forgotten");
1333
1334        assert!(pool.set(second, &instance(2)), "the handle is live");
1335        assert_eq!(
1336            taken(&mut pool),
1337            [1],
1338            "a same-bytes rewrite is still a write"
1339        );
1340        assert!(pool.set_bases(first, 4, 8), "the handle is live");
1341        assert_eq!(taken(&mut pool), [0], "a re-point is a write");
1342        assert!(pool.set_flags(second, 1 << 8), "the handle is live");
1343        assert_eq!(taken(&mut pool), [1], "a flag is a write");
1344        pool.clear_flags(1 << 8);
1345        assert_eq!(
1346            taken(&mut pool),
1347            [1],
1348            "clearing a flag writes what carried it"
1349        );
1350
1351        // The first element moved above, so the frame after its move puts its
1352        // `previous_transform` back at rest — a write the log reports.
1353        settle(&mut pool, device);
1354        assert_eq!(
1355            taken(&mut pool),
1356            [0],
1357            "the carry-forward wrote the mirror without naming the element"
1358        );
1359        for _ in 0..FRAMES * 3 {
1360            pool.begin_frame(device).expect("the null device writes");
1361        }
1362        assert!(
1363            taken(&mut pool).is_empty(),
1364            "a run of frames nobody wrote in named an element"
1365        );
1366
1367        assert!(pool.remove(first), "the handle is live");
1368        assert_eq!(taken(&mut pool), [0], "a removal is a write");
1369        let record = pool.record(0).expect("below the high-water mark");
1370        assert_eq!(
1371            record.flags & GpuInstance::LIVE,
1372            0,
1373            "a removed element reads back dead"
1374        );
1375        assert!(pool.record(2).is_none(), "past the high-water mark");
1376
1377        pool.destroy(device);
1378        recorder.assert_valid();
1379    }
1380
1381    /// [`InstancePool::set_bounds`] writes the box and the
1382    /// [`GpuInstance::OWNS_BOUNDS`] bit and nothing else: every other flag and
1383    /// field survives, a zero `owns` clears the bit, a bit `owns` carries
1384    /// besides it is ignored, the transform history is not touched, and a
1385    /// stale handle writes nothing.
1386    #[test]
1387    fn set_bounds_writes_the_box_and_its_bit_alone() {
1388        let (recorder, device) = open();
1389        let device = device.as_ref();
1390        let mut pool = pool(device, 4);
1391        let other_flags =
1392            (1 << 8) | GpuInstance::CASTS_NO_SHADOW | GpuInstance::BASE_VERTEX_OVERRIDE;
1393        let handle = pool
1394            .insert(&GpuInstance {
1395                flags: other_flags,
1396                ..instance(1)
1397            })
1398            .expect("room");
1399        assert!(pool.set(
1400            handle,
1401            &GpuInstance {
1402                flags: other_flags,
1403                ..instance(2)
1404            }
1405        ));
1406        let before = pool.get(handle).expect("live");
1407
1408        let (min, max) = ([-3.0, -2.0, -1.0], [1.0, 2.0, 3.0]);
1409        assert!(
1410            pool.set_bounds(handle, GpuInstance::OWNS_BOUNDS | (1 << 20), min, max),
1411            "the handle is live"
1412        );
1413        let owned = pool.get(handle).expect("live");
1414        assert_eq!(
1415            owned,
1416            GpuInstance {
1417                flags: before.flags | GpuInstance::OWNS_BOUNDS,
1418                bounds_min: min,
1419                bounds_max: max,
1420                ..before
1421            },
1422            "the box and its bit are written, the extra bit in `owns` is not, and nothing \
1423             else moves — the previous transform included"
1424        );
1425
1426        assert!(pool.set_bounds(handle, 0, [0.0; 3], [0.0; 3]));
1427        let cleared = pool.get(handle).expect("live");
1428        assert_eq!(
1429            cleared.flags, before.flags,
1430            "a zero `owns` clears the bit alone"
1431        );
1432
1433        assert!(pool.remove(handle), "the handle is live");
1434        let mut written = Vec::new();
1435        pool.take_written(&mut written);
1436        let dead = pool.record(0).expect("below the high-water mark");
1437        assert!(
1438            !pool.set_bounds(handle, GpuInstance::OWNS_BOUNDS, min, max),
1439            "a stale handle is refused"
1440        );
1441        assert_eq!(pool.record(0), Some(dead), "and writes nothing");
1442        written.clear();
1443        pool.take_written(&mut written);
1444        assert!(written.is_empty(), "nor names the element as written");
1445
1446        pool.destroy(device);
1447        recorder.assert_valid();
1448    }
1449
1450    /// Three adjacent instances written in one frame reach the device as **one**
1451    /// write of three elements, and two separated ones as two writes of one.
1452    /// This is the coalescing test above, seen from the device's side.
1453    #[test]
1454    fn adjacent_writes_reach_the_device_as_one_call() {
1455        let (recorder, device) = open();
1456        let mut pool = pool(device.as_ref(), 1024);
1457        let handles: Vec<_> = (0..6)
1458            .map(|n| pool.insert(&instance(n)).expect("room"))
1459            .collect();
1460        settle(&mut pool, device.as_ref());
1461
1462        let before = writes(&recorder).len();
1463        for handle in &handles[3..6] {
1464            pool.set(*handle, &instance(99));
1465        }
1466        pool.begin_frame(device.as_ref()).expect("writes");
1467        assert_eq!(
1468            writes(&recorder)[before..],
1469            [(3 * INSTANCE_STRIDE as u64, 3 * INSTANCE_STRIDE)],
1470            "instances 3, 4 and 5 must be one write of three elements"
1471        );
1472
1473        // Drained, so the next measurement is one slot's own runs rather than
1474        // that slot's leftovers from the write above — each slot lags the
1475        // others by a frame, which is the ring doing its job.
1476        settle(&mut pool, device.as_ref());
1477        let before = writes(&recorder).len();
1478        pool.set(handles[0], &instance(98));
1479        pool.set(handles[5], &instance(98));
1480        pool.begin_frame(device.as_ref()).expect("writes");
1481        assert_eq!(
1482            writes(&recorder)[before..],
1483            [
1484                (0, INSTANCE_STRIDE),
1485                (5 * INSTANCE_STRIDE as u64, INSTANCE_STRIDE)
1486            ],
1487            "instances 0 and 5 are not adjacent and must be two writes"
1488        );
1489
1490        pool.destroy(device.as_ref());
1491        recorder.assert_valid();
1492    }
1493
1494    /// A write reaches **every** buffer in the ring, not just the one that
1495    /// happened to be current: each slot is a separate copy, and a slot that
1496    /// missed an update would draw a stale instance every other frame.
1497    #[test]
1498    fn a_write_reaches_every_buffer_in_the_ring() {
1499        let (recorder, device) = open();
1500        let mut pool = pool(device.as_ref(), 16);
1501        let handle = pool.insert(&instance(1)).expect("room");
1502        settle(&mut pool, device.as_ref());
1503
1504        pool.set(handle, &instance(2));
1505        let mut written_to = Vec::new();
1506        for _ in 0..FRAMES {
1507            let slot = pool.begin_frame(device.as_ref()).expect("writes");
1508            written_to.push(pool.buffers()[slot]);
1509        }
1510        let targets: Vec<BufferHandle> = recorder
1511            .events()
1512            .into_iter()
1513            .filter_map(|event| match event {
1514                Event::BufferWritten { buffer, .. } => Some(buffer),
1515                _ => None,
1516            })
1517            .collect();
1518        for buffer in pool.buffers() {
1519            assert!(
1520                targets.contains(buffer),
1521                "buffer {buffer:?} never received the instance"
1522            );
1523        }
1524        assert_eq!(written_to.len(), FRAMES);
1525
1526        pool.destroy(device.as_ref());
1527        recorder.assert_valid();
1528    }
1529
1530    /// A full pool refuses by name, and takes nothing: the refused insert must
1531    /// not consume a slot, or a caller that retries would lose capacity each
1532    /// time it was told there was none.
1533    #[test]
1534    fn a_full_pool_fails_by_name_and_takes_nothing() {
1535        let (recorder, device) = open();
1536        let mut pool = pool(device.as_ref(), 2);
1537        let first = pool.insert(&instance(0)).expect("room");
1538        pool.insert(&instance(1)).expect("room");
1539
1540        let error = pool
1541            .insert(&instance(2))
1542            .expect_err("two instances fill a pool of two");
1543        assert!(
1544            matches!(
1545                error,
1546                InstancePoolError::PoolFull {
1547                    capacity: 2,
1548                    in_use: 2
1549                }
1550            ),
1551            "got: {error:?}"
1552        );
1553        assert_eq!(pool.len(), 2, "a refused insert must not consume a slot");
1554
1555        // And a freed slot is handed out again, so the refusal above is the
1556        // capacity rather than the pool having given up.
1557        assert!(pool.remove(first));
1558        let reused = pool.insert(&instance(3)).expect("the freed slot");
1559        assert_eq!(pool.index(reused), Some(0), "the low slot comes back");
1560        assert_eq!(pool.index(first), None, "and the old handle is retired");
1561
1562        pool.destroy(device.as_ref());
1563        recorder.assert_valid();
1564    }
1565
1566    /// The number a cull dispatch is sized by covers every occupied slot, and
1567    /// **it does not shrink when one is freed**.
1568    ///
1569    /// That is the whole difference from [`InstancePool::len`]: remove the
1570    /// middle instance of three and `len` says two, while the third is still at
1571    /// element 2 and a walk of `0..2` would never test it. A dispatch sized that
1572    /// way drops an instance from the picture and reports it as culled.
1573    #[test]
1574    fn the_slot_count_covers_every_occupied_element_and_never_shrinks() {
1575        let (recorder, device) = open();
1576        let mut pool = pool(device.as_ref(), 8);
1577        assert_eq!(pool.slot_count(), 0, "an empty pool has nothing to walk");
1578
1579        let handles: Vec<InstanceHandle> = (0..3)
1580            .map(|index| pool.insert(&instance(index)).expect("room"))
1581            .collect();
1582        assert_eq!(pool.slot_count(), 3);
1583
1584        assert!(pool.remove(handles[1]));
1585        assert_eq!(pool.len(), 2, "two are live");
1586        assert_eq!(
1587            pool.slot_count(),
1588            3,
1589            "and the highest is still at element 2, so a walk must still reach it"
1590        );
1591
1592        // A reused slot does not raise it either: the element was already
1593        // covered.
1594        pool.insert(&instance(9)).expect("the freed slot");
1595        assert_eq!(pool.slot_count(), 3);
1596
1597        pool.destroy(device.as_ref());
1598        recorder.assert_valid();
1599    }
1600
1601    /// One buffer per frame in flight, each sized for the whole capacity — the
1602    /// ring is what the module docs claim it is, and a pool that quietly kept
1603    /// one buffer would pass every other test here.
1604    #[test]
1605    fn the_ring_is_one_buffer_per_frame_in_flight() {
1606        let (recorder, device) = open();
1607        let pool = pool(device.as_ref(), 16);
1608        assert_eq!(pool.buffers().len(), FRAMES);
1609        let mut distinct = pool.buffers().to_vec();
1610        distinct.sort_unstable_by_key(|buffer| buffer.to_bits());
1611        distinct.dedup();
1612        assert_eq!(distinct.len(), FRAMES, "the slots must not share a buffer");
1613        assert_eq!(pool.capacity(), 16);
1614        assert!(pool.is_empty());
1615
1616        pool.destroy(device.as_ref());
1617        recorder.assert_valid();
1618    }
1619
1620    /// **Every buffer is cleared when the pool is created**, which is the other
1621    /// half of the removal contract: the cull pass walks from element zero, so
1622    /// the slots above the ones in use have to answer too, and a zeroed element
1623    /// is a dead instance.
1624    ///
1625    /// Asserted on the seam calls rather than on the bytes, and that is the
1626    /// only assertion available here: this recorder zero-fills a mappable
1627    /// buffer at creation, so a byte comparison would pass whether or not the
1628    /// pool ever wrote one. What a real driver leaves in a fresh host-visible
1629    /// allocation is its own business, which is why `crcbl-vk`'s `cull` e2e
1630    /// dispatches over a pool's whole capacity with only three slots inserted.
1631    #[test]
1632    fn every_buffer_is_cleared_when_the_pool_is_created() {
1633        let (recorder, device) = open();
1634        let pool = pool(device.as_ref(), 16);
1635        assert_eq!(
1636            writes(&recorder),
1637            vec![(0, 16 * INSTANCE_STRIDE); FRAMES],
1638            "each buffer in the ring must be cleared, whole, before anything reads it"
1639        );
1640
1641        pool.destroy(device.as_ref());
1642        recorder.assert_valid();
1643    }
1644
1645    /// **Where an instance was last frame, across the three cases that decide
1646    /// it**: a spawn is at rest, a move carries where it moved from, and a
1647    /// frame with no move puts it back at rest.
1648    ///
1649    /// The third is the one the carry-forward exists for and the one a pool
1650    /// without it would fail: `set` alone leaves the record naming the
1651    /// transform it left, so an instance that moved once and then stood still
1652    /// would report that move on every frame afterwards, forever.
1653    ///
1654    /// The order is a frame's real one — write the instances, *then*
1655    /// `begin_frame` — because that is what decides which frame a move belongs
1656    /// to.
1657    ///
1658    /// Read back off the device rather than out of the mirror: this is what a
1659    /// shader would fetch.
1660    #[test]
1661    fn an_instance_carries_where_it_was_last_frame() {
1662        let (recorder, device) = open();
1663        let mut pool = pool(device.as_ref(), 16);
1664        let handle = pool.insert(&instance(7)).expect("room");
1665        settle(&mut pool, device.as_ref());
1666        let index = pool.index(handle).expect("live");
1667        let slot = pool.frame;
1668        assert_eq!(
1669            on_device(&recorder, &pool, slot, index).previous_transform,
1670            instance(7).transform,
1671            "a spawn did not travel from anywhere"
1672        );
1673
1674        // The frame it moves: the record names both ends of the move.
1675        assert!(pool.set(handle, &instance(11)));
1676        let slot = pool
1677            .begin_frame(device.as_ref())
1678            .expect("the null device writes");
1679        let moved = on_device(&recorder, &pool, slot, index);
1680        assert_eq!(moved.transform, instance(11).transform, "it arrived");
1681        assert_eq!(
1682            moved.previous_transform,
1683            instance(7).transform,
1684            "and it says where from"
1685        );
1686
1687        // The next frame, with nothing written: back at rest.
1688        let slot = pool
1689            .begin_frame(device.as_ref())
1690            .expect("the null device writes");
1691        let stopped = on_device(&recorder, &pool, slot, index);
1692        assert_eq!(
1693            stopped.transform,
1694            instance(11).transform,
1695            "it has not moved"
1696        );
1697        assert_eq!(
1698            stopped.previous_transform, stopped.transform,
1699            "so it must report no motion"
1700        );
1701
1702        // And it stays at rest without being written again, in every buffer of
1703        // the ring rather than only the one the last frame rotated to.
1704        settle(&mut pool, device.as_ref());
1705        for slot in 0..FRAMES {
1706            let resting = on_device(&recorder, &pool, slot, index);
1707            assert_eq!(
1708                resting.previous_transform, resting.transform,
1709                "buffer {slot} still has it moving"
1710            );
1711        }
1712
1713        pool.destroy(device.as_ref());
1714        recorder.assert_valid();
1715    }
1716
1717    /// **An instance that keeps moving is never put at rest.** The
1718    /// carry-forward runs a frame behind, so the case it must not touch is the
1719    /// one where the caller wrote the instance again — settling that would
1720    /// erase a move before the frame holding it was ever drawn.
1721    #[test]
1722    fn an_instance_still_moving_is_not_put_at_rest() {
1723        let (recorder, device) = open();
1724        let mut pool = pool(device.as_ref(), 16);
1725        let handle = pool.insert(&instance(1)).expect("room");
1726        settle(&mut pool, device.as_ref());
1727        let index = pool.index(handle).expect("live");
1728
1729        for step in 2..6u32 {
1730            assert!(pool.set(handle, &instance(step)));
1731            let slot = pool
1732                .begin_frame(device.as_ref())
1733                .expect("the null device writes");
1734            let moving = on_device(&recorder, &pool, slot, index);
1735            assert_eq!(
1736                (moving.previous_transform, moving.transform),
1737                (instance(step - 1).transform, instance(step).transform),
1738                "the frame that moved it to {step} lost one end of the move"
1739            );
1740        }
1741
1742        pool.destroy(device.as_ref());
1743        recorder.assert_valid();
1744    }
1745
1746    /// **A re-point rewrites the two bases and leaves the move alone**, which
1747    /// is the whole of why [`InstancePool::set_bases`] exists.
1748    ///
1749    /// The record is moved first, so it is carrying a previous transform that
1750    /// differs from its current one when the bases are rewritten — a call that
1751    /// went through [`InstancePool::set`] would take the previous transform
1752    /// from the record it overwrites, which by then holds the move's *end*, and
1753    /// the move would be gone. That is what
1754    /// [`crate::forward::ForwardRenderer`]'s per-frame re-point did to every
1755    /// skinned instance.
1756    ///
1757    /// The frame checked on the device is the one the move is drawn in. The
1758    /// frame after it puts the record back at rest, which is
1759    /// [`carry_forward`](InstancePool::carry_forward)'s job rather than this
1760    /// call's — [`an_instance_carries_where_it_was_last_frame`] is where that
1761    /// half is asserted, and the renderer-level
1762    /// `a_skinned_instance_that_moves_carries_the_transform_it_moved_from` is
1763    /// where the two meet.
1764    ///
1765    /// The stale half is [`InstancePool::set`]'s contract: `false`, and nothing
1766    /// written — asserted on the bytes that reached the device and on the
1767    /// uploads a later frame performs, because a mirror written without being
1768    /// marked dirty would satisfy only one of the two.
1769    #[test]
1770    fn setting_the_bases_keeps_the_transform_the_record_moved_from() {
1771        let (recorder, device) = open();
1772        let mut pool = pool(device.as_ref(), 16);
1773        let handle = pool.insert(&instance(7)).expect("room");
1774        assert!(pool.set(handle, &instance(11)), "the handle is live");
1775
1776        assert!(pool.set_bases(handle, 40, 41), "the handle is still live");
1777        let repointed = GpuInstance {
1778            base_vertex: 40,
1779            previous_base_vertex: 41,
1780            ..stored_after(11, 7)
1781        };
1782        assert_eq!(
1783            pool.get(handle),
1784            Some(repointed),
1785            "a re-point owes the two bases it was given and every other field the record \
1786             already held — the previous transform above all"
1787        );
1788
1789        let index = pool.index(handle).expect("live");
1790        let slot = pool
1791            .begin_frame(device.as_ref())
1792            .expect("the null device writes");
1793        assert_eq!(
1794            on_device(&recorder, &pool, slot, index),
1795            repointed,
1796            "the buffer this frame draws from did not take the re-point, so a shader reads \
1797             the bases of the frame before"
1798        );
1799
1800        assert!(pool.remove(handle));
1801        for _ in 0..FRAMES * 2 {
1802            pool.begin_frame(device.as_ref())
1803                .expect("the null device writes");
1804        }
1805        recorder.clear();
1806        assert!(
1807            !pool.set_bases(handle, 60, 61),
1808            "a retired handle names no instance"
1809        );
1810        for _ in 0..FRAMES * 2 {
1811            pool.begin_frame(device.as_ref())
1812                .expect("the null device writes");
1813        }
1814        assert_eq!(
1815            writes(&recorder),
1816            [],
1817            "a stale re-point marked a slot dirty, so it wrote into whatever took it"
1818        );
1819        for slot in 0..FRAMES {
1820            let dead = on_device(&recorder, &pool, slot, index);
1821            assert_eq!(
1822                (dead.base_vertex, dead.previous_base_vertex),
1823                (40, 41),
1824                "buffer {slot} took a stale handle's bases"
1825            );
1826        }
1827
1828        pool.destroy(device.as_ref());
1829        recorder.assert_valid();
1830    }
1831
1832    /// **Standing still costs one upload per buffer and then nothing.** That is
1833    /// the claim delta upload is here to make, and an unconditional
1834    /// carry-forward would break it — every instance would be dirty in every
1835    /// frame forever.
1836    ///
1837    /// The first assertion is what keeps the second from being vacuous: a
1838    /// carry-forward that never reached the device would also produce no
1839    /// uploads at rest.
1840    #[test]
1841    fn an_instance_at_rest_is_uploaded_once_and_then_never() {
1842        let (recorder, device) = open();
1843        let mut pool = pool(device.as_ref(), 16);
1844        let handle = pool.insert(&instance(7)).expect("room");
1845        settle(&mut pool, device.as_ref());
1846
1847        assert!(pool.set(handle, &instance(11)));
1848        settle(&mut pool, device.as_ref());
1849
1850        // The move has reached every buffer and the last of those frames
1851        // carried it forward, which marked the element dirty everywhere again.
1852        recorder.clear();
1853        pool.begin_frame(device.as_ref())
1854            .expect("the null device writes");
1855        let carried = writes(&recorder).len();
1856        assert_eq!(
1857            carried, 1,
1858            "the buffer that had not seen the carry-forward yet should have taken it, \
1859             and {carried} write(s) says the carry-forward never reached the device"
1860        );
1861
1862        recorder.clear();
1863        for _ in 0..FRAMES * 2 {
1864            pool.begin_frame(device.as_ref())
1865                .expect("the null device writes");
1866        }
1867        assert_eq!(
1868            writes(&recorder),
1869            [],
1870            "an instance nobody has written costs no upload"
1871        );
1872
1873        pool.destroy(device.as_ref());
1874        recorder.assert_valid();
1875    }
1876
1877    /// What goes in comes out, field for field, and a removed handle stops
1878    /// resolving. The four ids are the same width and would permute silently,
1879    /// so the round trip is checked rather than assumed.
1880    #[test]
1881    fn an_instance_round_trips_through_the_pool() {
1882        let (recorder, device) = open();
1883        let mut pool = pool(device.as_ref(), 16);
1884        let handle = pool.insert(&instance(7)).expect("room");
1885        assert_eq!(pool.get(handle), Some(stored(7)));
1886
1887        assert!(pool.set(handle, &instance(11)));
1888        assert_eq!(
1889            pool.get(handle),
1890            Some(stored_after(11, 7)),
1891            "a rewrite keeps where the instance was"
1892        );
1893
1894        assert!(pool.remove(handle));
1895        assert_eq!(
1896            pool.get(handle),
1897            None,
1898            "a removed handle resolves to nothing"
1899        );
1900        assert!(!pool.set(handle, &instance(12)), "and cannot be written");
1901        assert!(!pool.remove(handle), "and cannot be removed twice");
1902
1903        pool.destroy(device.as_ref());
1904        recorder.assert_valid();
1905    }
1906
1907    /// **Removing an instance clears its live bit on the device, and changes
1908    /// nothing else about the record.**
1909    ///
1910    /// The whole slice: a slot the cull pass walks past has to be able to say
1911    /// it is free, and the bit is the only thing a removal is allowed to
1912    /// rewrite. Asserted on the bytes in the buffer rather than on the mirror,
1913    /// because a removal that never reached a buffer is a removal the GPU does
1914    /// not know about.
1915    #[test]
1916    fn removing_an_instance_clears_its_live_bit_on_the_device() {
1917        let (recorder, device) = open();
1918        let mut pool = pool(device.as_ref(), 16);
1919        let first = pool.insert(&instance(1)).expect("room");
1920        let second = pool.insert(&instance(3)).expect("room");
1921        settle(&mut pool, device.as_ref());
1922        for slot in 0..FRAMES {
1923            assert_eq!(
1924                on_device(&recorder, &pool, slot, 0),
1925                stored(1),
1926                "buffer {slot} did not receive the live instance"
1927            );
1928        }
1929
1930        assert!(pool.remove(first));
1931        settle(&mut pool, device.as_ref());
1932        for slot in 0..FRAMES {
1933            let removed = on_device(&recorder, &pool, slot, 0);
1934            assert_eq!(
1935                removed.flags & GpuInstance::LIVE,
1936                0,
1937                "buffer {slot} still holds a live instance at the removed slot: {removed:?}"
1938            );
1939            // And the rest of the record is exactly what it was. The pool
1940            // deliberately does not zero it — see the module docs — so a test
1941            // that only checked the bit would pass on an implementation that
1942            // wrote a degenerate instance at the origin instead.
1943            assert_eq!(
1944                removed,
1945                GpuInstance {
1946                    flags: stored(1).flags & !GpuInstance::LIVE,
1947                    ..stored(1)
1948                },
1949                "buffer {slot} rewrote more than the flags word"
1950            );
1951            assert_eq!(
1952                on_device(&recorder, &pool, slot, 1),
1953                stored(3),
1954                "buffer {slot} disturbed the instance beside the removed one"
1955            );
1956        }
1957
1958        assert_eq!(
1959            pool.get(second),
1960            Some(stored(3)),
1961            "and the other handle still resolves"
1962        );
1963
1964        // A second removal of the retired handle writes nothing at all, so a
1965        // caller cannot clear the live bit of whatever has since taken the slot.
1966        let before = writes(&recorder).len();
1967        assert!(!pool.remove(first));
1968        settle(&mut pool, device.as_ref());
1969        assert_eq!(
1970            writes(&recorder).len(),
1971            before,
1972            "removing a retired handle must upload nothing"
1973        );
1974
1975        pool.destroy(device.as_ref());
1976        recorder.assert_valid();
1977    }
1978
1979    /// **A slot reused after a removal is live again, holding its new
1980    /// contents.** The other direction of the same defect: a liveness bit that
1981    /// stuck would make the pool leak capacity that looks allocated and draws
1982    /// nothing.
1983    #[test]
1984    fn a_reused_slot_is_live_again_with_its_new_contents() {
1985        let (recorder, device) = open();
1986        let mut pool = pool(device.as_ref(), 16);
1987        let first = pool.insert(&instance(1)).expect("room");
1988        assert!(pool.remove(first));
1989        settle(&mut pool, device.as_ref());
1990
1991        let reused = pool.insert(&instance(5)).expect("the freed slot");
1992        assert_eq!(pool.index(reused), Some(0), "the low slot comes back");
1993        settle(&mut pool, device.as_ref());
1994        for slot in 0..FRAMES {
1995            assert_eq!(
1996                on_device(&recorder, &pool, slot, 0),
1997                stored(5),
1998                "buffer {slot} holds neither the new instance nor the live bit"
1999            );
2000        }
2001        assert_eq!(pool.get(reused), Some(stored(5)));
2002
2003        pool.destroy(device.as_ref());
2004        recorder.assert_valid();
2005    }
2006
2007    /// The bytes that reach the device are the instance's, at the offset its
2008    /// index names — checked by writing a high slot and reading back the offset
2009    /// the seam was given. An off-by-one in the element/byte conversion would
2010    /// put every instance one slot out and still upload the right number of
2011    /// bytes.
2012    #[test]
2013    fn an_instances_offset_is_its_index_times_the_stride() {
2014        let (recorder, device) = open();
2015        let mut pool = pool(device.as_ref(), 16);
2016        for n in 0..5 {
2017            pool.insert(&instance(n)).expect("room");
2018        }
2019        settle(&mut pool, device.as_ref());
2020        let handle = pool.insert(&instance(5)).expect("room");
2021        assert_eq!(pool.index(handle), Some(5));
2022
2023        let before = writes(&recorder).len();
2024        pool.begin_frame(device.as_ref()).expect("writes");
2025        assert_eq!(
2026            writes(&recorder)[before..],
2027            [(5 * INSTANCE_STRIDE as u64, INSTANCE_STRIDE)]
2028        );
2029
2030        pool.destroy(device.as_ref());
2031        recorder.assert_valid();
2032    }
2033
2034    /// Everything created is destroyed.
2035    #[test]
2036    fn a_pool_leaks_nothing() {
2037        let (recorder, device) = open();
2038        let before = recorder.total_live_objects();
2039        let mut pool = pool(device.as_ref(), 16);
2040        pool.insert(&instance(0)).expect("room");
2041        settle(&mut pool, device.as_ref());
2042        assert!(recorder.total_live_objects() > before);
2043
2044        pool.destroy(device.as_ref());
2045        assert_eq!(
2046            recorder.total_live_objects(),
2047            before,
2048            "every buffer created must be destroyed"
2049        );
2050        recorder.assert_valid();
2051    }
2052
2053    /// A pool error that has to travel as a [`HalError`] keeps its message,
2054    /// which is the whole reason the exhaustion error names its numbers.
2055    #[test]
2056    fn a_pool_error_flattens_into_the_seams_without_losing_its_message() {
2057        let full = InstancePoolError::PoolFull {
2058            capacity: 4,
2059            in_use: 4,
2060        };
2061        let message = full.to_string();
2062        assert_eq!(HalError::from(full).to_string(), message);
2063
2064        let hal = InstancePoolError::Hal(HalError::OutOfDeviceMemory);
2065        assert!(
2066            matches!(HalError::from(hal), HalError::OutOfDeviceMemory),
2067            "a HalError must not be stringified on the way through"
2068        );
2069    }
2070}