Skip to main content

crcbl_render/
mesh_pool.rs

1//! Global geometry pools: one vertex buffer, one index buffer, and a mesh that
2//! is three integers.
3//!
4//! ```text
5//! upload(vertices, indices) ──▶ suballocate both pools ──▶ staging ▸ copy ▸ submit
6//!                                                                       │ signals
7//!                                                                       ▼
8//!                                                              timeline value N
9//!                                                                       │
10//!  mesh(handle) ─── None until the timeline has passed N ────────────────┘
11//!                └── Some({base_vertex, base_index, index_count}) after
12//! ```
13//!
14//! Topic 03 §3.1: "One large vertex pool + one
15//! index pool (device-local, suballocated…). Meshes are
16//! `{base_vertex, base_index, count}` ranges — a mesh handle is three integers."
17//! Everything above this — instance data, GPU culling, indirect draws, meshlets
18//! — assumes a mesh is a range rather than a buffer, and none of it is here.
19//!
20//! # The same three integers — and the mesh's box — where the GPU can read them
21//!
22//! There is a third buffer: the **mesh table**, one
23//! [`crcbl_shaders::mesh::GpuMesh`] per slot this pool can hand out, kept in
24//! step with the free lists by [`MeshPool::upload`] and [`MeshPool::free`].
25//! [`MeshPool::table_index`] is the number that names an entry, and it is what
26//! an instance's [`GpuInstance::mesh`](crcbl_shaders::mesh::GpuInstance::mesh)
27//! carries.
28//!
29//! An entry carries a fourth thing the range's name does not suggest: the
30//! mesh's **local-space bounding box**, computed here from the vertex positions
31//! the caller uploaded. It lives in the same record rather than in a table of
32//! its own because it has the same lifetime as the range — written by the same
33//! call, cleared by the same call, indexed by the same id — and because §3.3's
34//! cull pass reads the box and the range together. See
35//! [`crate::cull`], which is what reads it.
36//!
37//! §3.3 is why it exists: a cull pass emits draws for the instances it keeps,
38//! so the GPU has to be able to resolve an instance's geometry with no CPU in
39//! the loop. It pays for itself before that pass is written, because a base
40//! vertex resolved per *instance* lets one draw cover instances of different
41//! meshes where a per-draw constant could not.
42//!
43//! **A freed mesh's entry is cleared**, so it reads as
44//! [`GpuMesh::default`](crcbl_shaders::mesh::GpuMesh) — the empty range, whose
45//! `index_count` is zero. An instance still naming it therefore resolves to no
46//! geometry rather than to whatever mesh next lands in that space, which is the
47//! defect a table left stale produces. What it cannot defend against is a slot
48//! *reused*: an id is a bare `u32` with no generation in it, so an instance
49//! holding the id of a freed mesh names the next mesh uploaded into that slot.
50//! [`MeshHandle`] is generational and a mesh id is not, and only the handle can
51//! tell those apart.
52//!
53//! # One pool means one vertex format
54//!
55//! The vertex pool is suballocated in **vertices**, not bytes, so
56//! [`MeshRange::base_vertex`] is a vertex index the shader can add and no caller
57//! divides anything. That only works because every mesh in the pool has the same
58//! stride, which is §3.1's "vertex pulling everywhere" stated as a data layout:
59//! [`crcbl_shaders::mesh::VERTEX_STRIDE`] is *the* vertex format, and a second
60//! one means a second pool rather than a stride field on this one.
61//!
62//! Indices are `Uint32` for the same reason, and are stored **mesh-relative**,
63//! so the bytes uploaded for a mesh do not depend on where in the pool it
64//! landed and a mesh can be freed and re-uploaded at a different base without
65//! being rewritten.
66//!
67//! **The base is not `draw_indexed`'s own `base_vertex` argument.** That is the
68//! obvious place for it and it is where this pool's first consumer put it, until
69//! the second resident showed what it does: the four shading languages disagree
70//! about whether a draw's base vertex is folded into `SV_VertexID`, and Slang's
71//! SPIR-V subtracts it back out. So [`crate::forward`] passes zero there and
72//! hands this number to the shader as data instead — see that module and
73//! `mesh.slang`'s header, which measure all four targets.
74//!
75//! # Fragmentation and exhaustion, which are not the same failure
76//!
77//! The suballocator is a first-fit free list that **coalesces on every free**,
78//! so two neighbouring frees become one block. What it never does is move a
79//! resident mesh: §3.1's risk section is explicit — "MVP: free-list + offline
80//! compaction on load only. **No live defrag.**"
81//!
82//! The consequence is the case a naive free list gets wrong, and it is
83//! documented behaviour rather than a bug: **a request no single free block can
84//! satisfy fails even when the total free space would have been enough.**
85//! [`MeshPoolError::PoolExhausted`] names both numbers so a caller can tell the
86//! two apart — a largest block far below the total is fragmentation, and a total
87//! below the request is a pool that is simply full. "Offline compaction" here
88//! means freeing everything and uploading again, which is what a load-time asset
89//! system does anyway.
90//!
91//! # The pools never grow
92//!
93//! Capacity is fixed by [`MeshPoolDesc`] and exhaustion is an error naming it.
94//! Growing a device-local pool means allocating a larger buffer, copying, and
95//! re-pointing every bind group that names the old one — the live-defrag cost
96//! §3.1 rules out, paid under a different name and in the middle of a frame.
97//! [`crcbl_core::FrameArena`] fixes its capacity for the same reason its docs
98//! give: a bound that grows on demand is indistinguishable from a leak.
99//!
100//! # Residency is the point of the timeline
101//!
102//! §3.1: "renderer consumes meshes only after the timeline value passes". Each
103//! upload's transfer submit signals a value on the pool's own timeline
104//! semaphore, and [`MeshPool::mesh`] answers `None` until that value has been
105//! observed to pass — so a caller cannot obtain a range for a mesh whose bytes
106//! may not have landed. [`MeshPool::flush`] is what makes it pass, and it is
107//! also what retires the staging buffers, because a staging buffer freed before
108//! its copy has run is the same bug from the other end.
109//!
110//! The semaphore is this crate's, not [`crcbl_hal`]'s to invent: timeline
111//! semaphores are the seam's one synchronisation primitive (see
112//! [`crcbl_hal::SemaphoreKind`], whose docs name this staging path), and the
113//! `wait_semaphores`-or-`wait_idle` fallback for a device without them is the
114//! one `crcbl::GpuContext::retire_to` already uses to retire command buffers.
115//!
116//! # This is a start-up path
117//!
118//! Like [`crate::texture`] and for the same reason, [`MeshPool::upload`] records
119//! its own barriers and [`MeshPool::flush`] blocks. Both are legal because there
120//! is no graph in the room: uploads happen before the frame loop, and the crate
121//! docs' "no manual barriers outside the graph" names exactly these. Streaming a
122//! mesh in *during* a frame is P9's, and it is the reason residency is a query
123//! rather than an assertion — the shape survives when `flush` becomes a poll.
124//!
125//! It is also why the mesh table is one host-visible buffer rather than a ring
126//! like [`crate::instance_pool`]'s: nothing rewrites an entry between frames, so
127//! there is no frame still reading the value a write would replace. The three
128//! calls that write it — [`MeshPool::upload`] and [`MeshPool::free`] — each
129//! write a given entry once, and both are the same calls the pools' own space
130//! moves under. P9's streaming path is where that, the free lists and `flush`
131//! all stop being start-up-only together.
132//!
133//! **Skinning does not disturb that**, even though it is the one thing in the
134//! engine whose base vertex changes every frame:
135//! [`crate::skinning::SkinnedRegion`] alternates halves, and what alternates is
136//! a field of the *instance* — see
137//! [`GpuInstance::base_vertex`](crcbl_shaders::mesh::GpuInstance::base_vertex).
138//! Instances go through [`crate::instance_pool`], which **is** a ring, so no
139//! entry of this table is ever rewritten between frames.
140
141use core::ops::Range;
142use core::time::Duration;
143
144use crcbl_core::{Handle, Pool};
145use crcbl_hal::{
146    Barriers, BufferBarrier, BufferCopy, BufferDesc, BufferHandle, BufferUsage,
147    CommandBufferHandle, CommandEncoderDesc, Device, Features, HalError, MemoryLocation,
148    QueueHandle, ResourceState, SemaphoreDesc, SemaphoreHandle, SemaphoreKind, SemaphoreSignal,
149    SemaphoreWait, SubmitInfo,
150};
151use crcbl_shaders::mesh::{
152    ATTRIBUTE_STRIDE, GpuMesh, MESH_ENTRY_STRIDE, POSITION_STRIDE, VERTEX_STRIDE,
153};
154use crcbl_shaders::vertex::UvRange;
155use glam::Vec3;
156
157use crate::cull::Aabb;
158
159/// Bytes per index. `Uint32` everywhere, so the index pool suballocates in
160/// indices and [`MeshRange::base_index`] is `draw_indexed`'s own first-index.
161const INDEX_STRIDE: u64 = 4;
162
163/// How long [`MeshPool::flush`] waits for its transfers before calling the
164/// device hung.
165///
166/// Not `u64::MAX`: a wait that cannot time out turns a lost device into a
167/// process that never returns, and this one runs at start-up where there is
168/// still a user watching. Long enough that a loaded CI machine running a
169/// software rasteriser is not mistaken for one.
170pub const UPLOAD_TIMEOUT: Duration = Duration::from_secs(10);
171
172/// Marker type for [`MeshHandle`]. Uninhabited.
173#[derive(Debug)]
174pub enum Mesh {}
175
176/// A mesh in a [`MeshPool`]. Generational, so a freed mesh's handle stops
177/// resolving rather than naming whatever took its place.
178pub type MeshHandle = Handle<Mesh>;
179
180/// Where a mesh lives in the pools — §3.1's three integers — **and the box its
181/// vertices fit in**.
182///
183/// Two of the three integers are `draw_indexed`'s own arguments — the draw is
184/// `draw_indexed(base_index..base_index + index_count, 0, …)` — and
185/// [`MeshRange::base_vertex`] is deliberately not the third. The
186/// [module docs](self) say why it reaches the shader as data instead.
187///
188/// `PartialEq` but no longer `Eq`: [`MeshRange::bounds`] is floats, and total
189/// equality over an `f32` is a claim `NaN` makes untrue.
190#[derive(Clone, Copy, Debug, Default, PartialEq)]
191pub struct MeshRange {
192    /// First vertex of this mesh in the vertex pool. Added to every index the
193    /// shader reads, which is why the indices themselves are mesh-relative.
194    ///
195    /// Never above `i32::MAX`: [`MeshPool::new`] refuses a vertex capacity that
196    /// a draw's *signed* base vertex could not address, which is the width
197    /// `VkDrawIndexedIndirectCommand::vertexOffset` and its D3D12 and WebGPU
198    /// equivalents have — so a pool this rule allows is one §3.3's indirect
199    /// draws can still address.
200    pub base_vertex: u32,
201    /// First index of this mesh in the index pool.
202    pub base_index: u32,
203    /// How many indices to draw.
204    pub index_count: u32,
205    /// The mesh's **local-space** bounds: the smallest axis-aligned box holding
206    /// every vertex position [`MeshPool::upload`] was handed.
207    ///
208    /// Computed by the pool rather than supplied by the caller, because the
209    /// pool has the vertex bytes and a caller that got this wrong would produce
210    /// geometry culled while it is on screen — a hole in the picture with
211    /// nothing to fail. It travels with the range for the reason the
212    /// [module docs](self) give: same lifetime, same table entry, same write.
213    pub bounds: Aabb,
214    /// The scale and offset this mesh's `unorm16` UV lanes were quantised
215    /// against, on its way to [`GpuMesh::uv_range`].
216    ///
217    /// Supplied by the caller rather than computed here, unlike
218    /// [`bounds`](Self::bounds): the pool receives coordinates that are
219    /// *already* lanes, so the float range they came from is the one thing
220    /// about a mesh it cannot recover. `crcbl_shaders::vertex::UvRange::from_uvs`
221    /// is what the caller builds it with, over every coordinate the mesh
222    /// carries — and, for a DAG, over every coordinate every level carries.
223    pub uv_range: UvRange,
224    /// The mesh's own bits, on their way to [`GpuMesh::flags`] — today only
225    /// [`GpuMesh::MESH_AUTHORED_TANGENTS`].
226    ///
227    /// Supplied by the caller for [`uv_range`](Self::uv_range)'s reason
228    /// exactly, and more strongly: the pool receives a `snorm16x4` quaternion
229    /// per vertex and every such quaternion is a valid frame, so whether the
230    /// frame *means* anything for sampling a texture is the one thing about a
231    /// mesh that cannot be read back out of its bytes. It is a claim, and only
232    /// whoever built the vertices can make it.
233    pub flags: u32,
234}
235
236/// One mesh as a caller hands it to [`MeshPool::upload`].
237///
238/// A description rather than six positional arguments, on
239/// [`MeshPoolDesc`]'s terms: three of the five are slices whose order a caller
240/// has no way to check at the call site, and `vertices` and `indices` swapped
241/// is a mesh that uploads and draws nothing.
242#[derive(Clone, Copy, Debug)]
243pub struct MeshUpload<'a> {
244    /// Debug name for the staging buffer and the command buffer this upload
245    /// records into, so a capture says which mesh a copy belongs to.
246    pub label: &'a str,
247    /// `VERTEX_STRIDE`-strided vertex data — one
248    /// [`MeshVertex::to_bytes`] record each, **interleaved**, which is not how
249    /// the pool stores them: [`MeshPool::upload`] is where the two streams are
250    /// separated, so a caller describes geometry once and the position region
251    /// stays contiguous for the passes that read nothing else.
252    ///
253    /// [`MeshVertex::to_bytes`]: crcbl_shaders::mesh::MeshVertex::to_bytes
254    pub vertices: &'a [u8],
255    /// Triangle indices, **mesh-relative**: the base vertex reaches the GPU
256    /// beside them rather than inside them, so a mesh's bytes never depend on
257    /// where in the pool it landed. The [module docs](self) say by which route.
258    pub indices: &'a [u32],
259    /// The pair every UV lane in `vertices` was quantised against, on its way
260    /// to [`MeshRange::uv_range`] and the mesh table.
261    pub uv_range: UvRange,
262    /// The mesh's own bits, on their way to [`MeshRange::flags`] — today only
263    /// [`GpuMesh::MESH_AUTHORED_TANGENTS`].
264    pub flags: u32,
265}
266
267/// What a [`MeshPool`] refuses to do.
268#[derive(Debug, thiserror::Error)]
269pub enum MeshPoolError {
270    /// No single free block is large enough.
271    ///
272    /// `largest_free` well below `total_free` is fragmentation — see the
273    /// [module docs](self) on why the pool does not compact to fix it. A
274    /// `total_free` below `requested` is a pool that is simply too small.
275    #[error(
276        "the {pool} pool cannot fit {requested} more: the largest free block holds \
277         {largest_free} and {total_free} are free in total, out of a capacity of {capacity}"
278    )]
279    PoolExhausted {
280        /// `"vertex"` or `"index"`.
281        pool: &'static str,
282        /// What the allocation asked for, in elements.
283        requested: u32,
284        /// The largest single run the free list could offer.
285        largest_free: u32,
286        /// Everything free, summed across blocks.
287        total_free: u32,
288        /// The pool's fixed capacity, in elements.
289        capacity: u32,
290    },
291    /// A vertex capacity no draw could address.
292    ///
293    /// `draw_indexed` takes its base vertex **signed** — Vulkan, D3D12 and
294    /// WebGPU all do — so a pool larger than that could hand out a base the
295    /// draw cannot express. Refused at creation, which is what lets
296    /// [`MeshRange::base_vertex`] be an ordinary count everywhere else.
297    #[error("a vertex capacity of {capacity} is past what a draw's signed base vertex can address")]
298    VertexCapacityTooLarge {
299        /// What was asked for.
300        capacity: u32,
301    },
302    /// Every mesh-table entry is spoken for.
303    ///
304    /// The table is one entry per mesh the pool can hold at once, and it is
305    /// fixed by [`MeshPoolDesc::mesh_capacity`] for the reason every other
306    /// capacity here is: the buffer is created once and bound into every group
307    /// that names it.
308    #[error("the mesh table holds {capacity} meshes and {in_use} of them are in use")]
309    MeshTableFull {
310        /// The table's fixed capacity.
311        capacity: u32,
312        /// Entries that cannot be handed out — live meshes, plus any slot
313        /// permanently withdrawn by generation exhaustion.
314        in_use: u32,
315    },
316    /// A reservation of no vertices, which has no address to hand back.
317    ///
318    /// Its own variant rather than [`EmptyMesh`](Self::EmptyMesh): a
319    /// [`reserve_vertices`](MeshPool::reserve_vertices) caller has no indices
320    /// to have got wrong, and a message naming them would send the reader
321    /// looking for a mistake that is not there.
322    #[error("a reserved vertex run needs at least one vertex")]
323    EmptyReservation,
324    /// A mesh with no vertices or no indices.
325    #[error("a mesh needs both vertices and indices; got {vertices} and {indices}")]
326    EmptyMesh {
327        /// Vertices offered.
328        vertices: u32,
329        /// Indices offered.
330        indices: u32,
331    },
332    /// The vertex bytes are not a whole number of vertices.
333    #[error(
334        "{bytes} bytes of vertex data is not a whole number of {VERTEX_STRIDE}-byte vertices; \
335         the pool holds one vertex format and this is not it"
336    )]
337    VertexStrideMismatch {
338        /// What the caller offered.
339        bytes: usize,
340    },
341    /// A mesh has no range to draw: unknown handle, freed handle, or an upload
342    /// that has not completed.
343    #[error(
344        "mesh {handle:?} is not resident: it was never uploaded to this pool, it has been freed, \
345         or its upload has not been flushed"
346    )]
347    NotResident {
348        /// The handle that resolved to nothing.
349        handle: MeshHandle,
350    },
351    /// The transfers did not complete within [`UPLOAD_TIMEOUT`].
352    #[error("the mesh pool's uploads did not complete within {}s", timeout.as_secs())]
353    UploadTimedOut {
354        /// How long the wait was given.
355        timeout: Duration,
356    },
357    /// Anything the seam refused.
358    #[error(transparent)]
359    Hal(#[from] HalError),
360}
361
362/// Flattens a pool error into the seam's, for callers whose constructors are
363/// already `Result<_, HalError>`.
364///
365/// The seam has no vocabulary for "this pool is fragmented", so everything that
366/// is not already a [`HalError`] arrives as
367/// [`Backend`](HalError::Backend) — which renders verbatim, so the message
368/// naming the numbers survives. Callers that want to *match* on exhaustion take
369/// [`MeshPoolError`] instead.
370impl From<MeshPoolError> for HalError {
371    fn from(error: MeshPoolError) -> Self {
372        match error {
373            MeshPoolError::Hal(hal) => hal,
374            other => Self::Backend(other.to_string()),
375        }
376    }
377}
378
379/// How large a [`MeshPool`]'s two buffers are, and what to call them.
380#[derive(Clone, Copy, Debug, PartialEq, Eq)]
381pub struct MeshPoolDesc<'a> {
382    /// Debug name; the two buffers and the semaphore are named after it.
383    pub label: Option<&'a str>,
384    /// Vertices the pool can hold. Fixed — see the [module docs](self).
385    pub vertex_capacity: u32,
386    /// Indices the pool can hold.
387    pub index_capacity: u32,
388    /// Meshes the pool can hold at once, which is the length of the mesh table.
389    ///
390    /// Counted in meshes rather than in bytes, so it is the largest
391    /// [`MeshPool::table_index`] plus one and the number an instance's mesh id
392    /// must stay below.
393    pub mesh_capacity: u32,
394}
395
396/// One suballocated mesh, and the timeline value its bytes arrive under.
397#[derive(Clone, Copy, Debug)]
398struct Resident {
399    range: MeshRange,
400    /// Kept so [`MeshPool::free`] can return the vertex range; the range itself
401    /// only carries the *index* count, because that is all a draw needs.
402    vertex_count: u32,
403    /// The timeline value the upload's submit signals. The mesh is resident
404    /// once [`MeshPool::completed`] has reached it.
405    ready_at: u64,
406}
407
408/// A staging buffer and command buffer that cannot be released until the copy
409/// using them has run.
410#[derive(Clone, Copy, Debug)]
411struct InFlight {
412    staging: BufferHandle,
413    commands: CommandBufferHandle,
414}
415
416/// One vertex pool and one index pool, with a free-list suballocator over each.
417///
418/// See the [module docs](self) for the fragmentation, growth and residency
419/// policies, all three of which are decisions rather than accidents.
420#[derive(Debug)]
421pub struct MeshPool {
422    vertices: BufferHandle,
423    indices: BufferHandle,
424    /// Vertices the pool can hold, which is also where its attribute region
425    /// begins — see [`MeshPool::attribute_base`].
426    vertex_capacity: u32,
427    vertex_alloc: FreeList,
428    index_alloc: FreeList,
429
430    /// The mesh table: `table_capacity` [`GpuMesh`] entries, indexed by a
431    /// mesh's slot. Host-visible and written in place — see the
432    /// [module docs](self) on why it needs no ring.
433    table: BufferHandle,
434    table_capacity: u32,
435
436    meshes: Pool<Resident>,
437
438    /// `None` on a device without [`Features::TIMELINE_SEMAPHORE`], where
439    /// [`MeshPool::flush`] falls back to `wait_idle` — the same fallback
440    /// `crcbl::GpuContext::retire_to` takes.
441    timeline: Option<SemaphoreHandle>,
442    /// Highest value any upload has been submitted with.
443    submitted: u64,
444    /// Highest value observed to have passed. Meshes at or below it are
445    /// resident.
446    completed: u64,
447    in_flight: Vec<InFlight>,
448}
449
450impl MeshPool {
451    /// Creates both pools, empty.
452    ///
453    /// # Errors
454    ///
455    /// [`MeshPoolError::Hal`] from any seam call. A failure part-way through
456    /// releases whatever was already created.
457    pub fn new(device: &dyn Device, desc: &MeshPoolDesc<'_>) -> Result<Self, MeshPoolError> {
458        if i32::try_from(desc.vertex_capacity).is_err() {
459            return Err(MeshPoolError::VertexCapacityTooLarge {
460                capacity: desc.vertex_capacity,
461            });
462        }
463        let stem = desc.label.unwrap_or("mesh pool");
464        let vertices = device.create_buffer(&BufferDesc {
465            label: Some(&format!("{stem} vertices")),
466            size: u64::from(desc.vertex_capacity) * VERTEX_STRIDE as u64,
467            // **Two regions, not one interleaved array.** The first
468            // `vertex_capacity * POSITION_STRIDE` bytes are every vertex's
469            // position and the rest is every vertex's attributes, which is
470            // topic 43 §2's split — see
471            // `MeshPool::attribute_base`, the one number a shader cannot derive
472            // for itself. The buffer is the same size either way.
473            //
474            // STORAGE, not a vertex buffer: §3.1's vertex pulling means the
475            // vertex stage indexes this with `SV_VertexID` and there is no
476            // vertex-input state anywhere in the engine.
477            usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_DST,
478            memory: MemoryLocation::DeviceLocal,
479        })?;
480        let indices = match device.create_buffer(&BufferDesc {
481            label: Some(&format!("{stem} indices")),
482            size: u64::from(desc.index_capacity) * INDEX_STRIDE,
483            usage: BufferUsage::INDEX | BufferUsage::TRANSFER_DST,
484            memory: MemoryLocation::DeviceLocal,
485        }) {
486            Ok(indices) => indices,
487            Err(error) => {
488                device.destroy_buffer(vertices);
489                return Err(error.into());
490            }
491        };
492
493        let table = match Self::create_table(device, stem, desc.mesh_capacity) {
494            Ok(table) => table,
495            Err(error) => {
496                device.destroy_buffer(indices);
497                device.destroy_buffer(vertices);
498                return Err(error);
499            }
500        };
501
502        // The capability check rather than the error, so a device that simply
503        // has no timeline semaphores takes the documented fallback and a device
504        // that has them but failed to make one still reports why.
505        let timeline = if device
506            .caps()
507            .features
508            .contains(Features::TIMELINE_SEMAPHORE)
509        {
510            match device.create_semaphore(&SemaphoreDesc {
511                label: Some(&format!("{stem} uploads")),
512                kind: SemaphoreKind::Timeline { initial_value: 0 },
513            }) {
514                Ok(semaphore) => Some(semaphore),
515                Err(error) => {
516                    device.destroy_buffer(table);
517                    device.destroy_buffer(indices);
518                    device.destroy_buffer(vertices);
519                    return Err(error.into());
520                }
521            }
522        } else {
523            crcbl_core::log::debug!(
524                "mesh pool: no timeline semaphores; draining uploads with wait_idle"
525            );
526            None
527        };
528
529        Ok(Self {
530            vertices,
531            indices,
532            vertex_capacity: desc.vertex_capacity,
533            vertex_alloc: FreeList::new(desc.vertex_capacity),
534            index_alloc: FreeList::new(desc.index_capacity),
535            table,
536            table_capacity: desc.mesh_capacity,
537            meshes: Pool::new(),
538            timeline,
539            submitted: 0,
540            completed: 0,
541            in_flight: Vec::new(),
542        })
543    }
544
545    /// Where the attribute region begins in the vertex pool, in **bytes**.
546    ///
547    /// Every position the pool can hold comes first, so the boundary is the
548    /// capacity rather than anything about the meshes actually resident — which
549    /// is what lets a mesh be freed and another uploaded at a different base
550    /// with nothing else moving.
551    const fn attribute_region(&self) -> u64 {
552        self.vertex_capacity as u64 * POSITION_STRIDE as u64
553    }
554
555    /// The same boundary as a **word** index, which is what the shaders take.
556    ///
557    /// `FrameUniforms::vertex_pool`'s `x` lane and
558    /// `crcbl_shaders::skinning::Params::attribute_base` are both this number:
559    /// a vertex `v`'s position is at word `3 v` and its attributes at word
560    /// `attribute_base() + 5 v`. It is the one thing about the split a shader
561    /// cannot derive, because the pool's capacity has never been something a
562    /// shader was told.
563    ///
564    /// [`MeshPool::new`] refuses a capacity above `i32::MAX`, so the product
565    /// with `POSITION_STRIDE / 4` cannot overflow a `u32`: three times two
566    /// billion is short of four.
567    #[must_use]
568    pub const fn attribute_base(&self) -> u32 {
569        self.vertex_capacity * (POSITION_STRIDE / size_of::<u32>()) as u32
570    }
571
572    /// The vertex pool. Bound as a storage buffer; the vertex stage indexes it.
573    #[must_use]
574    pub const fn vertex_buffer(&self) -> BufferHandle {
575        self.vertices
576    }
577
578    /// The index pool. Bound once, at offset zero, for every mesh in it.
579    #[must_use]
580    pub const fn index_buffer(&self) -> BufferHandle {
581        self.indices
582    }
583
584    /// The mesh table. Bound as a read-only storage buffer; the vertex stage
585    /// indexes it with an instance's mesh id.
586    #[must_use]
587    pub const fn table_buffer(&self) -> BufferHandle {
588        self.table
589    }
590
591    /// The mesh table as the device holds it: every slot, a resident mesh's
592    /// entry where one is and the cleared entry everywhere else.
593    ///
594    /// Built from the residents rather than mirrored, because the one place an
595    /// entry is written writes exactly a resident's range — so this is what a
596    /// readback of [`table_buffer`](Self::table_buffer) would decode to, without
597    /// a buffer the device has to make readable. For `crate::cull`'s oracle,
598    /// which indexes it by an instance's mesh id.
599    #[must_use]
600    pub fn table_entries(&self) -> Vec<GpuMesh> {
601        let mut entries = vec![GpuMesh::default(); self.table_capacity as usize];
602        for (handle, resident) in self.meshes.iter() {
603            let range = resident.range;
604            entries[handle.index() as usize] = GpuMesh {
605                base_vertex: range.base_vertex,
606                base_index: range.base_index,
607                index_count: range.index_count,
608                bounds_min: range.bounds.min.to_array(),
609                bounds_max: range.bounds.max.to_array(),
610                uv_range: range.uv_range,
611                flags: range.flags,
612            };
613        }
614        entries
615    }
616
617    /// How many meshes the table holds, which is the bound every mesh id is
618    /// below.
619    #[must_use]
620    pub const fn mesh_capacity(&self) -> u32 {
621        self.table_capacity
622    }
623
624    /// Creates the mesh table and clears it.
625    ///
626    /// Cleared rather than left as the driver handed it over: an entry no mesh
627    /// occupies is read by any instance naming it, and "all zeroes is the empty
628    /// range" is only a contract if it holds for the entries nothing has
629    /// written yet as well as for the ones [`MeshPool::free`] clears.
630    fn create_table(
631        device: &dyn Device,
632        stem: &str,
633        capacity: u32,
634    ) -> Result<BufferHandle, MeshPoolError> {
635        let size = u64::from(capacity) * MESH_ENTRY_STRIDE as u64;
636        let table = device.create_buffer(&BufferDesc {
637            label: Some(&format!("{stem} mesh table")),
638            size,
639            // Host-visible, for the reason `crate::instance_pool`'s buffers
640            // are: a write is then a `write_buffer` rather than a staging copy
641            // needing a barrier. Unlike those there is no ring, because nothing
642            // rewrites an entry between frames.
643            usage: BufferUsage::STORAGE,
644            memory: MemoryLocation::HostUpload,
645        })?;
646        let cleared = vec![0u8; usize::try_from(size).unwrap_or(usize::MAX)];
647        if let Err(error) = device.write_buffer(table, 0, &cleared) {
648            device.destroy_buffer(table);
649            return Err(error.into());
650        }
651        Ok(table)
652    }
653
654    /// Writes one mesh table entry, at the slot `index` names.
655    ///
656    /// The one place a [`MeshRange`] becomes the record the shader reads, so
657    /// the two layouts have a single point of contact rather than a conversion
658    /// per call site. A default range is the empty entry [`MeshPool::free`]
659    /// clears a slot with.
660    fn write_entry(
661        &self,
662        device: &dyn Device,
663        index: u32,
664        range: &MeshRange,
665    ) -> Result<(), MeshPoolError> {
666        let entry = GpuMesh {
667            base_vertex: range.base_vertex,
668            base_index: range.base_index,
669            index_count: range.index_count,
670            bounds_min: range.bounds.min.to_array(),
671            bounds_max: range.bounds.max.to_array(),
672            uv_range: range.uv_range,
673            flags: range.flags,
674        };
675        let at = u64::from(index) * MESH_ENTRY_STRIDE as u64;
676        device.write_buffer(self.table, at, &entry.to_bytes())?;
677        Ok(())
678    }
679
680    /// Table slots that cannot be handed out: live meshes, plus any
681    /// permanently withdrawn by generation exhaustion.
682    ///
683    /// Same shape and same reason as [`crate::instance_pool`]'s: [`Pool`] hands
684    /// out a fresh index only when it has no vacant slot, so this is exactly
685    /// the highest index it could be about to create.
686    fn table_slots_in_use(&self) -> u32 {
687        let used = self.meshes.len() + self.meshes.retired_slots();
688        u32::try_from(used).unwrap_or(u32::MAX)
689    }
690
691    /// Suballocates room for a mesh and records a staging copy into it.
692    ///
693    /// The returned mesh is not resident until [`MeshPool::flush`] has run, and
694    /// [`MeshPool::mesh`] says so.
695    ///
696    /// # Errors
697    ///
698    /// [`MeshPoolError::EmptyMesh`] or [`MeshPoolError::VertexStrideMismatch`]
699    /// for data this pool cannot describe, [`MeshPoolError::PoolExhausted`] when
700    /// either pool has no block large enough, [`MeshPoolError::MeshTableFull`]
701    /// when the table has no entry left, and [`MeshPoolError::Hal`] from any
702    /// seam call. Nothing is left allocated on any failing path: a vertex range
703    /// taken before the index pool refused is given back.
704    pub fn upload(
705        &mut self,
706        device: &dyn Device,
707        queue: QueueHandle,
708        mesh: &MeshUpload<'_>,
709    ) -> Result<MeshHandle, MeshPoolError> {
710        let MeshUpload {
711            label,
712            vertices,
713            indices,
714            uv_range,
715            flags,
716        } = *mesh;
717        if !vertices.len().is_multiple_of(VERTEX_STRIDE) {
718            return Err(MeshPoolError::VertexStrideMismatch {
719                bytes: vertices.len(),
720            });
721        }
722        let vertex_count = u32::try_from(vertices.len() / VERTEX_STRIDE).unwrap_or(u32::MAX);
723        let index_count = u32::try_from(indices.len()).unwrap_or(u32::MAX);
724        if vertex_count == 0 || index_count == 0 {
725            return Err(MeshPoolError::EmptyMesh {
726                vertices: vertex_count,
727                indices: index_count,
728            });
729        }
730
731        // Before either free list is touched, so a table that is full costs no
732        // allocation to give back. Checked rather than left to the write below
733        // running off the end of the buffer, which is the seam refusing an
734        // out-of-range write and says nothing about meshes.
735        let in_use = self.table_slots_in_use();
736        if in_use >= self.table_capacity {
737            return Err(MeshPoolError::MeshTableFull {
738                capacity: self.table_capacity,
739                in_use,
740            });
741        }
742
743        let base_vertex = self
744            .vertex_alloc
745            .alloc(vertex_count)
746            .ok_or_else(|| self.vertex_alloc.exhausted("vertex", vertex_count))?;
747        let base_index = match self.index_alloc.alloc(index_count) {
748            Some(base) => base,
749            None => {
750                // The vertex range is given back before the error leaves: a
751                // failed upload that kept half its allocation would leak pool
752                // space that nothing holds a handle to.
753                self.vertex_alloc.free(base_vertex, vertex_count);
754                return Err(self.index_alloc.exhausted("index", index_count));
755            }
756        };
757
758        let range = MeshRange {
759            base_vertex,
760            base_index,
761            index_count,
762            // From the bytes the caller just handed over, which is the only
763            // moment the pool ever sees them: the vertex pool is device-local
764            // and nothing reads it back.
765            bounds: local_bounds(vertices),
766            uv_range,
767            flags,
768        };
769        let ready_at = match self.record_upload(device, queue, label, vertices, indices, range) {
770            Ok(ready_at) => ready_at,
771            Err(error) => {
772                self.vertex_alloc.free(base_vertex, vertex_count);
773                self.index_alloc.free(base_index, index_count);
774                return Err(error);
775            }
776        };
777        let handle: MeshHandle = self
778            .meshes
779            .insert(Resident {
780                range,
781                vertex_count,
782                ready_at,
783            })
784            .cast();
785        // The slot the pool just handed out is the table entry this mesh owns,
786        // and it is written now rather than at `flush`: the CPU-side residency
787        // gate is `MeshPool::mesh`, so a draw for a mesh whose bytes have not
788        // landed cannot be recorded whatever the table says.
789        match self.write_entry(device, handle.index(), &range) {
790            Ok(()) => Ok(handle),
791            Err(error) => {
792                // A mesh no shader can resolve is not a mesh, so the handle is
793                // retired and the space goes back rather than being held by
794                // something nothing can draw. The copy already submitted still
795                // runs into that space — harmlessly, because the next upload's
796                // own copy is submitted after it on the same queue and lands
797                // second.
798                self.meshes.remove(handle.cast());
799                self.vertex_alloc.free(base_vertex, vertex_count);
800                self.index_alloc.free(base_index, index_count);
801                Err(error)
802            }
803        }
804    }
805
806    /// Stages both halves, records the copies and submits them, returning the
807    /// timeline value the submit signals.
808    ///
809    /// The staging buffer and the command buffer are handed to
810    /// [`MeshPool::in_flight`](Self::in_flight) rather than destroyed: the copy
811    /// has been *submitted*, not run.
812    fn record_upload(
813        &mut self,
814        device: &dyn Device,
815        queue: QueueHandle,
816        label: &str,
817        vertices: &[u8],
818        indices: &[u32],
819        range: MeshRange,
820    ) -> Result<u64, MeshPoolError> {
821        // One staging buffer for every half, positions first: three copies out
822        // of one allocation rather than three allocations, since they are
823        // submitted together anyway.
824        //
825        // **The de-interleave happens here**, on the host and once per upload.
826        // This is a start-up path — the [module docs](self) say so, and
827        // `MeshPool::flush` blocks — so the copy costs a load, not a frame.
828        let index_bytes: &[u8] = bytemuck::cast_slice(indices);
829        let mut positions = Vec::with_capacity(vertices.len() / VERTEX_STRIDE * POSITION_STRIDE);
830        let mut attributes = Vec::with_capacity(vertices.len() / VERTEX_STRIDE * ATTRIBUTE_STRIDE);
831        for vertex in vertices.as_chunks::<VERTEX_STRIDE>().0 {
832            positions.extend_from_slice(&vertex[..POSITION_STRIDE]);
833            attributes.extend_from_slice(&vertex[POSITION_STRIDE..]);
834        }
835        let staging = device.create_buffer(&BufferDesc {
836            label: Some(&format!("{label} staging")),
837            size: (vertices.len() + index_bytes.len()) as u64,
838            usage: BufferUsage::TRANSFER_SRC,
839            memory: MemoryLocation::HostUpload,
840        })?;
841        let submitted = match self.write_and_submit(
842            device,
843            queue,
844            label,
845            Staged {
846                staging,
847                position_bytes: &positions,
848                attribute_bytes: &attributes,
849                index_bytes,
850                range,
851            },
852        ) {
853            Ok(submitted) => submitted,
854            Err(error) => {
855                device.destroy_buffer(staging);
856                return Err(error);
857            }
858        };
859        Ok(submitted)
860    }
861
862    /// The half of [`MeshPool::record_upload`] the staging buffer is live
863    /// across, so the caller can release it on every failing path.
864    fn write_and_submit(
865        &mut self,
866        device: &dyn Device,
867        queue: QueueHandle,
868        label: &str,
869        staged: Staged<'_>,
870    ) -> Result<u64, MeshPoolError> {
871        let position_bytes = staged.position_bytes.len() as u64;
872        let attribute_bytes = staged.attribute_bytes.len() as u64;
873        device.write_buffer(staged.staging, 0, staged.position_bytes)?;
874        device.write_buffer(staged.staging, position_bytes, staged.attribute_bytes)?;
875        device.write_buffer(
876            staged.staging,
877            position_bytes + attribute_bytes,
878            staged.index_bytes,
879        )?;
880
881        let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
882            label: Some(&format!("{label} upload")),
883            queue,
884        });
885        // Back to TransferDst first. The pools are long-lived and already being
886        // read by the time a second mesh arrives, so unlike a freshly created
887        // buffer they have a state to come *from* — leaving this out is the
888        // hazard that only appears once the pool has more than one resident.
889        encoder.pipeline_barrier(&Barriers {
890            buffers: &[
891                BufferBarrier::new(
892                    self.vertices,
893                    ResourceState::ShaderRead,
894                    ResourceState::TransferDst,
895                ),
896                BufferBarrier::new(
897                    self.indices,
898                    ResourceState::IndexBuffer,
899                    ResourceState::TransferDst,
900                ),
901            ],
902            ..Barriers::default()
903        });
904        // Two copies into the vertex pool rather than one, which is the whole
905        // of what the split costs at upload: the position region at the top of
906        // the buffer and the attribute region past every position the pool can
907        // hold.
908        encoder.copy_buffer_to_buffer(&BufferCopy {
909            src: staged.staging,
910            src_offset: 0,
911            dst: self.vertices,
912            dst_offset: u64::from(staged.range.base_vertex) * POSITION_STRIDE as u64,
913            size: position_bytes,
914        });
915        encoder.copy_buffer_to_buffer(&BufferCopy {
916            src: staged.staging,
917            src_offset: position_bytes,
918            dst: self.vertices,
919            dst_offset: self.attribute_region()
920                + u64::from(staged.range.base_vertex) * ATTRIBUTE_STRIDE as u64,
921            size: attribute_bytes,
922        });
923        encoder.copy_buffer_to_buffer(&BufferCopy {
924            src: staged.staging,
925            src_offset: position_bytes + attribute_bytes,
926            dst: self.indices,
927            dst_offset: u64::from(staged.range.base_index) * INDEX_STRIDE,
928            size: staged.index_bytes.len() as u64,
929        });
930        encoder.pipeline_barrier(&Barriers {
931            buffers: &[
932                BufferBarrier::new(
933                    self.vertices,
934                    ResourceState::TransferDst,
935                    ResourceState::ShaderRead,
936                ),
937                BufferBarrier::new(
938                    self.indices,
939                    ResourceState::TransferDst,
940                    ResourceState::IndexBuffer,
941                ),
942            ],
943            ..Barriers::default()
944        });
945        let commands = encoder.finish()?;
946
947        let value = self.submitted + 1;
948        let signals = self
949            .timeline
950            .map(|semaphore| SemaphoreSignal { semaphore, value });
951        let submit = SubmitInfo {
952            command_buffers: &[commands],
953            waits: &[],
954            signals: signals.as_slice(),
955        };
956        if let Err(error) = device.submit(queue, &submit) {
957            device.destroy_command_buffer(commands);
958            return Err(error.into());
959        }
960        self.submitted = value;
961        self.in_flight.push(InFlight {
962            staging: staged.staging,
963            commands,
964        });
965        Ok(value)
966    }
967
968    /// Waits for every submitted upload, making its meshes resident, and
969    /// releases the staging buffers they used.
970    ///
971    /// # Errors
972    ///
973    /// [`MeshPoolError::UploadTimedOut`] if the transfers have not completed
974    /// within [`UPLOAD_TIMEOUT`], in which case nothing becomes resident and
975    /// nothing is released — the staging buffers may still be being read.
976    /// [`MeshPoolError::Hal`] if the wait itself failed.
977    pub fn flush(&mut self, device: &dyn Device) -> Result<(), MeshPoolError> {
978        if self.completed >= self.submitted {
979            return Ok(());
980        }
981        match self.timeline {
982            Some(semaphore) => {
983                let wait = SemaphoreWait {
984                    semaphore,
985                    value: self.submitted,
986                };
987                let timeout = u64::try_from(UPLOAD_TIMEOUT.as_nanos()).unwrap_or(u64::MAX);
988                if !device.wait_semaphores(&[wait], timeout)? {
989                    return Err(MeshPoolError::UploadTimedOut {
990                        timeout: UPLOAD_TIMEOUT,
991                    });
992                }
993            }
994            // The device-wide hammer, which is what a device with no timeline
995            // has. Correct, and coarser than it needs to be.
996            None => device.wait_idle()?,
997        }
998        self.completed = self.submitted;
999        for entry in self.in_flight.drain(..) {
1000            device.destroy_command_buffer(entry.commands);
1001            device.destroy_buffer(entry.staging);
1002        }
1003        Ok(())
1004    }
1005
1006    /// Where `handle`'s mesh is, or `None` if there is nothing safe to draw.
1007    ///
1008    /// `None` covers both halves of that: a handle this pool never issued or has
1009    /// since freed, and a mesh whose upload has not completed. A caller cannot
1010    /// obtain a range for a mesh the GPU may not have received yet, which is
1011    /// §3.1's "renderer consumes meshes only after the timeline value passes"
1012    /// expressed as a type rather than as a rule to remember.
1013    #[must_use]
1014    pub fn mesh(&self, handle: MeshHandle) -> Option<MeshRange> {
1015        self.resident(handle).map(|resident| resident.range)
1016    }
1017
1018    /// Which entry of the mesh table `handle` is: the number an instance's
1019    /// [`GpuInstance::mesh`](crcbl_shaders::mesh::GpuInstance::mesh) carries.
1020    ///
1021    /// `None` on the same terms as [`MeshPool::mesh`], and for the same reason:
1022    /// handing out an id for a mesh whose bytes may not have landed would move
1023    /// §3.1's residency gate from "the caller cannot get one" to "the caller
1024    /// must remember not to ask".
1025    #[must_use]
1026    pub fn table_index(&self, handle: MeshHandle) -> Option<u32> {
1027        self.resident(handle).map(|_| handle.index())
1028    }
1029
1030    /// `handle`'s mesh, if it is resident — the shared half of
1031    /// [`MeshPool::mesh`] and [`MeshPool::table_index`], so the two cannot come
1032    /// to disagree about what residency means.
1033    fn resident(&self, handle: MeshHandle) -> Option<&Resident> {
1034        self.meshes
1035            .get(handle.cast())
1036            .filter(|resident| resident.ready_at <= self.completed)
1037    }
1038
1039    /// Clears a mesh's table entry and returns its space to both free lists.
1040    ///
1041    /// The space is reusable immediately, which is only true because uploads are
1042    /// drained by [`MeshPool::flush`] before anything draws — freeing a mesh a
1043    /// submitted-but-unfinished copy still writes into would be a hazard, and
1044    /// P9's streaming path is where that stops being free.
1045    ///
1046    /// **The entry is cleared before the space goes back**, which is why this
1047    /// needs a device at all: an entry that outlived its mesh would resolve an
1048    /// instance's mesh id to space some other mesh now owns. Cleared, it reads
1049    /// as the empty range — see the [module docs](self), which also name the
1050    /// case clearing cannot cover.
1051    ///
1052    /// Returns whether the handle named a live mesh; a second free of the same
1053    /// handle answers `false` rather than corrupting the free list, because the
1054    /// handle's generation has moved on.
1055    ///
1056    /// # Errors
1057    ///
1058    /// [`MeshPoolError::Hal`] if the entry could not be cleared, in which case
1059    /// **nothing is freed** — the mesh is still live and the caller can retry.
1060    pub fn free(&mut self, device: &dyn Device, handle: MeshHandle) -> Result<bool, MeshPoolError> {
1061        let Some(resident) = self.meshes.get(handle.cast()).copied() else {
1062            return Ok(false);
1063        };
1064        self.write_entry(device, handle.index(), &MeshRange::default())?;
1065        self.meshes.remove(handle.cast());
1066        self.vertex_alloc
1067            .free(resident.range.base_vertex, resident.vertex_count);
1068        self.index_alloc
1069            .free(resident.range.base_index, resident.range.index_count);
1070        Ok(true)
1071    }
1072
1073    /// How many vertices `handle`'s mesh occupies in the vertex pool, or `None`
1074    /// on [`MeshPool::mesh`]'s terms.
1075    ///
1076    /// The fourth integer [`MeshRange`] deliberately does not carry, because a
1077    /// draw pulls through indices and needs none of it. A [`crate::skinning`]
1078    /// region does need it — a skinned run is exactly as long as the bind pose
1079    /// it deforms — and this is the only place the number exists.
1080    #[must_use]
1081    pub fn vertex_count(&self, handle: MeshHandle) -> Option<u32> {
1082        self.resident(handle).map(|resident| resident.vertex_count)
1083    }
1084
1085    /// Takes `count` vertices of the pool for a run **no upload fills**, and
1086    /// returns where it starts.
1087    ///
1088    /// The same suballocator [`MeshPool::upload`] draws from, without the
1089    /// staging copy, the mesh-table entry or the residency gate — because the
1090    /// caller is not uploading a mesh. [`crate::skinning`]'s transient skinned
1091    /// region is what this exists for: a run of the pool a compute pass writes
1092    /// and the vertex stage then pulls, whose bytes never come from the host at
1093    /// all.
1094    ///
1095    /// Two consequences, both of them the point rather than gaps:
1096    ///
1097    /// * **The space is undefined until something writes it.** There is no
1098    ///   staging buffer and no copy, so a draw over a reserved run that no
1099    ///   dispatch has filled reads whatever the allocation came with.
1100    /// * **It is disjoint from every other live allocation**, which is what
1101    ///   makes the skinning kernel's precondition true rather than merely
1102    ///   asserted: the free list never hands out an address twice, so a range
1103    ///   reserved here cannot overlap the bind-pose range a mesh occupies.
1104    ///
1105    /// It comes back through
1106    /// [`release_vertices`](Self::release_vertices) rather than
1107    /// [`free`](Self::free): there is no handle, no table entry and no
1108    /// generation here, so nothing can tell a second release from a first.
1109    ///
1110    /// # Errors
1111    ///
1112    /// [`MeshPoolError::EmptyReservation`] for a zero-length request, which has
1113    /// no address to hand back, and [`MeshPoolError::PoolExhausted`] when no
1114    /// single free block is large enough — see the [module docs](self) on why
1115    /// that can happen with the space free in total.
1116    pub fn reserve_vertices(&mut self, count: u32) -> Result<u32, MeshPoolError> {
1117        if count == 0 {
1118            return Err(MeshPoolError::EmptyReservation);
1119        }
1120        self.vertex_alloc
1121            .alloc(count)
1122            .ok_or_else(|| self.vertex_alloc.exhausted("vertex", count))
1123    }
1124
1125    /// Gives a run taken by [`reserve_vertices`](Self::reserve_vertices) back.
1126    ///
1127    /// `base` and `count` must be exactly what that call handed out and asked
1128    /// for. Releasing a run twice, or one that was never reserved, corrupts the
1129    /// free list — a debug build catches the overlap it produces, and a release
1130    /// build hands the same address out twice.
1131    pub fn release_vertices(&mut self, base: u32, count: u32) {
1132        self.vertex_alloc.free(base, count);
1133    }
1134
1135    /// Vertices free, and the largest single run of them: the pair that tells
1136    /// fragmentation from a full pool. Indices in
1137    /// [`MeshPool::index_space`](Self::index_space).
1138    #[must_use]
1139    pub fn vertex_space(&self) -> (u32, u32) {
1140        (
1141            self.vertex_alloc.total_free(),
1142            self.vertex_alloc.largest_free(),
1143        )
1144    }
1145
1146    /// Indices free, and the largest single run of them.
1147    #[must_use]
1148    pub fn index_space(&self) -> (u32, u32) {
1149        (
1150            self.index_alloc.total_free(),
1151            self.index_alloc.largest_free(),
1152        )
1153    }
1154
1155    /// Releases both pools and everything still staged. The device must be idle.
1156    pub fn destroy(self, device: &dyn Device) {
1157        for entry in self.in_flight {
1158            device.destroy_command_buffer(entry.commands);
1159            device.destroy_buffer(entry.staging);
1160        }
1161        if let Some(semaphore) = self.timeline {
1162            device.destroy_semaphore(semaphore);
1163        }
1164        device.destroy_buffer(self.table);
1165        device.destroy_buffer(self.indices);
1166        device.destroy_buffer(self.vertices);
1167    }
1168}
1169
1170/// The box holding every vertex position in `vertices`.
1171///
1172/// A zero box for no vertices, which [`MeshPool::upload`] has already refused by
1173/// name ([`MeshPoolError::EmptyMesh`]) before it gets here; the fallback exists
1174/// so this is total rather than panicking on a case its caller has excluded.
1175fn local_bounds(vertices: &[u8]) -> Aabb {
1176    Aabb::from_points(vertex_positions(vertices)).unwrap_or_default()
1177}
1178
1179/// The position of each whole [`VERTEX_STRIDE`]-byte vertex in `vertices`; a
1180/// trailing partial vertex is not read.
1181///
1182/// The position is the first three floats of each vertex —
1183/// [`crcbl_shaders::mesh::MeshVertex::position`], whose `w` is unused — read
1184/// straight out of the bytes rather than through a decoded `MeshVertex`,
1185/// because the pool never builds one and a second decoder is a second thing
1186/// that can disagree with the layout.
1187pub(crate) fn vertex_positions(vertices: &[u8]) -> impl Iterator<Item = Vec3> + '_ {
1188    vertices
1189        .as_chunks::<VERTEX_STRIDE>()
1190        .0
1191        .iter()
1192        .map(|vertex| {
1193            let float_at = |offset: usize| {
1194                f32::from_le_bytes(
1195                    vertex[offset..offset + 4]
1196                        .try_into()
1197                        .unwrap_or_else(|_| unreachable!("four bytes inside one vertex")),
1198                )
1199            };
1200            Vec3::new(float_at(0), float_at(4), float_at(8))
1201        })
1202}
1203
1204/// What [`MeshPool::write_and_submit`] needs that is not the device or the
1205/// queue — one struct rather than six positional arguments, two of which are
1206/// byte slices that would otherwise be swappable at the call site.
1207struct Staged<'a> {
1208    staging: BufferHandle,
1209    position_bytes: &'a [u8],
1210    attribute_bytes: &'a [u8],
1211    index_bytes: &'a [u8],
1212    range: MeshRange,
1213}
1214
1215/// A first-fit free-list suballocator over `0..capacity` **elements**.
1216///
1217/// Elements rather than bytes: the vertex pool counts vertices and the index
1218/// pool counts indices, so both hand back a number a draw call takes directly.
1219/// One type used twice rather than two nearly-identical ones, because the two
1220/// pools would always need the same fix.
1221///
1222/// The invariant every method preserves: `free` is sorted by `start`, holds no
1223/// empty block, and holds no two blocks that touch. Coalescing on [`FreeList::free`]
1224/// is what maintains the last of those, and it is what makes an alloc/free/alloc
1225/// cycle reuse the space instead of shredding it.
1226#[derive(Clone, Debug)]
1227struct FreeList {
1228    capacity: u32,
1229    free: Vec<Range<u32>>,
1230}
1231
1232impl FreeList {
1233    /// A pool with everything free.
1234    fn new(capacity: u32) -> Self {
1235        let mut free = Vec::new();
1236        // One block covering everything — and *no* block at all when there is
1237        // nothing to cover, because "sorted, non-empty, non-touching" is the
1238        // invariant every other method relies on.
1239        if capacity > 0 {
1240            free.push(0..capacity);
1241        }
1242        Self { capacity, free }
1243    }
1244
1245    /// Takes `len` elements from the first block that can hold them, returning
1246    /// where they start.
1247    ///
1248    /// `None` when no *single* block is large enough, whatever the total —
1249    /// which is the [module docs](self)' fragmentation case, not an oversight.
1250    /// A zero-length request is `None` too: it has no address to hand back.
1251    fn alloc(&mut self, len: u32) -> Option<u32> {
1252        if len == 0 {
1253            return None;
1254        }
1255        let index = self
1256            .free
1257            .iter()
1258            .position(|block| block.end - block.start >= len)?;
1259        let start = self.free[index].start;
1260        self.free[index].start += len;
1261        if self.free[index].is_empty() {
1262            self.free.remove(index);
1263        }
1264        Some(start)
1265    }
1266
1267    /// Gives `start..start + len` back, merging it with either neighbour it
1268    /// touches.
1269    fn free(&mut self, start: u32, len: u32) {
1270        if len == 0 {
1271            return;
1272        }
1273        let mut block = start..start + len;
1274        let at = self.free.partition_point(|other| other.start < start);
1275        debug_assert!(
1276            at == 0 || self.free[at - 1].end <= block.start,
1277            "freeing {block:?} overlaps the free block before it"
1278        );
1279        debug_assert!(
1280            self.free.get(at).is_none_or(|next| block.end <= next.start),
1281            "freeing {block:?} overlaps the free block after it"
1282        );
1283        // Absorb the following block first, so the merge into the preceding one
1284        // below carries it too and three neighbours collapse into one.
1285        if self
1286            .free
1287            .get(at)
1288            .is_some_and(|next| next.start == block.end)
1289        {
1290            block.end = self.free.remove(at).end;
1291        }
1292        if at > 0 && self.free[at - 1].end == block.start {
1293            self.free[at - 1].end = block.end;
1294        } else {
1295            self.free.insert(at, block);
1296        }
1297    }
1298
1299    /// Elements free across every block.
1300    fn total_free(&self) -> u32 {
1301        self.free.iter().map(|block| block.end - block.start).sum()
1302    }
1303
1304    /// The largest single run, which is what an allocation can actually get.
1305    fn largest_free(&self) -> u32 {
1306        self.free
1307            .iter()
1308            .map(|block| block.end - block.start)
1309            .max()
1310            .unwrap_or(0)
1311    }
1312
1313    /// The error for a request this list could not satisfy, with both numbers
1314    /// that distinguish fragmentation from a full pool.
1315    fn exhausted(&self, pool: &'static str, requested: u32) -> MeshPoolError {
1316        MeshPoolError::PoolExhausted {
1317            pool,
1318            requested,
1319            largest_free: self.largest_free(),
1320            total_free: self.total_free(),
1321            capacity: self.capacity,
1322        }
1323    }
1324}
1325
1326// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
1327#[cfg(all(test, not(target_arch = "wasm32")))]
1328mod tests {
1329    use super::*;
1330    use crcbl_hal::null::{Command, Event, NullInstance, Recorder};
1331    use crcbl_hal::{DeviceDesc, Instance, QueueKind};
1332    use crcbl_shaders::mesh;
1333
1334    fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
1335        let recorder = Recorder::new();
1336        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
1337        let adapter = instance.adapters().remove(0);
1338        let device = instance
1339            .create_device(&DeviceDesc::for_adapter(adapter.id))
1340            .expect("the null backend always opens");
1341        let queue = device.queue(QueueKind::Graphics).expect("always present");
1342        (recorder, device, queue)
1343    }
1344
1345    /// How many meshes the pools below can hold. More than any test uploads,
1346    /// so a table that is full is a case a test asks for rather than one it
1347    /// stumbles into.
1348    const TEST_MESHES: u32 = 8;
1349
1350    fn pool(device: &dyn Device, vertices: u32, indices: u32) -> MeshPool {
1351        MeshPool::new(
1352            device,
1353            &MeshPoolDesc {
1354                label: Some("test"),
1355                vertex_capacity: vertices,
1356                index_capacity: indices,
1357                mesh_capacity: TEST_MESHES,
1358            },
1359        )
1360        .expect("the null backend accepts every descriptor")
1361    }
1362
1363    /// `n` vertices' worth of bytes, distinct per vertex so a copy landing at
1364    /// the wrong offset could not compare equal by accident.
1365    fn vertex_bytes(n: u32) -> Vec<u8> {
1366        (0..n as usize * VERTEX_STRIDE)
1367            .map(|byte| (byte % 251) as u8)
1368            .collect()
1369    }
1370
1371    /// The mesh table as the GPU would read it: every entry decoded out of the
1372    /// bytes that actually reached the buffer, with the same layout
1373    /// `mesh.slang` indexes it by.
1374    ///
1375    /// Read back rather than mirrored, so this is evidence about the upload and
1376    /// not about the pool's own bookkeeping repeating itself.
1377    fn table(recorder: &Recorder, pool: &MeshPool) -> Vec<GpuMesh> {
1378        let bytes = recorder
1379            .buffer_bytes(pool.table_buffer())
1380            .expect("the table is live");
1381        assert_eq!(
1382            bytes.len(),
1383            pool.mesh_capacity() as usize * MESH_ENTRY_STRIDE,
1384            "the table must be one entry per mesh the pool can hold"
1385        );
1386        bytes
1387            .as_chunks::<MESH_ENTRY_STRIDE>()
1388            .0
1389            .iter()
1390            .map(GpuMesh::from_bytes)
1391            .collect()
1392    }
1393
1394    /// `range` as the entry the table holds for it.
1395    fn entry(range: MeshRange) -> GpuMesh {
1396        GpuMesh {
1397            base_vertex: range.base_vertex,
1398            base_index: range.base_index,
1399            index_count: range.index_count,
1400            bounds_min: range.bounds.min.to_array(),
1401            bounds_max: range.bounds.max.to_array(),
1402            uv_range: range.uv_range,
1403            flags: range.flags,
1404        }
1405    }
1406
1407    // --- the allocator, which is pure logic ---
1408
1409    /// Every allocation is inside the pool and disjoint from every other one.
1410    /// A first-fit list that forgot to advance a block's start would hand the
1411    /// same address out twice, and every mesh after the first would be drawn
1412    /// with another's vertices.
1413    #[test]
1414    fn every_allocation_is_inside_the_pool_and_disjoint_from_the_others() {
1415        let mut list = FreeList::new(64);
1416        let mut taken: Vec<Range<u32>> = Vec::new();
1417        for len in [8u32, 1, 16, 3, 8, 20] {
1418            let start = list.alloc(len).expect("64 elements is enough for these");
1419            let block = start..start + len;
1420            assert!(block.end <= 64, "{block:?} runs past the pool");
1421            for other in &taken {
1422                assert!(
1423                    block.end <= other.start || other.end <= block.start,
1424                    "{block:?} overlaps {other:?}"
1425                );
1426            }
1427            taken.push(block);
1428        }
1429        let handed_out: u32 = taken.iter().map(|block| block.end - block.start).sum();
1430        assert_eq!(
1431            list.total_free(),
1432            64 - handed_out,
1433            "what is free and what is handed out must add up to the capacity"
1434        );
1435    }
1436
1437    /// Free, and the space comes back — at the same address, because the list
1438    /// is first-fit and the hole is the first thing that fits.
1439    #[test]
1440    fn a_freed_block_is_reused() {
1441        let mut list = FreeList::new(32);
1442        let first = list.alloc(8).expect("empty pool");
1443        let middle = list.alloc(8).expect("still room");
1444        let last = list.alloc(8).expect("still room");
1445        assert_eq!((first, middle, last), (0, 8, 16));
1446
1447        list.free(middle, 8);
1448        assert_eq!(list.total_free(), 16, "the hole plus the tail");
1449        assert_eq!(
1450            list.alloc(8),
1451            Some(middle),
1452            "the hole is reused, not the tail"
1453        );
1454        assert_eq!(list.total_free(), 8);
1455    }
1456
1457    /// The case a naive free list gets wrong: enough space in total, no single
1458    /// block large enough, and **no compaction to fix it** — see the module
1459    /// docs. The error names both numbers so the two can be told apart.
1460    #[test]
1461    fn a_request_larger_than_every_block_fails_even_with_the_space_free() {
1462        let mut list = FreeList::new(10);
1463        let first = list.alloc(4).expect("empty");
1464        let fence = list.alloc(2).expect("room");
1465        let third = list.alloc(4).expect("room");
1466        assert_eq!((first, fence, third), (0, 4, 6));
1467
1468        // Two holes of four, kept apart by a live allocation of two.
1469        list.free(first, 4);
1470        list.free(third, 4);
1471        assert_eq!(list.total_free(), 8);
1472        assert_eq!(list.largest_free(), 4);
1473
1474        assert_eq!(list.alloc(5), None, "8 free, and not 5 of them in a row");
1475        let error = list.exhausted("vertex", 5);
1476        let message = error.to_string();
1477        assert!(
1478            message.contains("largest free block holds 4") && message.contains("8 are free"),
1479            "the error must name both numbers, got: {message}"
1480        );
1481        // And what does fit is still handed out, so the failure above is the
1482        // block size and not the list having given up.
1483        assert_eq!(list.alloc(4), Some(0));
1484    }
1485
1486    /// The other half of the same case: freeing the allocation between two
1487    /// holes merges all three, and the request that just failed now fits. A
1488    /// list that appended freed blocks without coalescing would still report
1489    /// three blocks of four, two and four, and still refuse.
1490    #[test]
1491    fn freeing_between_two_holes_coalesces_all_three() {
1492        let mut list = FreeList::new(10);
1493        let first = list.alloc(4).expect("empty");
1494        let fence = list.alloc(2).expect("room");
1495        let third = list.alloc(4).expect("room");
1496        list.free(first, 4);
1497        list.free(third, 4);
1498        assert_eq!(list.largest_free(), 4);
1499
1500        list.free(fence, 2);
1501        assert_eq!(list.total_free(), 10);
1502        assert_eq!(
1503            list.largest_free(),
1504            10,
1505            "three touching holes are one block, not three"
1506        );
1507        assert_eq!(list.alloc(10), Some(0), "and the whole pool is allocatable");
1508    }
1509
1510    /// Coalescing works from either side, not just when the freed block happens
1511    /// to sit after its neighbour.
1512    #[test]
1513    fn coalescing_merges_the_neighbour_on_either_side() {
1514        for order in [[0u32, 4], [4, 0]] {
1515            let mut list = FreeList::new(8);
1516            assert_eq!(list.alloc(4), Some(0));
1517            assert_eq!(list.alloc(4), Some(4));
1518            for start in order {
1519                list.free(start, 4);
1520            }
1521            assert_eq!(
1522                list.largest_free(),
1523                8,
1524                "freeing in the order {order:?} left the list fragmented"
1525            );
1526        }
1527    }
1528
1529    // --- the pool ---
1530
1531    /// A vertex capacity a draw's signed base vertex could not address is
1532    /// refused at creation, before any device object exists.
1533    ///
1534    /// This is the guard the draw call's conversion is allowed to call
1535    /// unreachable on, so it has to be shown to actually reject something —
1536    /// a capacity check that never fires would make that `unreachable!` a
1537    /// claim about nothing.
1538    #[test]
1539    fn a_vertex_capacity_a_draw_could_not_address_is_refused() {
1540        let (recorder, device, _) = open();
1541        let error = MeshPool::new(
1542            device.as_ref(),
1543            &MeshPoolDesc {
1544                label: Some("far too large"),
1545                vertex_capacity: u32::MAX,
1546                index_capacity: 8,
1547                mesh_capacity: TEST_MESHES,
1548            },
1549        )
1550        .expect_err("a draw cannot address that many vertices");
1551        assert!(
1552            matches!(error, MeshPoolError::VertexCapacityTooLarge { .. }),
1553            "got: {error:?}"
1554        );
1555        assert_eq!(
1556            recorder.total_live_objects(),
1557            0,
1558            "a refused pool creates nothing"
1559        );
1560        // And the largest capacity a draw *can* address is accepted, so the
1561        // check above is a boundary rather than a blanket refusal. The buffer is
1562        // never allocated by the null backend, which is what makes asking for
1563        // one this size a test rather than an out-of-memory.
1564        let pool = MeshPool::new(
1565            device.as_ref(),
1566            &MeshPoolDesc {
1567                label: Some("at the boundary"),
1568                vertex_capacity: i32::MAX as u32,
1569                index_capacity: 8,
1570                mesh_capacity: TEST_MESHES,
1571            },
1572        )
1573        .expect("the largest addressable capacity is not too large");
1574        pool.destroy(device.as_ref());
1575        recorder.assert_valid();
1576    }
1577
1578    /// A device without timeline semaphores drains with `wait_idle` and its
1579    /// meshes still become resident — the same fallback
1580    /// `crcbl::GpuContext::retire_to` takes, and a whole branch that no other
1581    /// test enters.
1582    #[test]
1583    fn a_device_without_timeline_semaphores_drains_with_wait_idle() {
1584        let recorder = Recorder::new();
1585        let instance = NullInstance::portable().with_recorder(recorder.clone());
1586        let adapter = instance.adapters().remove(0);
1587        // Not `for_adapter`: its required features include the timeline
1588        // semaphore this test exists to do without.
1589        let device = instance
1590            .create_device(&DeviceDesc {
1591                label: None,
1592                adapter: adapter.id,
1593                required_features: Features::COMPUTE,
1594                optional_features: Features::empty(),
1595                compatible_surface: None,
1596            })
1597            .expect("the portable null adapter opens");
1598        assert!(
1599            !device
1600                .caps()
1601                .features
1602                .contains(Features::TIMELINE_SEMAPHORE),
1603            "this test is only meaningful on a device that has none"
1604        );
1605        let queue = device.queue(QueueKind::Graphics).expect("always present");
1606
1607        let mut pool = pool(device.as_ref(), 64, 64);
1608        let handle = pool
1609            .upload(
1610                device.as_ref(),
1611                queue,
1612                &MeshUpload {
1613                    label: "cube",
1614                    vertices: &vertex_bytes(4),
1615                    indices: &[0, 1, 2],
1616                    uv_range: UvRange::default(),
1617                    flags: 0,
1618                },
1619            )
1620            .expect("it fits");
1621        let signals: Vec<_> = recorder
1622            .events()
1623            .into_iter()
1624            .filter_map(|event| match event {
1625                Event::Submitted { signals, .. } => Some(signals),
1626                _ => None,
1627            })
1628            .collect();
1629        assert_eq!(
1630            signals,
1631            vec![Vec::new()],
1632            "there is no timeline to signal, so the submit names none"
1633        );
1634        assert_eq!(pool.mesh(handle), None, "and it is still not resident");
1635
1636        pool.flush(device.as_ref()).expect("wait_idle always works");
1637        assert!(
1638            recorder
1639                .events()
1640                .iter()
1641                .any(|event| matches!(event, Event::WaitedIdle)),
1642            "the fallback is `wait_idle`; nothing else can drain this device"
1643        );
1644        assert!(
1645            pool.mesh(handle).is_some(),
1646            "and the mesh is resident afterwards, or this device could never draw"
1647        );
1648
1649        pool.destroy(device.as_ref());
1650        recorder.assert_valid();
1651    }
1652
1653    /// A pool that cannot fit a mesh says so by name, and takes nothing: the
1654    /// vertex range the failed upload had already reserved is given back, or a
1655    /// pool would leak space every time an index pool filled first.
1656    #[test]
1657    fn an_upload_that_does_not_fit_fails_by_name_and_reserves_nothing() {
1658        let (recorder, device, queue) = open();
1659        // Room for the vertices, not for the indices.
1660        let mut pool = pool(device.as_ref(), 64, 8);
1661        let before = pool.vertex_space();
1662
1663        let error = pool
1664            .upload(
1665                device.as_ref(),
1666                queue,
1667                &MeshUpload {
1668                    label: "too many indices",
1669                    vertices: &vertex_bytes(4),
1670                    indices: &[0; 16],
1671                    uv_range: UvRange::default(),
1672                    flags: 0,
1673                },
1674            )
1675            .expect_err("16 indices do not fit in 8");
1676        assert!(
1677            matches!(
1678                error,
1679                MeshPoolError::PoolExhausted {
1680                    pool: "index",
1681                    requested: 16,
1682                    capacity: 8,
1683                    ..
1684                }
1685            ),
1686            "got: {error:?}"
1687        );
1688        assert_eq!(
1689            pool.vertex_space(),
1690            before,
1691            "the vertex range reserved before the index pool refused must come back"
1692        );
1693        assert!(
1694            !recorder
1695                .events()
1696                .iter()
1697                .any(|event| matches!(event, Event::Submitted { .. })),
1698            "a refused upload submits nothing"
1699        );
1700        pool.destroy(device.as_ref());
1701        recorder.assert_valid();
1702    }
1703
1704    /// **The bug this design exists to prevent.** The mesh has been uploaded —
1705    /// the copy is recorded and submitted — and it is still not something a
1706    /// caller can draw, because the timeline value it was uploaded under has
1707    /// not been observed to pass. Only [`MeshPool::flush`] makes it resident.
1708    ///
1709    /// What this cannot show is a *real* GPU still executing the copy: the null
1710    /// backend records commands rather than running them, and satisfies every
1711    /// wait immediately. So this pins the gate's existence, not its timing —
1712    /// the timing is `crcbl-vk`'s e2e suite, where the cube either has vertices
1713    /// or does not.
1714    #[test]
1715    fn a_mesh_is_not_resident_until_its_upload_is_flushed() {
1716        let (recorder, device, queue) = open();
1717        let mut pool = pool(device.as_ref(), 64, 64);
1718        let handle = pool
1719            .upload(
1720                device.as_ref(),
1721                queue,
1722                &MeshUpload {
1723                    label: "cube",
1724                    vertices: &vertex_bytes(4),
1725                    indices: &[0, 1, 2, 0, 2, 3],
1726                    uv_range: UvRange::default(),
1727                    flags: 0,
1728                },
1729            )
1730            .expect("it fits");
1731
1732        assert!(
1733            recorder
1734                .events()
1735                .iter()
1736                .any(|event| matches!(event, Event::Submitted { .. })),
1737            "the copy really was submitted; residency is not just 'nothing happened yet'"
1738        );
1739        assert_eq!(
1740            pool.mesh(handle),
1741            None,
1742            "an unflushed mesh must not hand out a range"
1743        );
1744
1745        pool.flush(device.as_ref()).expect("the null device drains");
1746        assert_eq!(
1747            pool.mesh(handle),
1748            Some(MeshRange {
1749                uv_range: UvRange::default(),
1750                base_vertex: 0,
1751                base_index: 0,
1752                index_count: 6,
1753                bounds: local_bounds(&vertex_bytes(4)),
1754                flags: 0,
1755            }),
1756            "and once the timeline has passed, it must"
1757        );
1758
1759        pool.destroy(device.as_ref());
1760        recorder.assert_valid();
1761    }
1762
1763    /// The upload signals the pool's timeline, which is what residency is
1764    /// waiting on. A submit with no signal would make `flush` wait for a value
1765    /// nothing ever reaches.
1766    #[test]
1767    fn an_upload_signals_the_pools_timeline() {
1768        let (recorder, device, queue) = open();
1769        let mut pool = pool(device.as_ref(), 64, 64);
1770        pool.upload(
1771            device.as_ref(),
1772            queue,
1773            &MeshUpload {
1774                label: "cube",
1775                vertices: &vertex_bytes(4),
1776                indices: &[0, 1, 2],
1777                uv_range: UvRange::default(),
1778                flags: 0,
1779            },
1780        )
1781        .expect("it fits");
1782
1783        let signals: Vec<_> = recorder
1784            .events()
1785            .into_iter()
1786            .filter_map(|event| match event {
1787                Event::Submitted { signals, .. } => Some(signals),
1788                _ => None,
1789            })
1790            .collect();
1791        assert_eq!(signals.len(), 1, "one upload, one submit");
1792        assert_eq!(
1793            signals[0].len(),
1794            1,
1795            "the submit must signal something, or nothing can wait for it"
1796        );
1797        assert_eq!(
1798            signals[0][0].value, 1,
1799            "the first upload is timeline value 1"
1800        );
1801        pool.destroy(device.as_ref());
1802        recorder.assert_valid();
1803    }
1804
1805    /// Two meshes land at different bases, and the second's copies are offset
1806    /// by the first's size in **bytes** — the one place the element/byte
1807    /// conversion could go wrong without any test noticing.
1808    ///
1809    /// And by the *right* stride in each of the two vertex regions, which is
1810    /// what says the pool really de-interleaved rather than writing one array
1811    /// twice.
1812    #[test]
1813    fn a_second_mesh_lands_after_the_first_in_both_pools() {
1814        /// Where the attribute region of a 64-vertex pool begins, in bytes.
1815        ///
1816        /// Written out rather than taken from `MeshPool::attribute_base`: this
1817        /// is the assertion that the boundary is the capacity, and a test that
1818        /// asked the pool where it put things would agree with any answer.
1819        const ATTRIBUTES_AT: u64 = 64 * POSITION_STRIDE as u64;
1820
1821        let (recorder, device, queue) = open();
1822        let mut pool = pool(device.as_ref(), 64, 64);
1823        for (label, vertices, indices) in [
1824            ("first", 4u32, vec![0u32, 1, 2, 0, 2, 3]),
1825            ("second", 3, vec![0u32, 1, 2]),
1826        ] {
1827            pool.upload(
1828                device.as_ref(),
1829                queue,
1830                &MeshUpload {
1831                    label,
1832                    vertices: &vertex_bytes(vertices),
1833                    indices: &indices,
1834                    uv_range: UvRange::default(),
1835                    flags: 0,
1836                },
1837            )
1838            .expect("both fit");
1839        }
1840        pool.flush(device.as_ref()).expect("drains");
1841
1842        let copies: Vec<BufferCopy> = recorder
1843            .commands()
1844            .into_iter()
1845            .filter_map(|command| match command {
1846                Command::CopyBufferToBuffer(copy) => Some(copy),
1847                _ => None,
1848            })
1849            .collect();
1850        assert_eq!(
1851            copies.len(),
1852            6,
1853            "two meshes, and three copies each: the two vertex streams and the indices"
1854        );
1855        // First mesh: every region at the start of its own.
1856        assert_eq!(copies[0].dst_offset, 0, "the first mesh's positions");
1857        assert_eq!(
1858            copies[1].dst_offset, ATTRIBUTES_AT,
1859            "and its attributes, past every position the pool can hold"
1860        );
1861        assert_eq!(copies[2].dst_offset, 0, "and its indices");
1862        // Second mesh: four vertices and six indices further in — and the two
1863        // vertex regions step by *different* strides, which is the whole of
1864        // what the split is and the one thing an interleaved pool could not do.
1865        assert_eq!(
1866            copies[3].dst_offset,
1867            4 * POSITION_STRIDE as u64,
1868            "the second mesh's positions"
1869        );
1870        assert_eq!(
1871            copies[4].dst_offset,
1872            ATTRIBUTES_AT + 4 * ATTRIBUTE_STRIDE as u64,
1873            "and its attributes, at its own base inside the attribute region"
1874        );
1875        assert_eq!(copies[5].dst_offset, 6 * INDEX_STRIDE);
1876        pool.destroy(device.as_ref());
1877        recorder.assert_valid();
1878    }
1879
1880    /// Freeing a mesh returns its space and stops its handle resolving, so a
1881    /// stale handle cannot draw whatever moved in.
1882    #[test]
1883    fn freeing_a_mesh_returns_its_space_and_retires_its_handle() {
1884        let (recorder, device, queue) = open();
1885        let mut pool = pool(device.as_ref(), 64, 64);
1886        let handle = pool
1887            .upload(
1888                device.as_ref(),
1889                queue,
1890                &MeshUpload {
1891                    label: "cube",
1892                    vertices: &vertex_bytes(8),
1893                    indices: &[0; 12],
1894                    uv_range: UvRange::default(),
1895                    flags: 0,
1896                },
1897            )
1898            .expect("it fits");
1899        pool.flush(device.as_ref()).expect("drains");
1900        assert_eq!(pool.vertex_space(), (64 - 8, 64 - 8));
1901
1902        assert!(
1903            pool.free(device.as_ref(), handle).expect("the write lands"),
1904            "the handle names a live mesh"
1905        );
1906        assert_eq!(pool.vertex_space(), (64, 64), "and its space comes back");
1907        assert_eq!(pool.index_space(), (64, 64));
1908        assert_eq!(pool.mesh(handle), None, "the handle stops resolving");
1909        assert_eq!(pool.table_index(handle), None, "and names no table entry");
1910        assert!(
1911            !pool
1912                .free(device.as_ref(), handle)
1913                .expect("nothing to write"),
1914            "and a second free is refused"
1915        );
1916        assert_eq!(
1917            pool.vertex_space(),
1918            (64, 64),
1919            "a refused free must not double-count the space"
1920        );
1921
1922        pool.destroy(device.as_ref());
1923        recorder.assert_valid();
1924    }
1925
1926    // --- the mesh table ---
1927
1928    /// **The table is what the pool says it is, after a sequence of allocations
1929    /// and frees.** Decoded out of the buffer's own bytes, entry by entry,
1930    /// against what [`MeshPool::mesh`] hands the CPU for the same handle.
1931    ///
1932    /// The sequence is chosen so that no single mistake passes: three meshes,
1933    /// so an entry landing at the wrong stride is visible; a free in the
1934    /// *middle*, so the surviving neighbours must be untouched; and a fourth
1935    /// upload afterwards, which takes the freed slot and must replace that
1936    /// entry rather than append past it.
1937    #[test]
1938    fn the_table_matches_the_pool_through_allocations_and_frees() {
1939        let (recorder, device, queue) = open();
1940        let mut pool = pool(device.as_ref(), 64, 64);
1941
1942        // Distinct sizes, so no two meshes have interchangeable entries — and
1943        // distinct flags, because the flag word is the one column a row could
1944        // drop and still light every mesh in this tree correctly: a flat quad's
1945        // derivative frame is its authored frame, so no frame read off a device
1946        // can tell a pool that wrote the bit from one that wrote zero. Only the
1947        // bytes can.
1948        let handles: Vec<MeshHandle> = [
1949            (4u32, 6usize, GpuMesh::MESH_AUTHORED_TANGENTS),
1950            (3, 3, 0),
1951            (5, 9, GpuMesh::MESH_AUTHORED_TANGENTS),
1952        ]
1953        .into_iter()
1954        .map(|(vertices, indices, flags)| {
1955            pool.upload(
1956                device.as_ref(),
1957                queue,
1958                &MeshUpload {
1959                    label: "mesh",
1960                    vertices: &vertex_bytes(vertices),
1961                    indices: &vec![0u32; indices],
1962                    uv_range: UvRange::default(),
1963                    flags,
1964                },
1965            )
1966            .expect("they fit")
1967        })
1968        .collect();
1969        pool.flush(device.as_ref()).expect("drains");
1970
1971        let live = |pool: &MeshPool, recorder: &Recorder, handles: &[MeshHandle]| {
1972            let table = table(recorder, pool);
1973            for handle in handles {
1974                let range = pool.mesh(*handle).expect("resident");
1975                let index = pool.table_index(*handle).expect("resident") as usize;
1976                assert_eq!(
1977                    table[index],
1978                    entry(range),
1979                    "entry {index} does not hold {handle:?}'s range"
1980                );
1981            }
1982        };
1983        live(&pool, &recorder, &handles);
1984        // The ranges really are different, or the comparison above would hold
1985        // for a table that wrote the same entry three times.
1986        let ranges: Vec<MeshRange> = handles
1987            .iter()
1988            .map(|handle| pool.mesh(*handle).expect("resident"))
1989            .collect();
1990        assert_eq!(
1991            ranges[1].base_vertex, 4,
1992            "the second starts after the first"
1993        );
1994        assert_eq!(ranges[2].base_vertex, 7, "and the third after the second");
1995        // And the flags reached the CPU side as uploaded, or the comparison
1996        // above is two zeroes agreeing.
1997        assert_eq!(
1998            ranges.iter().map(|range| range.flags).collect::<Vec<u32>>(),
1999            [
2000                GpuMesh::MESH_AUTHORED_TANGENTS,
2001                0,
2002                GpuMesh::MESH_AUTHORED_TANGENTS
2003            ],
2004            "the pool must keep each mesh's flags, not the first's or none"
2005        );
2006
2007        // Free the middle one. Its entry is cleared and its neighbours' are not.
2008        let freed = pool.table_index(handles[1]).expect("resident");
2009        assert!(
2010            pool.free(device.as_ref(), handles[1])
2011                .expect("the write lands")
2012        );
2013        let after = table(&recorder, &pool);
2014        assert_eq!(
2015            after[freed as usize],
2016            GpuMesh::default(),
2017            "a freed mesh's entry must be cleared"
2018        );
2019        live(&pool, &recorder, &[handles[0], handles[2]]);
2020
2021        // And a fourth mesh takes the freed slot, replacing that entry rather
2022        // than landing past the ones already there.
2023        let reused = pool
2024            .upload(
2025                device.as_ref(),
2026                queue,
2027                &MeshUpload {
2028                    label: "fourth",
2029                    vertices: &vertex_bytes(2),
2030                    indices: &[0; 3],
2031                    uv_range: UvRange::default(),
2032                    flags: 0,
2033                },
2034            )
2035            .expect("the freed space fits it");
2036        pool.flush(device.as_ref()).expect("drains");
2037        assert_eq!(
2038            pool.table_index(reused),
2039            Some(freed),
2040            "the freed table slot is the one handed out again"
2041        );
2042        live(&pool, &recorder, &[handles[0], handles[2], reused]);
2043        assert_ne!(
2044            table(&recorder, &pool)[freed as usize],
2045            GpuMesh::default(),
2046            "and the slot is no longer the empty range"
2047        );
2048
2049        pool.destroy(device.as_ref());
2050        recorder.assert_valid();
2051    }
2052
2053    /// **What an instance naming a freed mesh resolves to**, which is the
2054    /// contract the module docs state: the empty range, and specifically *not*
2055    /// the range of whatever mesh moved into the space.
2056    ///
2057    /// A table left stale is the obvious defect and this is what fails on it —
2058    /// the freed mesh's entry would still name vertices that are now the
2059    /// second mesh's, so an instance pointing at it would draw geometry it has
2060    /// no relationship with rather than nothing at all.
2061    #[test]
2062    fn an_instance_naming_a_freed_mesh_resolves_to_the_empty_range() {
2063        let (recorder, device, queue) = open();
2064        let mut pool = pool(device.as_ref(), 64, 64);
2065        let first = pool
2066            .upload(
2067                device.as_ref(),
2068                queue,
2069                &MeshUpload {
2070                    label: "first",
2071                    vertices: &vertex_bytes(4),
2072                    indices: &[0; 6],
2073                    uv_range: UvRange::default(),
2074                    flags: 0,
2075                },
2076            )
2077            .expect("it fits");
2078        pool.flush(device.as_ref()).expect("drains");
2079        let mesh_id = pool.table_index(first).expect("resident");
2080        let freed_range = pool.mesh(first).expect("resident");
2081
2082        assert!(
2083            pool.free(device.as_ref(), first).expect("the write lands"),
2084            "the mesh was live"
2085        );
2086
2087        // The successor lands in the space the freed mesh had, which is what
2088        // makes a stale entry actively wrong rather than merely out of date.
2089        let second = pool
2090            .upload(
2091                device.as_ref(),
2092                queue,
2093                &MeshUpload {
2094                    label: "second",
2095                    vertices: &vertex_bytes(4),
2096                    indices: &[0; 6],
2097                    uv_range: UvRange::default(),
2098                    flags: 0,
2099                },
2100            )
2101            .expect("the freed space fits it");
2102        pool.flush(device.as_ref()).expect("drains");
2103        assert_eq!(
2104            pool.mesh(second).expect("resident"),
2105            freed_range,
2106            "this test is only meaningful while the successor takes the same space"
2107        );
2108
2109        // The mesh id the instance still carries. The successor took the same
2110        // *slot* too, so the entry is the successor's — see the module docs on
2111        // the case a `u32` id cannot tell apart, which is why this is asserted
2112        // against the successor rather than against the empty range here.
2113        assert_eq!(pool.table_index(second), Some(mesh_id));
2114
2115        // With the successor gone the entry is empty again, and that is what an
2116        // instance holding `mesh_id` reads: `index_count == 0`, no geometry —
2117        // rather than a range naming somebody else's vertices.
2118        assert!(pool.free(device.as_ref(), second).expect("the write lands"));
2119        assert_eq!(
2120            table(&recorder, &pool)[mesh_id as usize],
2121            GpuMesh::default(),
2122            "an id whose mesh was freed must resolve to the empty range"
2123        );
2124
2125        pool.destroy(device.as_ref());
2126        recorder.assert_valid();
2127    }
2128
2129    /// Every entry is the empty range before anything is uploaded, so an
2130    /// instance naming a slot no mesh has ever occupied reads no geometry
2131    /// rather than whatever the driver left in the buffer.
2132    ///
2133    /// Asserted on the *write* rather than only on the contents: the null
2134    /// backend hands out a zeroed buffer, so reading zeroes back says nothing
2135    /// about whether anything cleared it — and a real driver's host-visible
2136    /// allocation is not zeroed. The two halves together are the claim: the
2137    /// whole table was written, and what it holds is empty ranges.
2138    #[test]
2139    fn a_fresh_table_is_empty_ranges() {
2140        let (recorder, device, _) = open();
2141        let pool = pool(device.as_ref(), 64, 64);
2142        assert_eq!(pool.mesh_capacity(), TEST_MESHES);
2143
2144        let table_writes: Vec<(u64, usize)> = recorder
2145            .events()
2146            .into_iter()
2147            .filter_map(|event| match event {
2148                Event::BufferWritten {
2149                    buffer,
2150                    offset,
2151                    len,
2152                } if buffer == pool.table_buffer() => Some((offset, len)),
2153                _ => None,
2154            })
2155            .collect();
2156        assert_eq!(
2157            table_writes,
2158            [(0, TEST_MESHES as usize * MESH_ENTRY_STRIDE)],
2159            "creating a pool must clear the whole table, once"
2160        );
2161        assert_eq!(
2162            table(&recorder, &pool),
2163            vec![GpuMesh::default(); TEST_MESHES as usize],
2164            "and what it cleared it to is empty ranges"
2165        );
2166
2167        pool.destroy(device.as_ref());
2168        recorder.assert_valid();
2169    }
2170
2171    /// A table with no entry left refuses by name, and takes nothing: the
2172    /// refused upload must not consume pool space, or a caller that retried
2173    /// after making room would find less of it than before.
2174    #[test]
2175    fn a_full_mesh_table_fails_by_name_and_reserves_nothing() {
2176        let (recorder, device, queue) = open();
2177        let mut pool = MeshPool::new(
2178            device.as_ref(),
2179            &MeshPoolDesc {
2180                label: Some("two meshes"),
2181                vertex_capacity: 64,
2182                index_capacity: 64,
2183                mesh_capacity: 2,
2184            },
2185        )
2186        .expect("the null backend accepts every descriptor");
2187        let upload = |pool: &mut MeshPool| {
2188            pool.upload(
2189                device.as_ref(),
2190                queue,
2191                &MeshUpload {
2192                    label: "mesh",
2193                    vertices: &vertex_bytes(2),
2194                    indices: &[0; 3],
2195                    uv_range: UvRange::default(),
2196                    flags: 0,
2197                },
2198            )
2199        };
2200        let first = upload(&mut pool).expect("room");
2201        upload(&mut pool).expect("room");
2202        let before = pool.vertex_space();
2203
2204        let error = upload(&mut pool).expect_err("two meshes fill a table of two");
2205        assert!(
2206            matches!(
2207                error,
2208                MeshPoolError::MeshTableFull {
2209                    capacity: 2,
2210                    in_use: 2
2211                }
2212            ),
2213            "got: {error:?}"
2214        );
2215        assert_eq!(
2216            pool.vertex_space(),
2217            before,
2218            "a refused upload must reserve nothing, however much room the pools have"
2219        );
2220
2221        // And a freed entry is handed out again, so the refusal is the table's
2222        // size rather than the pool having given up.
2223        pool.flush(device.as_ref()).expect("drains");
2224        assert!(pool.free(device.as_ref(), first).expect("the write lands"));
2225        upload(&mut pool).expect("the freed entry");
2226
2227        pool.destroy(device.as_ref());
2228        recorder.assert_valid();
2229    }
2230
2231    /// A cube's worth of real geometry goes in and comes back out as the three
2232    /// integers a draw takes.
2233    #[test]
2234    fn the_cube_becomes_three_integers() {
2235        let (recorder, device, queue) = open();
2236        let mut pool = pool(device.as_ref(), 1024, 1024);
2237        let handle = pool
2238            .upload(
2239                device.as_ref(),
2240                queue,
2241                &MeshUpload {
2242                    label: "cube",
2243                    vertices: &mesh::cube_vertex_bytes(),
2244                    indices: &mesh::cube_indices(),
2245                    uv_range: UvRange::default(),
2246                    flags: 0,
2247                },
2248            )
2249            .expect("a cube is small");
2250        pool.flush(device.as_ref()).expect("drains");
2251        let range = pool.mesh(handle).expect("flushed");
2252        assert_eq!(range.base_vertex, 0);
2253        assert_eq!(range.base_index, 0);
2254        assert_eq!(range.index_count as usize, mesh::CUBE_INDEX_COUNT);
2255        pool.destroy(device.as_ref());
2256        recorder.assert_valid();
2257    }
2258
2259    /// The bounds the table carries are the box the uploaded vertices actually
2260    /// fit in, per mesh.
2261    ///
2262    /// Checked against positions decoded out of
2263    /// [`mesh::cube_vertices`](crcbl_shaders::mesh::cube_vertices) — the struct
2264    /// form — where the pool reads the packed bytes, so the two paths agree only
2265    /// if both are right. And checked against the *table*, not against the
2266    /// range, because the range is the pool repeating itself: a
2267    /// [`MeshRange`] and the entry derived from it cannot disagree.
2268    ///
2269    /// The pyramid is here because it is the case a pool that wrote one
2270    /// constant box for every mesh would pass without: it is not the cube's
2271    /// size and it is not centred where the cube is.
2272    #[test]
2273    fn each_mesh_gets_the_bounds_of_its_own_vertices() {
2274        let (recorder, device, queue) = open();
2275        let mut pool = pool(device.as_ref(), 1024, 1024);
2276        let cube = pool
2277            .upload(
2278                device.as_ref(),
2279                queue,
2280                &MeshUpload {
2281                    label: "cube",
2282                    vertices: &mesh::cube_vertex_bytes(),
2283                    indices: &mesh::cube_indices(),
2284                    uv_range: UvRange::default(),
2285                    flags: 0,
2286                },
2287            )
2288            .expect("a cube is small");
2289        let pyramid = pool
2290            .upload(
2291                device.as_ref(),
2292                queue,
2293                &MeshUpload {
2294                    label: "pyramid",
2295                    vertices: &mesh::pyramid_vertex_bytes(),
2296                    indices: &mesh::pyramid_indices(),
2297                    uv_range: UvRange::default(),
2298                    flags: 0,
2299                },
2300            )
2301            .expect("a pyramid is small");
2302        pool.flush(device.as_ref()).expect("drains");
2303
2304        // The oracle: the same positions, through the decoded vertex structs.
2305        let expected = |vertices: &[mesh::MeshVertex]| {
2306            Aabb::from_points(vertices.iter().map(|vertex| {
2307                Vec3::new(vertex.position[0], vertex.position[1], vertex.position[2])
2308            }))
2309            .expect("both meshes have vertices")
2310        };
2311        let cube_bounds = expected(&mesh::cube_vertices());
2312        let pyramid_bounds = expected(&mesh::pyramid_vertices());
2313        assert_ne!(
2314            cube_bounds, pyramid_bounds,
2315            "the two meshes must have different boxes, or this test cannot tell \
2316             per-mesh bounds from one constant"
2317        );
2318
2319        let entries = table(&recorder, &pool);
2320        for (handle, bounds) in [(cube, cube_bounds), (pyramid, pyramid_bounds)] {
2321            let entry = entries[pool.table_index(handle).expect("resident") as usize];
2322            assert_eq!(entry.bounds_min, bounds.min.to_array());
2323            assert_eq!(entry.bounds_max, bounds.max.to_array());
2324            assert_eq!(
2325                pool.mesh(handle).expect("resident").bounds,
2326                bounds,
2327                "and the range agrees with the table"
2328            );
2329        }
2330
2331        // A freed mesh's entry goes back to all zeroes, bounds included —
2332        // otherwise the cull pass would keep testing a box for geometry that is
2333        // no longer there.
2334        pool.free(device.as_ref(), cube).expect("the entry clears");
2335        let after_free = table(&recorder, &pool);
2336        let cleared = after_free[pool.mesh_capacity() as usize - 1];
2337        assert_eq!(cleared, GpuMesh::default(), "an unused slot is still empty");
2338        let freed = after_free[0];
2339        assert_eq!(freed, GpuMesh::default(), "and so is the freed one");
2340
2341        pool.destroy(device.as_ref());
2342        recorder.assert_valid();
2343    }
2344
2345    /// Vertex data that is not a whole number of vertices is refused before
2346    /// anything is allocated: the pool holds one vertex format, and bytes that
2347    /// are not it would silently shift every following mesh.
2348    #[test]
2349    fn vertex_data_of_the_wrong_stride_is_refused() {
2350        let (recorder, device, queue) = open();
2351        let mut pool = pool(device.as_ref(), 64, 64);
2352        let error = pool
2353            .upload(
2354                device.as_ref(),
2355                queue,
2356                &MeshUpload {
2357                    label: "ragged",
2358                    vertices: &[0u8; VERTEX_STRIDE + 1],
2359                    indices: &[0, 1, 2],
2360                    uv_range: UvRange::default(),
2361                    flags: 0,
2362                },
2363            )
2364            .expect_err("49 bytes is not a whole number of vertices");
2365        assert!(
2366            matches!(error, MeshPoolError::VertexStrideMismatch { .. }),
2367            "got: {error:?}"
2368        );
2369        assert_eq!(pool.vertex_space(), (64, 64), "and nothing was reserved");
2370
2371        let error = pool
2372            .upload(
2373                device.as_ref(),
2374                queue,
2375                &MeshUpload {
2376                    label: "empty",
2377                    vertices: &[],
2378                    indices: &[],
2379                    uv_range: UvRange::default(),
2380                    flags: 0,
2381                },
2382            )
2383            .expect_err("a mesh needs both halves");
2384        assert!(
2385            matches!(error, MeshPoolError::EmptyMesh { .. }),
2386            "got: {error:?}"
2387        );
2388
2389        pool.destroy(device.as_ref());
2390        recorder.assert_valid();
2391    }
2392
2393    /// Everything created is destroyed, staging buffers included — and a pool
2394    /// destroyed with an upload still in flight releases that too.
2395    #[test]
2396    fn a_pool_leaks_nothing() {
2397        let (recorder, device, queue) = open();
2398        let before = recorder.total_live_objects();
2399        let mut pool = pool(device.as_ref(), 64, 64);
2400        pool.upload(
2401            device.as_ref(),
2402            queue,
2403            &MeshUpload {
2404                label: "flushed",
2405                vertices: &vertex_bytes(4),
2406                indices: &[0, 1, 2],
2407                uv_range: UvRange::default(),
2408                flags: 0,
2409            },
2410        )
2411        .expect("fits");
2412        pool.flush(device.as_ref()).expect("drains");
2413        pool.upload(
2414            device.as_ref(),
2415            queue,
2416            &MeshUpload {
2417                label: "still staged",
2418                vertices: &vertex_bytes(4),
2419                indices: &[0, 1, 2],
2420                uv_range: UvRange::default(),
2421                flags: 0,
2422            },
2423        )
2424        .expect("fits");
2425        assert!(recorder.total_live_objects() > before);
2426
2427        pool.destroy(device.as_ref());
2428        assert_eq!(
2429            recorder.total_live_objects(),
2430            before,
2431            "every object created must be destroyed, staged or not"
2432        );
2433        recorder.assert_valid();
2434    }
2435
2436    /// A pool error that has to travel as a [`HalError`] keeps its message
2437    /// rather than becoming a generic failure — which is the whole reason the
2438    /// exhaustion error names its numbers.
2439    #[test]
2440    fn a_pool_error_flattens_into_the_seams_without_losing_its_message() {
2441        let exhausted = MeshPoolError::PoolExhausted {
2442            pool: "vertex",
2443            requested: 5,
2444            largest_free: 4,
2445            total_free: 8,
2446            capacity: 10,
2447        };
2448        let message = exhausted.to_string();
2449        let flattened = HalError::from(exhausted);
2450        assert_eq!(flattened.to_string(), message);
2451
2452        // And a seam error stays itself rather than being wrapped in a string.
2453        let hal = MeshPoolError::Hal(HalError::OutOfDeviceMemory);
2454        assert!(
2455            matches!(HalError::from(hal), HalError::OutOfDeviceMemory),
2456            "a HalError must not be stringified on the way through"
2457        );
2458    }
2459}