use core::ops::Range;
use core::time::Duration;
use crcbl_core::{Handle, Pool};
use crcbl_hal::{
Barriers, BufferBarrier, BufferCopy, BufferDesc, BufferHandle, BufferUsage,
CommandBufferHandle, CommandEncoderDesc, Device, Features, HalError, MemoryLocation,
QueueHandle, ResourceState, SemaphoreDesc, SemaphoreHandle, SemaphoreKind, SemaphoreSignal,
SemaphoreWait, SubmitInfo,
};
use crcbl_shaders::mesh::{
ATTRIBUTE_STRIDE, GpuMesh, MESH_ENTRY_STRIDE, POSITION_STRIDE, VERTEX_STRIDE,
};
use crcbl_shaders::vertex::UvRange;
use glam::Vec3;
use crate::cull::Aabb;
const INDEX_STRIDE: u64 = 4;
pub const UPLOAD_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Debug)]
pub enum Mesh {}
pub type MeshHandle = Handle<Mesh>;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct MeshRange {
pub base_vertex: u32,
pub base_index: u32,
pub index_count: u32,
pub bounds: Aabb,
pub uv_range: UvRange,
pub flags: u32,
}
#[derive(Clone, Copy, Debug)]
pub struct MeshUpload<'a> {
pub label: &'a str,
pub vertices: &'a [u8],
pub indices: &'a [u32],
pub uv_range: UvRange,
pub flags: u32,
}
#[derive(Debug, thiserror::Error)]
pub enum MeshPoolError {
#[error(
"the {pool} pool cannot fit {requested} more: the largest free block holds \
{largest_free} and {total_free} are free in total, out of a capacity of {capacity}"
)]
PoolExhausted {
pool: &'static str,
requested: u32,
largest_free: u32,
total_free: u32,
capacity: u32,
},
#[error("a vertex capacity of {capacity} is past what a draw's signed base vertex can address")]
VertexCapacityTooLarge {
capacity: u32,
},
#[error("the mesh table holds {capacity} meshes and {in_use} of them are in use")]
MeshTableFull {
capacity: u32,
in_use: u32,
},
#[error("a reserved vertex run needs at least one vertex")]
EmptyReservation,
#[error("a mesh needs both vertices and indices; got {vertices} and {indices}")]
EmptyMesh {
vertices: u32,
indices: u32,
},
#[error(
"{bytes} bytes of vertex data is not a whole number of {VERTEX_STRIDE}-byte vertices; \
the pool holds one vertex format and this is not it"
)]
VertexStrideMismatch {
bytes: usize,
},
#[error(
"mesh {handle:?} is not resident: it was never uploaded to this pool, it has been freed, \
or its upload has not been flushed"
)]
NotResident {
handle: MeshHandle,
},
#[error("the mesh pool's uploads did not complete within {}s", timeout.as_secs())]
UploadTimedOut {
timeout: Duration,
},
#[error(transparent)]
Hal(#[from] HalError),
}
impl From<MeshPoolError> for HalError {
fn from(error: MeshPoolError) -> Self {
match error {
MeshPoolError::Hal(hal) => hal,
other => Self::Backend(other.to_string()),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MeshPoolDesc<'a> {
pub label: Option<&'a str>,
pub vertex_capacity: u32,
pub index_capacity: u32,
pub mesh_capacity: u32,
}
#[derive(Clone, Copy, Debug)]
struct Resident {
range: MeshRange,
vertex_count: u32,
ready_at: u64,
}
#[derive(Clone, Copy, Debug)]
struct InFlight {
staging: BufferHandle,
commands: CommandBufferHandle,
}
#[derive(Debug)]
pub struct MeshPool {
vertices: BufferHandle,
indices: BufferHandle,
vertex_capacity: u32,
vertex_alloc: FreeList,
index_alloc: FreeList,
table: BufferHandle,
table_capacity: u32,
meshes: Pool<Resident>,
timeline: Option<SemaphoreHandle>,
submitted: u64,
completed: u64,
in_flight: Vec<InFlight>,
}
impl MeshPool {
pub fn new(device: &dyn Device, desc: &MeshPoolDesc<'_>) -> Result<Self, MeshPoolError> {
if i32::try_from(desc.vertex_capacity).is_err() {
return Err(MeshPoolError::VertexCapacityTooLarge {
capacity: desc.vertex_capacity,
});
}
let stem = desc.label.unwrap_or("mesh pool");
let vertices = device.create_buffer(&BufferDesc {
label: Some(&format!("{stem} vertices")),
size: u64::from(desc.vertex_capacity) * VERTEX_STRIDE as u64,
usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_DST,
memory: MemoryLocation::DeviceLocal,
})?;
let indices = match device.create_buffer(&BufferDesc {
label: Some(&format!("{stem} indices")),
size: u64::from(desc.index_capacity) * INDEX_STRIDE,
usage: BufferUsage::INDEX | BufferUsage::TRANSFER_DST,
memory: MemoryLocation::DeviceLocal,
}) {
Ok(indices) => indices,
Err(error) => {
device.destroy_buffer(vertices);
return Err(error.into());
}
};
let table = match Self::create_table(device, stem, desc.mesh_capacity) {
Ok(table) => table,
Err(error) => {
device.destroy_buffer(indices);
device.destroy_buffer(vertices);
return Err(error);
}
};
let timeline = if device
.caps()
.features
.contains(Features::TIMELINE_SEMAPHORE)
{
match device.create_semaphore(&SemaphoreDesc {
label: Some(&format!("{stem} uploads")),
kind: SemaphoreKind::Timeline { initial_value: 0 },
}) {
Ok(semaphore) => Some(semaphore),
Err(error) => {
device.destroy_buffer(table);
device.destroy_buffer(indices);
device.destroy_buffer(vertices);
return Err(error.into());
}
}
} else {
crcbl_core::log::debug!(
"mesh pool: no timeline semaphores; draining uploads with wait_idle"
);
None
};
Ok(Self {
vertices,
indices,
vertex_capacity: desc.vertex_capacity,
vertex_alloc: FreeList::new(desc.vertex_capacity),
index_alloc: FreeList::new(desc.index_capacity),
table,
table_capacity: desc.mesh_capacity,
meshes: Pool::new(),
timeline,
submitted: 0,
completed: 0,
in_flight: Vec::new(),
})
}
const fn attribute_region(&self) -> u64 {
self.vertex_capacity as u64 * POSITION_STRIDE as u64
}
#[must_use]
pub const fn attribute_base(&self) -> u32 {
self.vertex_capacity * (POSITION_STRIDE / size_of::<u32>()) as u32
}
#[must_use]
pub const fn vertex_buffer(&self) -> BufferHandle {
self.vertices
}
#[must_use]
pub const fn index_buffer(&self) -> BufferHandle {
self.indices
}
#[must_use]
pub const fn table_buffer(&self) -> BufferHandle {
self.table
}
#[must_use]
pub fn table_entries(&self) -> Vec<GpuMesh> {
let mut entries = vec![GpuMesh::default(); self.table_capacity as usize];
for (handle, resident) in self.meshes.iter() {
let range = resident.range;
entries[handle.index() as usize] = GpuMesh {
base_vertex: range.base_vertex,
base_index: range.base_index,
index_count: range.index_count,
bounds_min: range.bounds.min.to_array(),
bounds_max: range.bounds.max.to_array(),
uv_range: range.uv_range,
flags: range.flags,
};
}
entries
}
#[must_use]
pub const fn mesh_capacity(&self) -> u32 {
self.table_capacity
}
fn create_table(
device: &dyn Device,
stem: &str,
capacity: u32,
) -> Result<BufferHandle, MeshPoolError> {
let size = u64::from(capacity) * MESH_ENTRY_STRIDE as u64;
let table = device.create_buffer(&BufferDesc {
label: Some(&format!("{stem} mesh table")),
size,
usage: BufferUsage::STORAGE,
memory: MemoryLocation::HostUpload,
})?;
let cleared = vec![0u8; usize::try_from(size).unwrap_or(usize::MAX)];
if let Err(error) = device.write_buffer(table, 0, &cleared) {
device.destroy_buffer(table);
return Err(error.into());
}
Ok(table)
}
fn write_entry(
&self,
device: &dyn Device,
index: u32,
range: &MeshRange,
) -> Result<(), MeshPoolError> {
let entry = GpuMesh {
base_vertex: range.base_vertex,
base_index: range.base_index,
index_count: range.index_count,
bounds_min: range.bounds.min.to_array(),
bounds_max: range.bounds.max.to_array(),
uv_range: range.uv_range,
flags: range.flags,
};
let at = u64::from(index) * MESH_ENTRY_STRIDE as u64;
device.write_buffer(self.table, at, &entry.to_bytes())?;
Ok(())
}
fn table_slots_in_use(&self) -> u32 {
let used = self.meshes.len() + self.meshes.retired_slots();
u32::try_from(used).unwrap_or(u32::MAX)
}
pub fn upload(
&mut self,
device: &dyn Device,
queue: QueueHandle,
mesh: &MeshUpload<'_>,
) -> Result<MeshHandle, MeshPoolError> {
let MeshUpload {
label,
vertices,
indices,
uv_range,
flags,
} = *mesh;
if !vertices.len().is_multiple_of(VERTEX_STRIDE) {
return Err(MeshPoolError::VertexStrideMismatch {
bytes: vertices.len(),
});
}
let vertex_count = u32::try_from(vertices.len() / VERTEX_STRIDE).unwrap_or(u32::MAX);
let index_count = u32::try_from(indices.len()).unwrap_or(u32::MAX);
if vertex_count == 0 || index_count == 0 {
return Err(MeshPoolError::EmptyMesh {
vertices: vertex_count,
indices: index_count,
});
}
let in_use = self.table_slots_in_use();
if in_use >= self.table_capacity {
return Err(MeshPoolError::MeshTableFull {
capacity: self.table_capacity,
in_use,
});
}
let base_vertex = self
.vertex_alloc
.alloc(vertex_count)
.ok_or_else(|| self.vertex_alloc.exhausted("vertex", vertex_count))?;
let base_index = match self.index_alloc.alloc(index_count) {
Some(base) => base,
None => {
self.vertex_alloc.free(base_vertex, vertex_count);
return Err(self.index_alloc.exhausted("index", index_count));
}
};
let range = MeshRange {
base_vertex,
base_index,
index_count,
bounds: local_bounds(vertices),
uv_range,
flags,
};
let ready_at = match self.record_upload(device, queue, label, vertices, indices, range) {
Ok(ready_at) => ready_at,
Err(error) => {
self.vertex_alloc.free(base_vertex, vertex_count);
self.index_alloc.free(base_index, index_count);
return Err(error);
}
};
let handle: MeshHandle = self
.meshes
.insert(Resident {
range,
vertex_count,
ready_at,
})
.cast();
match self.write_entry(device, handle.index(), &range) {
Ok(()) => Ok(handle),
Err(error) => {
self.meshes.remove(handle.cast());
self.vertex_alloc.free(base_vertex, vertex_count);
self.index_alloc.free(base_index, index_count);
Err(error)
}
}
}
fn record_upload(
&mut self,
device: &dyn Device,
queue: QueueHandle,
label: &str,
vertices: &[u8],
indices: &[u32],
range: MeshRange,
) -> Result<u64, MeshPoolError> {
let index_bytes: &[u8] = bytemuck::cast_slice(indices);
let mut positions = Vec::with_capacity(vertices.len() / VERTEX_STRIDE * POSITION_STRIDE);
let mut attributes = Vec::with_capacity(vertices.len() / VERTEX_STRIDE * ATTRIBUTE_STRIDE);
for vertex in vertices.as_chunks::<VERTEX_STRIDE>().0 {
positions.extend_from_slice(&vertex[..POSITION_STRIDE]);
attributes.extend_from_slice(&vertex[POSITION_STRIDE..]);
}
let staging = device.create_buffer(&BufferDesc {
label: Some(&format!("{label} staging")),
size: (vertices.len() + index_bytes.len()) as u64,
usage: BufferUsage::TRANSFER_SRC,
memory: MemoryLocation::HostUpload,
})?;
let submitted = match self.write_and_submit(
device,
queue,
label,
Staged {
staging,
position_bytes: &positions,
attribute_bytes: &attributes,
index_bytes,
range,
},
) {
Ok(submitted) => submitted,
Err(error) => {
device.destroy_buffer(staging);
return Err(error);
}
};
Ok(submitted)
}
fn write_and_submit(
&mut self,
device: &dyn Device,
queue: QueueHandle,
label: &str,
staged: Staged<'_>,
) -> Result<u64, MeshPoolError> {
let position_bytes = staged.position_bytes.len() as u64;
let attribute_bytes = staged.attribute_bytes.len() as u64;
device.write_buffer(staged.staging, 0, staged.position_bytes)?;
device.write_buffer(staged.staging, position_bytes, staged.attribute_bytes)?;
device.write_buffer(
staged.staging,
position_bytes + attribute_bytes,
staged.index_bytes,
)?;
let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
label: Some(&format!("{label} upload")),
queue,
});
encoder.pipeline_barrier(&Barriers {
buffers: &[
BufferBarrier::new(
self.vertices,
ResourceState::ShaderRead,
ResourceState::TransferDst,
),
BufferBarrier::new(
self.indices,
ResourceState::IndexBuffer,
ResourceState::TransferDst,
),
],
..Barriers::default()
});
encoder.copy_buffer_to_buffer(&BufferCopy {
src: staged.staging,
src_offset: 0,
dst: self.vertices,
dst_offset: u64::from(staged.range.base_vertex) * POSITION_STRIDE as u64,
size: position_bytes,
});
encoder.copy_buffer_to_buffer(&BufferCopy {
src: staged.staging,
src_offset: position_bytes,
dst: self.vertices,
dst_offset: self.attribute_region()
+ u64::from(staged.range.base_vertex) * ATTRIBUTE_STRIDE as u64,
size: attribute_bytes,
});
encoder.copy_buffer_to_buffer(&BufferCopy {
src: staged.staging,
src_offset: position_bytes + attribute_bytes,
dst: self.indices,
dst_offset: u64::from(staged.range.base_index) * INDEX_STRIDE,
size: staged.index_bytes.len() as u64,
});
encoder.pipeline_barrier(&Barriers {
buffers: &[
BufferBarrier::new(
self.vertices,
ResourceState::TransferDst,
ResourceState::ShaderRead,
),
BufferBarrier::new(
self.indices,
ResourceState::TransferDst,
ResourceState::IndexBuffer,
),
],
..Barriers::default()
});
let commands = encoder.finish()?;
let value = self.submitted + 1;
let signals = self
.timeline
.map(|semaphore| SemaphoreSignal { semaphore, value });
let submit = SubmitInfo {
command_buffers: &[commands],
waits: &[],
signals: signals.as_slice(),
};
if let Err(error) = device.submit(queue, &submit) {
device.destroy_command_buffer(commands);
return Err(error.into());
}
self.submitted = value;
self.in_flight.push(InFlight {
staging: staged.staging,
commands,
});
Ok(value)
}
pub fn flush(&mut self, device: &dyn Device) -> Result<(), MeshPoolError> {
if self.completed >= self.submitted {
return Ok(());
}
match self.timeline {
Some(semaphore) => {
let wait = SemaphoreWait {
semaphore,
value: self.submitted,
};
let timeout = u64::try_from(UPLOAD_TIMEOUT.as_nanos()).unwrap_or(u64::MAX);
if !device.wait_semaphores(&[wait], timeout)? {
return Err(MeshPoolError::UploadTimedOut {
timeout: UPLOAD_TIMEOUT,
});
}
}
None => device.wait_idle()?,
}
self.completed = self.submitted;
for entry in self.in_flight.drain(..) {
device.destroy_command_buffer(entry.commands);
device.destroy_buffer(entry.staging);
}
Ok(())
}
#[must_use]
pub fn mesh(&self, handle: MeshHandle) -> Option<MeshRange> {
self.resident(handle).map(|resident| resident.range)
}
#[must_use]
pub fn table_index(&self, handle: MeshHandle) -> Option<u32> {
self.resident(handle).map(|_| handle.index())
}
fn resident(&self, handle: MeshHandle) -> Option<&Resident> {
self.meshes
.get(handle.cast())
.filter(|resident| resident.ready_at <= self.completed)
}
pub fn free(&mut self, device: &dyn Device, handle: MeshHandle) -> Result<bool, MeshPoolError> {
let Some(resident) = self.meshes.get(handle.cast()).copied() else {
return Ok(false);
};
self.write_entry(device, handle.index(), &MeshRange::default())?;
self.meshes.remove(handle.cast());
self.vertex_alloc
.free(resident.range.base_vertex, resident.vertex_count);
self.index_alloc
.free(resident.range.base_index, resident.range.index_count);
Ok(true)
}
#[must_use]
pub fn vertex_count(&self, handle: MeshHandle) -> Option<u32> {
self.resident(handle).map(|resident| resident.vertex_count)
}
pub fn reserve_vertices(&mut self, count: u32) -> Result<u32, MeshPoolError> {
if count == 0 {
return Err(MeshPoolError::EmptyReservation);
}
self.vertex_alloc
.alloc(count)
.ok_or_else(|| self.vertex_alloc.exhausted("vertex", count))
}
pub fn release_vertices(&mut self, base: u32, count: u32) {
self.vertex_alloc.free(base, count);
}
#[must_use]
pub fn vertex_space(&self) -> (u32, u32) {
(
self.vertex_alloc.total_free(),
self.vertex_alloc.largest_free(),
)
}
#[must_use]
pub fn index_space(&self) -> (u32, u32) {
(
self.index_alloc.total_free(),
self.index_alloc.largest_free(),
)
}
pub fn destroy(self, device: &dyn Device) {
for entry in self.in_flight {
device.destroy_command_buffer(entry.commands);
device.destroy_buffer(entry.staging);
}
if let Some(semaphore) = self.timeline {
device.destroy_semaphore(semaphore);
}
device.destroy_buffer(self.table);
device.destroy_buffer(self.indices);
device.destroy_buffer(self.vertices);
}
}
fn local_bounds(vertices: &[u8]) -> Aabb {
Aabb::from_points(vertex_positions(vertices)).unwrap_or_default()
}
pub(crate) fn vertex_positions(vertices: &[u8]) -> impl Iterator<Item = Vec3> + '_ {
vertices
.as_chunks::<VERTEX_STRIDE>()
.0
.iter()
.map(|vertex| {
let float_at = |offset: usize| {
f32::from_le_bytes(
vertex[offset..offset + 4]
.try_into()
.unwrap_or_else(|_| unreachable!("four bytes inside one vertex")),
)
};
Vec3::new(float_at(0), float_at(4), float_at(8))
})
}
struct Staged<'a> {
staging: BufferHandle,
position_bytes: &'a [u8],
attribute_bytes: &'a [u8],
index_bytes: &'a [u8],
range: MeshRange,
}
#[derive(Clone, Debug)]
struct FreeList {
capacity: u32,
free: Vec<Range<u32>>,
}
impl FreeList {
fn new(capacity: u32) -> Self {
let mut free = Vec::new();
if capacity > 0 {
free.push(0..capacity);
}
Self { capacity, free }
}
fn alloc(&mut self, len: u32) -> Option<u32> {
if len == 0 {
return None;
}
let index = self
.free
.iter()
.position(|block| block.end - block.start >= len)?;
let start = self.free[index].start;
self.free[index].start += len;
if self.free[index].is_empty() {
self.free.remove(index);
}
Some(start)
}
fn free(&mut self, start: u32, len: u32) {
if len == 0 {
return;
}
let mut block = start..start + len;
let at = self.free.partition_point(|other| other.start < start);
debug_assert!(
at == 0 || self.free[at - 1].end <= block.start,
"freeing {block:?} overlaps the free block before it"
);
debug_assert!(
self.free.get(at).is_none_or(|next| block.end <= next.start),
"freeing {block:?} overlaps the free block after it"
);
if self
.free
.get(at)
.is_some_and(|next| next.start == block.end)
{
block.end = self.free.remove(at).end;
}
if at > 0 && self.free[at - 1].end == block.start {
self.free[at - 1].end = block.end;
} else {
self.free.insert(at, block);
}
}
fn total_free(&self) -> u32 {
self.free.iter().map(|block| block.end - block.start).sum()
}
fn largest_free(&self) -> u32 {
self.free
.iter()
.map(|block| block.end - block.start)
.max()
.unwrap_or(0)
}
fn exhausted(&self, pool: &'static str, requested: u32) -> MeshPoolError {
MeshPoolError::PoolExhausted {
pool,
requested,
largest_free: self.largest_free(),
total_free: self.total_free(),
capacity: self.capacity,
}
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use crcbl_hal::null::{Command, Event, NullInstance, Recorder};
use crcbl_hal::{DeviceDesc, Instance, QueueKind};
use crcbl_shaders::mesh;
fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
let recorder = Recorder::new();
let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
let adapter = instance.adapters().remove(0);
let device = instance
.create_device(&DeviceDesc::for_adapter(adapter.id))
.expect("the null backend always opens");
let queue = device.queue(QueueKind::Graphics).expect("always present");
(recorder, device, queue)
}
const TEST_MESHES: u32 = 8;
fn pool(device: &dyn Device, vertices: u32, indices: u32) -> MeshPool {
MeshPool::new(
device,
&MeshPoolDesc {
label: Some("test"),
vertex_capacity: vertices,
index_capacity: indices,
mesh_capacity: TEST_MESHES,
},
)
.expect("the null backend accepts every descriptor")
}
fn vertex_bytes(n: u32) -> Vec<u8> {
(0..n as usize * VERTEX_STRIDE)
.map(|byte| (byte % 251) as u8)
.collect()
}
fn table(recorder: &Recorder, pool: &MeshPool) -> Vec<GpuMesh> {
let bytes = recorder
.buffer_bytes(pool.table_buffer())
.expect("the table is live");
assert_eq!(
bytes.len(),
pool.mesh_capacity() as usize * MESH_ENTRY_STRIDE,
"the table must be one entry per mesh the pool can hold"
);
bytes
.as_chunks::<MESH_ENTRY_STRIDE>()
.0
.iter()
.map(GpuMesh::from_bytes)
.collect()
}
fn entry(range: MeshRange) -> GpuMesh {
GpuMesh {
base_vertex: range.base_vertex,
base_index: range.base_index,
index_count: range.index_count,
bounds_min: range.bounds.min.to_array(),
bounds_max: range.bounds.max.to_array(),
uv_range: range.uv_range,
flags: range.flags,
}
}
#[test]
fn every_allocation_is_inside_the_pool_and_disjoint_from_the_others() {
let mut list = FreeList::new(64);
let mut taken: Vec<Range<u32>> = Vec::new();
for len in [8u32, 1, 16, 3, 8, 20] {
let start = list.alloc(len).expect("64 elements is enough for these");
let block = start..start + len;
assert!(block.end <= 64, "{block:?} runs past the pool");
for other in &taken {
assert!(
block.end <= other.start || other.end <= block.start,
"{block:?} overlaps {other:?}"
);
}
taken.push(block);
}
let handed_out: u32 = taken.iter().map(|block| block.end - block.start).sum();
assert_eq!(
list.total_free(),
64 - handed_out,
"what is free and what is handed out must add up to the capacity"
);
}
#[test]
fn a_freed_block_is_reused() {
let mut list = FreeList::new(32);
let first = list.alloc(8).expect("empty pool");
let middle = list.alloc(8).expect("still room");
let last = list.alloc(8).expect("still room");
assert_eq!((first, middle, last), (0, 8, 16));
list.free(middle, 8);
assert_eq!(list.total_free(), 16, "the hole plus the tail");
assert_eq!(
list.alloc(8),
Some(middle),
"the hole is reused, not the tail"
);
assert_eq!(list.total_free(), 8);
}
#[test]
fn a_request_larger_than_every_block_fails_even_with_the_space_free() {
let mut list = FreeList::new(10);
let first = list.alloc(4).expect("empty");
let fence = list.alloc(2).expect("room");
let third = list.alloc(4).expect("room");
assert_eq!((first, fence, third), (0, 4, 6));
list.free(first, 4);
list.free(third, 4);
assert_eq!(list.total_free(), 8);
assert_eq!(list.largest_free(), 4);
assert_eq!(list.alloc(5), None, "8 free, and not 5 of them in a row");
let error = list.exhausted("vertex", 5);
let message = error.to_string();
assert!(
message.contains("largest free block holds 4") && message.contains("8 are free"),
"the error must name both numbers, got: {message}"
);
assert_eq!(list.alloc(4), Some(0));
}
#[test]
fn freeing_between_two_holes_coalesces_all_three() {
let mut list = FreeList::new(10);
let first = list.alloc(4).expect("empty");
let fence = list.alloc(2).expect("room");
let third = list.alloc(4).expect("room");
list.free(first, 4);
list.free(third, 4);
assert_eq!(list.largest_free(), 4);
list.free(fence, 2);
assert_eq!(list.total_free(), 10);
assert_eq!(
list.largest_free(),
10,
"three touching holes are one block, not three"
);
assert_eq!(list.alloc(10), Some(0), "and the whole pool is allocatable");
}
#[test]
fn coalescing_merges_the_neighbour_on_either_side() {
for order in [[0u32, 4], [4, 0]] {
let mut list = FreeList::new(8);
assert_eq!(list.alloc(4), Some(0));
assert_eq!(list.alloc(4), Some(4));
for start in order {
list.free(start, 4);
}
assert_eq!(
list.largest_free(),
8,
"freeing in the order {order:?} left the list fragmented"
);
}
}
#[test]
fn a_vertex_capacity_a_draw_could_not_address_is_refused() {
let (recorder, device, _) = open();
let error = MeshPool::new(
device.as_ref(),
&MeshPoolDesc {
label: Some("far too large"),
vertex_capacity: u32::MAX,
index_capacity: 8,
mesh_capacity: TEST_MESHES,
},
)
.expect_err("a draw cannot address that many vertices");
assert!(
matches!(error, MeshPoolError::VertexCapacityTooLarge { .. }),
"got: {error:?}"
);
assert_eq!(
recorder.total_live_objects(),
0,
"a refused pool creates nothing"
);
let pool = MeshPool::new(
device.as_ref(),
&MeshPoolDesc {
label: Some("at the boundary"),
vertex_capacity: i32::MAX as u32,
index_capacity: 8,
mesh_capacity: TEST_MESHES,
},
)
.expect("the largest addressable capacity is not too large");
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_device_without_timeline_semaphores_drains_with_wait_idle() {
let recorder = Recorder::new();
let instance = NullInstance::portable().with_recorder(recorder.clone());
let adapter = instance.adapters().remove(0);
let device = instance
.create_device(&DeviceDesc {
label: None,
adapter: adapter.id,
required_features: Features::COMPUTE,
optional_features: Features::empty(),
compatible_surface: None,
})
.expect("the portable null adapter opens");
assert!(
!device
.caps()
.features
.contains(Features::TIMELINE_SEMAPHORE),
"this test is only meaningful on a device that has none"
);
let queue = device.queue(QueueKind::Graphics).expect("always present");
let mut pool = pool(device.as_ref(), 64, 64);
let handle = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "cube",
vertices: &vertex_bytes(4),
indices: &[0, 1, 2],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("it fits");
let signals: Vec<_> = recorder
.events()
.into_iter()
.filter_map(|event| match event {
Event::Submitted { signals, .. } => Some(signals),
_ => None,
})
.collect();
assert_eq!(
signals,
vec![Vec::new()],
"there is no timeline to signal, so the submit names none"
);
assert_eq!(pool.mesh(handle), None, "and it is still not resident");
pool.flush(device.as_ref()).expect("wait_idle always works");
assert!(
recorder
.events()
.iter()
.any(|event| matches!(event, Event::WaitedIdle)),
"the fallback is `wait_idle`; nothing else can drain this device"
);
assert!(
pool.mesh(handle).is_some(),
"and the mesh is resident afterwards, or this device could never draw"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn an_upload_that_does_not_fit_fails_by_name_and_reserves_nothing() {
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 64, 8);
let before = pool.vertex_space();
let error = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "too many indices",
vertices: &vertex_bytes(4),
indices: &[0; 16],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect_err("16 indices do not fit in 8");
assert!(
matches!(
error,
MeshPoolError::PoolExhausted {
pool: "index",
requested: 16,
capacity: 8,
..
}
),
"got: {error:?}"
);
assert_eq!(
pool.vertex_space(),
before,
"the vertex range reserved before the index pool refused must come back"
);
assert!(
!recorder
.events()
.iter()
.any(|event| matches!(event, Event::Submitted { .. })),
"a refused upload submits nothing"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_mesh_is_not_resident_until_its_upload_is_flushed() {
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 64, 64);
let handle = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "cube",
vertices: &vertex_bytes(4),
indices: &[0, 1, 2, 0, 2, 3],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("it fits");
assert!(
recorder
.events()
.iter()
.any(|event| matches!(event, Event::Submitted { .. })),
"the copy really was submitted; residency is not just 'nothing happened yet'"
);
assert_eq!(
pool.mesh(handle),
None,
"an unflushed mesh must not hand out a range"
);
pool.flush(device.as_ref()).expect("the null device drains");
assert_eq!(
pool.mesh(handle),
Some(MeshRange {
uv_range: UvRange::default(),
base_vertex: 0,
base_index: 0,
index_count: 6,
bounds: local_bounds(&vertex_bytes(4)),
flags: 0,
}),
"and once the timeline has passed, it must"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn an_upload_signals_the_pools_timeline() {
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 64, 64);
pool.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "cube",
vertices: &vertex_bytes(4),
indices: &[0, 1, 2],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("it fits");
let signals: Vec<_> = recorder
.events()
.into_iter()
.filter_map(|event| match event {
Event::Submitted { signals, .. } => Some(signals),
_ => None,
})
.collect();
assert_eq!(signals.len(), 1, "one upload, one submit");
assert_eq!(
signals[0].len(),
1,
"the submit must signal something, or nothing can wait for it"
);
assert_eq!(
signals[0][0].value, 1,
"the first upload is timeline value 1"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_second_mesh_lands_after_the_first_in_both_pools() {
const ATTRIBUTES_AT: u64 = 64 * POSITION_STRIDE as u64;
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 64, 64);
for (label, vertices, indices) in [
("first", 4u32, vec![0u32, 1, 2, 0, 2, 3]),
("second", 3, vec![0u32, 1, 2]),
] {
pool.upload(
device.as_ref(),
queue,
&MeshUpload {
label,
vertices: &vertex_bytes(vertices),
indices: &indices,
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("both fit");
}
pool.flush(device.as_ref()).expect("drains");
let copies: Vec<BufferCopy> = recorder
.commands()
.into_iter()
.filter_map(|command| match command {
Command::CopyBufferToBuffer(copy) => Some(copy),
_ => None,
})
.collect();
assert_eq!(
copies.len(),
6,
"two meshes, and three copies each: the two vertex streams and the indices"
);
assert_eq!(copies[0].dst_offset, 0, "the first mesh's positions");
assert_eq!(
copies[1].dst_offset, ATTRIBUTES_AT,
"and its attributes, past every position the pool can hold"
);
assert_eq!(copies[2].dst_offset, 0, "and its indices");
assert_eq!(
copies[3].dst_offset,
4 * POSITION_STRIDE as u64,
"the second mesh's positions"
);
assert_eq!(
copies[4].dst_offset,
ATTRIBUTES_AT + 4 * ATTRIBUTE_STRIDE as u64,
"and its attributes, at its own base inside the attribute region"
);
assert_eq!(copies[5].dst_offset, 6 * INDEX_STRIDE);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn freeing_a_mesh_returns_its_space_and_retires_its_handle() {
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 64, 64);
let handle = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "cube",
vertices: &vertex_bytes(8),
indices: &[0; 12],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("it fits");
pool.flush(device.as_ref()).expect("drains");
assert_eq!(pool.vertex_space(), (64 - 8, 64 - 8));
assert!(
pool.free(device.as_ref(), handle).expect("the write lands"),
"the handle names a live mesh"
);
assert_eq!(pool.vertex_space(), (64, 64), "and its space comes back");
assert_eq!(pool.index_space(), (64, 64));
assert_eq!(pool.mesh(handle), None, "the handle stops resolving");
assert_eq!(pool.table_index(handle), None, "and names no table entry");
assert!(
!pool
.free(device.as_ref(), handle)
.expect("nothing to write"),
"and a second free is refused"
);
assert_eq!(
pool.vertex_space(),
(64, 64),
"a refused free must not double-count the space"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn the_table_matches_the_pool_through_allocations_and_frees() {
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 64, 64);
let handles: Vec<MeshHandle> = [
(4u32, 6usize, GpuMesh::MESH_AUTHORED_TANGENTS),
(3, 3, 0),
(5, 9, GpuMesh::MESH_AUTHORED_TANGENTS),
]
.into_iter()
.map(|(vertices, indices, flags)| {
pool.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "mesh",
vertices: &vertex_bytes(vertices),
indices: &vec![0u32; indices],
uv_range: UvRange::default(),
flags,
},
)
.expect("they fit")
})
.collect();
pool.flush(device.as_ref()).expect("drains");
let live = |pool: &MeshPool, recorder: &Recorder, handles: &[MeshHandle]| {
let table = table(recorder, pool);
for handle in handles {
let range = pool.mesh(*handle).expect("resident");
let index = pool.table_index(*handle).expect("resident") as usize;
assert_eq!(
table[index],
entry(range),
"entry {index} does not hold {handle:?}'s range"
);
}
};
live(&pool, &recorder, &handles);
let ranges: Vec<MeshRange> = handles
.iter()
.map(|handle| pool.mesh(*handle).expect("resident"))
.collect();
assert_eq!(
ranges[1].base_vertex, 4,
"the second starts after the first"
);
assert_eq!(ranges[2].base_vertex, 7, "and the third after the second");
assert_eq!(
ranges.iter().map(|range| range.flags).collect::<Vec<u32>>(),
[
GpuMesh::MESH_AUTHORED_TANGENTS,
0,
GpuMesh::MESH_AUTHORED_TANGENTS
],
"the pool must keep each mesh's flags, not the first's or none"
);
let freed = pool.table_index(handles[1]).expect("resident");
assert!(
pool.free(device.as_ref(), handles[1])
.expect("the write lands")
);
let after = table(&recorder, &pool);
assert_eq!(
after[freed as usize],
GpuMesh::default(),
"a freed mesh's entry must be cleared"
);
live(&pool, &recorder, &[handles[0], handles[2]]);
let reused = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "fourth",
vertices: &vertex_bytes(2),
indices: &[0; 3],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("the freed space fits it");
pool.flush(device.as_ref()).expect("drains");
assert_eq!(
pool.table_index(reused),
Some(freed),
"the freed table slot is the one handed out again"
);
live(&pool, &recorder, &[handles[0], handles[2], reused]);
assert_ne!(
table(&recorder, &pool)[freed as usize],
GpuMesh::default(),
"and the slot is no longer the empty range"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn an_instance_naming_a_freed_mesh_resolves_to_the_empty_range() {
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 64, 64);
let first = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "first",
vertices: &vertex_bytes(4),
indices: &[0; 6],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("it fits");
pool.flush(device.as_ref()).expect("drains");
let mesh_id = pool.table_index(first).expect("resident");
let freed_range = pool.mesh(first).expect("resident");
assert!(
pool.free(device.as_ref(), first).expect("the write lands"),
"the mesh was live"
);
let second = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "second",
vertices: &vertex_bytes(4),
indices: &[0; 6],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("the freed space fits it");
pool.flush(device.as_ref()).expect("drains");
assert_eq!(
pool.mesh(second).expect("resident"),
freed_range,
"this test is only meaningful while the successor takes the same space"
);
assert_eq!(pool.table_index(second), Some(mesh_id));
assert!(pool.free(device.as_ref(), second).expect("the write lands"));
assert_eq!(
table(&recorder, &pool)[mesh_id as usize],
GpuMesh::default(),
"an id whose mesh was freed must resolve to the empty range"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_fresh_table_is_empty_ranges() {
let (recorder, device, _) = open();
let pool = pool(device.as_ref(), 64, 64);
assert_eq!(pool.mesh_capacity(), TEST_MESHES);
let table_writes: Vec<(u64, usize)> = recorder
.events()
.into_iter()
.filter_map(|event| match event {
Event::BufferWritten {
buffer,
offset,
len,
} if buffer == pool.table_buffer() => Some((offset, len)),
_ => None,
})
.collect();
assert_eq!(
table_writes,
[(0, TEST_MESHES as usize * MESH_ENTRY_STRIDE)],
"creating a pool must clear the whole table, once"
);
assert_eq!(
table(&recorder, &pool),
vec![GpuMesh::default(); TEST_MESHES as usize],
"and what it cleared it to is empty ranges"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_full_mesh_table_fails_by_name_and_reserves_nothing() {
let (recorder, device, queue) = open();
let mut pool = MeshPool::new(
device.as_ref(),
&MeshPoolDesc {
label: Some("two meshes"),
vertex_capacity: 64,
index_capacity: 64,
mesh_capacity: 2,
},
)
.expect("the null backend accepts every descriptor");
let upload = |pool: &mut MeshPool| {
pool.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "mesh",
vertices: &vertex_bytes(2),
indices: &[0; 3],
uv_range: UvRange::default(),
flags: 0,
},
)
};
let first = upload(&mut pool).expect("room");
upload(&mut pool).expect("room");
let before = pool.vertex_space();
let error = upload(&mut pool).expect_err("two meshes fill a table of two");
assert!(
matches!(
error,
MeshPoolError::MeshTableFull {
capacity: 2,
in_use: 2
}
),
"got: {error:?}"
);
assert_eq!(
pool.vertex_space(),
before,
"a refused upload must reserve nothing, however much room the pools have"
);
pool.flush(device.as_ref()).expect("drains");
assert!(pool.free(device.as_ref(), first).expect("the write lands"));
upload(&mut pool).expect("the freed entry");
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn the_cube_becomes_three_integers() {
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 1024, 1024);
let handle = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "cube",
vertices: &mesh::cube_vertex_bytes(),
indices: &mesh::cube_indices(),
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("a cube is small");
pool.flush(device.as_ref()).expect("drains");
let range = pool.mesh(handle).expect("flushed");
assert_eq!(range.base_vertex, 0);
assert_eq!(range.base_index, 0);
assert_eq!(range.index_count as usize, mesh::CUBE_INDEX_COUNT);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn each_mesh_gets_the_bounds_of_its_own_vertices() {
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 1024, 1024);
let cube = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "cube",
vertices: &mesh::cube_vertex_bytes(),
indices: &mesh::cube_indices(),
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("a cube is small");
let pyramid = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "pyramid",
vertices: &mesh::pyramid_vertex_bytes(),
indices: &mesh::pyramid_indices(),
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("a pyramid is small");
pool.flush(device.as_ref()).expect("drains");
let expected = |vertices: &[mesh::MeshVertex]| {
Aabb::from_points(vertices.iter().map(|vertex| {
Vec3::new(vertex.position[0], vertex.position[1], vertex.position[2])
}))
.expect("both meshes have vertices")
};
let cube_bounds = expected(&mesh::cube_vertices());
let pyramid_bounds = expected(&mesh::pyramid_vertices());
assert_ne!(
cube_bounds, pyramid_bounds,
"the two meshes must have different boxes, or this test cannot tell \
per-mesh bounds from one constant"
);
let entries = table(&recorder, &pool);
for (handle, bounds) in [(cube, cube_bounds), (pyramid, pyramid_bounds)] {
let entry = entries[pool.table_index(handle).expect("resident") as usize];
assert_eq!(entry.bounds_min, bounds.min.to_array());
assert_eq!(entry.bounds_max, bounds.max.to_array());
assert_eq!(
pool.mesh(handle).expect("resident").bounds,
bounds,
"and the range agrees with the table"
);
}
pool.free(device.as_ref(), cube).expect("the entry clears");
let after_free = table(&recorder, &pool);
let cleared = after_free[pool.mesh_capacity() as usize - 1];
assert_eq!(cleared, GpuMesh::default(), "an unused slot is still empty");
let freed = after_free[0];
assert_eq!(freed, GpuMesh::default(), "and so is the freed one");
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn vertex_data_of_the_wrong_stride_is_refused() {
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 64, 64);
let error = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "ragged",
vertices: &[0u8; VERTEX_STRIDE + 1],
indices: &[0, 1, 2],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect_err("49 bytes is not a whole number of vertices");
assert!(
matches!(error, MeshPoolError::VertexStrideMismatch { .. }),
"got: {error:?}"
);
assert_eq!(pool.vertex_space(), (64, 64), "and nothing was reserved");
let error = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "empty",
vertices: &[],
indices: &[],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect_err("a mesh needs both halves");
assert!(
matches!(error, MeshPoolError::EmptyMesh { .. }),
"got: {error:?}"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_pool_leaks_nothing() {
let (recorder, device, queue) = open();
let before = recorder.total_live_objects();
let mut pool = pool(device.as_ref(), 64, 64);
pool.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "flushed",
vertices: &vertex_bytes(4),
indices: &[0, 1, 2],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("fits");
pool.flush(device.as_ref()).expect("drains");
pool.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "still staged",
vertices: &vertex_bytes(4),
indices: &[0, 1, 2],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("fits");
assert!(recorder.total_live_objects() > before);
pool.destroy(device.as_ref());
assert_eq!(
recorder.total_live_objects(),
before,
"every object created must be destroyed, staged or not"
);
recorder.assert_valid();
}
#[test]
fn a_pool_error_flattens_into_the_seams_without_losing_its_message() {
let exhausted = MeshPoolError::PoolExhausted {
pool: "vertex",
requested: 5,
largest_free: 4,
total_free: 8,
capacity: 10,
};
let message = exhausted.to_string();
let flattened = HalError::from(exhausted);
assert_eq!(flattened.to_string(), message);
let hal = MeshPoolError::Hal(HalError::OutOfDeviceMemory);
assert!(
matches!(HalError::from(hal), HalError::OutOfDeviceMemory),
"a HalError must not be stringified on the way through"
);
}
}