use crcbl_core::{Handle, Pool};
use crcbl_hal::{BufferDesc, BufferHandle, BufferUsage, Device, HalError, MemoryLocation};
use crcbl_shaders::mesh::{GpuMaterial, MATERIAL_STRIDE};
#[derive(Debug)]
pub enum Material {}
pub type MaterialHandle = Handle<Material>;
#[derive(Debug, thiserror::Error)]
pub enum MaterialTableError {
#[error("the material table holds {capacity} materials and {in_use} of them are in use")]
TableFull {
capacity: u32,
in_use: u32,
},
#[error(transparent)]
Hal(#[from] HalError),
}
impl From<MaterialTableError> for HalError {
fn from(error: MaterialTableError) -> Self {
match error {
MaterialTableError::Hal(hal) => hal,
other => Self::Backend(other.to_string()),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MaterialTableDesc<'a> {
pub label: Option<&'a str>,
pub capacity: u32,
}
#[derive(Debug)]
pub struct MaterialTable {
buffer: BufferHandle,
slots: Pool<()>,
capacity: u32,
modes: Vec<u32>,
}
impl MaterialTable {
pub fn new(
device: &dyn Device,
desc: &MaterialTableDesc<'_>,
) -> Result<Self, MaterialTableError> {
let stem = desc.label.unwrap_or("material table");
let size = u64::from(desc.capacity) * MATERIAL_STRIDE as u64;
let buffer = device.create_buffer(&BufferDesc {
label: Some(&format!("{stem} materials")),
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(buffer, 0, &cleared) {
device.destroy_buffer(buffer);
return Err(error.into());
}
Ok(Self {
buffer,
slots: Pool::new(),
capacity: desc.capacity,
modes: vec![0; usize::try_from(desc.capacity).unwrap_or(usize::MAX)],
})
}
#[must_use]
pub const fn buffer(&self) -> BufferHandle {
self.buffer
}
#[must_use]
pub const fn capacity(&self) -> u32 {
self.capacity
}
#[must_use]
pub const fn len(&self) -> usize {
self.slots.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.slots.is_empty()
}
#[must_use]
pub fn mode(&self, index: u32) -> u32 {
self.modes.get(index as usize).copied().unwrap_or(0)
}
pub fn insert(
&mut self,
device: &dyn Device,
material: &GpuMaterial,
) -> Result<MaterialHandle, MaterialTableError> {
let in_use = self.in_use();
if in_use >= self.capacity {
return Err(MaterialTableError::TableFull {
capacity: self.capacity,
in_use,
});
}
let handle: MaterialHandle = self.slots.insert(()).cast();
match self.write(device, handle.index(), material) {
Ok(()) => Ok(handle),
Err(error) => {
self.slots.remove(handle.cast());
Err(error.into())
}
}
}
pub fn set(
&mut self,
device: &dyn Device,
handle: MaterialHandle,
material: &GpuMaterial,
) -> Result<bool, HalError> {
if !self.slots.contains(handle.cast()) {
return Ok(false);
}
self.write(device, handle.index(), material)?;
Ok(true)
}
#[must_use]
pub fn index(&self, handle: MaterialHandle) -> Option<u32> {
self.slots.contains(handle.cast()).then(|| handle.index())
}
pub fn remove(
&mut self,
device: &dyn Device,
handle: MaterialHandle,
) -> Result<bool, HalError> {
if self.slots.remove(handle.cast()).is_none() {
return Ok(false);
}
self.write(device, handle.index(), &GpuMaterial::default())?;
Ok(true)
}
pub fn destroy(self, device: &dyn Device) {
device.destroy_buffer(self.buffer);
}
fn in_use(&self) -> u32 {
let used = self.slots.len() + self.slots.retired_slots();
u32::try_from(used).unwrap_or(u32::MAX)
}
fn write(
&mut self,
device: &dyn Device,
index: u32,
material: &GpuMaterial,
) -> Result<(), HalError> {
let at = u64::from(index) * MATERIAL_STRIDE as u64;
device.write_buffer(self.buffer, at, &material.to_bytes())?;
if let Some(entry) = self.modes.get_mut(index as usize) {
*entry = material.mode();
}
Ok(())
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use crcbl_hal::null::{Event, NullInstance, Recorder};
use crcbl_hal::{DeviceDesc, Instance};
fn open() -> (Recorder, Box<dyn Device>) {
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");
(recorder, device)
}
fn table(device: &dyn Device, capacity: u32) -> MaterialTable {
MaterialTable::new(
device,
&MaterialTableDesc {
label: Some("test"),
capacity,
},
)
.expect("the null backend accepts every descriptor")
}
fn material(n: u32) -> GpuMaterial {
let base = n as f32;
GpuMaterial {
base_color: [base, base + 0.125, base + 0.25, base + 0.375],
base_color_texture: n + 7,
metallic: base + 0.5,
roughness: base + 0.625,
tiling: n % 2,
tile_metres: base + 0.75,
emissive: [base + 0.8125, base + 0.875, base + 0.9375],
normal_texture: n + 11,
normal_scale: base + 0.9375 + 1.0 / 32.0,
metallic_roughness_occlusion_texture: n + 13,
emissive_texture: n + 17,
alpha_cutoff: base + 0.9375 + 1.0 / 64.0,
flags: n + 19,
specular_f0: [
base + 0.9375 + 3.0 / 128.0,
base + 0.9375 + 5.0 / 128.0,
base + 0.9375 + 7.0 / 128.0,
],
specular_f90: base + 0.9375 + 1.0 / 128.0,
}
}
fn on_device(recorder: &Recorder, table: &MaterialTable, index: u32) -> GpuMaterial {
let bytes = recorder
.buffer_bytes(table.buffer())
.expect("the buffer is live");
let at = index as usize * MATERIAL_STRIDE;
GpuMaterial::from_bytes(bytes[at..at + MATERIAL_STRIDE].try_into().expect("one row"))
}
fn writes(recorder: &Recorder) -> Vec<(u64, usize)> {
recorder
.events()
.into_iter()
.filter_map(|event| match event {
Event::BufferWritten { offset, len, .. } => Some((offset, len)),
_ => None,
})
.collect()
}
#[test]
fn the_table_reports_each_rows_material_mode() {
let (recorder, device) = open();
let device = device.as_ref();
let mut table = table(device, 8);
let masked = |n: u32| GpuMaterial {
flags: GpuMaterial::ALPHA_MODE_MASK,
..material(n)
};
let unmasked = |n: u32| GpuMaterial {
flags: 0,
..material(n)
};
let mode = |table: &MaterialTable, handle: MaterialHandle| table.mode(handle.index());
assert_eq!(
table.mode(0),
0,
"a row nothing has written is cleared, and a cleared row is OPAQUE — or every \
instance placed before a material exists routes to a cutout bucket"
);
let opaque = table
.insert(device, &unmasked(0))
.expect("a table of eight has room");
assert_eq!(
mode(&table, opaque),
0,
"an opaque row's mode is zero, whatever else is in its flags"
);
let first = table.insert(device, &masked(1)).expect("room");
assert_eq!(
mode(&table, first),
GpuMaterial::ALPHA_MODE_MASK,
"a row inserted with the mask bit reports it, or the instances naming it scatter \
into the opaque bucket and the depth passes write their full silhouette"
);
let second = table.insert(device, &masked(2)).expect("room");
table
.set(device, first, &unmasked(3))
.expect("a live handle rewrites its row");
assert_eq!(
mode(&table, first),
0,
"a rewritten row reports its new mode"
);
assert_eq!(
mode(&table, second),
GpuMaterial::ALPHA_MODE_MASK,
"and the other masked row is untouched, which is what a per-row answer buys over \
one about the table"
);
table
.remove(device, second)
.expect("a live handle frees its row");
assert_eq!(
table.mode(second.index()),
0,
"removing a row clears it to black, whose flags are zero"
);
assert_eq!(
table.mode(table.capacity()),
0,
"a row past the table is OPAQUE rather than a panic: an index the caller cannot \
have been given is not a routing decision"
);
table.remove(device, opaque).expect("live");
table.destroy(device);
recorder.assert_valid();
}
#[test]
fn a_materials_row_is_its_index_times_the_stride() {
let (recorder, device) = open();
let mut table = table(device.as_ref(), 8);
let handles: Vec<MaterialHandle> = (0..4)
.map(|n| {
table
.insert(device.as_ref(), &material(n))
.expect("room for four")
})
.collect();
for (n, handle) in handles.iter().enumerate() {
let index = u32::try_from(n).expect("four rows");
assert_eq!(
table.index(*handle),
Some(index),
"the {n}th insert must take the {n}th row"
);
assert_eq!(
on_device(&recorder, &table, index),
material(index),
"row {index} does not hold the material inserted into it"
);
}
let before = writes(&recorder).len();
table
.insert(device.as_ref(), &material(9))
.expect("room for five");
assert_eq!(
writes(&recorder)[before..],
[(4 * MATERIAL_STRIDE as u64, MATERIAL_STRIDE)]
);
table.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_rows_texture_layer_is_written_beside_its_factor() {
let (recorder, device) = open();
let mut table = table(device.as_ref(), 4);
let untextured = GpuMaterial::UNTINTED;
let textured = GpuMaterial {
base_color_texture: 2,
..untextured
};
assert_eq!(
untextured.base_color, textured.base_color,
"the pair must differ in the texture layer and nothing else"
);
let first = table.insert(device.as_ref(), &untextured).expect("room");
let second = table.insert(device.as_ref(), &textured).expect("room");
assert_eq!(on_device(&recorder, &table, 0), untextured);
assert_eq!(on_device(&recorder, &table, 1), textured);
assert_eq!(
on_device(&recorder, &table, 1).base_color_texture,
2,
"the layer a caller asked for must be the layer the buffer holds"
);
assert_ne!(
on_device(&recorder, &table, 0),
on_device(&recorder, &table, 1),
"two rows differing only in their layer must be two different rows"
);
assert_eq!(table.index(first), Some(0));
assert_eq!(table.index(second), Some(1));
table.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn the_table_is_cleared_when_it_is_created() {
let (recorder, device) = open();
let table = table(device.as_ref(), 8);
assert_eq!(
writes(&recorder),
[(0, 8 * MATERIAL_STRIDE)],
"the whole table must be cleared before anything reads it"
);
assert_eq!(table.capacity(), 8);
assert!(table.is_empty());
table.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_material_can_be_rewritten_and_a_stale_handle_cannot() {
let (recorder, device) = open();
let mut table = table(device.as_ref(), 4);
let handle = table.insert(device.as_ref(), &material(1)).expect("room");
assert_eq!(on_device(&recorder, &table, 0), material(1));
assert!(
table
.set(device.as_ref(), handle, &material(2))
.expect("the null device writes")
);
assert_eq!(on_device(&recorder, &table, 0), material(2));
assert!(table.remove(device.as_ref(), handle).expect("writes"));
let before = writes(&recorder).len();
assert!(
!table
.set(device.as_ref(), handle, &material(3))
.expect("a stale handle is not an error"),
"a retired handle must not resolve"
);
assert_eq!(
writes(&recorder).len(),
before,
"and must not reach the device at all"
);
assert_eq!(table.index(handle), None);
table.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn removing_a_material_clears_its_row_and_leaves_its_neighbours() {
let (recorder, device) = open();
let mut table = table(device.as_ref(), 4);
let first = table.insert(device.as_ref(), &material(1)).expect("room");
let second = table.insert(device.as_ref(), &material(2)).expect("room");
assert!(table.remove(device.as_ref(), first).expect("writes"));
assert_eq!(
on_device(&recorder, &table, 0),
GpuMaterial::default(),
"the freed row must read black"
);
assert_ne!(
GpuMaterial::default(),
material(1),
"the material removed was not already black, so the clear is observable"
);
assert_eq!(
on_device(&recorder, &table, 1),
material(2),
"the row beside the removed one was disturbed"
);
assert_eq!(table.index(second), Some(1));
let before = writes(&recorder).len();
assert!(!table.remove(device.as_ref(), first).expect("writes"));
assert_eq!(writes(&recorder).len(), before);
table.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_full_table_fails_by_name_and_takes_nothing() {
let (recorder, device) = open();
let mut table = table(device.as_ref(), 2);
let first = table.insert(device.as_ref(), &material(0)).expect("room");
table.insert(device.as_ref(), &material(1)).expect("room");
let error = table
.insert(device.as_ref(), &material(2))
.expect_err("two materials fill a table of two");
assert!(
matches!(
error,
MaterialTableError::TableFull {
capacity: 2,
in_use: 2
}
),
"got: {error:?}"
);
assert_eq!(table.len(), 2, "a refused insert must not consume a row");
assert!(table.remove(device.as_ref(), first).expect("writes"));
let reused = table
.insert(device.as_ref(), &material(3))
.expect("the freed row");
assert_eq!(table.index(reused), Some(0), "the low row comes back");
assert_eq!(table.index(first), None, "and the old handle is retired");
assert_eq!(on_device(&recorder, &table, 0), material(3));
table.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_table_leaks_nothing() {
let (recorder, device) = open();
let before = recorder.total_live_objects();
let mut table = table(device.as_ref(), 4);
table.insert(device.as_ref(), &material(0)).expect("room");
assert!(recorder.total_live_objects() > before);
table.destroy(device.as_ref());
assert_eq!(
recorder.total_live_objects(),
before,
"every buffer created must be destroyed"
);
recorder.assert_valid();
}
#[test]
fn a_table_error_flattens_into_the_seams_without_losing_its_message() {
let full = MaterialTableError::TableFull {
capacity: 4,
in_use: 4,
};
let message = full.to_string();
assert_eq!(HalError::from(full).to_string(), message);
let hal = MaterialTableError::Hal(HalError::OutOfDeviceMemory);
assert!(
matches!(HalError::from(hal), HalError::OutOfDeviceMemory),
"a HalError must not be stringified on the way through"
);
}
}