Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

18.1 KB
Raw Blame
// Copyright 2022 the Vello Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT

use guillotiere::{AllocId, AtlasAllocator, size2};
use peniko::ImageData;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::atomic::{AtomicI32, Ordering};

const DEFAULT_ATLAS_SIZE: i32 = 1024;
/// raea: the atlas's largest side, Vello's 8192 unless the renderer's device can make a larger texture
/// (`set_max_atlas_size`). Every filtered element is an image in the atlas, and 8192 held six full-frame layers of a
/// 2160x3840 page, so a page with a seventh was refused (#125); 16384 holds 28.
static MAX_ATLAS_SIZE: AtomicI32 = AtomicI32::new(8192);

/// raea: the side image atlases made now grow to (`set_max_atlas_size`)
pub fn max_atlas_size() -> u32 {
    MAX_ATLAS_SIZE.load(Ordering::Relaxed) as u32
}

/// raea: lets image atlases made after this grow to `px` a side (the device's `max_texture_dimension_2d`): the
/// largest power of two up to it, from 1024 to 16384 (a full 16384 atlas is 1 GiB, made only when a page needs it).
pub fn set_max_atlas_size(px: u32) {
    let px = px.clamp(DEFAULT_ATLAS_SIZE as u32, 16384);
    MAX_ATLAS_SIZE.store(1 << (31 - px.leading_zeros()), Ordering::Relaxed);
}
const EVICT_AFTER_GENERATIONS: u64 = 2;

#[derive(Default)]
pub struct Images<'a> {
    /// Width of the square image atlas texture.
    pub width: u32,
    /// Height of the square image atlas texture.
    pub height: u32,
    /// Number of resident images evicted during the current resolve pass.
    ///
    /// This is only used for renderer-side debug logging.
    pub evicted: usize,
    /// Images that must be uploaded in the current resolve pass, with atlas locations.
    pub images: &'a [(ImageData, u32, u32)],
}

#[derive(Clone)]
struct ResidentImage {
    image: ImageData,
    alloc_id: AllocId,
    x: u32,
    y: u32,
    dirty: bool,
    last_used_generation: u64,
}

pub(crate) struct ImageCache {
    atlas: AtlasAllocator,
    /// Maximum side length for the square image atlas texture.
    max_size: i32,
    /// Monotonic counter for resolve passes, used to track when resident images were last used.
    generation: u64,
    /// Number of resident images evicted during the current resolve pass.
    ///
    /// This is exposed through [`Images::evicted`] for renderer-side debug logging, and also
    /// prevents repeated stale-eviction scans during the same resolve pass.
    evicted_in_resolve: usize,
    /// Map from image blob id to atlas residency.
    map: HashMap<u64, ResidentImage>,
    /// Images that must be uploaded in the current resolve pass, with atlas locations.
    images: Vec<(ImageData, u32, u32)>,
    /// raea: whether the current resolve has packed the atlas again (`repack_with`: once a resolve)
    repacked_in_resolve: bool,
}

impl Default for ImageCache {
    fn default() -> Self {
        Self::new()
    }
}

impl ImageCache {
    pub(crate) fn new() -> Self {
        Self::new_with_sizes(DEFAULT_ATLAS_SIZE, MAX_ATLAS_SIZE.load(Ordering::Relaxed))
    }

    fn new_with_sizes(initial_size: i32, max_size: i32) -> Self {
        Self {
            atlas: AtlasAllocator::new(size2(initial_size, initial_size)),
            max_size,
            generation: 0,
            evicted_in_resolve: 0,
            map: HashMap::default(),
            images: Vec::default(),
            repacked_in_resolve: false,
        }
    }

    pub(crate) fn begin_resolve(&mut self) {
        self.generation = self.generation.wrapping_add(1);
        self.evicted_in_resolve = 0;
        self.images.clear();
        self.repacked_in_resolve = false;
    }

    pub(crate) fn restart_resolve_pass(&mut self) {
        self.images.clear();
        let previous_generation = self.generation.wrapping_sub(1);
        for resident in self.map.values_mut() {
            if resident.last_used_generation == self.generation {
                resident.last_used_generation = previous_generation;
            }
        }
    }

    pub(crate) fn images(&self) -> Images<'_> {
        Images {
            width: self.atlas.size().width as u32,
            height: self.atlas.size().height as u32,
            evicted: self.evicted_in_resolve,
            images: &self.images,
        }
    }

    /// raea: the atlas at its size with nothing to upload, for a resolve that uses no images (it keeps the renderer's
    /// persistent atlas texture and what's resident in it)
    pub(crate) fn unchanged(&self) -> Images<'_> {
        Images { width: self.atlas.size().width as u32, height: self.atlas.size().height as u32, evicted: 0, images: &[] }
    }

    pub(crate) fn bump_size(&mut self) -> bool {
        let mut new_size = self.atlas.size().width * 2;
        while new_size <= self.max_size {
            if self.repack_to_size(new_size) {
                self.images.clear();
                return true;
            }
            new_size *= 2;
        }
        false
    }

    pub(crate) fn get_or_insert(&mut self, image: &ImageData) -> Option<(u32, u32)> {
        match self.map.entry(image.data.id()) {
            Entry::Occupied(mut occupied) => {
                let resident = occupied.get_mut();
                let xy = (resident.x, resident.y);
                if resident.last_used_generation != self.generation {
                    resident.last_used_generation = self.generation;
                    if resident.dirty {
                        self.images
                            .push((resident.image.clone(), resident.x, resident.y));
                    }
                }
                Some(xy)
            }
            Entry::Vacant(vacant) => {
                let alloc = self
                    .atlas
                    .allocate(size2(image.width as _, image.height as _))?;
                let x = alloc.rectangle.min.x as u32;
                let y = alloc.rectangle.min.y as u32;
                let resident = ResidentImage {
                    image: image.clone(),
                    alloc_id: alloc.id,
                    x,
                    y,
                    dirty: true,
                    last_used_generation: self.generation,
                };
                self.images.push((image.clone(), x, y));
                vacant.insert(resident);
                Some((x, y))
            }
        }
    }

    pub(crate) fn finish_resolve(&mut self) {
        for resident in self.map.values_mut() {
            if resident.last_used_generation == self.generation {
                resident.dirty = false;
            }
        }
    }

    pub(crate) fn mark_dirty(&mut self, image: &ImageData) {
        if let Some(resident) = self.map.get_mut(&image.data.id()) {
            resident.dirty = true;
        }
    }

    pub(crate) fn can_fit_image(&self, image: &ImageData) -> bool {
        image.width <= self.atlas.size().width as u32
            && image.height <= self.atlas.size().height as u32
    }

    pub(crate) fn evict_stale_entries(&mut self) -> bool {
        if self.evicted_in_resolve != 0 {
            return false;
        }
        let Some(stale_before) = self.generation.checked_sub(EVICT_AFTER_GENERATIONS) else {
            return false;
        };
        for (_id, resident) in self
            .map
            .extract_if(|_, resident| resident.last_used_generation < stale_before)
        {
            self.atlas.deallocate(resident.alloc_id);
            self.evicted_in_resolve += 1;
        }
        self.evicted_in_resolve != 0
    }

    /// raea: with the atlas at its largest and no room for an image, the resident images the current resolve hasn't
    /// used are let go, the ones unused longest first (one generation a call; false when none is left). Upstream stops
    /// at `evict_stale_entries`, which keeps what the last two resolves used: an embedder whose images are new in
    /// every frame (raea-page's layers, each a placeholder the size of its box) fills the atlas with the last two
    /// frames' and draws the frame without its last images.
    pub(crate) fn evict_unused(&mut self) -> bool {
        // once packed again (`repack_with`), what's resident is the resolve's own images, the ones its pass hasn't
        // reached yet among them
        if self.repacked_in_resolve {
            return false;
        }
        let generation = self.generation;
        let Some(oldest) = self.map.values().map(|resident| resident.last_used_generation).filter(|used| *used != generation).min() else {
            return false;
        };
        for (_id, resident) in self.map.extract_if(|_, resident| resident.last_used_generation == oldest) {
            self.atlas.deallocate(resident.alloc_id);
            self.evicted_in_resolve += 1;
        }
        true
    }

    /// raea: the atlas emptied and packed with `wanted` alone (the current resolve's images), the tallest first, once
    /// a resolve (false after that). What `evict_unused` leaves lies where the images it let go had put it, and
    /// images met in paint order cut the room up: 18 images near a 1080p frame's size, a few px apart, didn't all
    /// find a place in an atlas with the area for 28. Tallest first, a guillotine packs them in rows. The caller
    /// starts its pass again, as after `bump_size`: every image is uploaded again.
    pub(crate) fn repack_with<'a>(&mut self, wanted: impl Iterator<Item = &'a ImageData>) -> bool {
        if std::mem::replace(&mut self.repacked_in_resolve, true) {
            return false;
        }
        let mut wanted: Vec<&ImageData> = wanted.collect();
        wanted.sort_by_key(|image| (std::cmp::Reverse(image.height), std::cmp::Reverse(image.width), image.data.id()));
        wanted.dedup_by_key(|image| image.data.id());
        self.evicted_in_resolve += self.map.keys().filter(|id| !wanted.iter().any(|image| image.data.id() == **id)).count();
        self.atlas = AtlasAllocator::new(self.atlas.size());
        self.map.clear();
        // not yet used by this pass: `get_or_insert` uploads each as it meets it
        let unused = self.generation.wrapping_sub(1);
        for image in wanted {
            let Some(alloc) = self.atlas.allocate(size2(image.width as _, image.height as _)) else { continue };
            let (x, y) = (alloc.rectangle.min.x as u32, alloc.rectangle.min.y as u32);
            self.map.insert(image.data.id(), ResidentImage { image: image.clone(), alloc_id: alloc.id, x, y, dirty: true, last_used_generation: unused });
        }
        self.images.clear();
        true
    }

    fn repack_to_size(&mut self, size: i32) -> bool {
        let mut atlas = AtlasAllocator::new(size2(size, size));
        let mut entries: Vec<_> = self.map.iter().collect();
        entries.sort_by_key(|(id, _)| *id);
        let mut map = HashMap::with_capacity(self.map.len());
        for (id, resident) in entries {
            let Some(alloc) =
                atlas.allocate(size2(resident.image.width as _, resident.image.height as _))
            else {
                return false;
            };
            let mut resident = resident.clone();
            resident.alloc_id = alloc.id;
            resident.x = alloc.rectangle.min.x as u32;
            resident.y = alloc.rectangle.min.y as u32;
            resident.dirty = true;
            map.insert(*id, resident);
        }
        self.atlas = atlas;
        self.map = map;
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use peniko::{Blob, ImageAlphaType, ImageFormat};
    use std::sync::Arc;

    /// raea: a resolve with no images reports the atlas as it is, not 0x0 (which made the renderer drop its atlas)
    #[test]
    fn unchanged_keeps_the_atlas_size() {
        let mut cache = ImageCache::new_with_sizes(64, 256);
        cache.begin_resolve();
        assert!(cache.get_or_insert(&image(1, 16, 16)).is_some());
        cache.finish_resolve();
        let i = cache.unchanged();
        assert_eq!((i.width, i.height, i.images.len()), (64, 64, 0));
    }

    fn image(id_byte: u8, width: u32, height: u32) -> ImageData {
        let len = (width * height * 4) as usize;
        ImageData {
            data: Blob::new(Arc::new(vec![id_byte; len])),
            format: ImageFormat::Rgba8,
            width,
            height,
            alpha_type: ImageAlphaType::Alpha,
        }
    }

    #[test]
    fn atlas_size_persists_after_growth() {
        let mut cache = ImageCache::new_with_sizes(16, 64);
        assert_eq!(cache.atlas.size().width, 16);
        assert!(cache.bump_size());
        assert_eq!(cache.atlas.size().width, 32);
        cache.begin_resolve();
        assert_eq!(cache.atlas.size().width, 32);
    }

    #[test]
    fn resident_entries_are_reused_across_resolves() {
        let mut cache = ImageCache::new_with_sizes(32, 64);
        let image = image(7, 8, 8);

        cache.begin_resolve();
        let first = cache.get_or_insert(&image).unwrap();
        assert_eq!(cache.images.len(), 1);
        cache.finish_resolve();

        cache.begin_resolve();
        let second = cache.get_or_insert(&image).unwrap();
        assert_eq!(first, second);
        assert_eq!(cache.images.len(), 0);
        assert_eq!(cache.map.len(), 1);
    }

    #[test]
    fn marked_dirty_resident_entries_are_uploaded_again() {
        let mut cache = ImageCache::new_with_sizes(32, 64);
        let image = image(7, 8, 8);

        cache.begin_resolve();
        let first = cache.get_or_insert(&image).unwrap();
        cache.finish_resolve();

        cache.mark_dirty(&image);
        cache.begin_resolve();
        let second = cache.get_or_insert(&image).unwrap();
        assert_eq!(first, second);
        assert_eq!(cache.images.len(), 1);
        assert_eq!(cache.images[0].0.data.id(), image.data.id());
        assert_eq!((cache.images[0].1, cache.images[0].2), first);
        cache.finish_resolve();

        cache.begin_resolve();
        assert_eq!(cache.get_or_insert(&image), Some(first));
        assert_eq!(cache.images.len(), 0);
    }

    #[test]
    fn marked_dirty_unused_entries_stay_dirty() {
        let mut cache = ImageCache::new_with_sizes(32, 64);
        let image = image(7, 8, 8);

        cache.begin_resolve();
        let xy = cache.get_or_insert(&image).unwrap();
        cache.finish_resolve();

        cache.mark_dirty(&image);
        cache.begin_resolve();
        cache.finish_resolve();

        cache.begin_resolve();
        assert_eq!(cache.get_or_insert(&image), Some(xy));
        assert_eq!(cache.images.len(), 1);
    }

    #[test]
    fn stale_entries_can_be_evicted_under_pressure() {
        let mut cache = ImageCache::new_with_sizes(16, 16);
        let image_a = image(1, 10, 10);
        let image_b = image(2, 10, 10);

        cache.begin_resolve();
        assert!(cache.get_or_insert(&image_a).is_some());

        cache.begin_resolve();

        cache.begin_resolve();
        cache.begin_resolve();
        assert!(cache.get_or_insert(&image_b).is_none());
        assert!(cache.evict_stale_entries());
        assert!(cache.get_or_insert(&image_b).is_some());
        assert!(!cache.map.contains_key(&image_a.data.id()));
    }

    #[test]
    fn stale_entries_are_evicted_at_most_once_per_resolve() {
        let mut cache = ImageCache::new_with_sizes(32, 32);
        let image_a = image(1, 8, 8);
        let image_b = image(2, 8, 8);

        cache.begin_resolve();
        assert!(cache.get_or_insert(&image_a).is_some());
        cache.finish_resolve();

        cache.begin_resolve();
        assert!(cache.get_or_insert(&image_b).is_some());
        cache.finish_resolve();

        cache.begin_resolve();
        cache.begin_resolve();
        cache.begin_resolve();

        assert!(cache.evict_stale_entries());
        assert!(!cache.evict_stale_entries());
    }

    /// raea: at the atlas's largest size, what the resolve hasn't used goes the longest unused first, and what it has
    /// used stays
    #[test]
    fn unused_entries_are_let_go_longest_unused_first() {
        let mut cache = ImageCache::new_with_sizes(32, 32);
        let (old, last, this) = (image(1, 8, 8), image(2, 8, 8), image(3, 8, 8));
        for image in [&old, &last, &this] {
            cache.begin_resolve();
            assert!(cache.get_or_insert(image).is_some());
        }
        let resident = |cache: &ImageCache| [&old, &last, &this].map(|image| cache.map.contains_key(&image.data.id()));
        assert!(cache.evict_unused());
        assert_eq!(resident(&cache), [false, true, true]);
        assert!(cache.evict_unused());
        assert_eq!(resident(&cache), [false, false, true]);
        assert!(!cache.evict_unused());
        assert_eq!((resident(&cache), cache.evicted_in_resolve), ([false, false, true], 2));
    }

    /// raea: a crowded atlas packed again holds the wanted images alone, each to be uploaded as the pass meets it, and
    /// is packed once a resolve
    #[test]
    fn a_crowded_atlas_is_packed_again_with_the_wanted_images() {
        let mut cache = ImageCache::new_with_sizes(16, 16);
        let (before, a, b) = (image(1, 10, 10), image(2, 16, 6), image(3, 16, 10));
        cache.begin_resolve();
        assert!(cache.get_or_insert(&before).is_some());
        cache.finish_resolve();
        cache.begin_resolve();
        // twice wanted: one place
        assert!(cache.repack_with([&a, &b, &a].into_iter()));
        assert!(!cache.map.contains_key(&before.data.id()));
        assert_eq!((cache.map.len(), cache.evicted_in_resolve, cache.images.len()), (2, 1, 0));
        // what it packed is the resolve's own, though the pass hasn't met it yet: none of it is let go
        assert!(!cache.evict_unused());
        assert_eq!(cache.map.len(), 2);
        // the taller first, at the top
        assert_eq!((cache.get_or_insert(&b), cache.get_or_insert(&a)), (Some((0, 0)), Some((0, 10))));
        assert_eq!(cache.images.len(), 2);
        assert!(!cache.repack_with([&a, &b].into_iter()));
        cache.begin_resolve();
        assert!(cache.repack_with([&a].into_iter()));
    }

    #[test]
    fn failed_repack_leaves_existing_residency_unchanged() {
        let mut cache = ImageCache::new_with_sizes(16, 16);
        let image = image(1, 12, 12);

        cache.begin_resolve();
        let xy = cache.get_or_insert(&image).unwrap();

        assert!(!cache.repack_to_size(8));
        assert_eq!(cache.atlas.size().width, 16);
        assert_eq!(cache.get_or_insert(&image), Some(xy));
        assert_eq!(cache.map.len(), 1);
    }
}