mln-rs-engine 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
// What a tile shows, and whether it can draw, as its loads end: in errors,
// with no data, or with data its jobs decode on other threads.

use std::sync::Arc;

use geo_types::Point;
use mln_style::error::Error;
use mln_style::feature::Feature;
use mln_style::layer::{Layer, LayerStyle, SourceKind};
use mln_style::layers::{Circle, Fill};
use mln_style::size::Size;
use mln_style::tileset::RasterEncoding;

use crate::exec::pool::TaskGroup;
use crate::layer::layer_type::{ErasedEvaluatedLayer, EvaluatedLayer};
use crate::map::MapMode;
use crate::query::SourceQueryOptions;
use crate::tests::OneTile;
use crate::tests::tile_jobs_test::Manual;
use crate::tile::dem_data::DEMData;
use crate::tile::{MltTile, OverscaledTileID, TileData};
use crate::tile_store::contents::Contents;
use crate::worker::tile_workers::{InlineWorkers, TileWorkers};

/// The tiles' thread pool, which their stores free on.
struct Pools(TaskGroup);

impl Pools {
    fn new() -> Self {
        Pools(TaskGroup::new(&crate::tests::pool()))
    }

    /// Tile `id` of `kind`, whose jobs run on `workers`.
    fn tile_at(&self, kind: SourceKind, id: OverscaledTileID, workers: Box<dyn TileWorkers>) -> OneTile {
        OneTile::new(crate::tests::tile_store(&self.0, workers), kind, id, MapMode::Static)
    }

    /// Tile 0/0/0 of `kind`, whose jobs run on `workers`.
    fn tile(&self, kind: SourceKind, workers: Box<dyn TileWorkers>) -> OneTile {
        self.tile_at(kind, OverscaledTileID::from_zxy(0, 0, 0), workers)
    }

    /// Tile 0/0/0 of `kind`, whose jobs run on the thread pool.
    fn pool_tile(&self, kind: SourceKind) -> OneTile {
        OneTile::new(crate::tests::pool_store(&self.0), kind, OverscaledTileID::from_zxy(0, 0, 0), MapMode::Static)
    }

    /// Tiles 1/0/0 and 1/1/0 of `kind`, whose jobs run in two worker
    /// instances on threads, reached only through the worker codec.
    fn remote_tiles(&self, kind: SourceKind) -> OneTile {
        let workers = Box::new(crate::tests::remote_workers(2));
        let mut tiles = self.tile_at(kind, OverscaledTileID::from_zxy(1, 0, 0), workers);
        tiles.add(OverscaledTileID::from_zxy(1, 1, 0));
        tiles
    }
}

impl Drop for Pools {
    fn drop(&mut self) {
        self.0.wait();
    }
}

const KINDS: [SourceKind; 3] = [SourceKind::Geometry, SourceKind::Raster, SourceKind::RasterDem];

/// A circle layer on "source".
fn circle_layer() -> Arc<dyn ErasedEvaluatedLayer> {
    let layer = Layer::new(crate::tests::registry().style(), "circle", "circle", "source").unwrap();
    Arc::new(EvaluatedLayer::<Circle>::registered(LayerStyle::recover(layer.style()).unwrap()))
}

/// Whether `tiles`' tile shows what it laid out or decoded.
fn shows_data(tiles: &mut OneTile, kind: SourceKind, layer: &Arc<dyn ErasedEvaluatedLayer>) -> bool {
    match kind {
        SourceKind::Geometry => tiles.with(|tile| tile.parts().1.layer_properties_updated(layer)),
        _ => matches!(tiles.tile().contents(), Some(Contents::Raster(_) | Contents::Dem(_))),
    }
}

/// Asserts whether `tiles`' tile can draw, and that its load has ended.
#[track_caller]
fn assert_settled(tiles: &OneTile, renderable: bool, context: &str) {
    let tile = tiles.tile();
    assert_eq!(renderable, tile.is_renderable(), "renderable, {context}");
    assert!(tile.is_settled() && tile.is_complete(), "settled and complete, {context}");
}

/// A tile that fails before it has data can't draw, and is done loading.
#[test]
fn a_tile_that_fails_before_it_has_data_cannot_draw() {
    let pools = Pools::new();
    for kind in KINDS {
        let mut tiles = pools.tile(kind, Box::new(InlineWorkers));
        tiles.with(|tile| tile.fail(Error::failed("test")));
        assert_settled(&tiles, false, &format!("{kind:?}"));
    }
}

/// A tile that has drawn keeps what it shows through the errors of later
/// loads, such as a refresh that goes offline or data that doesn't parse.
#[test]
fn a_tile_that_fails_after_it_has_data_keeps_it() {
    let pools = Pools::new();
    let layer = circle_layer();
    for kind in KINDS {
        let mut tiles = pools.pool_tile(kind);
        let id = tiles.id;
        if kind == SourceKind::Geometry {
            tiles.set_style(&crate::tests::style(std::slice::from_ref(&layer)));
            let point = Feature { geometry: Some(Point::new(0i16, 0).into()), ..Feature::default() };
            tiles.set_data(Some(TileData::Features(Arc::new(vec![point]))));
        } else {
            tiles.set_image(&id, Some(crate::tests::png(16, 16)));
        }
        tiles.settle(&[id]);
        assert!(shows_data(&mut tiles, kind, &layer), "{kind:?}");

        for error in ["Connection offline", "Parse error"] {
            tiles.with(|tile| tile.fail(Error::failed(error)));
            assert_settled(&tiles, true, &format!("{kind:?} after {error}"));
            assert!(shows_data(&mut tiles, kind, &layer), "{kind:?} after {error}");
        }
    }
}

/// A raster tile with no data draws nothing, and one the tileset doesn't
/// have can't draw, so that a tile of another zoom draws in its place. Each
/// replaces the image the tile had.
#[test]
fn an_empty_raster_tile_draws_nothing_and_a_missing_one_cannot_draw() {
    /// A load, and what it leaves the tile showing.
    #[derive(Debug)]
    enum Load {
        Empty,
        Image,
        Missing,
    }
    let pools = Pools::new();
    for kind in [SourceKind::Raster, SourceKind::RasterDem] {
        let mut tiles = pools.pool_tile(kind);
        let id = tiles.id;
        for (step, load) in [Load::Empty, Load::Image, Load::Missing, Load::Empty].iter().enumerate() {
            match load {
                Load::Empty => tiles.set_image(&id, None),
                Load::Image => tiles.set_image(&id, Some(crate::tests::png(16, 16))),
                Load::Missing => tiles.set_missing(&id),
            }
            tiles.settle(&[id]);
            let context = format!("{kind:?}, load {step}, {load:?}");
            let contents = tiles.tile().contents();
            match load {
                Load::Empty => assert!(matches!(contents, Some(Contents::Empty)), "{context}"),
                Load::Image => assert!(matches!(contents, Some(Contents::Raster(_) | Contents::Dem(_))), "{context}"),
                Load::Missing => assert!(contents.is_none(), "{context}"),
            }
            assert_settled(&tiles, !matches!(load, Load::Missing), &context);
        }
    }
}

/// The size of the image raster tile `id` shows.
fn image_size(tiles: &OneTile, id: &OverscaledTileID) -> Option<Size> {
    match tiles.tile_at(id).contents() {
        Some(Contents::Raster(raster)) => Some(raster.image.size),
        _ => None,
    }
}

/// The DEM raster-dem tile `id` shows.
fn dem<'a>(tiles: &'a OneTile, id: &OverscaledTileID) -> &'a DEMData {
    match tiles.tile_at(id).contents() {
        Some(Contents::Dem(dem)) => dem.dem(),
        _ => panic!("tile {id} shows no DEM"),
    }
}

/// Raster tiles whose jobs run in worker instances on other threads get
/// their images back through the codec; an image that doesn't decode
/// becomes the tile's error, and the tile keeps the image it had.
#[test]
fn raster_decodes_cross_the_worker_codec() {
    let pools = Pools::new();
    let mut tiles = pools.remote_tiles(SourceKind::Raster);
    let ids = [OverscaledTileID::from_zxy(1, 0, 0), OverscaledTileID::from_zxy(1, 1, 0)];
    for (id, size) in ids.iter().zip([16, 32]) {
        tiles.set_image(id, Some(crate::tests::png(size, size)));
        assert!(!tiles.tile_at(id).is_complete());
    }
    tiles.settle(&ids);
    for (id, size) in ids.iter().zip([16, 32]) {
        assert!(tiles.tile_at(id).is_renderable());
        assert_eq!(image_size(&tiles, id), Some(Size::new(size, size)));
    }
    assert_eq!(tiles.errors(), Vec::<String>::new());

    tiles.set_image(&ids[0], Some(Arc::new(b"not an image".to_vec())));
    tiles.settle(&ids[..1]);
    assert_eq!(tiles.errors().len(), 1);
    assert_eq!(image_size(&tiles, &ids[0]), Some(Size::new(16, 16)));
}

/// Raster-dem tiles whose jobs run in worker instances on other threads get
/// their DEMs back through the codec, borders included, and the store
/// backfills neighbours from each other as their DEMs arrive. A DEM that
/// isn't square becomes the tile's error.
#[test]
fn dem_decodes_and_backfills_cross_the_worker_codec() {
    let pools = Pools::new();
    let mut tiles = pools.remote_tiles(SourceKind::RasterDem);
    let ids = [OverscaledTileID::from_zxy(1, 0, 0), OverscaledTileID::from_zxy(1, 1, 0)];
    for (seed, id) in ids.iter().enumerate() {
        tiles.set_image(id, Some(crate::tests::dem_png(seed as u32)));
    }
    tiles.settle(&ids);
    for id in &ids {
        assert!(tiles.tile_at(id).is_renderable());
        let dem = dem(&tiles, id);
        assert_eq!((dem.dim, dem.stride, dem.encoding), (16, 18, RasterEncoding::Mapbox));
    }
    let (left, right) = (dem(&tiles, &ids[0]), dem(&tiles, &ids[1]));
    for y in 0..16 {
        assert_eq!(left.get(16, y), right.get(0, y));
        assert_eq!(right.get(-1, y), left.get(15, y));
    }

    tiles.set_image(&ids[1], Some(crate::tests::png(16, 8)));
    tiles.settle(&ids[1..]);
    assert_eq!(tiles.errors(), ["raster-dem tiles must be square."]);
    assert!(tiles.tile_at(&ids[1]).is_renderable());
}

/// A load without an image while the tile decodes shows nothing at once, and
/// the decode in flight stays the tile's one job: an image that comes before
/// it replies decodes after.
#[test]
fn an_empty_load_during_a_decode_keeps_one_decode_in_flight() {
    let pools = Pools::new();
    let manual = Manual::default();
    let mut tiles = pools.tile(SourceKind::Raster, Box::new(manual.clone()));
    let id = tiles.id;
    tiles.set_image(&id, Some(crate::tests::png(16, 16)));
    tiles.update();
    assert_eq!(manual.submitted(), 1);
    let decode = manual.take();

    tiles.set_image(&id, None);
    assert!(matches!(tiles.tile().contents(), Some(Contents::Empty)));
    assert!(tiles.tile().is_complete());
    tiles.set_image(&id, Some(crate::tests::png(8, 8)));
    tiles.update();
    assert_eq!(manual.submitted(), 1, "one decode in flight");

    manual.reply(InlineWorkers::run(decode));
    tiles.update();
    assert!(matches!(tiles.tile().contents(), Some(Contents::Empty)), "the stale decode isn't shown");
    assert_eq!(manual.submitted(), 2);
    manual.run();
    tiles.update();
    assert_eq!(image_size(&tiles, &id), Some(Size::new(8, 8)));
    assert!(tiles.tile().is_complete());
}

/// A query of a vector tile's source, here of MLT data, finds the features
/// of the source layers it names, each labeled with its layer, and nothing
/// before the tile has data or without a source layer.
#[test]
fn a_source_query_finds_the_features_of_the_source_layers_it_names() {
    let pools = Pools::new();
    let mut tiles = pools.pool_tile(SourceKind::Geometry);
    let query = |tiles: &OneTile, source_layers: Option<&[&str]>| {
        let source_layers = source_layers.map(|layers| layers.iter().map(|&layer| layer.to_owned()).collect());
        let source = tiles.store.source(tiles.key).expect("the source");
        let options = SourceQueryOptions::new(source_layers, None);
        source.query_source_features(&options, None, &mln_style::crs::WorldMapping::default()).unwrap()
    };
    assert_eq!(query(&tiles, Some(&["water"])), Vec::new(), "before data");

    let mut layer = Layer::new(crate::tests::registry().style(), "fill", "water", "source").unwrap();
    layer.set_source_layer("water");
    let layer: Arc<dyn ErasedEvaluatedLayer> =
        Arc::new(EvaluatedLayer::<Fill>::registered(LayerStyle::recover(layer.style()).unwrap()));
    tiles.set_style(&crate::tests::style(&[layer]));
    let data = crate::tests::testdata("test/fixtures/map/issue12432/0-0-0.mlt");
    tiles.set_data(Some(TileData::Mlt(MltTile::new(Arc::new(data)))));
    let id = tiles.id;
    tiles.settle(&[id]);

    let water = query(&tiles, Some(&["water", "nowhere"]));
    assert_ne!(water, Vec::new());
    assert!(water.iter().all(|feature| feature.source_layer == "water"));
    assert_eq!(query(&tiles, None), Vec::new(), "without a source layer");
}