use std::borrow::Cow;
use crcbl_core::{Handle, Pool};
use crcbl_hal::{
BufferHandle, BufferImageCopy, Device, Extent3d, Format, HalError, ImageAspect, ImageCopy,
ImageHandle, ImageSubresourceLayers, ImageUsage, Offset3d, ResourceState,
};
use crcbl_sprite::SampleMode;
use super::{SheetId, SpriteRenderer};
use crate::graph::{ImageId, ImportedImage, InitialClaim, RenderGraph};
use crate::texture::{UploadedTexture, stage_region};
pub const GUTTER: u32 = 1;
pub const ATLAS_FORMAT: Format = Format::Rgba8UnormSrgb;
pub const ATLAS_FORMATS: [Format; 2] = [ATLAS_FORMAT, Format::Bgra8UnormSrgb];
const TEXEL_BYTES: u32 = match ATLAS_FORMAT.texel_size(ImageAspect::COLOR) {
Some(bytes) => bytes,
None => panic!("the atlas format is a single colour plane"),
};
#[derive(Clone, Copy, Debug)]
pub struct AtlasDesc<'a> {
pub label: &'a str,
pub cell: (u32, u32),
pub columns: u32,
pub rows: u32,
pub sample: SampleMode,
pub format: Format,
}
#[derive(Debug)]
enum Cell {}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AtlasSlot {
sheet: SheetId,
cell: Handle<Cell>,
uv: [f32; 4],
}
impl AtlasSlot {
#[must_use]
pub const fn sheet(&self) -> SheetId {
self.sheet
}
#[must_use]
pub const fn uv(&self) -> [f32; 4] {
self.uv
}
#[must_use]
pub const fn index(&self) -> u32 {
self.cell.index()
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SlotCopy {
pub source: ImageId,
pub slot: AtlasSlot,
}
#[derive(Debug, thiserror::Error)]
pub enum SheetError {
#[error("atlas {sheet:?} has all {capacity} of its cells in use")]
AtlasFull {
sheet: SheetId,
capacity: u32,
},
#[error("sheet {sheet:?} is not an atlas of this renderer")]
NotAnAtlas {
sheet: SheetId,
},
#[error("slot {index} of atlas {sheet:?} was freed; this handle no longer owns the cell")]
StaleSlot {
sheet: SheetId,
index: u32,
},
#[error(
"copy into slot {index} of atlas {sheet:?}: the source must be a {cell:?} {format:?} \
image this graph can copy from, and {found}"
)]
SourceMismatch {
sheet: SheetId,
index: u32,
cell: (u32, u32),
format: Format,
found: String,
},
#[error("atlas {label:?} asked for {format:?}, and an atlas is one of {ATLAS_FORMATS:?}")]
AtlasFormat {
label: String,
format: Format,
},
#[error(
"write into slot {index} of atlas {sheet:?}: a {cell:?} cell is {expected} bytes of \
tightly packed {ATLAS_FORMAT:?}, and {found} were given"
)]
PixelsMismatch {
sheet: SheetId,
index: u32,
cell: (u32, u32),
expected: u64,
found: u64,
},
#[error(transparent)]
Hal(#[from] HalError),
}
#[derive(Debug)]
pub(super) struct Atlas {
pub(super) sheet: SheetId,
pub(super) texture: UploadedTexture,
pub(super) extent: (u32, u32),
format: Format,
cell: (u32, u32),
columns: u32,
capacity: u32,
cells: Pool<()>,
}
impl Atlas {
pub(super) fn extent(desc: &AtlasDesc<'_>) -> Result<(u32, u32), HalError> {
let (width, height) = desc.cell;
if width == 0 || height == 0 || desc.columns == 0 || desc.rows == 0 {
return Err(HalError::InvalidDescriptor(format!(
"{}: an atlas needs a non-empty cell and at least one column and one row, \
not a {width}x{height} cell in {} x {}",
desc.label, desc.columns, desc.rows
)));
}
let side = |cell: u32, count: u32| {
(cell.checked_add(GUTTER)?)
.checked_mul(count)?
.checked_add(GUTTER)
};
let capacity = desc.columns.checked_mul(desc.rows);
match (side(width, desc.columns), side(height, desc.rows), capacity) {
(Some(across), Some(down), Some(_)) => Ok((across, down)),
_ => Err(HalError::InvalidDescriptor(format!(
"{}: {} x {} cells of {width}x{height} is past what a u32 extent holds",
desc.label, desc.columns, desc.rows
))),
}
}
pub(super) fn new(
sheet: SheetId,
texture: UploadedTexture,
extent: (u32, u32),
desc: &AtlasDesc<'_>,
) -> Self {
let capacity = desc.columns * desc.rows;
Self {
sheet,
texture,
extent,
format: desc.format,
cell: desc.cell,
columns: desc.columns,
capacity,
cells: Pool::with_capacity(capacity as usize),
}
}
pub(super) fn allocate(&mut self) -> Result<AtlasSlot, SheetError> {
let used = self.cells.len() + self.cells.retired_slots();
if used >= self.capacity as usize {
return Err(SheetError::AtlasFull {
sheet: self.sheet,
capacity: self.capacity,
});
}
let cell = self.cells.insert(()).cast::<Cell>();
Ok(AtlasSlot {
sheet: self.sheet,
cell,
uv: self.uv(cell.index()),
})
}
pub(super) fn free(&mut self, slot: AtlasSlot) -> Result<(), SheetError> {
self.check(slot)?;
self.cells.remove(slot.cell.cast::<()>());
Ok(())
}
pub(super) fn check(&self, slot: AtlasSlot) -> Result<(), SheetError> {
if self.cells.contains(slot.cell.cast::<()>()) {
Ok(())
} else {
Err(SheetError::StaleSlot {
sheet: self.sheet,
index: slot.cell.index(),
})
}
}
fn origin(&self, index: u32) -> (u32, u32) {
let (column, row) = (index % self.columns, index / self.columns);
(
GUTTER + column * (self.cell.0 + GUTTER),
GUTTER + row * (self.cell.1 + GUTTER),
)
}
fn uv(&self, index: u32) -> [f32; 4] {
let (x, y) = self.origin(index);
let (width, height) = (self.extent.0 as f32, self.extent.1 as f32);
[
x as f32 / width,
y as f32 / height,
(x + self.cell.0) as f32 / width,
(y + self.cell.1) as f32 / height,
]
}
pub(super) fn import(&self, graph: &mut RenderGraph<'_>) -> ImageId {
graph.import_image(
"sprite atlas",
ImportedImage {
image: self.texture.image,
view: self.texture.view,
format: self.format,
extent: self.extent,
initial: ResourceState::ShaderRead,
claim: InitialClaim::Tracked,
final_state: ResourceState::ShaderRead,
},
)
}
fn destination(&self, slot: AtlasSlot) -> (ImageHandle, (u32, u32), (u32, u32)) {
(
self.texture.image,
self.origin(slot.cell.index()),
self.cell,
)
}
fn check_source(&self, graph: &RenderGraph<'_>, copy: &SlotCopy) -> Result<(), SheetError> {
let mismatch = |found: String| SheetError::SourceMismatch {
sheet: self.sheet,
index: copy.slot.cell.index(),
cell: self.cell,
format: self.format,
found,
};
let Some((format, extent, usage)) = graph.image_facts(copy.source) else {
return Err(mismatch(format!(
"{:?} is not an image of this graph",
copy.source
)));
};
if format != self.format || extent != self.cell {
return Err(mismatch(format!("it is a {extent:?} {format:?} image")));
}
if usage.is_some_and(|usage| !usage.contains(ImageUsage::TRANSFER_SRC)) {
return Err(mismatch(
"it is a transient created without ImageUsage::TRANSFER_SRC".to_string(),
));
}
Ok(())
}
fn texels_from_rgba<'p>(&self, pixels: &'p [u8]) -> Cow<'p, [u8]> {
if self.format == Format::Bgra8UnormSrgb {
let mut swapped = pixels.to_vec();
for texel in swapped.as_chunks_mut::<{ TEXEL_BYTES as usize }>().0 {
texel.swap(0, 2);
}
Cow::Owned(swapped)
} else {
Cow::Borrowed(pixels)
}
}
fn check_pixels(&self, slot: AtlasSlot, pixels: &[u8]) -> Result<(), SheetError> {
let expected = u64::from(self.cell.0) * u64::from(self.cell.1) * u64::from(TEXEL_BYTES);
let found = pixels.len() as u64;
if found == expected {
Ok(())
} else {
Err(SheetError::PixelsMismatch {
sheet: self.sheet,
index: slot.cell.index(),
cell: self.cell,
expected,
found,
})
}
}
}
#[derive(Debug, Default)]
pub(super) struct WriteStaging {
staged: Vec<(u64, BufferHandle)>,
begun: u64,
}
impl WriteStaging {
fn push(&mut self, buffer: BufferHandle) {
self.staged.push((self.begun, buffer));
}
pub(super) fn advance(&mut self, device: &dyn Device) {
self.begun += 1;
let (now, depth) = (self.begun, super::FRAMES_IN_FLIGHT as u64);
self.staged.retain(|&(at, buffer)| {
let retired = now.saturating_sub(at) > depth;
if retired {
device.destroy_buffer(buffer);
}
!retired
});
}
pub(super) fn destroy(&mut self, device: &dyn Device) {
for (_, buffer) in self.staged.drain(..) {
device.destroy_buffer(buffer);
}
}
}
impl SpriteRenderer {
pub fn create_atlas(
&mut self,
device: &dyn crcbl_hal::Device,
desc: &AtlasDesc<'_>,
) -> Result<SheetId, SheetError> {
if !ATLAS_FORMATS.contains(&desc.format) {
return Err(SheetError::AtlasFormat {
label: desc.label.to_string(),
format: desc.format,
});
}
let extent = Atlas::extent(desc)?;
let texture = crate::texture::upload_cleared_texture(
device,
self.queue,
&crate::texture::ClearedTextureDesc {
label: desc.label,
format: desc.format,
width: extent.0,
height: extent.1,
layers: 1,
view_type: crcbl_hal::ImageViewType::D2,
patches: &[],
},
)?;
let sheet = self.adopt(device, desc.label, texture, extent, desc.sample)?;
self.atlases.push(Atlas::new(sheet, texture, extent, desc));
Ok(sheet)
}
pub fn allocate_slot(&mut self, atlas: SheetId) -> Result<AtlasSlot, SheetError> {
self.atlas_mut(atlas)?.allocate()
}
pub fn free_slot(&mut self, slot: AtlasSlot) -> Result<(), SheetError> {
self.atlas_mut(slot.sheet)?.free(slot)
}
pub fn add_slot_copies(
&self,
graph: &mut RenderGraph<'_>,
copies: &[SlotCopy],
) -> Result<(), SheetError> {
for copy in copies {
let atlas = self.atlas(copy.slot.sheet)?;
atlas.check(copy.slot)?;
atlas.check_source(graph, copy)?;
}
if copies.is_empty() {
return Ok(());
}
let mut sources: Vec<ImageId> = Vec::new();
let mut targets: Vec<ImageId> = Vec::new();
let mut planned = Vec::with_capacity(copies.len());
for copy in copies {
let atlas = self.atlas(copy.slot.sheet)?;
let target = atlas.import(graph);
if !sources.contains(©.source) {
sources.push(copy.source);
}
if !targets.contains(&target) {
targets.push(target);
}
planned.push((copy.source, atlas.destination(copy.slot)));
}
let mut pass = graph.add_copy_pass("sprite atlas copies");
for &source in &sources {
pass = pass.use_image(source, ResourceState::TransferSrc);
}
for &target in &targets {
pass = pass.use_image(target, ResourceState::TransferDst);
}
pass.execute(move |ctx| {
for (source, (atlas, origin, cell)) in planned {
let copy = cell_copy(ctx.image(source), atlas, origin, cell);
ctx.encoder().copy_image_to_image(©);
}
});
Ok(())
}
pub fn write_slot(
&mut self,
device: &dyn Device,
graph: &mut RenderGraph<'_>,
slot: AtlasSlot,
pixels: &[u8],
) -> Result<(), SheetError> {
let atlas = self.atlas(slot.sheet)?;
atlas.check(slot)?;
atlas.check_pixels(slot, pixels)?;
let (image, origin, cell) = atlas.destination(slot);
let texels = atlas.texels_from_rgba(pixels);
let (staging, row_texels) = stage_region(
device,
"sprite atlas write staging",
atlas.format,
cell,
&texels,
)?;
let target = atlas.import(graph);
self.atlas_staging.push(staging);
graph
.add_copy_pass("sprite atlas write")
.use_image(target, ResourceState::TransferDst)
.execute(move |ctx| {
ctx.encoder().copy_buffer_to_image(&BufferImageCopy {
buffer: staging,
buffer_offset: 0,
buffer_row_length: row_texels,
buffer_image_height: cell.1,
image,
image_subresource: COLOR_LAYER,
image_offset: offset(origin),
image_extent: Extent3d::d2(cell.0, cell.1),
});
});
Ok(())
}
fn atlas(&self, sheet: SheetId) -> Result<&Atlas, SheetError> {
self.atlases
.iter()
.find(|atlas| atlas.sheet == sheet)
.ok_or(SheetError::NotAnAtlas { sheet })
}
fn atlas_mut(&mut self, sheet: SheetId) -> Result<&mut Atlas, SheetError> {
self.atlases
.iter_mut()
.find(|atlas| atlas.sheet == sheet)
.ok_or(SheetError::NotAnAtlas { sheet })
}
}
const COLOR_LAYER: ImageSubresourceLayers = ImageSubresourceLayers {
aspect: ImageAspect::COLOR,
mip: 0,
base_layer: 0,
layer_count: 1,
};
const fn offset(origin: (u32, u32)) -> Offset3d {
Offset3d {
x: origin.0 as i32,
y: origin.1 as i32,
z: 0,
}
}
fn cell_copy(
source: ImageHandle,
atlas: ImageHandle,
origin: (u32, u32),
cell: (u32, u32),
) -> ImageCopy {
ImageCopy {
src: source,
src_subresource: COLOR_LAYER,
src_offset: Offset3d::default(),
dst: atlas,
dst_subresource: COLOR_LAYER,
dst_offset: offset(origin),
extent: Extent3d::d2(cell.0, cell.1),
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use crate::sprite_pass::tests::{open, target};
use crate::sprite_pass::{FRAMES_IN_FLIGHT, Sprite};
use crate::transient::{TransientImageDesc, TransientPool};
use crcbl_hal::null::{Command, ObjectKind, Recorder};
use crcbl_hal::{CommandEncoderDesc, Device, QueueHandle};
const CELL: (u32, u32) = (4, 2);
const SOURCE_USAGE: ImageUsage = ImageUsage::COLOR_ATTACHMENT.union(ImageUsage::TRANSFER_SRC);
fn desc(columns: u32, rows: u32) -> AtlasDesc<'static> {
AtlasDesc {
label: "test atlas",
cell: CELL,
columns,
rows,
sample: SampleMode::Smooth,
format: ATLAS_FORMAT,
}
}
fn renderer(device: &dyn Device, queue: QueueHandle) -> SpriteRenderer {
SpriteRenderer::new(device, queue, Format::Bgra8UnormSrgb)
.expect("the null backend builds the pass")
}
fn source(graph: &mut RenderGraph<'_>, extent: (u32, u32), usage: ImageUsage) -> ImageId {
source_in(graph, extent, usage, ATLAS_FORMAT)
}
fn source_in(
graph: &mut RenderGraph<'_>,
extent: (u32, u32),
usage: ImageUsage,
format: Format,
) -> ImageId {
graph.create_image(
"rendered icon",
TransientImageDesc::new(extent, format, usage),
)
}
fn frame(
device: &dyn Device,
queue: QueueHandle,
recorder: &Recorder,
renderer: &mut SpriteRenderer,
slot: AtlasSlot,
) -> Vec<Command> {
run_frame(
device,
queue,
recorder,
renderer,
slot,
Staged::AfterBegin,
|renderer, graph| {
let icon = source(graph, CELL, SOURCE_USAGE);
graph
.add_render_pass("icon")
.clear_color(icon, [1.0, 0.0, 0.0, 1.0])
.execute(|_| {});
renderer
.add_slot_copies(graph, &[SlotCopy { source: icon, slot }])
.expect("a cell-sized source copies");
},
)
}
fn run_frame(
device: &dyn Device,
queue: QueueHandle,
recorder: &Recorder,
renderer: &mut SpriteRenderer,
slot: AtlasSlot,
staged: Staged,
fill: impl FnOnce(&mut SpriteRenderer, &mut RenderGraph<'_>),
) -> Vec<Command> {
let sprites = [Sprite::new(slot.sheet(), [0.0, 0.0, 1.0, 1.0], slot.uv())];
let begin = |renderer: &mut SpriteRenderer| {
renderer
.begin_frame(device, &sprites, glam::Mat4::IDENTITY, (256, 192))
.expect("the ring is writable");
};
let before = recorder.commands().len();
let imported = target(device);
let mut pool = TransientPool::new();
{
let mut graph = RenderGraph::new(queue);
let swap = graph.import_image("swapchain", imported);
match staged {
Staged::AfterBegin => {
begin(renderer);
fill(renderer, &mut graph);
}
Staged::BeforeBegin => {
fill(renderer, &mut graph);
begin(renderer);
}
}
renderer.add_pass(&mut graph, swap);
let compiled = graph.compile(&pool).expect("a legal frame");
let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
label: Some("atlas frame"),
queue,
});
compiled
.execute(device, &mut pool, encoder.as_mut(), None)
.expect("execution succeeded");
let commands = encoder.finish().expect("recording succeeded");
device.destroy_command_buffer(commands);
}
pool.destroy(device);
device.destroy_image_view(imported.view);
device.destroy_image(imported.image);
recorder.commands().split_off(before)
}
#[derive(Clone, Copy, Debug)]
enum Staged {
AfterBegin,
BeforeBegin,
}
fn write_frame(
device: &dyn Device,
queue: QueueHandle,
recorder: &Recorder,
renderer: &mut SpriteRenderer,
slot: AtlasSlot,
staged: Staged,
pixels: &[u8],
) -> Vec<Command> {
run_frame(
device,
queue,
recorder,
renderer,
slot,
staged,
|renderer, graph| {
renderer
.write_slot(device, graph, slot, pixels)
.expect("a cell of pixels writes");
},
)
}
fn cell_pixels(seed: u8) -> Vec<u8> {
(0..CELL.0 * CELL.1 * TEXEL_BYTES)
.map(|byte| seed.wrapping_add(byte as u8))
.collect()
}
fn staged_buffers(commands: &[Command]) -> Vec<BufferHandle> {
commands
.iter()
.filter_map(|command| match command {
Command::CopyBufferToImage(copy) => Some(copy.buffer),
_ => None,
})
.collect()
}
#[test]
fn a_full_atlas_refuses_the_next_slot_and_recovers_when_one_is_freed() {
let recorder = Recorder::new();
let (device, queue) = open(&recorder);
let mut renderer = renderer(device.as_ref(), queue);
let atlas = renderer
.create_atlas(device.as_ref(), &desc(2, 1))
.expect("the atlas is created");
let first = renderer.allocate_slot(atlas).expect("cell 0 is free");
let second = renderer.allocate_slot(atlas).expect("cell 1 is free");
assert_ne!(first.index(), second.index());
match renderer.allocate_slot(atlas) {
Err(SheetError::AtlasFull { sheet, capacity }) => {
assert_eq!(sheet, atlas);
assert_eq!(capacity, 2);
}
other => panic!("a third slot in a two-cell atlas must be AtlasFull, got {other:?}"),
}
renderer.free_slot(first).expect("the slot is live");
let again = renderer
.allocate_slot(atlas)
.expect("the freed cell is handed out again");
assert_eq!(
again.index(),
first.index(),
"the freed cell, not a new one"
);
assert!(
matches!(
renderer.allocate_slot(atlas),
Err(SheetError::AtlasFull { .. })
),
"and the atlas is full again"
);
renderer.destroy(device.as_ref());
}
#[test]
fn a_freed_slot_is_stale_even_after_its_cell_is_reused() {
let recorder = Recorder::new();
let (device, queue) = open(&recorder);
let mut renderer = renderer(device.as_ref(), queue);
let atlas = renderer
.create_atlas(device.as_ref(), &desc(1, 1))
.expect("the atlas is created");
let old = renderer.allocate_slot(atlas).expect("a free cell");
renderer.free_slot(old).expect("the slot is live");
let new = renderer.allocate_slot(atlas).expect("the cell again");
assert_eq!(old.index(), new.index());
assert_ne!(old, new, "a reused cell's slot is a different slot");
assert!(matches!(
renderer.free_slot(old),
Err(SheetError::StaleSlot { index: 0, .. })
));
let mut graph = RenderGraph::new(queue);
let icon = source(&mut graph, CELL, SOURCE_USAGE);
let copy = SlotCopy {
source: icon,
slot: old,
};
assert!(matches!(
renderer.add_slot_copies(&mut graph, &[copy]),
Err(SheetError::StaleSlot { .. })
));
let buffers = recorder.live_objects(ObjectKind::Buffer);
assert!(matches!(
renderer.write_slot(device.as_ref(), &mut graph, old, &cell_pixels(0)),
Err(SheetError::StaleSlot { index: 0, .. })
));
assert_eq!(
recorder.live_objects(ObjectKind::Buffer),
buffers,
"a refused write stages nothing"
);
assert_eq!(
graph.pass_count(),
0,
"a refused copy or write adds no pass"
);
drop(graph);
renderer.destroy(device.as_ref());
}
#[test]
fn a_write_that_is_not_one_cell_of_pixels_is_refused() {
let recorder = Recorder::new();
let (device, queue) = open(&recorder);
let mut renderer = renderer(device.as_ref(), queue);
let atlas = renderer
.create_atlas(device.as_ref(), &desc(1, 1))
.expect("the atlas is created");
let slot = renderer.allocate_slot(atlas).expect("a free cell");
let cell_bytes = (CELL.0 * CELL.1 * TEXEL_BYTES) as usize;
let buffers = recorder.live_objects(ObjectKind::Buffer);
let mut graph = RenderGraph::new(queue);
for len in [cell_bytes - 1, cell_bytes + 4, 0] {
let refused = renderer.write_slot(device.as_ref(), &mut graph, slot, &vec![7; len]);
match refused {
Err(SheetError::PixelsMismatch {
sheet,
index,
cell,
expected,
found,
}) => {
assert_eq!((sheet, index, cell), (atlas, slot.index(), CELL));
assert_eq!((expected, found), (cell_bytes as u64, len as u64));
}
other => panic!("{len} bytes must be PixelsMismatch, got {other:?}"),
}
}
assert_eq!(graph.pass_count(), 0, "a refused write adds no pass");
assert_eq!(
recorder.live_objects(ObjectKind::Buffer),
buffers,
"a refused write stages nothing"
);
drop(graph);
renderer.destroy(device.as_ref());
}
#[test]
fn a_written_cell_is_staged_and_barriered_back_to_sampled_before_the_draw() {
let recorder = Recorder::new();
let (device, queue) = open(&recorder);
let mut renderer = renderer(device.as_ref(), queue);
let atlas = renderer
.create_atlas(device.as_ref(), &desc(2, 1))
.expect("the atlas is created");
let image = renderer.atlases[0].texture.image;
let _first = renderer.allocate_slot(atlas).expect("cell 0");
let second = renderer.allocate_slot(atlas).expect("cell 1");
let pixels = cell_pixels(3);
let commands = write_frame(
device.as_ref(),
queue,
&recorder,
&mut renderer,
second,
Staged::AfterBegin,
&pixels,
);
let position = |wanted: &dyn Fn(&Command) -> bool| {
commands
.iter()
.position(wanted)
.unwrap_or_else(|| panic!("missing from {commands:#?}"))
};
let origin = Offset3d {
x: (GUTTER + CELL.0 + GUTTER) as i32,
y: GUTTER as i32,
z: 0,
};
let copy = position(&|command| {
matches!(command, Command::CopyBufferToImage(copy)
if copy.image == image
&& copy.image_offset == origin
&& copy.image_extent == Extent3d::d2(CELL.0, CELL.1))
});
let Command::CopyBufferToImage(region) = &commands[copy] else {
unreachable!("`position` matched a buffer-to-image copy");
};
let staged = recorder
.buffer_bytes(region.buffer)
.expect("the staging buffer is live while its frame may be in flight");
let row = (CELL.0 * TEXEL_BYTES) as usize;
let pitch = (region.buffer_row_length * TEXEL_BYTES) as usize;
for y in 0..CELL.1 as usize {
assert_eq!(
&staged[y * pitch..y * pitch + row],
&pixels[y * row..(y + 1) * row],
"staged row {y}"
);
}
let sampled = position(&|command| {
matches!(command, Command::Barrier { images, .. }
if images.iter().any(|barrier| barrier.image == image
&& barrier.from == ResourceState::TransferDst
&& barrier.to == ResourceState::ShaderRead))
});
let draw = position(&|command| matches!(command, Command::Draw { .. }));
assert!(
copy < sampled && sampled < draw,
"copy at {copy}, back to ShaderRead at {sampled}, draw at {draw}"
);
renderer.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn write_staging_is_released_by_the_ring_and_by_destroy() {
let recorder = Recorder::new();
let (device, queue) = open(&recorder);
let mut renderer = renderer(device.as_ref(), queue);
let atlas = renderer
.create_atlas(device.as_ref(), &desc(1, 1))
.expect("the atlas is created");
let slot = renderer.allocate_slot(atlas).expect("a free cell");
let draw_only = |renderer: &mut SpriteRenderer| {
run_frame(
device.as_ref(),
queue,
&recorder,
renderer,
slot,
Staged::AfterBegin,
|_, _| {},
)
};
for staged in [Staged::AfterBegin, Staged::BeforeBegin] {
let written = write_frame(
device.as_ref(),
queue,
&recorder,
&mut renderer,
slot,
staged,
&cell_pixels(0),
);
let &[staging] = staged_buffers(&written).as_slice() else {
panic!("one write, one staging buffer: {written:#?}");
};
draw_only(&mut renderer);
assert!(
recorder.buffer_size(staging).is_some(),
"{staged:?}: the next begin_frame must not release a buffer the frame before \
it may still be copying from"
);
for _ in 0..FRAMES_IN_FLIGHT {
draw_only(&mut renderer);
}
assert_eq!(
recorder.buffer_size(staging),
None,
"{staged:?}: the ring has come round past the frame that copied from it"
);
}
let steady = recorder.live_objects(ObjectKind::Buffer);
let bound = FRAMES_IN_FLIGHT + 1;
for round in 0..FRAMES_IN_FLIGHT * 4 {
write_frame(
device.as_ref(),
queue,
&recorder,
&mut renderer,
slot,
Staged::AfterBegin,
&cell_pixels(round as u8),
);
let held = recorder.live_objects(ObjectKind::Buffer) - steady;
assert!(held <= bound, "round {round} holds {held} staging buffers");
}
renderer.destroy(device.as_ref());
assert_eq!(
recorder.live_objects(ObjectKind::Buffer),
0,
"destroy releases the staging still held"
);
recorder.assert_valid();
}
#[test]
fn a_source_that_is_not_the_cell_is_refused_before_anything_is_added() {
let recorder = Recorder::new();
let (device, queue) = open(&recorder);
let mut renderer = renderer(device.as_ref(), queue);
let pixels = [255u8; 2 * 2 * 4];
let sheet = renderer
.register_sheet(
device.as_ref(),
&super::super::SheetDesc {
label: "uploaded",
width: 2,
height: 2,
sample: SampleMode::Pixel,
pixels: &pixels,
},
)
.expect("the upload succeeds");
assert!(matches!(
renderer.allocate_slot(sheet),
Err(SheetError::NotAnAtlas { .. })
));
let atlas = renderer
.create_atlas(device.as_ref(), &desc(1, 1))
.expect("the atlas is created");
let slot = renderer.allocate_slot(atlas).expect("a free cell");
let mut graph = RenderGraph::new(queue);
let too_big = source(&mut graph, (CELL.0 + 1, CELL.1), SOURCE_USAGE);
let no_copy = source(&mut graph, CELL, ImageUsage::COLOR_ATTACHMENT);
for bad in [too_big, no_copy] {
let copy = SlotCopy { source: bad, slot };
let refused = renderer.add_slot_copies(&mut graph, &[copy]);
assert!(
matches!(refused, Err(SheetError::SourceMismatch { .. })),
"{refused:?}"
);
}
assert_eq!(graph.pass_count(), 0, "a refused copy adds no pass");
drop(graph);
renderer.destroy(device.as_ref());
}
#[test]
fn every_atlas_format_is_four_bytes_a_texel() {
for format in ATLAS_FORMATS {
assert_eq!(
format.texel_size(ImageAspect::COLOR),
Some(TEXEL_BYTES),
"{format:?}"
);
assert!(format.is_srgb(), "{format:?} is sampled into linear light");
}
}
#[test]
fn an_atlas_in_a_format_outside_the_list_is_refused_and_creates_nothing() {
let recorder = Recorder::new();
let (device, queue) = open(&recorder);
let mut renderer = renderer(device.as_ref(), queue);
let images = recorder.live_objects(ObjectKind::Image);
for format in [Format::Rgba8Unorm, Format::Bgra8Unorm, Format::Rgba16Float] {
let refused = renderer.create_atlas(
device.as_ref(),
&AtlasDesc {
format,
..desc(1, 1)
},
);
assert!(
matches!(
refused,
Err(SheetError::AtlasFormat { format: named, .. }) if named == format
),
"{format:?}: {refused:?}"
);
}
assert_eq!(
recorder.live_objects(ObjectKind::Image),
images,
"a refused atlas creates no image"
);
for format in ATLAS_FORMATS {
let atlas = renderer
.create_atlas(
device.as_ref(),
&AtlasDesc {
format,
..desc(1, 1)
},
)
.unwrap_or_else(|error| panic!("{format:?} is an atlas format: {error}"));
let mut graph = RenderGraph::new(queue);
let imported = renderer
.atlas(atlas)
.expect("just created")
.import(&mut graph);
assert_eq!(
graph.image_facts(imported).map(|(format, _, _)| format),
Some(format),
"every graph that copies into the atlas or samples it is told its own format"
);
}
renderer.destroy(device.as_ref());
}
#[test]
fn a_copy_source_must_match_the_atlas_s_own_format() {
let recorder = Recorder::new();
let (device, queue) = open(&recorder);
let mut renderer = renderer(device.as_ref(), queue);
for (atlas_format, other) in [
(Format::Bgra8UnormSrgb, Format::Rgba8UnormSrgb),
(Format::Rgba8UnormSrgb, Format::Bgra8UnormSrgb),
] {
let atlas = renderer
.create_atlas(
device.as_ref(),
&AtlasDesc {
format: atlas_format,
..desc(1, 1)
},
)
.expect("an atlas format");
let slot = renderer.allocate_slot(atlas).expect("a free cell");
let mut graph = RenderGraph::new(queue);
let wrong = source_in(&mut graph, CELL, SOURCE_USAGE, other);
let refused = renderer.add_slot_copies(
&mut graph,
&[SlotCopy {
source: wrong,
slot,
}],
);
assert!(
matches!(
refused,
Err(SheetError::SourceMismatch { format, .. }) if format == atlas_format
),
"a {other:?} source into a {atlas_format:?} atlas: {refused:?}"
);
assert_eq!(graph.pass_count(), 0, "a refused copy adds no pass");
let right = source_in(&mut graph, CELL, SOURCE_USAGE, atlas_format);
renderer
.add_slot_copies(
&mut graph,
&[SlotCopy {
source: right,
slot,
}],
)
.unwrap_or_else(|error| panic!("a {atlas_format:?} source copies: {error}"));
assert_eq!(graph.pass_count(), 1, "the matching source copies");
}
renderer.destroy(device.as_ref());
}
#[test]
fn a_write_into_a_bgra_atlas_stages_its_pixels_swizzled() {
let recorder = Recorder::new();
let (device, queue) = open(&recorder);
let mut renderer = renderer(device.as_ref(), queue);
let pixels = cell_pixels(9);
let swapped: Vec<u8> = pixels
.as_chunks::<{ TEXEL_BYTES as usize }>()
.0
.iter()
.flat_map(|texel| [texel[2], texel[1], texel[0], texel[3]])
.collect();
for (format, expected) in [
(Format::Bgra8UnormSrgb, &swapped),
(Format::Rgba8UnormSrgb, &pixels),
] {
let atlas = renderer
.create_atlas(
device.as_ref(),
&AtlasDesc {
format,
..desc(1, 1)
},
)
.expect("an atlas format");
let slot = renderer.allocate_slot(atlas).expect("a free cell");
let commands = write_frame(
device.as_ref(),
queue,
&recorder,
&mut renderer,
slot,
Staged::AfterBegin,
&pixels,
);
let &[staging] = staged_buffers(&commands).as_slice() else {
panic!("one write, one staging buffer: {commands:#?}");
};
let region = commands
.iter()
.find_map(|command| match command {
Command::CopyBufferToImage(copy) if copy.buffer == staging => Some(copy),
_ => None,
})
.expect("the write's copy");
let staged = recorder.buffer_bytes(staging).expect("still held");
let row = (CELL.0 * TEXEL_BYTES) as usize;
let pitch = (region.buffer_row_length * TEXEL_BYTES) as usize;
for y in 0..CELL.1 as usize {
assert_eq!(
&staged[y * pitch..y * pitch + row],
&expected[y * row..(y + 1) * row],
"{format:?}: staged row {y}"
);
}
}
renderer.destroy(device.as_ref());
}
#[test]
fn slots_sit_inside_a_one_texel_gutter() {
let recorder = Recorder::new();
let (device, queue) = open(&recorder);
let mut renderer = renderer(device.as_ref(), queue);
assert_eq!(Atlas::extent(&desc(2, 1)).expect("a valid grid"), (11, 4));
let atlas = renderer
.create_atlas(device.as_ref(), &desc(2, 1))
.expect("the atlas is created");
let first = renderer.allocate_slot(atlas).expect("cell 0");
let second = renderer.allocate_slot(atlas).expect("cell 1");
assert_eq!(first.uv(), [1.0 / 11.0, 0.25, 5.0 / 11.0, 0.75]);
assert_eq!(second.uv(), [6.0 / 11.0, 0.25, 10.0 / 11.0, 0.75]);
assert!(matches!(
renderer.create_atlas(device.as_ref(), &desc(0, 1)),
Err(SheetError::Hal(HalError::InvalidDescriptor(_)))
));
renderer.destroy(device.as_ref());
}
#[test]
fn a_copied_cell_is_barriered_back_to_sampled_before_the_draw() {
let recorder = Recorder::new();
let (device, queue) = open(&recorder);
let mut renderer = renderer(device.as_ref(), queue);
let atlas = renderer
.create_atlas(device.as_ref(), &desc(2, 1))
.expect("the atlas is created");
let image = renderer.atlases[0].texture.image;
let _first = renderer.allocate_slot(atlas).expect("cell 0");
let second = renderer.allocate_slot(atlas).expect("cell 1");
let commands = frame(device.as_ref(), queue, &recorder, &mut renderer, second);
let position = |wanted: &dyn Fn(&Command) -> bool| {
commands
.iter()
.position(wanted)
.unwrap_or_else(|| panic!("missing from {commands:#?}"))
};
let origin = Offset3d {
x: (GUTTER + CELL.0 + GUTTER) as i32,
y: GUTTER as i32,
z: 0,
};
let copy = position(&|command| {
matches!(command, Command::CopyImageToImage(copy)
if copy.dst == image
&& copy.dst_offset == origin
&& copy.extent == Extent3d::d2(CELL.0, CELL.1))
});
let sampled = position(&|command| {
matches!(command, Command::Barrier { images, .. }
if images.iter().any(|barrier| barrier.image == image
&& barrier.from == ResourceState::TransferDst
&& barrier.to == ResourceState::ShaderRead))
});
let draw = position(&|command| matches!(command, Command::Draw { .. }));
assert!(
copy < sampled && sampled < draw,
"copy at {copy}, back to ShaderRead at {sampled}, draw at {draw}"
);
renderer.destroy(device.as_ref());
}
#[test]
fn freeing_and_refilling_a_slot_destroys_no_image() {
let recorder = Recorder::new();
let (device, queue) = open(&recorder);
let mut renderer = renderer(device.as_ref(), queue);
let atlas = renderer
.create_atlas(device.as_ref(), &desc(1, 1))
.expect("the atlas is created");
let slot = renderer.allocate_slot(atlas).expect("a free cell");
frame(device.as_ref(), queue, &recorder, &mut renderer, slot);
let images = recorder.live_objects(ObjectKind::Image);
renderer.free_slot(slot).expect("the slot is live");
let refilled = renderer.allocate_slot(atlas).expect("the cell again");
let commands = frame(device.as_ref(), queue, &recorder, &mut renderer, refilled);
assert_eq!(
recorder.live_objects(ObjectKind::Image),
images,
"a free and a refill neither create nor destroy an image"
);
assert!(
commands
.iter()
.any(|command| matches!(command, Command::CopyImageToImage(_))),
"the refill is a copy in the next frame"
);
renderer.destroy(device.as_ref());
assert_eq!(
recorder.live_objects(ObjectKind::Image),
0,
"destroy releases the atlas"
);
}
}