use core::fmt;
use std::collections::HashMap;
use glam::Vec2;
use crate::widget::SkinInsets;
pub const PAGE_SIZE: u32 = 1024;
pub const GUTTER: u32 = 1;
const TEXEL_BYTES: usize = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ImageId(u32);
impl ImageId {
#[must_use]
pub const fn index(self) -> u32 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TextureId(u32);
impl TextureId {
#[must_use]
pub const fn new(index: u32) -> Self {
Self(index)
}
#[must_use]
pub const fn index(self) -> u32 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AtlasImage {
pub id: ImageId,
pub x: u32,
pub y: u32,
pub width: u32,
pub height: u32,
}
impl AtlasImage {
#[must_use]
pub fn uv(&self, texel: Vec2) -> Vec2 {
let page = PAGE_SIZE as f32;
Vec2::new(
(self.x as f32 + texel.x) / page,
(self.y as f32 + texel.y) / page,
)
}
#[must_use]
pub fn uv_min(&self) -> Vec2 {
self.uv(Vec2::ZERO)
}
#[must_use]
pub fn uv_max(&self) -> Vec2 {
self.uv(self.size())
}
#[must_use]
pub fn size(&self) -> Vec2 {
Vec2::new(self.width as f32, self.height as f32)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NineSliceImage {
pub image: AtlasImage,
pub insets: SkinInsets,
}
impl NineSliceImage {
#[must_use]
pub fn clamped_insets(&self) -> SkinInsets {
let (width, height) = (self.image.width as f32, self.image.height as f32);
let fit = |inset: f32, room: f32| inset.max(0.0).min(room);
let left = fit(self.insets.left, width);
let top = fit(self.insets.top, height);
SkinInsets::new(
left,
fit(self.insets.right, width - left),
top,
fit(self.insets.bottom, height - top),
)
}
}
#[must_use]
pub fn slice_bands(low: f32, high: f32, extent: f32) -> [f32; 3] {
if extent.is_nan() || extent <= 0.0 {
return [0.0; 3];
}
let fixed = low + high;
if extent < fixed {
let low = low * (extent / fixed);
return [low, 0.0, extent - low];
}
[low, extent - fixed, high]
}
#[must_use]
pub fn slice_cuts(origin: f32, bands: [f32; 3], extent: f32) -> [f32; 4] {
[
origin,
origin + bands[0],
origin + bands[0] + bands[1],
origin + extent,
]
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TexelRect {
pub x: u32,
pub y: u32,
pub width: u32,
pub height: u32,
}
impl TexelRect {
#[must_use]
pub fn union(self, other: Self) -> Self {
let x = self.x.min(other.x);
let y = self.y.min(other.y);
let right = (self.x + self.width).max(other.x + other.width);
let bottom = (self.y + self.height).max(other.y + other.height);
Self {
x,
y,
width: right - x,
height: bottom - y,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AtlasError {
Empty,
PixelCount {
expected: usize,
actual: usize,
},
Full {
width: u32,
height: u32,
},
}
impl fmt::Display for AtlasError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => f.write_str("an image with no texels cannot be registered"),
Self::PixelCount { expected, actual } => write!(
f,
"the image's extent implies {expected} bytes of RGBA8 and {actual} arrived"
),
Self::Full { width, height } => write!(
f,
"the {PAGE_SIZE}x{PAGE_SIZE} image atlas has no room for a {width}x{height} \
image and its gutter"
),
}
}
}
impl std::error::Error for AtlasError {}
#[derive(Debug, Clone)]
struct Shelf {
y: u32,
height: u32,
cursor: u32,
free: Vec<(u32, u32)>,
}
impl Shelf {
fn claim(&mut self, width: u32) -> Option<u32> {
if let Some(at) = self.free.iter().position(|&(_, span)| span >= width) {
let (x, span) = self.free[at];
if span == width {
self.free.remove(at);
} else {
self.free[at] = (x + width, span - width);
}
return Some(x);
}
(PAGE_SIZE - self.cursor >= width).then(|| {
let x = self.cursor;
self.cursor += width;
x
})
}
fn free(&mut self, x: u32, width: u32) {
let at = self.free.partition_point(|&(start, _)| start < x);
let (mut x, mut width) = (x, width);
if at < self.free.len() && x + width == self.free[at].0 {
width += self.free.remove(at).1;
}
if at > 0 && self.free[at - 1].0 + self.free[at - 1].1 == x {
let (start, span) = self.free.remove(at - 1);
x = start;
width += span;
}
if x + width == self.cursor {
self.cursor = x;
} else {
let at = self.free.partition_point(|&(start, _)| start < x);
self.free.insert(at, (x, width));
}
}
}
#[derive(Clone)]
pub struct ImageAtlas {
pixels: Vec<u8>,
images: Vec<AtlasImage>,
next_id: u32,
shelves: Vec<Shelf>,
dirty: Option<TexelRect>,
evictable: HashMap<ImageId, u64>,
frame: u64,
}
impl fmt::Debug for ImageAtlas {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ImageAtlas")
.field("images", &self.images)
.field("shelves", &self.shelves.len())
.field("dirty", &self.dirty)
.field("evictable", &self.evictable.len())
.finish_non_exhaustive()
}
}
impl Default for ImageAtlas {
fn default() -> Self {
Self::new()
}
}
impl ImageAtlas {
#[must_use]
pub fn new() -> Self {
Self {
pixels: vec![0; PAGE_SIZE as usize * PAGE_SIZE as usize * TEXEL_BYTES],
images: Vec::new(),
next_id: 0,
shelves: Vec::new(),
dirty: None,
evictable: HashMap::new(),
frame: 0,
}
}
pub fn begin_frame(&mut self) {
self.frame += 1;
}
pub fn register_evictable(
&mut self,
width: u32,
height: u32,
pixels: &[u8],
) -> Result<AtlasImage, AtlasError> {
let image = self.register(width, height, pixels)?;
self.evictable.insert(image.id, self.frame);
Ok(image)
}
pub fn touch(&mut self, id: ImageId) -> Option<AtlasImage> {
let image = self.image(id)?;
if let Some(last_used) = self.evictable.get_mut(&id) {
*last_used = self.frame;
}
Some(image)
}
pub fn register(
&mut self,
width: u32,
height: u32,
pixels: &[u8],
) -> Result<AtlasImage, AtlasError> {
if width == 0 || height == 0 {
return Err(AtlasError::Empty);
}
let expected = width as usize * height as usize * TEXEL_BYTES;
if pixels.len() != expected {
return Err(AtlasError::PixelCount {
expected,
actual: pixels.len(),
});
}
let full = AtlasError::Full { width, height };
let padded_width = width.checked_add(2 * GUTTER).ok_or(full)?;
let padded_height = height.checked_add(2 * GUTTER).ok_or(full)?;
let id = ImageId(self.next_id);
let next_id = self.next_id.checked_add(1).ok_or(full)?;
let (shelf_x, shelf_y) = self
.place_evicting(padded_width, padded_height)
.ok_or(full)?;
self.next_id = next_id;
let image = AtlasImage {
id,
x: shelf_x + GUTTER,
y: shelf_y + GUTTER,
width,
height,
};
self.blit(&image, pixels);
self.images.push(image);
let covered = TexelRect {
x: shelf_x,
y: shelf_y,
width: padded_width,
height: padded_height,
};
self.dirty = Some(self.dirty.map_or(covered, |dirty| dirty.union(covered)));
Ok(image)
}
fn place_evicting(&mut self, width: u32, height: u32) -> Option<(u32, u32)> {
loop {
if let Some(placed) = self.place(width, height) {
return Some(placed);
}
if width > PAGE_SIZE || height > PAGE_SIZE {
return None;
}
let oldest = self
.evictable
.iter()
.filter(|&(_, &last_used)| last_used < self.frame)
.min_by_key(|&(id, &last_used)| (last_used, id.0))
.map(|(&id, _)| id)?;
self.unregister(oldest);
}
}
fn place(&mut self, width: u32, height: u32) -> Option<(u32, u32)> {
if width > PAGE_SIZE || height > PAGE_SIZE {
return None;
}
for shelf in self
.shelves
.iter_mut()
.filter(|shelf| shelf.height >= height)
{
if let Some(x) = shelf.claim(width) {
return Some((x, shelf.y));
}
}
let top = self
.shelves
.last()
.map_or(0, |shelf| shelf.y + shelf.height);
if PAGE_SIZE - top < height {
return None;
}
self.shelves.push(Shelf {
y: top,
height,
cursor: width,
free: Vec::new(),
});
Some((0, top))
}
pub fn unregister(&mut self, id: ImageId) -> Option<AtlasImage> {
let at = self
.images
.binary_search_by_key(&id.0, |image| image.id.0)
.ok()?;
let image = self.images.remove(at);
self.evictable.remove(&id);
let shelf = self
.shelves
.iter_mut()
.find(|shelf| shelf.y == image.y - GUTTER)
.expect("every image sits on the shelf it was placed on");
shelf.free(image.x - GUTTER, image.width + 2 * GUTTER);
while self.shelves.last().is_some_and(|shelf| shelf.cursor == 0) {
self.shelves.pop();
}
Some(image)
}
fn blit(&mut self, image: &AtlasImage, pixels: &[u8]) {
let page = PAGE_SIZE as usize;
let (x0, y0) = (image.x as usize, image.y as usize);
let (width, height) = (image.width as usize, image.height as usize);
let gutter = GUTTER as usize;
for row in 0..height + 2 * gutter {
let source_row = row.saturating_sub(gutter).min(height - 1);
for column in 0..width + 2 * gutter {
let source_column = column.saturating_sub(gutter).min(width - 1);
let source = (source_row * width + source_column) * TEXEL_BYTES;
let target = ((y0 - gutter + row) * page + (x0 - gutter + column)) * TEXEL_BYTES;
self.pixels[target..target + TEXEL_BYTES]
.copy_from_slice(&pixels[source..source + TEXEL_BYTES]);
}
}
}
#[must_use]
pub fn image(&self, id: ImageId) -> Option<AtlasImage> {
self.images
.binary_search_by_key(&id.0, |image| image.id.0)
.ok()
.map(|at| self.images[at])
}
#[must_use]
pub fn images(&self) -> &[AtlasImage] {
&self.images
}
#[must_use]
pub fn pixels(&self) -> &[u8] {
&self.pixels
}
#[must_use]
pub const fn dirty(&self) -> Option<TexelRect> {
self.dirty
}
pub fn take_dirty(&mut self) -> Option<TexelRect> {
self.dirty.take()
}
pub fn mark_dirty(&mut self, rect: TexelRect) {
self.dirty = Some(self.dirty.map_or(rect, |dirty| dirty.union(rect)));
}
#[must_use]
pub fn region(&self, rect: TexelRect) -> Vec<u8> {
let page = PAGE_SIZE as usize;
let row_bytes = rect.width as usize * TEXEL_BYTES;
let mut out = Vec::with_capacity(row_bytes * rect.height as usize);
for row in rect.y as usize..(rect.y + rect.height) as usize {
let start = (row * page + rect.x as usize) * TEXEL_BYTES;
out.extend_from_slice(&self.pixels[start..start + row_bytes]);
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn numbered(width: u32, height: u32) -> Vec<u8> {
let mut pixels = Vec::new();
for y in 0..height {
for x in 0..width {
pixels.extend_from_slice(&[x as u8, y as u8, 200, 255]);
}
}
pixels
}
fn texel(atlas: &ImageAtlas, x: u32, y: u32) -> [u8; 4] {
let at = ((y * PAGE_SIZE + x) * 4) as usize;
atlas.pixels()[at..at + 4]
.try_into()
.expect("four channels")
}
#[test]
fn a_registered_image_is_on_the_page_where_it_says() {
let mut atlas = ImageAtlas::new();
let first = atlas.register(3, 2, &numbered(3, 2)).expect("fits");
let second = atlas.register(5, 4, &numbered(5, 4)).expect("fits");
assert_eq!(first.id.index(), 0);
assert_eq!(second.id.index(), 1);
assert_eq!(atlas.image(second.id), Some(second));
for image in [first, second] {
for y in 0..image.height {
for x in 0..image.width {
assert_eq!(
texel(&atlas, image.x + x, image.y + y),
[x as u8, y as u8, 200, 255],
"image {:?} texel ({x}, {y})",
image.id
);
}
}
}
assert!(
second.x >= first.x + first.width + 2 * GUTTER
|| second.y >= first.y + first.height + 2 * GUTTER,
"{first:?} {second:?}"
);
}
#[test]
fn the_gutter_repeats_the_images_own_edge() {
let mut atlas = ImageAtlas::new();
let image = atlas.register(4, 3, &numbered(4, 3)).expect("fits");
let (x0, y0) = (image.x, image.y);
let (x1, y1) = (image.x + image.width - 1, image.y + image.height - 1);
assert_eq!(texel(&atlas, x0 - 1, y0 + 1), texel(&atlas, x0, y0 + 1));
assert_eq!(texel(&atlas, x1 + 1, y0 + 2), texel(&atlas, x1, y0 + 2));
assert_eq!(texel(&atlas, x0 + 2, y0 - 1), texel(&atlas, x0 + 2, y0));
assert_eq!(texel(&atlas, x0 + 3, y1 + 1), texel(&atlas, x0 + 3, y1));
assert_eq!(texel(&atlas, x0 - 1, y0 - 1), texel(&atlas, x0, y0));
assert_eq!(texel(&atlas, x1 + 1, y1 + 1), texel(&atlas, x1, y1));
assert_eq!(texel(&atlas, x0 - 1, y0 - 1)[3], 255);
assert_eq!(texel(&atlas, x1 + 3, y1 + 3), [0; 4]);
}
#[test]
fn uvs_land_exactly_on_texel_centres_and_boundaries() {
let mut atlas = ImageAtlas::new();
atlas.register(7, 9, &numbered(7, 9)).expect("fits");
let image = atlas.register(13, 5, &numbered(13, 5)).expect("fits");
let page = PAGE_SIZE as f32;
for y in 0..image.height {
for x in 0..image.width {
let centre = image.uv(Vec2::new(x as f32 + 0.5, y as f32 + 0.5));
assert_eq!(
centre * page,
Vec2::new((image.x + x) as f32 + 0.5, (image.y + y) as f32 + 0.5),
"texel ({x}, {y})"
);
}
}
assert_eq!(
image.uv_min() * page,
Vec2::new(image.x as f32, image.y as f32)
);
assert_eq!(
image.uv_max() * page,
Vec2::new((image.x + 13) as f32, (image.y + 5) as f32)
);
}
#[test]
fn a_taller_image_opens_a_shelf_below_rather_than_overlapping() {
let mut atlas = ImageAtlas::new();
let short = atlas.register(10, 4, &numbered(10, 4)).expect("fits");
let tall = atlas.register(10, 20, &numbered(10, 20)).expect("fits");
assert!(
tall.y >= short.y + short.height + GUTTER,
"a 20-tall image cannot sit on a 6-tall shelf: {short:?} {tall:?}"
);
let again = atlas.register(10, 4, &numbered(10, 4)).expect("fits");
assert_eq!(again.y, short.y);
}
#[test]
fn a_full_page_refuses_rather_than_panicking_and_changes_nothing() {
let mut atlas = ImageAtlas::new();
let side = PAGE_SIZE - 2 * GUTTER;
atlas
.register(side, side, &vec![255; (side * side * 4) as usize])
.expect("exactly the page, gutters included");
let before = (atlas.images().len(), atlas.dirty());
assert_eq!(
atlas.register(1, 1, &[1, 2, 3, 4]),
Err(AtlasError::Full {
width: 1,
height: 1
})
);
assert_eq!((atlas.images().len(), atlas.dirty()), before);
let mut fresh = ImageAtlas::new();
let over = PAGE_SIZE - 1;
assert!(matches!(
fresh.register(over, 1, &vec![0; (over * 4) as usize]),
Err(AtlasError::Full { .. })
));
assert!(fresh.images().is_empty());
}
#[test]
fn a_malformed_image_is_refused() {
let mut atlas = ImageAtlas::new();
assert_eq!(atlas.register(0, 4, &[]), Err(AtlasError::Empty));
assert_eq!(
atlas.register(2, 2, &[0; 15]),
Err(AtlasError::PixelCount {
expected: 16,
actual: 15
})
);
assert!(atlas.images().is_empty());
assert_eq!(atlas.dirty(), None);
}
fn filled(side: u32) -> (ImageAtlas, Vec<AtlasImage>) {
let padded = side + 2 * GUTTER;
assert_eq!(PAGE_SIZE % padded, 0, "the images tile the page");
let mut atlas = ImageAtlas::new();
let count = (PAGE_SIZE / padded).pow(2);
let images = (0..count)
.map(|_| {
atlas
.register(side, side, &numbered(side, side))
.expect("fits")
})
.collect();
assert!(matches!(
atlas.register(1, 1, &[0; 4]),
Err(AtlasError::Full { .. })
));
(atlas, images)
}
#[test]
fn an_unregistered_image_gives_its_space_to_the_next_and_its_id_to_none() {
let side = 62;
let (mut atlas, images) = filled(side);
let gone = images[images.len() / 2];
let kept = images[images.len() / 2 + 1];
assert_eq!(atlas.unregister(gone.id), Some(gone));
assert_eq!(atlas.image(gone.id), None);
assert_eq!(atlas.unregister(gone.id), None, "only once");
assert_eq!(atlas.image(kept.id), Some(kept), "the rest are still found");
assert_eq!(atlas.images().len(), images.len() - 1);
assert!(!atlas.images().contains(&gone));
let new = atlas
.register(side, side, &numbered(side, side))
.expect("the freed space");
assert_eq!((new.x, new.y), (gone.x, gone.y));
assert!(new.id.index() > images.last().expect("filled").id.index());
assert_eq!(atlas.image(new.id), Some(new));
assert_eq!(
atlas.image(gone.id),
None,
"the new image took the space, not the id"
);
}
#[test]
fn neighbouring_free_spans_join_into_room_for_a_wider_image() {
let side = 62;
let padded = side + 2 * GUTTER;
let (mut atlas, images) = filled(side);
atlas.unregister(images[1].id).expect("held");
atlas.unregister(images[0].id).expect("held");
let wide = 2 * padded - 2 * GUTTER;
let joined = atlas
.register(wide, side, &numbered(wide, side))
.expect("the two spans as one");
assert_eq!((joined.x, joined.y), (images[0].x, images[0].y));
atlas.unregister(joined.id).expect("held");
let left = atlas
.register(side, side, &numbered(side, side))
.expect("fits");
let right = atlas
.register(side, side, &numbered(side, side))
.expect("fits");
assert_eq!(
[(left.x, left.y), (right.x, right.y)],
[(images[0].x, images[0].y), (images[1].x, images[1].y)]
);
let per_shelf = (PAGE_SIZE / padded) as usize;
atlas.unregister(images[per_shelf - 2].id).expect("held");
atlas.unregister(images[per_shelf - 1].id).expect("held");
let at_end = atlas
.register(wide, side, &numbered(wide, side))
.expect("the shelf's end");
assert_eq!((at_end.x, at_end.y), (images[per_shelf - 2].x, images[0].y));
}
#[test]
fn emptying_the_last_shelf_frees_its_rows_for_a_taller_image() {
let mut atlas = ImageAtlas::new();
let rest = PAGE_SIZE - 2 * GUTTER;
let top = atlas
.register(rest, rest - 10, &vec![9; (rest * (rest - 10) * 4) as usize])
.expect("fits");
let low = atlas.register(4, 4, &numbered(4, 4)).expect("fits below");
assert!(
matches!(
atlas.register(4, 7, &numbered(4, 7)),
Err(AtlasError::Full { .. })
),
"taller than the low shelf, and no rows left under it"
);
atlas.unregister(low.id).expect("held");
let tall = atlas
.register(4, 7, &numbered(4, 7))
.expect("the closed shelf's rows");
assert_eq!(tall.y, top.y + top.height + 2 * GUTTER);
}
#[test]
fn the_dirty_rectangle_is_what_changed_and_taking_it_clears_it() {
let mut atlas = ImageAtlas::new();
assert_eq!(atlas.dirty(), None, "a fresh page owes no upload");
let a = atlas.register(6, 3, &numbered(6, 3)).expect("fits");
let b = atlas.register(2, 8, &numbered(2, 8)).expect("fits");
let dirty = atlas.take_dirty().expect("two images changed the page");
for image in [a, b] {
assert!(dirty.x + GUTTER <= image.x && dirty.y + GUTTER <= image.y);
assert!(image.x + image.width + GUTTER <= dirty.x + dirty.width);
assert!(image.y + image.height + GUTTER <= dirty.y + dirty.height);
}
assert_eq!(atlas.dirty(), None);
let region = atlas.region(dirty);
assert_eq!(region.len(), (dirty.width * dirty.height * 4) as usize);
let row = (b.y - dirty.y) as usize;
let column = (b.x - dirty.x) as usize;
let at = (row * dirty.width as usize + column) * 4;
assert_eq!(®ion[at..at + 4], &[0, 0, 200, 255]);
atlas.mark_dirty(dirty);
assert_eq!(
atlas.dirty(),
Some(dirty),
"an unrecorded upload comes back"
);
}
#[test]
fn evictable_images_give_way_oldest_first_and_only_when_unused() {
let side = 62;
let padded = side + 2 * GUTTER;
assert_eq!(PAGE_SIZE % padded, 0, "the images tile the page");
let pixels = numbered(side, side);
let mut atlas = ImageAtlas::new();
let places = (PAGE_SIZE / padded).pow(2) as usize;
let kept: Vec<AtlasImage> = (0..places - 2)
.map(|_| atlas.register(side, side, &pixels).expect("fits"))
.collect();
atlas.begin_frame();
let older = atlas.register_evictable(side, side, &pixels).expect("fits");
atlas.begin_frame();
let newer = atlas.register_evictable(side, side, &pixels).expect("fits");
atlas.begin_frame();
assert_eq!(atlas.touch(newer.id), Some(newer));
let first = atlas
.register(side, side, &pixels)
.expect("the older gives way");
assert_eq!((first.x, first.y), (older.x, older.y));
assert_eq!(atlas.touch(older.id), None, "evicted");
assert_eq!(
atlas.register(side, side, &pixels),
Err(AtlasError::Full {
width: side,
height: side
}),
"the newer was touched this frame"
);
assert_eq!(atlas.image(newer.id), Some(newer));
atlas.begin_frame();
let second = atlas
.register_evictable(side, side, &pixels)
.expect("the newer gives way, to an evictable image too");
assert_eq!((second.x, second.y), (newer.x, newer.y));
atlas.begin_frame();
let third = atlas.register(side, side, &pixels).expect("then that one");
assert!(matches!(
atlas.register(side, side, &pixels),
Err(AtlasError::Full { .. })
));
for image in kept.iter().chain([&first, &third]) {
assert_eq!(atlas.image(image.id), Some(*image), "never evicted");
}
}
}