mln-rs-engine 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use std::sync::Arc;

use mln_style::bitmap::PremultipliedImage;
use mln_style::hash::HashSet;
use mln_style::image::StyleImage;
use mln_style::size::Size;

use super::{DEFAULT_ON_DEMAND_IMAGES_CACHE_SIZE, ImageDependencies, ImageStore, ImageType, ImageWait};
use crate::render::events::RendererEvent;

fn image(id: &str, size: u32, pixel_ratio: f32, sdf: bool) -> Arc<StyleImage> {
    let pixels = PremultipliedImage::new(Size::new(size, size));
    let image = StyleImage::new(id.to_owned(), pixels, pixel_ratio, sdf, Vec::new(), Vec::new(), None, None, None);
    Arc::new(image.expect("an image"))
}

fn icons_of(ids: &[&str]) -> ImageDependencies {
    ids.iter().map(|id| ((*id).to_owned(), ImageType::Icon)).collect()
}

fn ids(ids: &[&str]) -> HashSet<String> {
    ids.iter().map(|id| (*id).to_owned()).collect()
}

/// The images the store asked the app for since the last call.
fn missing(store: &mut ImageStore) -> Vec<String> {
    let events = store.take_events();
    events
        .into_iter()
        .filter_map(|event| if let RendererEvent::StyleImageMissing(id) = event { Some(id) } else { None })
        .collect()
}

/// The images the store asks the app to remove once no tile uses any of
/// `used`, sorted.
fn unused(store: &mut ImageStore, used: &[&str]) -> Vec<String> {
    store.take_events();
    store.reduce_memory_use(&ids(used));
    let mut unused: Vec<String> = store
        .take_events()
        .into_iter()
        .flat_map(|event| if let RendererEvent::UnusedStyleImages(ids) = event { ids } else { Vec::new() })
        .collect();
    unused.sort();
    unused
}

/// The icons a resolve answered with, sorted, or `None` while it waits.
fn resolved_icons(store: &mut ImageStore, wants: &ImageDependencies, wait: &mut ImageWait) -> Option<Vec<String>> {
    let resolved = store.resolve(wants, wait)?;
    Some(resolved.icons.keys().cloned().collect())
}

/// Added images are there until removed, and an id can be added again
/// after its removal; every change moves the revision, so waiting tiles
/// resolve again.
#[test]
fn added_images_stay_until_removed() {
    let mut store = ImageStore::default();
    let mut revision = store.revision();
    let mut changed = |store: &ImageStore| std::mem::replace(&mut revision, store.revision()) != store.revision();

    for id in ["one", "two", "three"] {
        store.add_image(image(id, 16, 2.0, false));
        assert!(changed(&store));
    }
    store.remove_image("one");
    assert!(changed(&store));
    store.remove_image("two");

    assert!(store.image("three").is_some());
    assert!(store.image("two").is_none());
    assert!(store.image("four").is_none());
    assert_eq!(store.available_images().iter().collect::<Vec<_>>(), ["three"]);

    store.add_image(image("one", 32, 1.0, false));
    assert_eq!(store.image("one").expect("added again").image.size, Size::new(32, 32));

    let quiet = store.revision();
    store.begin_update();
    assert_eq!(store.revision(), quiet, "an update that asked for nothing changes nothing");
}

/// An update to an image says whether the tiles that use it lay out again:
/// when its size or SDF flag changes. Otherwise the atlas patches its pixels.
#[test]
fn an_update_lays_out_again_when_the_size_or_sdf_flag_changes() {
    for (size, sdf, lays_out) in [(16, false, false), (32, false, true), (16, true, true)] {
        let mut store = ImageStore::default();
        store.add_image(image("one", 16, 2.0, false));
        assert_eq!(store.update_image(image("one", size, 2.0, sdf)), lays_out, "{size} px, sdf {sdf}");
        assert_eq!(store.image("one").expect("one").sdf, sdf);
    }
}

#[test]
fn a_wait_for_images_that_are_there_resolves_at_once() {
    let mut store = ImageStore::default();
    store.add_image(image("one", 16, 2.0, false));
    let resolved = resolved_icons(&mut store, &icons_of(&["one"]), &mut ImageWait::default());
    assert_eq!(resolved, Some(vec!["one".to_owned()]));
}

/// Before the sprite loads, a missing image may still come with it: the
/// store waits without asking the app. Once it loads, the store asks for
/// each missing image once per update, and the wait resolves without them
/// in the next update.
#[test]
fn missing_images_are_asked_for_once_the_sprite_loads() {
    let mut store = ImageStore::default();
    let mut wait = ImageWait::default();
    let mut wants = icons_of(&["pre"]);

    store.begin_update();
    assert!(store.resolve(&wants, &mut wait).is_none(), "the sprite may still bring it");
    assert_eq!(missing(&mut store), Vec::<String>::new());

    let revision = store.revision();
    store.set_loaded(true);
    assert_ne!(store.revision(), revision, "a waiting tile asks again");
    assert!(store.resolve(&wants, &mut wait).is_none(), "the app gets an update to add it");
    assert_eq!(missing(&mut store), ["pre"]);

    store.begin_update();
    assert_eq!(resolved_icons(&mut store, &wants, &mut wait), Some(Vec::new()));
    assert_eq!(missing(&mut store), Vec::<String>::new());

    // A new wait for more images asks for all it lacks.
    wants.insert("post".to_owned(), ImageType::Icon);
    let mut wait = ImageWait::default();
    assert!(store.resolve(&wants, &mut wait).is_none());
    assert_eq!(missing(&mut store), ["post", "pre"]);

    // Another wait in the same update doesn't ask again, and waits as long.
    let mut another = ImageWait::default();
    assert!(store.resolve(&wants, &mut another).is_none());
    assert_eq!(missing(&mut store), Vec::<String>::new());
    store.begin_update();
    assert!(store.resolve(&wants, &mut another).is_some());
}

/// The app adds the image it is asked for before the next update: the wait
/// resolves with it.
#[test]
fn an_image_the_app_adds_when_asked_resolves_the_wait() {
    let mut store = ImageStore::default();
    store.set_loaded(true);
    store.begin_update();

    let mut wait = ImageWait::default();
    let wants = icons_of(&["late"]);
    assert!(store.resolve(&wants, &mut wait).is_none());
    assert_eq!(missing(&mut store), ["late"]);

    store.add_image(image("late", 16, 1.0, false));
    store.begin_update();
    assert_eq!(resolved_icons(&mut store, &wants, &mut wait), Some(vec!["late".to_owned()]));
}

/// The store asks the app to remove the images it asked for and the app
/// added once no tile uses them, never the sprite's; the bytes of those
/// images, at their latest size, are what count against the cache's size.
#[test]
fn requested_images_no_tile_uses_are_reported_unused() {
    let mut store = ImageStore::default();
    store.set_loaded(true);
    store.add_image(image("sprite", 16, 1.0, false));

    // Asks for the images, which the app adds.
    let request = |store: &mut ImageStore, ids: &[&str], size: u32| {
        store.begin_update();
        assert!(store.resolve(&icons_of(ids), &mut ImageWait::default()).is_none());
        for id in ids {
            if store.image(id).is_none() {
                store.add_image(image(id, size, 1.0, false));
            }
        }
    };

    request(&mut store, &["missing"], 16);
    assert!(!store.exceeds_cache_size_limit());
    // An update counts the image's new size.
    store.update_image(image("missing", 1024, 1.0, false));
    assert!(store.exceeds_cache_size_limit());
    store.update_image(image("missing", 16, 1.0, false));
    assert!(!store.exceeds_cache_size_limit());
    assert_eq!(unused(&mut store, &["missing"]), Vec::<String>::new());
    assert_eq!(unused(&mut store, &[]), ["missing"]);
    store.remove_image("missing");

    request(&mut store, &["1024px"], 1024);
    assert!(store.exceeds_cache_size_limit());
    assert_eq!(unused(&mut store, &[]), ["1024px"]);
    store.remove_image("1024px");
    assert!(!store.exceeds_cache_size_limit());

    request(&mut store, &["missing", "1024px"], 16);
    assert_eq!(unused(&mut store, &["missing", "1024px"]), Vec::<String>::new());
    assert_eq!(unused(&mut store, &["missing"]), ["1024px"]);
}

fn keys(wants: &ImageDependencies) -> Vec<&str> {
    wants.keys().map(String::as_str).collect()
}

/// Requested images over the cache's size stay while tiles use them, beside
/// the sprite's that the same tiles use.
#[test]
fn requested_images_in_use_stay_past_the_cache_size() {
    const COUNT: usize = 6;
    const SIDE: u32 = 256;
    const _: () = assert!(COUNT * (SIDE * SIDE * 4) as usize > DEFAULT_ON_DEMAND_IMAGES_CACHE_SIZE);

    let mut store = ImageStore::default();
    store.set_loaded(true);
    store.add_image(image("sprite", 16, 1.0, false));
    let mut wants = icons_of(&["sprite"]);
    wants.extend((0..COUNT).map(|i| (format!("a{i}"), ImageType::Icon)));

    // One tile's wait: asks for the missing images, which the app adds, and
    // resolves with all of them in the next update.
    let request = |store: &mut ImageStore, wants: &ImageDependencies| {
        store.begin_update();
        let mut wait = ImageWait::default();
        if store.resolve(wants, &mut wait).is_none() {
            for id in missing(store) {
                store.add_image(image(&id, SIDE, 3.0, false));
            }
            store.begin_update();
        }
        assert_eq!(resolved_icons(store, wants, &mut wait).expect("resolved").len(), wants.len());
    };

    request(&mut store, &wants);
    assert_eq!(unused(&mut store, &keys(&wants)), Vec::<String>::new());

    wants.extend((0..COUNT).map(|i| (format!("b{i}"), ImageType::Icon)));
    request(&mut store, &wants);
    assert!(store.exceeds_cache_size_limit());
    assert_eq!(unused(&mut store, &keys(&wants)), Vec::<String>::new());

    let unused = unused(&mut store, &[]);
    assert_eq!(unused.len(), 2 * COUNT);
    assert!(!unused.contains(&"sprite".to_owned()));
}