Skip to main content

crcbl_render/
material_table.rs

1//! The material table: one storage-buffer row per material, and the id an
2//! instance carries to select one.
3//!
4//! ```text
5//!  insert(device, material) ──▶ takes a slot ──▶ one write_buffer of one row
6//!                               └─▶ index(handle) is what a GpuInstance carries
7//!
8//!  remove(device, handle) ──▶ frees the slot ──▶ the row is cleared to black
9//! ```
10//!
11//! Topic 03 §3.2: "Material table (SSBO) …
12//! Material id indexes the table". [`crcbl_shaders::mesh::GpuInstance::material`]
13//! is that id and [`crcbl_shaders::mesh::GpuMaterial`] is that row — the layout
14//! lives in the crate that owns `mesh.slang`, because it is a contract with the
15//! shader.
16//!
17//! # The factors and one texture, which is an [`ArrayPages`] layer
18//!
19//! §3.2's sentence is "the table holds texture indices + factors", and a row
20//! now holds both: [`GpuMaterial::base_color`] and
21//! [`GpuMaterial::base_color_texture`]. The second is a **layer** of the one
22//! `Texture2DArray` `mesh.slang` binds — an [`ArrayPages`] page — and not a
23//! [`BindingModel::Bindless`] descriptor slot, which is the binding-model
24//! decision this table used to be waiting on. A layer index needs nothing of a
25//! device; a descriptor array needs `DESCRIPTOR_INDEXING`, which `crcbl-mtl`
26//! withdraws. So one column serves every backend, and this table does not have
27//! to know which model the device it is bound on selected.
28//!
29//! **This type does not own the page.** It stores an index and nothing else:
30//! which image the layers live in, how many there are and which page kind they
31//! belong to are [`crate::forward`]'s, exactly as which *mesh* a `GpuInstance::mesh`
32//! names is [`crate::mesh_pool`]'s. So a row naming a layer the page does not
33//! have samples out of range and nothing *here* can tell — which is why the
34//! type that does own both refuses it: [`ForwardRenderer::with_scene`] checks
35//! every [`SceneDesc::materials`] row against the page's layer count before it
36//! creates anything, and names the row and the layer when it declines. A row
37//! reaching [`MaterialTable::insert`] has already been through that.
38//!
39//! Still absent, and still deliberately: every other texture slot a material
40//! could have — normal, metallic-roughness, emissive. `docs/plan/37-materials.md`
41//! owns the shape a real material takes. The page's mip chain is [`crate::mip`]'s
42//! and goes up with the page, and the sampler reads it trilinear.
43//!
44//! # One buffer, and no ring — unlike [`crate::instance_pool`]
45//!
46//! This is the decision worth reading before changing anything here, because
47//! the two tables look alike and are not.
48//!
49//! [`InstancePool`](crate::instance_pool::InstancePool) keeps one buffer per
50//! frame in flight and a set of dirty runs per buffer, because **the instance
51//! array is rewritten every frame while the previous frame is still drawing
52//! from it**: a moving object writes its transform each frame, so the coalesced
53//! delta upload is the whole reason that type exists rather than a `Vec` the
54//! renderer re-uploads.
55//!
56//! A material is written when it is *created*. That is [`crate::mesh_pool`]'s
57//! mesh table exactly — "one host-visible buffer rather than a ring … nothing
58//! rewrites an entry between frames, so there is no frame still reading the
59//! value a write would replace" — and this follows it: one buffer, shared by
60//! every frame's bind group, written in place. Copying the ring and the dirty
61//! runs across would be a delta upload whose deltas are always one row, plus
62//! `frames_in_flight` copies of a table nothing varies per frame; and factoring
63//! the run-coalescing out to share it would be an abstraction with one real
64//! user and one that only wants `write_buffer`.
65//!
66//! The cost is stated rather than hidden: **rewriting a material while a frame
67//! is in flight is a read-after-write hazard across submissions**, the one
68//! stage 2 called its headline risk. So
69//! [`MaterialTable::set`] is a start-up call, like [`crate::mesh_pool::MeshPool::upload`]
70//! and [`crate::texture::upload_texture`] beside it. An animated material is
71//! what makes this a ring, and on that day the coalescing in
72//! [`crate::instance_pool`] is worth sharing because there would be two callers
73//! that need it.
74//!
75//! # The table never grows
76//!
77//! Capacity is fixed by [`MaterialTableDesc`] and [`MaterialTable::insert`]
78//! fails by name when it runs out — [`crate::instance_pool`]'s reason, since
79//! every row is the same size: growing a device buffer means allocating a
80//! larger one, copying, and re-pointing every bind group that names the old
81//! one.
82//!
83//! # A cleared row is black, which is the point
84//!
85//! [`MaterialTable::new`] clears the buffer and [`MaterialTable::remove`]
86//! clears the row it frees, so a row nobody has written and a row whose
87//! material was removed read the same: a base colour of zero, which shades
88//! black.
89//!
90//! There is no "no material" value to write instead. A mesh table has one —
91//! `index_count == 0` is an entry naming no mesh — because a mesh id resolves
92//! to a *range*, and the empty range draws nothing. Every RGBA factor is a
93//! material somebody could want, so the empty value and a legitimate one are
94//! the same bytes. Black is therefore chosen for how it fails: an instance
95//! whose material was never created is a black object, which is seen, where a
96//! white one is an object that looks correct.
97//!
98//! [`BindingModel::Bindless`]: crcbl_hal::BindingModel::Bindless
99//! [`ArrayPages`]: crcbl_hal::BindingModel::ArrayPages
100//! [`GpuMaterial::base_color`]: crcbl_shaders::mesh::GpuMaterial::base_color
101//! [`GpuMaterial::base_color_texture`]: crcbl_shaders::mesh::GpuMaterial::base_color_texture
102//! [`ForwardRenderer::with_scene`]: crate::forward::ForwardRenderer::with_scene
103//! [`SceneDesc::materials`]: crate::scene::SceneDesc::materials
104
105use crcbl_core::{Handle, Pool};
106use crcbl_hal::{BufferDesc, BufferHandle, BufferUsage, Device, HalError, MemoryLocation};
107use crcbl_shaders::mesh::{GpuMaterial, MATERIAL_STRIDE};
108
109/// Marker type for [`MaterialHandle`]. Uninhabited.
110#[derive(Debug)]
111pub enum Material {}
112
113/// A material in a [`MaterialTable`]. Generational, so a removed material's
114/// handle stops resolving rather than naming whatever took its row.
115pub type MaterialHandle = Handle<Material>;
116
117/// What a [`MaterialTable`] refuses to do.
118#[derive(Debug, thiserror::Error)]
119pub enum MaterialTableError {
120    /// Every row is in use.
121    ///
122    /// `in_use` is normally the number of live materials. It can exceed that
123    /// only through generation exhaustion — see [`Pool`]'s docs on retired
124    /// slots — and the two are reported together for
125    /// [`InstancePoolError::PoolFull`](crate::instance_pool::InstancePoolError::PoolFull)'s
126    /// reason: so that case is legible rather than baffling.
127    #[error("the material table holds {capacity} materials and {in_use} of them are in use")]
128    TableFull {
129        /// The table's fixed capacity.
130        capacity: u32,
131        /// Rows that cannot be handed out.
132        in_use: u32,
133    },
134    /// Anything the seam refused.
135    #[error(transparent)]
136    Hal(#[from] HalError),
137}
138
139/// Flattens a table error into the seam's, for callers whose constructors are
140/// already `Result<_, HalError>`.
141///
142/// Same shape and same reason as
143/// [`InstancePoolError`](crate::instance_pool::InstancePoolError)'s: the seam
144/// has no vocabulary for "this table is full", so everything that is not
145/// already a [`HalError`] arrives as [`Backend`](HalError::Backend), which
146/// renders verbatim and keeps the numbers.
147impl From<MaterialTableError> for HalError {
148    fn from(error: MaterialTableError) -> Self {
149        match error {
150            MaterialTableError::Hal(hal) => hal,
151            other => Self::Backend(other.to_string()),
152        }
153    }
154}
155
156/// How large a [`MaterialTable`] is, and what to call it.
157#[derive(Clone, Copy, Debug, PartialEq, Eq)]
158pub struct MaterialTableDesc<'a> {
159    /// Debug name; the buffer is named after it.
160    pub label: Option<&'a str>,
161    /// Materials the table can hold. Fixed — see the [module docs](self).
162    pub capacity: u32,
163}
164
165/// One `GpuMaterial` array, written in place.
166///
167/// See the [module docs](self) for why there is no ring and why a cleared row
168/// is black — both are decisions rather than accidents.
169#[derive(Debug)]
170pub struct MaterialTable {
171    buffer: BufferHandle,
172    /// Generational row allocation, and nothing else: the values live in the
173    /// buffer. Reusing the crate's pool rather than writing a second allocator
174    /// that gets the generation-retirement rule subtly different, exactly as
175    /// [`crate::instance_pool`] does.
176    slots: Pool<()>,
177    capacity: u32,
178    /// Each row's [`GpuMaterial::mode`], one entry per row — the only thing
179    /// about a row's *value* this type keeps a copy of.
180    ///
181    /// It is kept because a mode is what **routes** a draw: `draw_gen.slang`
182    /// buckets an instance by its mesh and by the mode of the material it names,
183    /// so the renderer has to be able to read a row's mode back when it writes
184    /// an instance record. See [`MaterialTable::mode`]. Reading it off the
185    /// buffer is not open to a `HostUpload` binding, and asking every caller to
186    /// remember what it inserted is the drift this removes.
187    ///
188    /// Written only where a row is — see [`MaterialTable::write`], which is the
189    /// single point of contact — so a refused write leaves the entry describing
190    /// the bytes the device actually holds.
191    modes: Vec<u32>,
192}
193
194impl MaterialTable {
195    /// Creates the table, **cleared**.
196    ///
197    /// Cleared rather than left as the driver handed it over, for the reason
198    /// [`crate::mesh_pool::MeshPool`] clears its own table: a row nothing has
199    /// written is read by any instance naming it, and "a zeroed row is black"
200    /// is only a contract if it holds for the rows nobody has touched as well
201    /// as for the ones [`MaterialTable::remove`] clears. A driver's leftovers
202    /// are not zeroes, and they are not a colour anybody chose either.
203    ///
204    /// # Errors
205    ///
206    /// [`MaterialTableError::Hal`] from any seam call. A failure part-way
207    /// through releases the buffer it had already created.
208    pub fn new(
209        device: &dyn Device,
210        desc: &MaterialTableDesc<'_>,
211    ) -> Result<Self, MaterialTableError> {
212        let stem = desc.label.unwrap_or("material table");
213        let size = u64::from(desc.capacity) * MATERIAL_STRIDE as u64;
214        let buffer = device.create_buffer(&BufferDesc {
215            label: Some(&format!("{stem} materials")),
216            size,
217            // Host-visible, so a write is a `write_buffer` rather than a
218            // staging copy needing a barrier. Same choice, and the same
219            // reasoning, as the mesh table's.
220            usage: BufferUsage::STORAGE,
221            memory: MemoryLocation::HostUpload,
222        })?;
223        let cleared = vec![0u8; usize::try_from(size).unwrap_or(usize::MAX)];
224        if let Err(error) = device.write_buffer(buffer, 0, &cleared) {
225            device.destroy_buffer(buffer);
226            return Err(error.into());
227        }
228        Ok(Self {
229            buffer,
230            slots: Pool::new(),
231            capacity: desc.capacity,
232            // Every row cleared, so every row's mode is zero — `OPAQUE`, which
233            // is what the zeroes written above actually say.
234            modes: vec![0; usize::try_from(desc.capacity).unwrap_or(usize::MAX)],
235        })
236    }
237
238    /// The table. Bound as a read-only storage buffer; the vertex stage indexes
239    /// it with an instance's material id.
240    ///
241    /// One buffer for every frame's bind group, unlike
242    /// [`InstancePool::buffers`](crate::instance_pool::InstancePool::buffers) —
243    /// see the [module docs](self).
244    #[must_use]
245    pub const fn buffer(&self) -> BufferHandle {
246        self.buffer
247    }
248
249    /// How many materials the table can hold, which is the bound every material
250    /// id is below.
251    #[must_use]
252    pub const fn capacity(&self) -> u32 {
253        self.capacity
254    }
255
256    /// How many materials are live.
257    #[must_use]
258    pub const fn len(&self) -> usize {
259        self.slots.len()
260    }
261
262    /// Whether no material is live.
263    #[must_use]
264    pub const fn is_empty(&self) -> bool {
265        self.slots.is_empty()
266    }
267
268    /// Row `index`'s [`GpuMaterial::mode`] — the bits a draw is routed by.
269    ///
270    /// **What the caller does with it is write it into an instance**:
271    /// [`crate::forward`] shifts it into
272    /// [`GpuInstance::flags`](crcbl_shaders::mesh::GpuInstance::flags) at
273    /// [`MATERIAL_MODE_SHIFT`](crcbl_shaders::mesh::GpuInstance::MATERIAL_MODE_SHIFT),
274    /// and `draw_gen.slang` buckets the instance by its mesh id and that field
275    /// together. So a scene's cutout materials cost a fragment stage in the
276    /// depth passes for their own meshes and for no others.
277    ///
278    /// **An instance's mode is captured when its record is written.** Rewriting
279    /// a row with [`MaterialTable::set`] moves this answer and does *not* re-key
280    /// the instances already naming the row — see that method's own note.
281    ///
282    /// Zero — `OPAQUE` — for a row past the table's capacity and for a removed
283    /// one: [`MaterialTable::remove`] clears it to [`GpuMaterial::default`],
284    /// whose flags are zero.
285    #[must_use]
286    pub fn mode(&self, index: u32) -> u32 {
287        self.modes.get(index as usize).copied().unwrap_or(0)
288    }
289
290    /// Takes a row, writes `material` into it, and returns its handle.
291    ///
292    /// # Errors
293    ///
294    /// [`MaterialTableError::TableFull`] when every row is in use — the table
295    /// never grows, see the [module docs](self) — and
296    /// [`MaterialTableError::Hal`] if the row could not be written. A refused
297    /// insert takes no row.
298    pub fn insert(
299        &mut self,
300        device: &dyn Device,
301        material: &GpuMaterial,
302    ) -> Result<MaterialHandle, MaterialTableError> {
303        // `Pool` hands out a fresh index only when it has no vacant slot, so
304        // "live plus permanently retired" is exactly the highest index it could
305        // be about to create. Checked before inserting rather than after, so a
306        // refused insert does not burn a generation.
307        let in_use = self.in_use();
308        if in_use >= self.capacity {
309            return Err(MaterialTableError::TableFull {
310                capacity: self.capacity,
311                in_use,
312            });
313        }
314        let handle: MaterialHandle = self.slots.insert(()).cast();
315        match self.write(device, handle.index(), material) {
316            Ok(()) => Ok(handle),
317            // The row is whatever the clear or the previous occupant left, and
318            // the slot goes back rather than staying allocated to a material
319            // the GPU never received.
320            Err(error) => {
321                self.slots.remove(handle.cast());
322                Err(error.into())
323            }
324        }
325    }
326
327    /// Rewrites `handle`'s row.
328    ///
329    /// Returns whether the handle named a live material; a stale one writes
330    /// nothing rather than recolouring whatever took its row.
331    ///
332    /// **A start-up call**, like [`crate::mesh_pool::MeshPool::upload`]: the
333    /// table has no ring, so a row rewritten while a frame is in flight is a
334    /// read-after-write hazard across submissions. The [module docs](self) say
335    /// what would have to change first.
336    ///
337    /// # A rewritten mode does not re-key the instances that name the row
338    ///
339    /// [`GpuMaterial::mode`] decides which draw bucket an instance of this
340    /// material is scattered into, and that decision is baked into the
341    /// instance's own record when the record is written — the draw-argument pass
342    /// has no binding for this table and cannot get one. So a row that goes from
343    /// `OPAQUE` to `MASK` here leaves every instance already naming it in the
344    /// opaque bucket, whose depth pass has no fragment stage: the cutout would
345    /// cast a solid shadow.
346    ///
347    /// Nothing in the tree can reach that state — `crcbl_render::ForwardRenderer`
348    /// takes its materials from the scene description at build and exposes no
349    /// insert or rewrite — which is why this is a documented precondition rather
350    /// than a guard. The fix, if a caller ever needs one, is a renderer-side
351    /// re-key over the live instances rather than anything this type can do
352    /// alone; `docs/backlog.md` carries it.
353    ///
354    /// # Errors
355    ///
356    /// [`HalError`] if the row could not be written.
357    pub fn set(
358        &mut self,
359        device: &dyn Device,
360        handle: MaterialHandle,
361        material: &GpuMaterial,
362    ) -> Result<bool, HalError> {
363        if !self.slots.contains(handle.cast()) {
364            return Ok(false);
365        }
366        self.write(device, handle.index(), material)?;
367        Ok(true)
368    }
369
370    /// Which row `handle` is, or `None` if the handle is stale.
371    ///
372    /// This is the number a [`GpuInstance::material`](crcbl_shaders::mesh::GpuInstance::material)
373    /// carries, which is why it is public: an instance has to be able to say
374    /// which material it is shaded with.
375    #[must_use]
376    pub fn index(&self, handle: MaterialHandle) -> Option<u32> {
377        self.slots.contains(handle.cast()).then(|| handle.index())
378    }
379
380    /// Frees `handle`'s row for reuse, retires the handle, and **clears the row
381    /// to black**.
382    ///
383    /// Returns whether the handle named a live material. The clear is what
384    /// makes an instance still naming the row shade black rather than take the
385    /// colour of whatever material lands there next — the same defect a stale
386    /// mesh-table entry produces, and the same answer
387    /// [`crate::mesh_pool::MeshPool::free`] gives it. What neither can defend
388    /// against is a row *reused*: a material id is a bare `u32` with no
389    /// generation in it, and only [`MaterialHandle`] can tell those apart.
390    ///
391    /// # Errors
392    ///
393    /// [`HalError`] if the row could not be cleared. The slot is freed either
394    /// way: a handle that failed to clear is still retired, and the row holds
395    /// its old colour until something writes it.
396    pub fn remove(
397        &mut self,
398        device: &dyn Device,
399        handle: MaterialHandle,
400    ) -> Result<bool, HalError> {
401        if self.slots.remove(handle.cast()).is_none() {
402            return Ok(false);
403        }
404        self.write(device, handle.index(), &GpuMaterial::default())?;
405        Ok(true)
406    }
407
408    /// Releases the buffer. The device must be idle.
409    pub fn destroy(self, device: &dyn Device) {
410        device.destroy_buffer(self.buffer);
411    }
412
413    /// Rows that cannot be handed out: live ones, plus any permanently
414    /// withdrawn by generation exhaustion.
415    fn in_use(&self) -> u32 {
416        let used = self.slots.len() + self.slots.retired_slots();
417        u32::try_from(used).unwrap_or(u32::MAX)
418    }
419
420    /// Writes one row, at the offset `index` names.
421    ///
422    /// The one place a [`GpuMaterial`] becomes bytes, so the element/byte
423    /// conversion has a single point of contact rather than one per call site.
424    fn write(
425        &mut self,
426        device: &dyn Device,
427        index: u32,
428        material: &GpuMaterial,
429    ) -> Result<(), HalError> {
430        let at = u64::from(index) * MATERIAL_STRIDE as u64;
431        device.write_buffer(self.buffer, at, &material.to_bytes())?;
432        // After the write and not before it: the record is of what the device
433        // holds, and a refused write left the row as it was.
434        if let Some(entry) = self.modes.get_mut(index as usize) {
435            *entry = material.mode();
436        }
437        Ok(())
438    }
439}
440
441// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
442#[cfg(all(test, not(target_arch = "wasm32")))]
443mod tests {
444    use super::*;
445    use crcbl_hal::null::{Event, NullInstance, Recorder};
446    use crcbl_hal::{DeviceDesc, Instance};
447
448    fn open() -> (Recorder, Box<dyn Device>) {
449        let recorder = Recorder::new();
450        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
451        let adapter = instance.adapters().remove(0);
452        let device = instance
453            .create_device(&DeviceDesc::for_adapter(adapter.id))
454            .expect("the null backend always opens");
455        (recorder, device)
456    }
457
458    fn table(device: &dyn Device, capacity: u32) -> MaterialTable {
459        MaterialTable::new(
460            device,
461            &MaterialTableDesc {
462                label: Some("test"),
463                capacity,
464            },
465        )
466        .expect("the null backend accepts every descriptor")
467    }
468
469    /// A material distinguishable from every other `n`, with no two floats
470    /// equal — so a row read at the wrong offset, or a word written in the
471    /// wrong order, is a different value rather than the same one.
472    ///
473    /// The texture layer is `n + 7` rather than `n`, so it is different from the
474    /// row index, from the material number and from every factor in the row: an
475    /// index read out of the wrong word cannot come out right by coincidence.
476    ///
477    /// The shading factors, the tiling pair and the emissive triple are on the
478    /// same scheme, and they are the ones the scheme most has to cover: they sit
479    /// past the texture index, so a writer that still stops there leaves them
480    /// zero and this is what says so. Every fraction is distinct and inside
481    /// `0..1`, so no value of one row can coincide with a value of another.
482    fn material(n: u32) -> GpuMaterial {
483        let base = n as f32;
484        GpuMaterial {
485            base_color: [base, base + 0.125, base + 0.25, base + 0.375],
486            base_color_texture: n + 7,
487            metallic: base + 0.5,
488            roughness: base + 0.625,
489            tiling: n % 2,
490            tile_metres: base + 0.75,
491            // The last three words of the row, and the ones a writer that
492            // stopped at the old padding leaves zero.
493            emissive: [base + 0.8125, base + 0.875, base + 0.9375],
494            // And the six the material pages added past those, which are now
495            // the words a writer that stopped at the emissive triple leaves
496            // zero. Distinct from every other row's for the reason above.
497            normal_texture: n + 11,
498            normal_scale: base + 0.9375 + 1.0 / 32.0,
499            metallic_roughness_occlusion_texture: n + 13,
500            emissive_texture: n + 17,
501            alpha_cutoff: base + 0.9375 + 1.0 / 64.0,
502            flags: n + 19,
503            // And the dielectric specular appended past the flags, which a
504            // writer that stopped at sixty-four bytes leaves zero.
505            specular_f0: [
506                base + 0.9375 + 3.0 / 128.0,
507                base + 0.9375 + 5.0 / 128.0,
508                base + 0.9375 + 7.0 / 128.0,
509            ],
510            specular_f90: base + 0.9375 + 1.0 / 128.0,
511        }
512    }
513
514    /// Row `index` of the table, decoded from the bytes that actually reached
515    /// the device.
516    ///
517    /// Read back rather than taken from any host-side copy — there is none, and
518    /// that is the point: an assertion here is evidence about what a shader
519    /// would read.
520    fn on_device(recorder: &Recorder, table: &MaterialTable, index: u32) -> GpuMaterial {
521        let bytes = recorder
522            .buffer_bytes(table.buffer())
523            .expect("the buffer is live");
524        let at = index as usize * MATERIAL_STRIDE;
525        GpuMaterial::from_bytes(bytes[at..at + MATERIAL_STRIDE].try_into().expect("one row"))
526    }
527
528    /// Every `BufferWritten` this recorder saw, as `(offset, len)`.
529    fn writes(recorder: &Recorder) -> Vec<(u64, usize)> {
530        recorder
531            .events()
532            .into_iter()
533            .filter_map(|event| match event {
534                Event::BufferWritten { offset, len, .. } => Some((offset, len)),
535                _ => None,
536            })
537            .collect()
538    }
539
540    /// **The table reports each row's material mode, and the answer tracks every
541    /// way a row can change.**
542    ///
543    /// [`crate::forward`] reads this when it writes an instance record, and the
544    /// mode is what routes the draw: a stale answer is either a cutout scattered
545    /// into the opaque bucket — whose depth pass has no fragment stage, so it
546    /// casts a solid shadow — or an opaque mesh paying for a `discard` nothing
547    /// uses.
548    ///
549    /// Four transitions, because the record is written in one place —
550    /// `MaterialTable::write` — and each of the four reaches it differently: an
551    /// opaque insert, a masked insert, a `set` that un-masks a live row, and a
552    /// `remove`, which clears the row to [`GpuMaterial::default`] and must
553    /// therefore also clear the record. **Per row and not "does anything mask"**,
554    /// so un-masking one of two masked rows is visible as the one row it moved:
555    /// an answer about the table as a whole would report the same `true` before
556    /// and after.
557    #[test]
558    fn the_table_reports_each_rows_material_mode() {
559        let (recorder, device) = open();
560        let device = device.as_ref();
561        let mut table = table(device, 8);
562        let masked = |n: u32| GpuMaterial {
563            flags: GpuMaterial::ALPHA_MODE_MASK,
564            ..material(n)
565        };
566        // `material`'s own flags word is a distinctness scheme rather than a
567        // meaning — it carries `n + 19`, which has bit 0 set for every even `n`
568        // — so the rows this test calls opaque have to say so.
569        let unmasked = |n: u32| GpuMaterial {
570            flags: 0,
571            ..material(n)
572        };
573        let mode = |table: &MaterialTable, handle: MaterialHandle| table.mode(handle.index());
574
575        assert_eq!(
576            table.mode(0),
577            0,
578            "a row nothing has written is cleared, and a cleared row is OPAQUE — or every \
579             instance placed before a material exists routes to a cutout bucket"
580        );
581        let opaque = table
582            .insert(device, &unmasked(0))
583            .expect("a table of eight has room");
584        assert_eq!(
585            mode(&table, opaque),
586            0,
587            "an opaque row's mode is zero, whatever else is in its flags"
588        );
589
590        let first = table.insert(device, &masked(1)).expect("room");
591        assert_eq!(
592            mode(&table, first),
593            GpuMaterial::ALPHA_MODE_MASK,
594            "a row inserted with the mask bit reports it, or the instances naming it scatter \
595             into the opaque bucket and the depth passes write their full silhouette"
596        );
597        let second = table.insert(device, &masked(2)).expect("room");
598
599        table
600            .set(device, first, &unmasked(3))
601            .expect("a live handle rewrites its row");
602        assert_eq!(
603            mode(&table, first),
604            0,
605            "a rewritten row reports its new mode"
606        );
607        assert_eq!(
608            mode(&table, second),
609            GpuMaterial::ALPHA_MODE_MASK,
610            "and the other masked row is untouched, which is what a per-row answer buys over \
611             one about the table"
612        );
613        table
614            .remove(device, second)
615            .expect("a live handle frees its row");
616        assert_eq!(
617            table.mode(second.index()),
618            0,
619            "removing a row clears it to black, whose flags are zero"
620        );
621
622        assert_eq!(
623            table.mode(table.capacity()),
624            0,
625            "a row past the table is OPAQUE rather than a panic: an index the caller cannot \
626             have been given is not a routing decision"
627        );
628
629        table.remove(device, opaque).expect("live");
630        table.destroy(device);
631        recorder.assert_valid();
632    }
633
634    /// **The headline claim: a material id is a row, and the row it is is
635    /// `index * MATERIAL_STRIDE` bytes in.**
636    ///
637    /// Checked by filling several rows and reading each back at the offset its
638    /// index names. An off-by-one or a stride the two sides disagree about
639    /// would put every material one row out and still write the right number of
640    /// bytes — which is the failure a second material exists to expose and a
641    /// single-row table cannot.
642    #[test]
643    fn a_materials_row_is_its_index_times_the_stride() {
644        let (recorder, device) = open();
645        let mut table = table(device.as_ref(), 8);
646        let handles: Vec<MaterialHandle> = (0..4)
647            .map(|n| {
648                table
649                    .insert(device.as_ref(), &material(n))
650                    .expect("room for four")
651            })
652            .collect();
653
654        for (n, handle) in handles.iter().enumerate() {
655            let index = u32::try_from(n).expect("four rows");
656            assert_eq!(
657                table.index(*handle),
658                Some(index),
659                "the {n}th insert must take the {n}th row"
660            );
661            assert_eq!(
662                on_device(&recorder, &table, index),
663                material(index),
664                "row {index} does not hold the material inserted into it"
665            );
666        }
667
668        // And the seam was given exactly one row's worth at that offset, so the
669        // agreement above is not a table that writes itself whole every time.
670        let before = writes(&recorder).len();
671        table
672            .insert(device.as_ref(), &material(9))
673            .expect("room for five");
674        assert_eq!(
675            writes(&recorder)[before..],
676            [(4 * MATERIAL_STRIDE as u64, MATERIAL_STRIDE)]
677        );
678
679        table.destroy(device.as_ref());
680        recorder.assert_valid();
681    }
682
683    /// **A row's texture layer reaches the device, and two rows can differ in
684    /// nothing else.**
685    ///
686    /// §3.2's "texture indices + factors", from the table's side: the number a
687    /// shader reads to pick a page layer is the number a caller inserted, at
688    /// the offset the row's layout puts it. Two materials with an identical
689    /// factor and different layers are what the rendered observable rests on,
690    /// so they are checked here to be two different rows rather than one value
691    /// written twice.
692    #[test]
693    fn a_rows_texture_layer_is_written_beside_its_factor() {
694        let (recorder, device) = open();
695        let mut table = table(device.as_ref(), 4);
696        let untextured = GpuMaterial::UNTINTED;
697        let textured = GpuMaterial {
698            base_color_texture: 2,
699            ..untextured
700        };
701        assert_eq!(
702            untextured.base_color, textured.base_color,
703            "the pair must differ in the texture layer and nothing else"
704        );
705
706        let first = table.insert(device.as_ref(), &untextured).expect("room");
707        let second = table.insert(device.as_ref(), &textured).expect("room");
708
709        assert_eq!(on_device(&recorder, &table, 0), untextured);
710        assert_eq!(on_device(&recorder, &table, 1), textured);
711        assert_eq!(
712            on_device(&recorder, &table, 1).base_color_texture,
713            2,
714            "the layer a caller asked for must be the layer the buffer holds"
715        );
716        assert_ne!(
717            on_device(&recorder, &table, 0),
718            on_device(&recorder, &table, 1),
719            "two rows differing only in their layer must be two different rows"
720        );
721        assert_eq!(table.index(first), Some(0));
722        assert_eq!(table.index(second), Some(1));
723
724        table.destroy(device.as_ref());
725        recorder.assert_valid();
726    }
727
728    /// **The table is cleared when it is created**, whole — the other half of
729    /// the black-row contract: an instance may name a row nobody has written,
730    /// and what it reads has to be a colour this crate chose.
731    #[test]
732    fn the_table_is_cleared_when_it_is_created() {
733        let (recorder, device) = open();
734        let table = table(device.as_ref(), 8);
735        assert_eq!(
736            writes(&recorder),
737            [(0, 8 * MATERIAL_STRIDE)],
738            "the whole table must be cleared before anything reads it"
739        );
740        assert_eq!(table.capacity(), 8);
741        assert!(table.is_empty());
742
743        table.destroy(device.as_ref());
744        recorder.assert_valid();
745    }
746
747    /// A rewritten material reaches the device, and a stale handle rewrites
748    /// nothing.
749    #[test]
750    fn a_material_can_be_rewritten_and_a_stale_handle_cannot() {
751        let (recorder, device) = open();
752        let mut table = table(device.as_ref(), 4);
753        let handle = table.insert(device.as_ref(), &material(1)).expect("room");
754        assert_eq!(on_device(&recorder, &table, 0), material(1));
755
756        assert!(
757            table
758                .set(device.as_ref(), handle, &material(2))
759                .expect("the null device writes")
760        );
761        assert_eq!(on_device(&recorder, &table, 0), material(2));
762
763        assert!(table.remove(device.as_ref(), handle).expect("writes"));
764        let before = writes(&recorder).len();
765        assert!(
766            !table
767                .set(device.as_ref(), handle, &material(3))
768                .expect("a stale handle is not an error"),
769            "a retired handle must not resolve"
770        );
771        assert_eq!(
772            writes(&recorder).len(),
773            before,
774            "and must not reach the device at all"
775        );
776        assert_eq!(table.index(handle), None);
777
778        table.destroy(device.as_ref());
779        recorder.assert_valid();
780    }
781
782    /// **Removing a material clears its row to black on the device, and
783    /// disturbs no other row.**
784    ///
785    /// The whole of what a removal owes the GPU: an instance still naming the
786    /// row shades black rather than taking the next material's colour. Asserted
787    /// on the bytes in the buffer, because a removal that never reached it is a
788    /// removal the GPU does not know about.
789    #[test]
790    fn removing_a_material_clears_its_row_and_leaves_its_neighbours() {
791        let (recorder, device) = open();
792        let mut table = table(device.as_ref(), 4);
793        let first = table.insert(device.as_ref(), &material(1)).expect("room");
794        let second = table.insert(device.as_ref(), &material(2)).expect("room");
795
796        assert!(table.remove(device.as_ref(), first).expect("writes"));
797        assert_eq!(
798            on_device(&recorder, &table, 0),
799            GpuMaterial::default(),
800            "the freed row must read black"
801        );
802        assert_ne!(
803            GpuMaterial::default(),
804            material(1),
805            "the material removed was not already black, so the clear is observable"
806        );
807        assert_eq!(
808            on_device(&recorder, &table, 1),
809            material(2),
810            "the row beside the removed one was disturbed"
811        );
812        assert_eq!(table.index(second), Some(1));
813
814        // A second removal of the retired handle writes nothing, so a caller
815        // cannot black out whatever has since taken the row.
816        let before = writes(&recorder).len();
817        assert!(!table.remove(device.as_ref(), first).expect("writes"));
818        assert_eq!(writes(&recorder).len(), before);
819
820        table.destroy(device.as_ref());
821        recorder.assert_valid();
822    }
823
824    /// A full table refuses by name and takes nothing, and a freed row is
825    /// handed out again — so the refusal is the capacity rather than the table
826    /// having given up.
827    #[test]
828    fn a_full_table_fails_by_name_and_takes_nothing() {
829        let (recorder, device) = open();
830        let mut table = table(device.as_ref(), 2);
831        let first = table.insert(device.as_ref(), &material(0)).expect("room");
832        table.insert(device.as_ref(), &material(1)).expect("room");
833
834        let error = table
835            .insert(device.as_ref(), &material(2))
836            .expect_err("two materials fill a table of two");
837        assert!(
838            matches!(
839                error,
840                MaterialTableError::TableFull {
841                    capacity: 2,
842                    in_use: 2
843                }
844            ),
845            "got: {error:?}"
846        );
847        assert_eq!(table.len(), 2, "a refused insert must not consume a row");
848
849        assert!(table.remove(device.as_ref(), first).expect("writes"));
850        let reused = table
851            .insert(device.as_ref(), &material(3))
852            .expect("the freed row");
853        assert_eq!(table.index(reused), Some(0), "the low row comes back");
854        assert_eq!(table.index(first), None, "and the old handle is retired");
855        assert_eq!(on_device(&recorder, &table, 0), material(3));
856
857        table.destroy(device.as_ref());
858        recorder.assert_valid();
859    }
860
861    /// Everything created is destroyed.
862    #[test]
863    fn a_table_leaks_nothing() {
864        let (recorder, device) = open();
865        let before = recorder.total_live_objects();
866        let mut table = table(device.as_ref(), 4);
867        table.insert(device.as_ref(), &material(0)).expect("room");
868        assert!(recorder.total_live_objects() > before);
869
870        table.destroy(device.as_ref());
871        assert_eq!(
872            recorder.total_live_objects(),
873            before,
874            "every buffer created must be destroyed"
875        );
876        recorder.assert_valid();
877    }
878
879    /// A table error that has to travel as a [`HalError`] keeps its message,
880    /// which is the whole reason the exhaustion error names its numbers.
881    #[test]
882    fn a_table_error_flattens_into_the_seams_without_losing_its_message() {
883        let full = MaterialTableError::TableFull {
884            capacity: 4,
885            in_use: 4,
886        };
887        let message = full.to_string();
888        assert_eq!(HalError::from(full).to_string(), message);
889
890        let hal = MaterialTableError::Hal(HalError::OutOfDeviceMemory);
891        assert!(
892            matches!(HalError::from(hal), HalError::OutOfDeviceMemory),
893            "a HalError must not be stringified on the way through"
894        );
895    }
896}