use crcbl_hal::{
BindGroupDesc, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutHandle, BufferDesc,
BufferHandle, BufferUsage, ComputePipelineHandle, Device, HalError, MemoryLocation,
PipelineLayoutDesc, PipelineLayoutHandle, ResourceState, check_portable_storage_buffers,
};
use crcbl_shaders::mesh::MeshVertex;
use crcbl_shaders::skinning::{
JOINT_STRIDE, JOINTS_PER_VERTEX, PARAMS_SIZE, Params, SKIN_BINDING_STRIDE, SkinBinding,
WORKGROUP_SIZE,
};
use crcbl_shaders::vertex::{QTangent, TangentFrame};
use glam::{Mat3, Mat4, Vec3, Vec4};
use crate::draw_gen::{UINT_STRIDE, bound, compute_pipeline, storage, uniform};
use crate::graph::{BufferId, ImportedBuffer, RenderGraph};
use crate::mesh_pool::{MeshHandle, MeshPool, MeshPoolError};
#[derive(Debug)]
pub struct SkinnedRegion {
bases: [u32; 2],
vertex_count: u32,
}
impl SkinnedRegion {
pub fn reserve(pool: &mut MeshPool, vertex_count: u32) -> Result<Self, MeshPoolError> {
let first = pool.reserve_vertices(vertex_count)?;
let second = match pool.reserve_vertices(vertex_count) {
Ok(second) => second,
Err(error) => {
pool.release_vertices(first, vertex_count);
return Err(error);
}
};
Ok(Self {
bases: [first, second],
vertex_count,
})
}
pub fn release(self, pool: &mut MeshPool) {
for base in self.bases {
pool.release_vertices(base, self.vertex_count);
}
}
#[must_use]
pub const fn vertex_count(&self) -> u32 {
self.vertex_count
}
#[must_use]
pub const fn base(&self, parity: u32) -> u32 {
self.bases[(parity & 1) as usize]
}
#[must_use]
pub const fn previous_base(&self, parity: u32) -> u32 {
self.bases[((parity ^ 1) & 1) as usize]
}
}
#[derive(Debug)]
pub struct SkinnedMesh {
region: SkinnedRegion,
mesh: u32,
input_base: u32,
}
impl SkinnedMesh {
pub fn reserve(pool: &mut MeshPool, source: MeshHandle) -> Result<Self, MeshPoolError> {
let range = pool
.mesh(source)
.ok_or(MeshPoolError::NotResident { handle: source })?;
let vertex_count = pool
.vertex_count(source)
.ok_or(MeshPoolError::NotResident { handle: source })?;
let region = SkinnedRegion::reserve(pool, vertex_count)?;
Ok(Self {
region,
mesh: source.index(),
input_base: range.base_vertex,
})
}
pub fn release(self, pool: &mut MeshPool) {
self.region.release(pool);
}
#[must_use]
pub const fn region(&self) -> &SkinnedRegion {
&self.region
}
#[must_use]
pub const fn vertex_count(&self) -> u32 {
self.region.vertex_count()
}
#[must_use]
pub const fn input_base(&self) -> u32 {
self.input_base
}
#[must_use]
pub const fn mesh_id(&self) -> u32 {
self.mesh
}
#[must_use]
pub const fn skin_range<'a>(
&'a self,
palette: &'a [Mat4],
bindings: &'a [SkinBinding],
) -> SkinRange<'a> {
SkinRange {
input_base: self.input_base,
region: &self.region,
palette,
bindings,
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum SkinningError {
#[error(
"range {range}'s vertex {vertex} is bound to joint {joint} in slot {slot}, and its \
palette holds {palette} — the shader would clamp it and the mesh would deform wrongly"
)]
JointOutOfRange {
range: usize,
vertex: usize,
slot: usize,
joint: u32,
palette: usize,
},
#[error("range {range} has an empty joint palette, which the shader's index clamp would wrap")]
EmptyPalette {
range: usize,
},
#[error(
"range {range} covers {vertices} vertices and was given {bindings} skin bindings; they \
are parallel runs and must be the same length"
)]
BindingCountMismatch {
range: usize,
vertices: u32,
bindings: usize,
},
#[error(
"this skinning pass holds {capacity} {what} and the frame asked for {asked}; raise \
the renderer's skinning capacity rather than dropping a character, which no counter \
would report"
)]
OverCapacity {
what: &'static str,
capacity: u32,
asked: u64,
},
#[error(transparent)]
Hal(#[from] HalError),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SkinningDesc<'a> {
pub label: Option<&'a str>,
pub frames: usize,
pub ranges: u32,
pub joints: u32,
pub bindings: u32,
pub vertices: BufferHandle,
pub attribute_base: u32,
}
#[derive(Clone, Copy, Debug)]
pub struct SkinRange<'a> {
pub input_base: u32,
pub region: &'a SkinnedRegion,
pub palette: &'a [Mat4],
pub bindings: &'a [SkinBinding],
}
#[derive(Debug)]
pub struct Skinning {
palettes: Vec<BufferHandle>,
bindings: Vec<BufferHandle>,
params: Vec<Vec<BufferHandle>>,
groups: Vec<Vec<BindGroupHandle>>,
active: Vec<Vec<u32>>,
layout: BindGroupLayoutHandle,
pipeline_layout: PipelineLayoutHandle,
pipeline: ComputePipelineHandle,
vertices: BufferHandle,
attribute_base: u32,
range_capacity: u32,
joint_capacity: u32,
binding_capacity: u32,
frames_begun: u64,
}
impl Skinning {
pub fn new(device: &dyn Device, desc: &SkinningDesc<'_>) -> Result<Self, SkinningError> {
if desc.frames == 0 || desc.ranges == 0 || desc.joints == 0 || desc.bindings == 0 {
return Err(HalError::InvalidDescriptor(
"a skinning pass needs at least one frame in flight, one range, one palette \
matrix and one skin binding"
.to_string(),
)
.into());
}
let label = desc.label.unwrap_or("skinning");
let mut rollback = Rollback::default();
let result = Self::build(device, desc, label, &mut rollback);
if result.is_err() {
rollback.run(device);
}
result
}
fn build(
device: &dyn Device,
desc: &SkinningDesc<'_>,
label: &str,
rollback: &mut Rollback,
) -> Result<Self, SkinningError> {
let entries = [
uniform(0),
storage(1, true, crcbl_shaders::skinning::JOINT_STRIDE as u32),
storage(2, true, crcbl_shaders::skinning::SKIN_BINDING_STRIDE as u32),
storage(3, false, UINT_STRIDE),
];
let layout_desc = BindGroupLayoutDesc {
label: Some(label),
entries: &entries,
};
check_portable_storage_buffers(Some(label), &[&layout_desc])?;
let layout = device.create_bind_group_layout(&layout_desc)?;
rollback.layouts.push(layout);
let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some(label),
bind_group_layouts: &[layout],
push_constants: None,
})?;
rollback.pipeline_layouts.push(pipeline_layout);
let pipeline = compute_pipeline(
device,
label,
&crcbl_shaders::SKINNING,
pipeline_layout,
WORKGROUP_SIZE,
)?;
rollback.pipelines.push(pipeline);
let mut palettes = Vec::with_capacity(desc.frames);
let mut bindings = Vec::with_capacity(desc.frames);
let mut params = Vec::with_capacity(desc.frames);
let mut groups = Vec::with_capacity(desc.frames);
for frame in 0..desc.frames {
let mut buffer = |name: &str, size: u64, usage| {
let handle = device.create_buffer(&BufferDesc {
label: Some(&format!("{label} {name} {frame}")),
size,
usage,
memory: MemoryLocation::HostUpload,
})?;
rollback.buffers.push(handle);
Ok::<_, HalError>(handle)
};
let palette = buffer(
"palette",
u64::from(desc.joints) * JOINT_STRIDE as u64,
BufferUsage::STORAGE,
)?;
let skin = buffer(
"bindings",
u64::from(desc.bindings) * SKIN_BINDING_STRIDE as u64,
BufferUsage::STORAGE,
)?;
let mut frame_params = Vec::with_capacity(desc.ranges as usize);
let mut frame_groups = Vec::with_capacity(desc.ranges as usize);
for range in 0..desc.ranges {
let block = buffer(
&format!("params {range}"),
PARAMS_SIZE as u64,
BufferUsage::UNIFORM,
)?;
let group = device.create_bind_group(&BindGroupDesc {
label: Some(&format!("{label} {frame} {range}")),
layout,
entries: &[
bound(0, block),
bound(1, palette),
bound(2, skin),
bound(3, desc.vertices),
],
variable_count: None,
})?;
rollback.groups.push(group);
frame_params.push(block);
frame_groups.push(group);
}
palettes.push(palette);
bindings.push(skin);
params.push(frame_params);
groups.push(frame_groups);
}
Ok(Self {
palettes,
bindings,
params,
groups,
active: vec![Vec::new(); desc.frames],
layout,
pipeline_layout,
pipeline,
vertices: desc.vertices,
attribute_base: desc.attribute_base,
range_capacity: desc.ranges,
joint_capacity: desc.joints,
binding_capacity: desc.bindings,
frames_begun: 0,
})
}
#[must_use]
pub const fn range_capacity(&self) -> u32 {
self.range_capacity
}
#[must_use]
pub const fn joint_capacity(&self) -> u32 {
self.joint_capacity
}
#[must_use]
pub const fn binding_capacity(&self) -> u32 {
self.binding_capacity
}
#[must_use]
pub const fn parity(&self) -> u32 {
(self.frames_begun % 2) as u32
}
pub fn begin_frame(
&mut self,
device: &dyn Device,
frame: usize,
ranges: &[SkinRange<'_>],
) -> Result<(), SkinningError> {
self.check(ranges)?;
self.active[frame].clear();
self.frames_begun = self.frames_begun.wrapping_add(1);
let parity = self.parity();
let mut palette_bytes = Vec::new();
let mut binding_bytes = Vec::new();
let mut plan = Vec::with_capacity(ranges.len());
for (slot, range) in ranges.iter().enumerate() {
let vertex_count = range.region.vertex_count();
let block = Params {
vertex_count,
input_base: range.input_base,
output_base: range.region.base(parity),
binding_base: (binding_bytes.len() / SKIN_BINDING_STRIDE) as u32,
joint_base: (palette_bytes.len() / JOINT_STRIDE) as u32,
joint_count: range.palette.len() as u32,
attribute_base: self.attribute_base,
};
device.write_buffer(self.params[frame][slot], 0, &block.to_bytes())?;
for matrix in range.palette {
for value in matrix.to_cols_array() {
palette_bytes.extend_from_slice(&value.to_le_bytes());
}
}
for binding in range.bindings {
binding_bytes.extend_from_slice(&binding.to_bytes());
}
plan.push(vertex_count.div_ceil(WORKGROUP_SIZE));
}
if !palette_bytes.is_empty() {
device.write_buffer(self.palettes[frame], 0, &palette_bytes)?;
}
if !binding_bytes.is_empty() {
device.write_buffer(self.bindings[frame], 0, &binding_bytes)?;
}
self.active[frame] = plan;
Ok(())
}
fn check(&self, ranges: &[SkinRange<'_>]) -> Result<(), SkinningError> {
let over = |what, capacity, asked| SkinningError::OverCapacity {
what,
capacity,
asked,
};
if ranges.len() as u64 > u64::from(self.range_capacity) {
return Err(over("ranges", self.range_capacity, ranges.len() as u64));
}
let mut joints = 0u64;
let mut bindings = 0u64;
for (index, range) in ranges.iter().enumerate() {
if range.palette.is_empty() {
return Err(SkinningError::EmptyPalette { range: index });
}
let vertices = range.region.vertex_count();
if range.bindings.len() as u64 != u64::from(vertices) {
return Err(SkinningError::BindingCountMismatch {
range: index,
vertices,
bindings: range.bindings.len(),
});
}
for (vertex, binding) in range.bindings.iter().enumerate() {
for (slot, joint) in binding.joints.iter().enumerate() {
if *joint as usize >= range.palette.len() {
return Err(SkinningError::JointOutOfRange {
range: index,
vertex,
slot,
joint: *joint,
palette: range.palette.len(),
});
}
}
}
joints += range.palette.len() as u64;
bindings += range.bindings.len() as u64;
}
if joints > u64::from(self.joint_capacity) {
return Err(over("palette matrices", self.joint_capacity, joints));
}
if bindings > u64::from(self.binding_capacity) {
return Err(over("skin bindings", self.binding_capacity, bindings));
}
Ok(())
}
pub const MAX_PASSES: u32 = 1;
pub fn add_pass(&self, graph: &mut RenderGraph<'_>, frame: usize) -> Option<BufferId> {
let dispatches: Vec<(BindGroupHandle, u32)> = self.active[frame]
.iter()
.enumerate()
.map(|(slot, &groups)| (self.groups[frame][slot], groups))
.collect();
if dispatches.is_empty() {
return None;
}
let pool = graph.import_buffer(
"vertex-pool",
ImportedBuffer {
buffer: self.vertices,
initial: ResourceState::ShaderRead,
final_state: ResourceState::ShaderRead,
},
);
let pipeline = self.pipeline;
let layout = self.pipeline_layout;
graph
.add_compute_pass("skinning")
.use_buffer(pool, ResourceState::ShaderReadWrite)
.execute(move |ctx| {
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(pipeline);
for (group, groups) in dispatches {
encoder.bind_group(0, group, &[], layout);
encoder.dispatch(groups, 1, 1);
}
});
Some(pool)
}
pub fn destroy(self, device: &dyn Device) {
device.destroy_compute_pipeline(self.pipeline);
device.destroy_pipeline_layout(self.pipeline_layout);
for group in self.groups.into_iter().flatten() {
device.destroy_bind_group(group);
}
device.destroy_bind_group_layout(self.layout);
for buffer in self
.palettes
.into_iter()
.chain(self.bindings)
.chain(self.params.into_iter().flatten())
{
device.destroy_buffer(buffer);
}
}
}
#[derive(Default)]
struct Rollback {
pipelines: Vec<ComputePipelineHandle>,
pipeline_layouts: Vec<PipelineLayoutHandle>,
groups: Vec<BindGroupHandle>,
layouts: Vec<BindGroupLayoutHandle>,
buffers: Vec<BufferHandle>,
}
impl Rollback {
fn run(self, device: &dyn Device) {
for pipeline in self.pipelines {
device.destroy_compute_pipeline(pipeline);
}
for layout in self.pipeline_layouts {
device.destroy_pipeline_layout(layout);
}
for group in self.groups {
device.destroy_bind_group(group);
}
for layout in self.layouts {
device.destroy_bind_group_layout(layout);
}
for buffer in self.buffers {
device.destroy_buffer(buffer);
}
}
}
#[must_use]
pub fn blend(palette: &[Mat4], binding: &SkinBinding) -> Mat4 {
assert!(
!palette.is_empty(),
"a skinned vertex with an empty joint palette has nothing to blend onto, and the \
shader's index clamp would wrap"
);
let last = palette.len() - 1;
let mut blended = Mat4::ZERO;
for slot in 0..JOINTS_PER_VERTEX {
let joint = (binding.joints[slot] as usize).min(last);
blended += palette[joint] * binding.weights[slot];
}
blended
}
#[must_use]
pub fn normal_basis(basis: Mat3) -> Mat3 {
let (first, second, third) = (basis.row(0), basis.row(1), basis.row(2));
Mat3::from_cols(second.cross(third), third.cross(first), first.cross(second)).transpose()
}
#[must_use]
pub fn skin_vertex(palette: &[Mat4], binding: &SkinBinding, vertex: &MeshVertex) -> MeshVertex {
let blended = blend(palette, binding);
let position = blended * Vec4::from((Vec3::from_array(vertex.position), 1.0));
let bind_pose = vertex.qtangent.decode();
let bind_normal = Vec3::from_array(bind_pose.normal);
let bind_tangent = Vec3::from_array(bind_pose.tangent);
let carried = normal_basis(Mat3::from_mat4(blended)) * bind_normal;
let square_length = carried.dot(carried);
let normal = if square_length > 0.0 {
carried / square_length.sqrt()
} else {
bind_normal
};
let projected = {
let moved = Mat3::from_mat4(blended) * bind_tangent;
moved - normal * normal.dot(moved)
};
let square_length = projected.dot(projected);
let tangent = if square_length > 0.0 {
projected / square_length.sqrt()
} else {
bind_tangent
};
let handedness = Vec3::from_array(bind_pose.normal)
.cross(bind_tangent)
.dot(Vec3::from_array(bind_pose.bitangent));
MeshVertex {
position: [position.x, position.y, position.z],
qtangent: QTangent::encode(TangentFrame {
tangent: tangent.to_array(),
bitangent: (normal.cross(tangent) * if handedness < 0.0 { -1.0 } else { 1.0 })
.to_array(),
normal: normal.to_array(),
}),
uv0: vertex.uv0,
uv1: vertex.uv1,
color: vertex.color,
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use crcbl_shaders::vertex::UvRange;
use crcbl_hal::null::{Command, NullInstance, Recorder};
use crcbl_hal::{CommandEncoderDesc, DeviceDesc, Instance, QueueHandle, QueueKind};
use crcbl_shaders::mesh::VERTEX_STRIDE;
use super::*;
use crate::mesh_pool::{MeshPoolDesc, MeshUpload};
use crate::transient::TransientPool;
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)
}
fn pool(device: &dyn Device, vertices: u32) -> MeshPool {
MeshPool::new(
device,
&MeshPoolDesc {
label: Some("skinning test"),
vertex_capacity: vertices,
index_capacity: 64,
mesh_capacity: 4,
},
)
.expect("the null backend accepts every descriptor")
}
fn skinning(
device: &dyn Device,
pool: &MeshPool,
ranges: u32,
joints: u32,
bindings: u32,
) -> Skinning {
Skinning::new(
device,
&SkinningDesc {
label: Some("skinning test"),
frames: 2,
ranges,
joints,
bindings,
vertices: pool.vertex_buffer(),
attribute_base: pool.attribute_base(),
},
)
.expect("the null backend accepts every descriptor")
}
fn rigid(n: usize) -> Vec<SkinBinding> {
vec![
SkinBinding {
joints: [0; JOINTS_PER_VERTEX],
weights: [1.0, 0.0, 0.0, 0.0],
};
n
]
}
fn run(
recorder: &Recorder,
device: &dyn Device,
queue: QueueHandle,
pass: &Skinning,
frame: usize,
) {
let mut transients = TransientPool::new();
let mut graph = RenderGraph::new(queue);
pass.add_pass(&mut graph, frame);
let compiled = graph.compile(&transients).expect("a legal frame");
let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
label: Some("skinning"),
queue,
});
compiled
.execute(device, &mut transients, encoder.as_mut(), None)
.expect("the graph executed");
let commands = encoder.finish().expect("a legal command stream");
device.destroy_command_buffer(commands);
recorder.assert_valid();
}
fn dispatches(recorder: &Recorder) -> Vec<u32> {
recorder
.commands()
.into_iter()
.filter_map(|command| match command {
Command::Dispatch { x, y, z } => {
assert_eq!((y, z), (1, 1), "the kernel is one-dimensional");
Some(x)
}
_ => None,
})
.collect()
}
fn params_of(recorder: &Recorder, pass: &Skinning, frame: usize, slot: usize) -> Params {
let bytes = recorder
.buffer_bytes(pass.params[frame][slot])
.expect("the block is live");
assert_eq!(bytes.len(), PARAMS_SIZE);
let word = |at: usize| {
u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes of a word"))
};
Params {
vertex_count: word(0),
input_base: word(4),
output_base: word(8),
binding_base: word(12),
joint_base: word(16),
joint_count: word(20),
attribute_base: word(24),
}
}
#[test]
fn releasing_a_skinned_mesh_returns_its_region() {
let (recorder, device, queue) = open();
let device = device.as_ref();
let mut pool = pool(device, 64);
const VERTICES: u32 = 8;
let source = pool
.upload(
device,
queue,
&MeshUpload {
label: "source",
vertices: &vec![0u8; VERTICES as usize * VERTEX_STRIDE],
indices: &[0, 1, 2],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("the pool has room");
pool.flush(device).expect("the null backend completes it");
let (free_before, _) = pool.vertex_space();
let skinned = SkinnedMesh::reserve(&mut pool, source).expect("room for two halves");
assert_eq!(
skinned.vertex_count(),
VERTICES,
"each half is as long as the bind pose it deforms"
);
assert_eq!(
skinned.input_base(),
pool.mesh(source).expect("resident").base_vertex,
"the range reads the bind pose where the pool put it"
);
assert_eq!(
skinned.mesh_id(),
source.index(),
"a skinned instance names the mesh it was deformed from, so the bucket, the \
level tables and the bounding box all resolve as the source's"
);
assert_eq!(
pool.vertex_space().0,
free_before - 2 * VERTICES,
"two halves are taken, not one"
);
skinned.release(&mut pool);
assert_eq!(
pool.vertex_space().0,
free_before,
"the region goes back whole, and the free list coalesces it"
);
let again = SkinnedMesh::reserve(&mut pool, source).expect("the vertices came back");
again.release(&mut pool);
pool.destroy(device);
recorder.assert_valid();
}
#[test]
fn a_reservation_needs_no_spare_table_entry() {
let (recorder, device, queue) = open();
let device = device.as_ref();
let mut pool = MeshPool::new(
device,
&MeshPoolDesc {
label: Some("no spare entry"),
vertex_capacity: 64,
index_capacity: 64,
mesh_capacity: 1,
},
)
.expect("the null backend accepts every descriptor");
let source = pool
.upload(
device,
queue,
&MeshUpload {
label: "source",
vertices: &vec![0u8; 8 * VERTEX_STRIDE],
indices: &[0, 1, 2],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("the pool has room");
pool.flush(device).expect("the null backend completes it");
let skinned = SkinnedMesh::reserve(&mut pool, source)
.expect("a region is vertices, and the table is untouched");
assert_eq!(
skinned.mesh_id(),
source.index(),
"and the entry it draws through is the one the source already had"
);
skinned.release(&mut pool);
pool.destroy(device);
recorder.assert_valid();
}
#[test]
fn a_refused_region_gives_back_the_half_it_took() {
let (recorder, device, queue) = open();
let device = device.as_ref();
const VERTICES: u32 = 8;
let mut pool = MeshPool::new(
device,
&MeshPoolDesc {
label: Some("room for one half"),
vertex_capacity: 2 * VERTICES + VERTICES / 2,
index_capacity: 64,
mesh_capacity: 4,
},
)
.expect("the null backend accepts every descriptor");
let source = pool
.upload(
device,
queue,
&MeshUpload {
label: "source",
vertices: &vec![0u8; VERTICES as usize * VERTEX_STRIDE],
indices: &[0, 1, 2],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("the pool has room");
pool.flush(device).expect("the null backend completes it");
let space = pool.vertex_space();
let refused = SkinnedMesh::reserve(&mut pool, source);
assert!(
refused.is_err(),
"the pool has room for one half of the region and not for two: {refused:?}"
);
assert_eq!(
pool.vertex_space(),
space,
"a refused reservation leaks no pool space"
);
pool.destroy(device);
recorder.assert_valid();
}
fn vertex(position: Vec3, normal: Vec3) -> MeshVertex {
MeshVertex::from_normal(
position.to_array(),
normal.to_array(),
[0.25, 0.5, 0.75, 1.0],
[0.125, 0.375],
&UvRange {
scale: [1.0, 1.0],
offset: [0.0, 0.0],
},
)
}
fn normal_of(vertex: &MeshVertex) -> Vec3 {
Vec3::from_array(vertex.qtangent.decode().normal)
}
#[test]
fn a_vertex_bound_wholly_to_one_joint_is_transformed_exactly() {
let joint = Mat4::from_rotation_translation(
glam::Quat::from_rotation_z(core::f32::consts::FRAC_PI_3),
Vec3::new(2.0, -3.0, 0.5),
);
let palette = [Mat4::IDENTITY, joint];
let binding = SkinBinding {
joints: [1, 0, 0, 0],
weights: [1.0, 0.0, 0.0, 0.0],
};
let bind_pose = vertex(Vec3::new(1.0, 2.0, 3.0), Vec3::Y);
let skinned = skin_vertex(&palette, &binding, &bind_pose);
let expected = joint * Vec4::new(1.0, 2.0, 3.0, 1.0);
assert_eq!(
skinned.position,
[expected.x, expected.y, expected.z],
"a rigidly bound vertex is the joint's transform of it and nothing else"
);
let want = Mat3::from_mat4(joint) * Vec3::Y;
let got = normal_of(&skinned);
for (got, want) in got.to_array().iter().zip(want.to_array()) {
assert!(
(got - want).abs() <= QTangent::MAX_COMPONENT_ERROR,
"a rigidly bound normal is the joint's rotation of it: {got:?} against {want}"
);
}
assert_eq!(skinned.color, bind_pose.color, "colour is copied through");
assert_eq!(skinned.uv0, bind_pose.uv0, "uv is copied through");
assert_eq!(skinned.uv1, bind_pose.uv1, "and the second set with it");
}
#[test]
fn a_vertex_blended_across_two_joints_is_the_weighted_sum_of_both() {
let palette = [
Mat4::from_translation(Vec3::new(4.0, 0.0, 0.0)),
Mat4::from_translation(Vec3::new(0.0, 8.0, 0.0)),
];
let binding = SkinBinding {
joints: [0, 1, 0, 0],
weights: [0.25, 0.75, 0.0, 0.0],
};
let bind_pose = vertex(Vec3::new(1.0, 1.0, 1.0), Vec3::Z);
let skinned = skin_vertex(&palette, &binding, &bind_pose);
assert_eq!(
skinned.position,
[1.0 + 0.25 * 4.0, 1.0 + 0.75 * 8.0, 1.0],
"a quarter of the first joint's translation and three quarters of the second's"
);
assert_eq!(
skinned.qtangent, bind_pose.qtangent,
"a blend of translations has an identity linear part, so the frame is unmoved — \
and lane for lane, because the re-encode is the same arithmetic on the same frame"
);
}
#[test]
fn a_normal_under_a_non_uniform_scale_goes_through_the_cofactor_not_the_basis() {
let scale = Mat4::from_scale(Vec3::new(4.0, 1.0, 1.0));
let palette = [scale];
let binding = SkinBinding {
joints: [0, 0, 0, 0],
weights: [1.0, 0.0, 0.0, 0.0],
};
let diagonal = Vec3::new(1.0, 1.0, 0.0).normalize();
let skinned = skin_vertex(&palette, &binding, &vertex(Vec3::X, diagonal));
let through_cofactor = (Vec3::new(1.0, 4.0, 0.0)).normalize();
let through_basis = (Vec3::new(4.0, 1.0, 0.0)).normalize();
let got = normal_of(&skinned);
assert!(
(got - through_cofactor).length() <= QTangent::MAX_COMPONENT_ERROR,
"{got:?} is not the cofactor's answer {through_cofactor:?}"
);
assert!(
(got - through_basis).length() > 0.5,
"the bare basis would have given {through_basis:?}, which is not far from {got:?} — \
this test would pass with the wrong matrix"
);
assert!(
(got.length() - 1.0).abs() <= QTangent::MAX_COMPONENT_ERROR,
"the shader normalises, so the written normal is unit length"
);
}
#[test]
fn the_cofactor_matches_the_inverse_transpose_scaled_by_the_determinant() {
for basis in [
Mat3::from_mat4(Mat4::from_scale(Vec3::new(2.0, 3.0, 0.5))),
Mat3::from_rotation_y(0.7) * Mat3::from_diagonal(Vec3::new(1.0, 4.0, 0.25)),
Mat3::from_diagonal(Vec3::new(-1.0, 2.0, 3.0)),
] {
let textbook = basis.inverse().transpose() * basis.determinant();
let cofactor = normal_basis(basis);
for (got, want) in cofactor
.to_cols_array()
.iter()
.zip(textbook.to_cols_array())
{
assert!(
(got - want).abs() < 1e-4,
"{cofactor:?} is not {textbook:?} for basis {basis:?}"
);
}
}
}
#[test]
fn a_blend_that_collapses_to_zero_keeps_the_bind_pose_normal() {
let palette = [Mat4::IDENTITY];
let binding = SkinBinding {
joints: [0; JOINTS_PER_VERTEX],
weights: [0.0; JOINTS_PER_VERTEX],
};
let bind_pose = vertex(Vec3::new(1.0, 2.0, 3.0), Vec3::Y);
let skinned = skin_vertex(&palette, &binding, &bind_pose);
assert_eq!(
skinned.position,
[0.0, 0.0, 0.0],
"no weight at all puts the vertex at the palette's origin"
);
assert_eq!(
skinned.qtangent, bind_pose.qtangent,
"and the frame is the bind pose's, finite and already orthonormal"
);
assert!(
normal_of(&skinned)
.to_array()
.iter()
.all(|value| value.is_finite()),
"nothing written into the vertex pool may be NaN"
);
}
#[test]
fn weights_that_do_not_sum_to_one_deflate_the_vertex_rather_than_being_renormalised() {
let palette = [Mat4::IDENTITY];
let binding = SkinBinding {
joints: [0; JOINTS_PER_VERTEX],
weights: [0.9, 0.0, 0.0, 0.0],
};
let skinned = skin_vertex(
&palette,
&binding,
&vertex(Vec3::new(10.0, 0.0, 0.0), Vec3::Y),
);
assert_eq!(
skinned.position[0], 9.0,
"a tenth of the way toward the origin, not renormalised back out to 10"
);
}
#[test]
fn a_joint_index_past_the_palette_is_clamped_the_way_the_shader_clamps_it() {
let palette = [
Mat4::from_translation(Vec3::X),
Mat4::from_translation(Vec3::Y),
];
let past = SkinBinding {
joints: [99, 0, 0, 0],
weights: [1.0, 0.0, 0.0, 0.0],
};
let last = SkinBinding {
joints: [1, 0, 0, 0],
weights: [1.0, 0.0, 0.0, 0.0],
};
let bind_pose = vertex(Vec3::ZERO, Vec3::Y);
assert_eq!(
skin_vertex(&palette, &past, &bind_pose).position,
skin_vertex(&palette, &last, &bind_pose).position,
"an out-of-range index resolves to the palette's last matrix"
);
}
#[test]
fn a_regions_two_halves_alternate_with_the_parity() {
let (_recorder, device, _queue) = open();
let mut pool = pool(device.as_ref(), 64);
let region = SkinnedRegion::reserve(&mut pool, 8).expect("room for both halves");
assert_ne!(
region.base(0),
region.base(1),
"the two parities must name different runs, or the previous frame's skinned \
positions are this frame's"
);
assert_eq!(region.base(0), region.previous_base(1));
assert_eq!(region.base(1), region.previous_base(0));
assert_eq!(region.base(2), region.base(0));
assert_eq!(region.base(3), region.base(1));
assert_eq!(region.vertex_count(), 8);
}
#[test]
fn a_regions_halves_never_overlap_each_other_or_the_bind_pose() {
let (_recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 64);
let count = 6u32;
let handle = pool
.upload(
device.as_ref(),
queue,
&MeshUpload {
label: "bind pose",
vertices: &vec![0u8; count as usize * VERTEX_STRIDE],
indices: &[0, 1, 2],
uv_range: UvRange::default(),
flags: 0,
},
)
.expect("room in both pools");
pool.flush(device.as_ref()).expect("the null backend lands");
let bind_pose = pool.mesh(handle).expect("resident").base_vertex;
let region = SkinnedRegion::reserve(&mut pool, count).expect("room for both halves");
let runs = [
bind_pose..bind_pose + count,
region.base(0)..region.base(0) + count,
region.base(1)..region.base(1) + count,
];
for (index, run) in runs.iter().enumerate() {
for other in &runs[index + 1..] {
assert!(
run.end <= other.start || other.end <= run.start,
"{run:?} overlaps {other:?}; one invocation would read a vertex another had \
already overwritten"
);
}
}
for parity in [0, 1] {
let _ = Params {
vertex_count: count,
input_base: bind_pose,
output_base: region.base(parity),
binding_base: 0,
joint_base: 0,
joint_count: 1,
attribute_base: 0,
}
.to_bytes();
}
}
#[test]
fn a_released_region_gives_both_halves_back() {
let (_recorder, device, _queue) = open();
let mut pool = pool(device.as_ref(), 16);
let before = pool.vertex_space();
let region = SkinnedRegion::reserve(&mut pool, 8).expect("exactly fits");
assert_eq!(pool.vertex_space().0, 0, "both halves are taken");
region.release(&mut pool);
assert_eq!(
pool.vertex_space(),
before,
"everything is free again, and in one block"
);
SkinnedRegion::reserve(&mut pool, 8).expect("the space really came back");
}
#[test]
fn a_pool_with_room_for_one_half_gives_it_back_rather_than_leaking_it() {
let (_recorder, device, _queue) = open();
let mut pool = pool(device.as_ref(), 8);
let before = pool.vertex_space();
let error = SkinnedRegion::reserve(&mut pool, 6).expect_err("no room for twelve vertices");
assert!(
matches!(error, MeshPoolError::PoolExhausted { .. }),
"{error} does not name the exhausted pool"
);
assert_eq!(
pool.vertex_space(),
before,
"the first half must have gone back"
);
}
#[test]
fn a_region_of_no_vertices_is_refused() {
let (_recorder, device, _queue) = open();
let mut pool = pool(device.as_ref(), 8);
let error = SkinnedRegion::reserve(&mut pool, 0).expect_err("no address to hand back");
assert!(
matches!(error, MeshPoolError::EmptyReservation),
"{error} does not name the empty reservation"
);
}
#[test]
fn the_dispatch_covers_every_vertex_and_no_more() {
for count in [1u32, 63, 64, 65, 127, 128, 200] {
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), count * 2 + 1);
let region = SkinnedRegion::reserve(&mut pool, count).expect("room");
let mut pass = skinning(device.as_ref(), &pool, 1, 2, count);
let bindings = rigid(count as usize);
pass.begin_frame(
device.as_ref(),
0,
&[SkinRange {
input_base: 0,
region: ®ion,
palette: &[Mat4::IDENTITY, Mat4::IDENTITY],
bindings: &bindings,
}],
)
.expect("a legal frame");
run(&recorder, device.as_ref(), queue, &pass, 0);
let groups = dispatches(&recorder);
assert_eq!(groups.len(), 1, "one range is one dispatch");
assert_eq!(
groups[0],
count.div_ceil(WORKGROUP_SIZE),
"{count} vertices at {WORKGROUP_SIZE} per group"
);
assert!(
u64::from(groups[0]) * u64::from(WORKGROUP_SIZE) >= u64::from(count),
"{count} vertices need at least that many invocations, and {} groups give {}",
groups[0],
u64::from(groups[0]) * u64::from(WORKGROUP_SIZE)
);
pass.destroy(device.as_ref());
region.release(&mut pool);
pool.destroy(device.as_ref());
}
}
#[test]
fn every_range_gets_its_own_dispatch_and_its_own_bind_group() {
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 64);
let counts = [1u32, 2, 3];
let regions: Vec<SkinnedRegion> = counts
.iter()
.map(|count| SkinnedRegion::reserve(&mut pool, *count).expect("room"))
.collect();
let mut pass = skinning(device.as_ref(), &pool, 3, 6, 8);
let bindings: Vec<Vec<SkinBinding>> =
counts.iter().map(|count| rigid(*count as usize)).collect();
let ranges: Vec<SkinRange<'_>> = (0..3)
.map(|index| SkinRange {
input_base: 32 + index as u32,
region: ®ions[index],
palette: &[Mat4::IDENTITY, Mat4::IDENTITY],
bindings: &bindings[index],
})
.collect();
pass.begin_frame(device.as_ref(), 1, &ranges)
.expect("a legal frame");
run(&recorder, device.as_ref(), queue, &pass, 1);
assert_eq!(dispatches(&recorder), vec![1, 1, 1], "three ranges");
let bound: Vec<_> = recorder
.commands()
.into_iter()
.filter_map(|command| match command {
Command::BindGroup { group, .. } => Some(group),
_ => None,
})
.collect();
assert_eq!(
bound, pass.groups[1],
"each dispatch is preceded by that range's own group, in range order"
);
}
#[test]
fn the_params_block_names_this_frames_half_and_the_next_frames_names_the_other() {
let (recorder, device, _queue) = open();
let mut pool = pool(device.as_ref(), 64);
let region = SkinnedRegion::reserve(&mut pool, 5).expect("room");
let mut pass = skinning(device.as_ref(), &pool, 1, 3, 5);
let bindings = rigid(5);
let palette = [Mat4::IDENTITY; 3];
let mut seen = Vec::new();
for frame in [0usize, 1] {
pass.begin_frame(
device.as_ref(),
frame,
&[SkinRange {
input_base: 40,
region: ®ion,
palette: &palette,
bindings: &bindings,
}],
)
.expect("a legal frame");
let block = params_of(&recorder, &pass, frame, 0);
assert_eq!(
block,
Params {
vertex_count: 5,
input_base: 40,
output_base: region.base(pass.parity()),
binding_base: 0,
joint_base: 0,
joint_count: 3,
attribute_base: pool.attribute_base(),
}
);
seen.push(block.output_base);
}
assert_ne!(
seen[0], seen[1],
"two consecutive frames must write different halves of the region"
);
}
#[test]
fn each_ranges_palette_and_binding_bases_follow_the_range_before_it() {
let (recorder, device, _queue) = open();
let mut pool = pool(device.as_ref(), 64);
let first = SkinnedRegion::reserve(&mut pool, 3).expect("room");
let second = SkinnedRegion::reserve(&mut pool, 4).expect("room");
let mut pass = skinning(device.as_ref(), &pool, 2, 5, 7);
let (three, four) = (rigid(3), rigid(4));
pass.begin_frame(
device.as_ref(),
0,
&[
SkinRange {
input_base: 50,
region: &first,
palette: &[Mat4::IDENTITY; 2],
bindings: &three,
},
SkinRange {
input_base: 54,
region: &second,
palette: &[Mat4::IDENTITY; 3],
bindings: &four,
},
],
)
.expect("a legal frame");
let first_block = params_of(&recorder, &pass, 0, 0);
let second_block = params_of(&recorder, &pass, 0, 1);
assert_eq!((first_block.joint_base, first_block.binding_base), (0, 0));
assert_eq!(
(second_block.joint_base, second_block.binding_base),
(2, 3),
"the second range starts where the first one's palette and bindings ended"
);
assert_eq!((first_block.joint_count, second_block.joint_count), (2, 3));
}
#[test]
fn the_uploaded_palette_and_bindings_are_the_bytes_the_shader_reads() {
let (recorder, device, _queue) = open();
let mut pool = pool(device.as_ref(), 32);
let region = SkinnedRegion::reserve(&mut pool, 2).expect("room");
let mut pass = skinning(device.as_ref(), &pool, 1, 2, 2);
let palette = [
Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0)),
Mat4::from_scale(Vec3::new(2.0, 4.0, 8.0)),
];
let bindings = [
SkinBinding {
joints: [1, 0, 1, 0],
weights: [0.5, 0.25, 0.125, 0.125],
},
SkinBinding {
joints: [0, 1, 0, 1],
weights: [1.0, 0.0, 0.0, 0.0],
},
];
pass.begin_frame(
device.as_ref(),
0,
&[SkinRange {
input_base: 8,
region: ®ion,
palette: &palette,
bindings: &bindings,
}],
)
.expect("a legal frame");
let written = recorder
.buffer_bytes(pass.palettes[0])
.expect("the palette is live");
for (index, matrix) in palette.iter().enumerate() {
let want: Vec<u8> = matrix
.to_cols_array()
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(
&written[index * JOINT_STRIDE..(index + 1) * JOINT_STRIDE],
&want[..],
"palette matrix {index} is not the columns the shader reads with no transpose"
);
}
let written = recorder
.buffer_bytes(pass.bindings[0])
.expect("the binding buffer is live");
for (index, binding) in bindings.iter().enumerate() {
assert_eq!(
&written[index * SKIN_BINDING_STRIDE..(index + 1) * SKIN_BINDING_STRIDE],
&binding.to_bytes()[..],
"skin binding {index} is not what the shader crate encodes"
);
}
}
#[test]
fn a_binding_naming_a_joint_the_palette_has_not_got_is_refused() {
let (recorder, device, _queue) = open();
let mut pool = pool(device.as_ref(), 32);
let region = SkinnedRegion::reserve(&mut pool, 3).expect("room");
let mut pass = skinning(device.as_ref(), &pool, 1, 2, 3);
let mut bindings = rigid(3);
bindings[1].joints[2] = 7;
let error = pass
.begin_frame(
device.as_ref(),
0,
&[SkinRange {
input_base: 0,
region: ®ion,
palette: &[Mat4::IDENTITY, Mat4::IDENTITY],
bindings: &bindings,
}],
)
.expect_err("joint 7 of a two-joint palette");
match error {
SkinningError::JointOutOfRange {
range,
vertex,
slot,
joint,
palette,
} => assert_eq!((range, vertex, slot, joint, palette), (0, 1, 2, 7, 2)),
other => panic!("{other} does not name the joint that is out of range"),
}
assert!(
recorder
.buffer_bytes(pass.params[0][0])
.is_some_and(|bytes| bytes.iter().all(|byte| *byte == 0)),
"a refused frame must not have written a uniform block"
);
assert!(
pass.active[0].is_empty(),
"and it must not have left a dispatch plan behind"
);
}
#[test]
fn a_joint_index_is_checked_against_its_own_ranges_palette() {
let (_recorder, device, _queue) = open();
let mut pool = pool(device.as_ref(), 32);
let long = SkinnedRegion::reserve(&mut pool, 1).expect("room");
let short = SkinnedRegion::reserve(&mut pool, 1).expect("room");
let mut pass = skinning(device.as_ref(), &pool, 2, 6, 2);
let mut named_three = rigid(1);
named_three[0].joints[0] = 3;
pass.begin_frame(
device.as_ref(),
0,
&[SkinRange {
input_base: 0,
region: &long,
palette: &[Mat4::IDENTITY; 4],
bindings: &named_three,
}],
)
.expect("joint 3 of a four-joint palette");
let error = pass
.begin_frame(
device.as_ref(),
0,
&[
SkinRange {
input_base: 0,
region: &long,
palette: &[Mat4::IDENTITY; 4],
bindings: &rigid(1),
},
SkinRange {
input_base: 1,
region: &short,
palette: &[Mat4::IDENTITY; 2],
bindings: &named_three,
},
],
)
.expect_err("joint 3 of a two-joint palette");
assert!(
matches!(error, SkinningError::JointOutOfRange { range: 1, .. }),
"{error} blames the wrong range"
);
}
#[test]
fn an_empty_palette_is_refused_rather_than_reaching_the_blocks_panic() {
let (_recorder, device, _queue) = open();
let mut pool = pool(device.as_ref(), 32);
let region = SkinnedRegion::reserve(&mut pool, 1).expect("room");
let mut pass = skinning(device.as_ref(), &pool, 1, 1, 1);
let error = pass
.begin_frame(
device.as_ref(),
0,
&[SkinRange {
input_base: 0,
region: ®ion,
palette: &[],
bindings: &rigid(1),
}],
)
.expect_err("no joints to blend onto");
assert!(
matches!(error, SkinningError::EmptyPalette { range: 0 }),
"{error}"
);
}
#[test]
fn a_binding_run_that_is_not_one_per_vertex_is_refused() {
let (_recorder, device, _queue) = open();
let mut pool = pool(device.as_ref(), 32);
let region = SkinnedRegion::reserve(&mut pool, 4).expect("room");
let mut pass = skinning(device.as_ref(), &pool, 1, 1, 8);
for offered in [3usize, 5] {
let error = pass
.begin_frame(
device.as_ref(),
0,
&[SkinRange {
input_base: 0,
region: ®ion,
palette: &[Mat4::IDENTITY],
bindings: &rigid(offered),
}],
)
.expect_err("four vertices need four bindings");
assert!(
matches!(
error,
SkinningError::BindingCountMismatch {
vertices: 4,
bindings,
..
} if bindings == offered
),
"{error}"
);
}
}
#[test]
fn a_frame_over_any_capacity_is_refused_and_names_which() {
let (_recorder, device, _queue) = open();
let mut pool = pool(device.as_ref(), 64);
let region = SkinnedRegion::reserve(&mut pool, 2).expect("room");
let two = rigid(2);
let range = |palette: &'static [Mat4]| SkinRange {
input_base: 0,
region: ®ion,
palette,
bindings: &two,
};
const ONE: &[Mat4] = &[Mat4::IDENTITY];
const THREE: &[Mat4] = &[Mat4::IDENTITY, Mat4::IDENTITY, Mat4::IDENTITY];
let mut pass = skinning(device.as_ref(), &pool, 1, 8, 8);
let error = pass
.begin_frame(device.as_ref(), 0, &[range(ONE), range(ONE)])
.expect_err("two ranges in a pass built for one");
assert!(
matches!(
error,
SkinningError::OverCapacity {
what: "ranges",
capacity: 1,
asked: 2
}
),
"{error}"
);
let mut pass = skinning(device.as_ref(), &pool, 2, 2, 8);
let error = pass
.begin_frame(device.as_ref(), 0, &[range(THREE)])
.expect_err("three matrices in a buffer of two");
assert!(
matches!(
error,
SkinningError::OverCapacity {
what: "palette matrices",
capacity: 2,
asked: 3
}
),
"{error}"
);
let mut pass = skinning(device.as_ref(), &pool, 2, 8, 3);
let error = pass
.begin_frame(device.as_ref(), 0, &[range(ONE), range(ONE)])
.expect_err("four bindings in a buffer of three");
assert!(
matches!(
error,
SkinningError::OverCapacity {
what: "skin bindings",
capacity: 3,
asked: 4
}
),
"{error}"
);
}
#[test]
fn a_frame_with_nothing_to_skin_adds_no_pass_and_clears_the_slot() {
let (recorder, device, queue) = open();
let mut pool = pool(device.as_ref(), 32);
let region = SkinnedRegion::reserve(&mut pool, 4).expect("room");
let mut pass = skinning(device.as_ref(), &pool, 1, 1, 4);
pass.begin_frame(
device.as_ref(),
0,
&[SkinRange {
input_base: 0,
region: ®ion,
palette: &[Mat4::IDENTITY],
bindings: &rigid(4),
}],
)
.expect("a legal frame");
let mut graph = RenderGraph::new(queue);
assert!(
pass.add_pass(&mut graph, 0).is_some(),
"a frame with a range has a pass"
);
pass.begin_frame(device.as_ref(), 0, &[])
.expect("an empty frame is legal");
recorder.clear();
let mut graph = RenderGraph::new(queue);
assert!(
pass.add_pass(&mut graph, 0).is_none(),
"a frame with no ranges adds nothing"
);
let compiled = graph.compile(&TransientPool::new()).expect("a legal frame");
assert!(
compiled.passes().is_empty(),
"and the graph has no skinning pass in it"
);
run(&recorder, device.as_ref(), queue, &pass, 0);
assert!(
dispatches(&recorder).is_empty(),
"nothing is dispatched for a frame with nothing to skin"
);
}
#[test]
fn the_bind_group_layout_is_the_order_the_shader_declares() {
let (recorder, device, _queue) = open();
let pool = pool(device.as_ref(), 8);
let pass = skinning(device.as_ref(), &pool, 1, 1, 1);
let (_, entries) = recorder
.bind_group_layouts_created()
.into_iter()
.find(|(label, _)| label.as_deref() == Some("skinning test"))
.expect("the pass created its layout");
assert_eq!(entries.len(), 4);
assert!(matches!(
entries[0].kind,
crcbl_hal::BindingKind::UniformBuffer { .. }
));
for (binding, read_only) in [(1usize, true), (2, true), (3, false)] {
match entries[binding].kind {
crcbl_hal::BindingKind::StorageBuffer { read_only: got, .. } => assert_eq!(
got, read_only,
"binding {binding} is the wrong kind of storage buffer"
),
other => panic!("binding {binding} is {other:?}, not a storage buffer"),
}
}
pass.destroy(device.as_ref());
}
#[test]
fn destroy_releases_everything_the_pass_made_and_nothing_it_borrowed() {
let (recorder, device, _queue) = open();
let pool = pool(device.as_ref(), 8);
let borrowed = recorder.total_live_objects();
let pass = skinning(device.as_ref(), &pool, 2, 4, 4);
assert!(recorder.total_live_objects() > borrowed);
pass.destroy(device.as_ref());
assert_eq!(
recorder.total_live_objects(),
borrowed,
"the pass released everything it made, and left the pool's buffers alone"
);
pool.destroy(device.as_ref());
assert_eq!(
recorder.total_live_objects(),
0,
"and the pool's own buffers were still there to release"
);
}
#[test]
fn a_descriptor_with_a_zero_in_it_is_refused() {
let (_recorder, device, _queue) = open();
let pool = pool(device.as_ref(), 8);
let base = SkinningDesc {
label: Some("zero"),
frames: 1,
ranges: 1,
joints: 1,
bindings: 1,
vertices: pool.vertex_buffer(),
attribute_base: pool.attribute_base(),
};
for desc in [
SkinningDesc { frames: 0, ..base },
SkinningDesc { ranges: 0, ..base },
SkinningDesc { joints: 0, ..base },
SkinningDesc {
bindings: 0,
..base
},
] {
let error = Skinning::new(device.as_ref(), &desc).expect_err("a zero is refused");
assert!(matches!(error, SkinningError::Hal(_)), "{error}");
}
}
}