From 771b089bcd25637f21ce8bd896b15daf36baeb7e Mon Sep 17 00:00:00 2001 From: Milo van der Linden Date: Mon, 2 Nov 2026 19:38:55 +0100 Subject: [PATCH] feat(tiles): read every sprite of a style, and the image expression A style may name several sprites, each with an id, and its icons `:`. Only one sprite was read, so the icons of the others were never drawn: Open Waters' Seamap, whose seamarks are in a second sprite, showed no buoys, beacons or lights. `["image", name]` was always null, so icons a style chooses with `coalesce` over `image` weren't drawn either. - Every sprite of a style is read, and an image is looked up as MapLibre names it: `:` in the sprite with that id (the longest, as an id may hold a colon), any other name in the `default` sprite. A style giving one address has a `default` sprite. - `["image", name]` is `name` when a sprite has an image it can draw, and null otherwise, for a label's icon and for a fill pattern. - When a visible layer of a style draws images, a notice says what is missing, one line per reason, on the vector-mesh path too: entries of a `sprite` array that can't be read, sprites at an address RustGIS won't fetch, and sprites whose download failed, for the images each drawing path takes from them. The limit of 16 counts the entries that can be read. - Meshes and tile pictures with pattern fills are made again, once, when other sprites are read (one that failed read after all, say). A fill whose pattern changes with the zoom is drawn zoom by zoom, not from one mesh colour for the level. A feature with no pattern name doesn't wait for the sprite, and meshes without pattern fills don't load it. While a sprite is tried again, a mesh drawing reports pending, so an export waits for it. - Decoded sprites and the images cut from them have memory budgets that hold across all kept sprites, with room for a style's 16 at both densities. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/tile_mesh.rs | 111 ++++++++-- crates/render/src/tiles.rs | 9 +- crates/tiles/src/draw.rs | 110 ++++++++-- crates/tiles/src/picture.rs | 59 +++++- crates/tiles/src/shapes.rs | 113 +++++++++-- crates/tiles/src/source.rs | 123 +++++++++-- crates/tiles/src/sprite.rs | 358 +++++++++++++++++++++++++++++---- crates/tiles/src/style.rs | 226 +++++++++++++++++++-- crates/tiles/src/symbols.rs | 15 +- docs/user-guide/maps.md | 9 +- 10 files changed, 1003 insertions(+), 130 deletions(-) diff --git a/crates/render/src/tile_mesh.rs b/crates/render/src/tile_mesh.rs index fd0312688c..707dde7d52 100644 --- a/crates/render/src/tile_mesh.rs +++ b/crates/render/src/tile_mesh.rs @@ -49,6 +49,8 @@ pub struct TileMesh { /// Made while the sprite was on its way, without the pattern fills: made again once it has /// arrived. pub waiting: bool, + /// The ids of the style's sprites its pattern fills were made from, if it has any. + pub sheets: Option>, } /// The indices of one or more style layers showing at the same zooms. @@ -253,7 +255,7 @@ pub fn tessellate(tile: &Tile, runs: &[Run], z: u8) -> TileMesh { _ => mesh_runs.push(MeshRun { first, count, min_zoom: run.min_zoom, max_zoom: run.max_zoom }), } } - TileMesh { vertices: out.vertices, indices: out.indices, runs: mesh_runs, waiting: false } + TileMesh { vertices: out.vertices, indices: out.indices, runs: mesh_runs, waiting: false, sheets: None } } /// The most points of a ring fanned rather than given to lyon: the walk round it stays cheap, @@ -350,6 +352,16 @@ struct Entry { /// Made while the sprite was on its way: made again once it has arrived (or failed), not /// before. waiting: bool, + /// The ids of the style's sprites its pattern fills were made from, if it has any. + sheets: Option>, +} + +/// Whether a mesh made from the sprites `sheets`, `waiting` for them or not, still serves while +/// `pending` of them are on their way and `read` have been read. Other sprites read (one that +/// failed read after all, or another failing instead) make those with pattern fills again, once; +/// until then they stand, however long one keeps failing. +fn still_serves(waiting: bool, sheets: Option<&[String]>, pending: bool, read: &[String]) -> bool { + pending || (!waiting && sheets.is_none_or(|ids| ids == read)) } #[derive(Default)] @@ -368,18 +380,28 @@ fn lock() -> MutexGuard<'static, Store> { /// (while its tile and the style are, and within a memory budget; one made while the sprite was /// on its way until it has arrived); `None` for one that is no vector tile, or not made /// yet: with `until`, those missing are made nearest `centre` first until then (a round of them -/// at least). Natively, they are made on several threads. +/// at least). Natively, they are made on several threads. Also whether the sprites of its pattern +/// fills are on their way, as a mesh kept meanwhile (one made when a sprite failed, which is now +/// tried again) doesn't say so itself. pub fn meshes( style: &Arc, source: &str, tiles: &[DataTile], level: u8, until: Option<(web_time::Instant, [f64; 2])>, -) -> Vec>> { +) -> (Vec>>, bool) { // Whether the style's sprite is still on its way, asked before the store is locked (a // lookup in the sprites the tile cache keeps). - let sprite_pending = - style.sprite.as_deref().is_some_and(|b| matches!(rustgis_tiles::sprite::load(b, false), rustgis_tiles::sprite::Load::Pending)); + let (sprite_pending, sprites_read) = if rustgis_tiles::shapes::draws_patterns(style, level) { + match rustgis_tiles::sprite::load(&style.sprites, false) { + rustgis_tiles::sprite::Load::Pending => (true, Vec::new()), + rustgis_tiles::sprite::Load::Ready(s) => (false, s.sheet_ids()), + rustgis_tiles::sprite::Load::Failed => (false, Vec::new()), + } + } else { + // No pattern fills here: nothing to load the sprites for. + (false, Vec::new()) + }; let key = |t: &DataTile| Key { payload: Arc::as_ptr(&t.payload) as usize, style: Arc::as_ptr(style) as usize, level }; let mut out: Vec>> = Vec::with_capacity(tiles.len()); let mut missing = Vec::new(); @@ -394,7 +416,7 @@ pub fn meshes( let found = s.entries.get_mut(&key(t)).filter(|e| { e.payload.upgrade().is_some_and(|p| Arc::ptr_eq(&p, &t.payload)) && e.style.upgrade().is_some_and(|x| Arc::ptr_eq(&x, style)) - && (!e.waiting || sprite_pending) + && still_serves(e.waiting, e.sheets.as_deref(), sprite_pending, &sprites_read) }); match found { Some(e) => { @@ -420,7 +442,7 @@ pub fn meshes( let t = tiles.get(*i)?; let Payload::Vector(tile) = &*t.payload else { return None }; let s = shapes(style, source, tile, level); - Some(Arc::new(TileMesh { waiting: s.waiting, ..tessellate(tile, &s.runs, t.z) })) + Some(Arc::new(TileMesh { waiting: s.waiting, sheets: s.sheets, ..tessellate(tile, &s.runs, t.z) })) }; // A tile that panicked (hostile data) is done: an empty mesh, kept, so it isn't made again // every frame, and the map settles. @@ -461,6 +483,7 @@ pub fn meshes( mesh: mesh.clone(), used: tick, waiting: mesh.waiting, + sheets: mesh.sheets.clone(), }; // The bytes are counted again by `evict`, below. s.entries.insert(key(t), entry); @@ -476,7 +499,7 @@ pub fn meshes( } // Every call, so meshes of tiles the cache let go go as the map moves over others. evict(&mut s, tick); - out + (out, sprite_pending) } /// `f` of every item (`None` for one that panicked), natively shared among threads. In the @@ -628,6 +651,60 @@ mod tests { assert_eq!(dash_pattern(Some(&[1.0, 2.0, 3.0, 4.0, 5.0])), None); } + #[test] + fn a_mesh_is_made_again_when_other_sprites_are_read() { + let ids = |list: &[&str]| list.iter().map(|id| id.to_string()).collect::>(); + let (none, a, b, both) = (ids(&[]), ids(&["a"]), ids(&["b"]), ids(&["a", "b"])); + // Without pattern fills it stands, whatever the sprites do. + assert!(still_serves(false, None, false, &none) && still_serves(false, None, false, &both)); + // Made from all that could be read: it stands while the other keeps failing... + assert!(still_serves(false, Some(&a), false, &a)); + // ...and while that one is asked for again... + assert!(still_serves(false, Some(&a), true, &none)); + // ...and is made again, once, when it is read. + assert!(!still_serves(false, Some(&a), false, &both)); + assert!(still_serves(false, Some(&both), false, &both)); + // As many sprites, but another one: made again. + assert!(!still_serves(false, Some(&a), false, &b)); + // Made while they were on their way: until they've come. + assert!(still_serves(true, Some(&none), true, &none)); + assert!(!still_serves(true, Some(&none), false, &both) && !still_serves(true, Some(&none), false, &none)); + // None could be read: it stands, not made again on every frame. + assert!(still_serves(false, Some(&none), false, &none)); + } + + #[test] + fn meshes_say_a_sprite_is_on_its_way() { + use rustgis_tiles::style::{Source, Style, StyleLayer}; + // Left unanswered, so the sprite stays on its way. + crate::tiles::tests::serve(); + let address = "https://stuck.test/mesh-sprite".to_owned(); + let resolved = |paint: serde_json::Value| { + let layer = serde_json::json!({"id": "p", "type": "fill", "source": "s", "source-layer": "l", "paint": paint}); + let sprites = vec![("default".to_owned(), address.clone())]; + Arc::new(Resolved { + style: Style { + name: String::new(), + sources: vec![("s".into(), Source::parse(&serde_json::json!({"type": "vector", "tiles": ["x/{z}/{x}/{y}"]})))], + layers: StyleLayer::parse(&layer).into_iter().collect(), + glyphs: None, + sprites: sprites.clone(), + sprites_left_out: Vec::new(), + sprites_listed: 1, + view: Default::default(), + }, + sprites, + attribution: Vec::new(), + left_out: Vec::new(), + made: std::sync::Mutex::new(web_time::Instant::now()), + waiting: false, + }) + }; + assert!(meshes(&resolved(serde_json::json!({"fill-pattern": "dots"})), "s", &[], 3, None).1); + // Without pattern fills, a mesh doesn't wait for sprites. + assert!(!meshes(&resolved(serde_json::json!({"fill-color": "#f00"})), "s", &[], 3, None).1); + } + #[test] fn meshes_are_made_once() { let mut t = tile(); @@ -641,10 +718,12 @@ mod tests { sources: vec![("s".into(), Source::parse(&serde_json::json!({"type": "vector", "tiles": ["x/{z}/{x}/{y}"]})))], layers: StyleLayer::parse(&layer).into_iter().collect(), glyphs: None, - sprite: None, + sprites: Vec::new(), + sprites_left_out: Vec::new(), + sprites_listed: 0, view: Default::default(), }, - sprite: None, + sprites: Vec::new(), attribution: Vec::new(), left_out: Vec::new(), made: std::sync::Mutex::new(web_time::Instant::now()), @@ -653,16 +732,16 @@ mod tests { let at = Extent::new(0.0, 0.0, 1.0, 1.0); let tiles = [DataTile { payload: payload.clone(), at, z: 1, clip: at }, DataTile { payload: Arc::new(Payload::Empty), at, z: 1, clip: at }]; - let a = meshes(&style, "s", &tiles, 3, None); + let (a, _) = meshes(&style, "s", &tiles, 3, None); assert!(a[0].as_ref().is_some_and(|m| !m.indices.is_empty()) && a[1].is_none()); - let b = meshes(&style, "s", &tiles, 3, None); + let (b, _) = meshes(&style, "s", &tiles, 3, None); // A payload standing in twice is made once, for both. let twice = [tiles[0].clone(), tiles[0].clone()]; - let t = meshes(&style, "s", &twice, 6, None); + let (t, _) = meshes(&style, "s", &twice, 6, None); assert!(Arc::ptr_eq(t[0].as_ref().unwrap(), t[1].as_ref().unwrap())); assert!(Arc::ptr_eq(a[0].as_ref().unwrap(), b[0].as_ref().unwrap()), "kept"); // Another level is another mesh. - let c = meshes(&style, "s", &tiles, 4, None); + let (c, _) = meshes(&style, "s", &tiles, 4, None); assert!(!Arc::ptr_eq(a[0].as_ref().unwrap(), c[0].as_ref().unwrap())); // Out of time before it starts: a round made, nearest the centre first; the rest later. let many: Vec = (0..64) @@ -671,10 +750,10 @@ mod tests { DataTile { payload: Arc::new(Payload::Vector(tile_named("parks"))), at, z: 1, clip: at } }) .collect(); - let some = meshes(&style, "s", &many, 5, Some((web_time::Instant::now(), [63.5, 0.5]))); + let (some, _) = meshes(&style, "s", &many, 5, Some((web_time::Instant::now(), [63.5, 0.5]))); let made = some.iter().filter(|m| m.is_some()).count(); assert!(made >= 1 && made < many.len() && some[63].is_some() && some[0].is_none(), "{made} made"); - let all = meshes(&style, "s", &many, 5, Some((web_time::Instant::now() + std::time::Duration::from_secs(60), [0.0, 0.0]))); + let (all, _) = meshes(&style, "s", &many, 5, Some((web_time::Instant::now() + std::time::Duration::from_secs(60), [0.0, 0.0]))); assert!(all.iter().all(Option::is_some)); } diff --git a/crates/render/src/tiles.rs b/crates/render/src/tiles.rs index defcb1db37..0f803e3deb 100644 --- a/crates/render/src/tiles.rs +++ b/crates/render/src/tiles.rs @@ -164,13 +164,13 @@ type LastTile = (std::sync::Weak, [f64; 2], [f32; 4] type Last = std::collections::HashMap, Vec)>; static LAST: std::sync::OnceLock> = std::sync::OnceLock::new(); -/// The meshes of `v`'s tiles, and whether some were made while the sprite was on its way. A map +/// The meshes of `v`'s tiles, and whether a sprite they use is on its way. A map /// drawn for the screen at a pace (see `rustgis_tiles::Pace`) makes those missing a frame's worth /// at a time, nearest `centre` first, the tiles drawn last standing in for the rest meanwhile, /// clipped to their squares. fn mesh_tiles(v: &rustgis_tiles::shapes::VectorTiles, centre: [f64; 2]) -> (Vec, bool) { let pace = rustgis_tiles::pace(); - let meshes = crate::tile_mesh::meshes(&v.style, &v.source, &v.tiles, v.level, pace.map(|(_, until)| (until, centre))); + let (meshes, mut waiting) = crate::tile_mesh::meshes(&v.style, &v.source, &v.tiles, v.level, pace.map(|(_, until)| (until, centre))); let lock = || LAST.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner()); let key = std::sync::Arc::as_ptr(&v.style) as usize; let last: Vec = lock() @@ -183,7 +183,7 @@ fn mesh_tiles(v: &rustgis_tiles::shapes::VectorTiles, centre: [f64; 2]) -> (Vec< .collect() }) .unwrap_or_default(); - let (mut stood_in, mut tiles, mut waiting) = (Vec::new(), Vec::new(), false); + let (mut stood_in, mut tiles) = (Vec::new(), Vec::new()); for (d, m) in v.tiles.iter().zip(meshes) { let o = [d.at.min_x, d.at.max_y]; match m { @@ -346,7 +346,8 @@ pub(crate) fn draw( if !tiles.is_empty() { g.cmds.push(DrawCmd::TileMeshes { tiles }); } - let d = rustgis_tiles::Drawn { labels: v.labels, attribution: v.attribution, pending: v.pending || waiting, error: None }; + let d = + rustgis_tiles::Drawn { labels: v.labels, attribution: v.attribution, pending: v.pending || waiting, error: v.error }; collect(d, &t.name, &mut out); continue; } diff --git a/crates/tiles/src/draw.rs b/crates/tiles/src/draw.rs index e6d8b7d4c4..e509df59aa 100644 --- a/crates/tiles/src/draw.rs +++ b/crates/tiles/src/draw.rs @@ -61,9 +61,37 @@ pub(crate) struct Item { pub(crate) clip: Extent, } -/// What of a resolved style was left out, as a drawing's error: the style still draws. -fn left_out(r: &Resolved) -> Option { - (!r.left_out.is_empty()).then(|| r.left_out.join("; ")) +/// What of a resolved style was left out, as a drawing's error (the style still draws): what +/// resolving it left out, and any sprites that couldn't be read, for the images shown at `frame`. +/// A drawing takes its images at the frame's density; a mesh (`mesh`) its pattern fills at 1×. +pub(crate) fn left_out(r: &Resolved, frame: &Frame, mesh: bool) -> Option { + let zoom = template::style_zoom(frame.m_per_px * f64::from(frame.ppp)); + let shown = |draws: fn(&StyleLayer) -> bool| r.style.layers.iter().any(|l| l.visible_at(zoom) && draws(l)); + let hi_dpi = frame.ppp >= 1.5; + let unread = sprite_notes(shown(StyleLayer::draws_icons), shown(StyleLayer::draws_patterns), hi_dpi, hi_dpi && !mesh, |hi, what| { + sprite::unread_note(&r.sprites, r.style.sprites_listed, &sprite::load(&r.sprites, hi), what) + }); + let all: Vec<&str> = r.left_out.iter().map(String::as_str).chain(unread.iter().map(String::as_str)).collect(); + (!all.is_empty()).then(|| all.join("; ")) +} + +/// What to say of sprites that couldn't be read (`note`, at a density), for what is shown: a style's +/// `icons` come at one density, and its `patterns` at another or the same. +fn sprite_notes( + icons: bool, + patterns: bool, + icons_hi: bool, + patterns_hi: bool, + note: impl Fn(bool, &str) -> Option, +) -> Vec { + let notes = match (icons, patterns) { + (false, false) => [None, None], + (true, false) => [note(icons_hi, "icons"), None], + (false, true) => [note(patterns_hi, "patterns"), None], + (true, true) if icons_hi == patterns_hi => [note(icons_hi, "icons and patterns"), None], + (true, true) => [note(icons_hi, "icons"), note(patterns_hi, "patterns")], + }; + notes.into_iter().flatten().collect() } /// Draws `spec` into `pm` at `opacity`. Labels are collected when `labels` is set. @@ -81,7 +109,7 @@ pub fn draw(pm: &mut Pixmap, spec: &Spec, opacity: f32, frame: &Frame, labels: b } }; out.attribution = r.attribution.clone(); - out.error = left_out(&r); + out.error = left_out(&r, frame, false); out.pending |= r.waiting; if !(frame.m_per_px.is_finite() && frame.m_per_px > 0.0) || opacity <= 0.0 { return out; @@ -141,13 +169,13 @@ pub(crate) fn draw_layers( let mut sprite_state: Option>> = None; let mut sprite = |pending: &mut bool| -> Option> { sprite_state - .get_or_insert_with(|| match r.sprite.as_deref().map(|b| sprite::load(b, frame.ppp >= 1.5)) { - Some(Load::Ready(s)) => Some(s), - Some(Load::Pending) => { + .get_or_insert_with(|| match sprite::load(&r.sprites, frame.ppp >= 1.5) { + Load::Ready(s) => Some(s), + Load::Pending => { *pending = true; None } - Some(Load::Failed) | None => None, + Load::Failed => None, }) .clone() }; @@ -306,7 +334,7 @@ fn place_as( } }; out.attribution = r.attribution.clone(); - out.error = left_out(&r); + out.error = left_out(&r, frame, false); out.pending |= r.waiting; if !(frame.m_per_px.is_finite() && frame.m_per_px > 0.0) || opacity <= 0.0 { return Some(out); @@ -413,7 +441,7 @@ pub fn pick(spec: &Spec, x: f64, y: f64, m_per_px: f64, tol_px: f32, limit: usiz let p = [((x - it.at.min_x) * units) as f32, ((it.at.max_y - y) * units) as f32]; let px = (m_per_px * units) as f32; for (fi, f) in l.features.iter().enumerate() { - let ctx = FeatureCtx { zoom, kind: f.kind, id: f.id, props: &f.props }; + let ctx = FeatureCtx { zoom, kind: f.kind, id: f.id, props: &f.props, images: None }; if !layer.matches(&ctx) { continue; } @@ -781,7 +809,7 @@ fn draw_vector(pm: &mut Pixmap, it: &Item, layer: &StyleLayer, frame: &Frame, zo if boxes.get(i).is_some_and(|b| b[0] > area[2] || b[2] < area[0] || b[1] > area[3] || b[3] < area[1]) { continue; } - let ctx = FeatureCtx { zoom, kind: f.kind, id: f.id, props: &f.props }; + let ctx = FeatureCtx { zoom, kind: f.kind, id: f.id, props: &f.props, images: None }; if !layer.matches(&ctx) { continue; } @@ -801,8 +829,9 @@ fn draw_vector(pm: &mut Pixmap, it: &Item, layer: &StyleLayer, frame: &Frame, zo paint.anti_alias = true; // A pattern from the sprite, repeated from a fixed point of the world so it // lines up across tiles and stays put as the map moves. + // (Its name may be an `image` expression, which asks the sprite.) let image = pattern(layer).and_then(|p| { - let name = layer.paint_value(p, &ctx)?; + let name = layer.paint_value(p, &FeatureCtx { images: sheet, ..ctx })?; sheet?.image(name.as_str()?, None) }); if pattern(layer).is_some() && image.is_none() { @@ -1185,8 +1214,63 @@ pub(crate) mod tests { &serde_json::json!({"id": "a", "type": "fill", "source": "s", "source-layer": "l", "paint": {"fill-pattern": "nope"}}), ) .unwrap(); - draw_vector(&mut pm, &item(vec![square]), &missing, &world_frame(), 0.0, Some(&sheet()), &[]); + draw_vector(&mut pm, &item(vec![square.clone()]), &missing, &world_frame(), 0.0, Some(&sheet()), &[]); assert_eq!(pm.pixel(32, 32).unwrap().alpha(), 0); + // A pattern chosen with `image`: the first the sprite has. + let chosen = StyleLayer::parse(&serde_json::json!({"id": "a", "type": "fill", "source": "s", "source-layer": "l", + "paint": {"fill-pattern": ["coalesce", ["image", "nope"], ["image", "red"]]}})) + .unwrap(); + let mut pm = Pixmap::new(64, 64).unwrap(); + draw_vector(&mut pm, &item(vec![square]), &chosen, &world_frame(), 0.0, Some(&sheet()), &[]); + let px = pm.pixel(32, 32).unwrap(); + assert_eq!((px.red(), px.green(), px.alpha()), (255, 0, 255)); + } + + #[test] + fn sprite_notes_say_what_each_density_loses() { + // Only the 1× sprites failed. + let note = |hi: bool, what: &str| (!hi).then(|| what.to_owned()); + // A drawing at high density takes all from `@2x`: nothing lost. + assert!(sprite_notes(true, true, true, true, note).is_empty()); + // A mesh at high density: its icons from `@2x`, its patterns from 1×. + assert_eq!(sprite_notes(true, true, true, false, note), ["patterns"]); + // At 1×, both, in one line. + assert_eq!(sprite_notes(true, true, false, false, note), ["icons and patterns"]); + assert_eq!(sprite_notes(true, false, false, false, note), ["icons"]); + assert_eq!(sprite_notes(false, true, false, false, note), ["patterns"]); + // Nothing shown that needs them: nothing to say, however they fared. + assert!(sprite_notes(false, false, false, false, note).is_empty()); + // Each density failing: a line each. + assert_eq!(sprite_notes(true, true, true, false, |_, what| Some(what.to_owned())), ["icons", "patterns"]); + } + + #[test] + fn fills_with_a_pattern_of_a_named_sprite() { + let picture = |c: tiny_skia::Color| { + let mut p = Pixmap::new(4, 4).unwrap(); + p.fill(c); + p + }; + let at = serde_json::json!({"x": 0, "y": 0, "width": 4, "height": 4}); + let (red, green) = (tiny_skia::Color::from_rgba8(255, 0, 0, 255), tiny_skia::Color::from_rgba8(0, 255, 0, 255)); + // Two sprites with an image of the same name: the id picks. + let sprites = crate::sprite::Sprite::of(vec![ + ("base", serde_json::json!({"dots": at}), picture(red)), + ("nautical", serde_json::json!({"dots": at}), picture(green)), + ]); + let square = crate::mvt::Feature { + id: None, + kind: GeomKind::Polygon, + geometry: vec![vec![[0.0, 0.0], [4096.0, 0.0], [4096.0, 4096.0], [0.0, 4096.0], [0.0, 0.0]]], + props: Vec::new(), + }; + let layer = StyleLayer::parse(&serde_json::json!({"id": "a", "type": "fill", "source": "s", "source-layer": "l", + "paint": {"fill-pattern": ["image", "nautical:dots"]}})) + .unwrap(); + let mut pm = Pixmap::new(64, 64).unwrap(); + draw_vector(&mut pm, &item(vec![square]), &layer, &world_frame(), 0.0, Some(&sprites), &[]); + let px = pm.pixel(32, 32).unwrap(); + assert_eq!((px.red(), px.green(), px.alpha()), (0, 255, 255)); } /// A one-feature MVT layer with one string property, `name`. diff --git a/crates/tiles/src/picture.rs b/crates/tiles/src/picture.rs index b58b9c6675..d646e4c8d8 100644 --- a/crates/tiles/src/picture.rs +++ b/crates/tiles/src/picture.rs @@ -30,6 +30,7 @@ use web_time::{Duration, Instant}; use crate::cache::{self, Payload}; use crate::draw::{Drawn, Frame, Item, Pass, draw_layers, overhang}; use crate::source::Resolved; +use crate::sprite::{self, Load}; use crate::style::{LayerKind, Source}; use crate::template::{self, Placed, TileId}; @@ -67,6 +68,28 @@ struct Entry { /// Drawn while some of it was on its way, at this cache generation: drawn again once the /// cache has more. waiting: Option, + /// For a style with pattern fills, the ids of the sprites it was drawn from. + sheets: Option>, +} + +/// Whether any of a style's sprites are on their way and, if it shows pattern fills at `zoom` and +/// none are, the ids of those read: what its pictures' fills are drawn from now. +fn sprites_read(r: &Resolved, zoom: f32, ppp: f32) -> (bool, Option>) { + if !r.style.layers.iter().any(|l| l.visible_at(zoom) && l.draws_patterns()) { + return (false, None); + } + match sprite::load(&r.sprites, ppp >= 1.5) { + Load::Pending => (true, None), + Load::Ready(s) => (false, Some(s.sheet_ids())), + Load::Failed => (false, Some(Vec::new())), + } +} + +/// Whether a picture drawn from the sprites `sheets` still serves while `pending` of them are on +/// their way and `read` have been read. Other sprites read (one that failed read after all, or +/// another failing instead) draw it again, once; until then it stands. +fn sprites_serve(sheets: Option<&[String]>, pending: bool, read: Option<&[String]>) -> bool { + pending || sheets == read } #[derive(Default)] @@ -209,6 +232,7 @@ pub(crate) fn cover(r: &Arc, frame: &Frame, view: &Extent, reach: Opti let m_per_px = TileId::span(z) / f64::from(side); let key = |tile| Key { style: Arc::as_ptr(r) as usize, tile, step: step as i32, ppp: ppp.to_bits() }; let generation = cache::generation(); + let (sprites_pending, read) = sprites_read(r, zoom, ppp); // A view of more squares than a covering holds (a huge window) is drawn straight instead; // a reach of more keeps to the view. let span = TileId::span(z); @@ -229,9 +253,14 @@ pub(crate) fn cover(r: &Arc, frame: &Frame, view: &Extent, reach: Opti let in_view = p.extent().intersects(view); let e = s.entries.get_mut(&key(p.id)).filter(|e| e.style.upgrade().is_some_and(|x| Arc::ptr_eq(&x, r))); match e { - Some(e) if !in_view || e.waiting.is_none_or(|g| g == generation) => { + Some(e) + if !in_view + || (e.waiting.is_none_or(|g| g == generation) + && sprites_serve(e.sheets.as_deref(), sprites_pending, read.as_deref())) => + { e.used = tick; - *pending |= in_view && e.waiting.is_some(); + // (A sprite on its way may add to it: an export waits.) + *pending |= in_view && (e.waiting.is_some() || sprites_pending); found.push((p, Some(e.picture.clone()))); } _ if in_view => { @@ -286,8 +315,14 @@ pub(crate) fn cover(r: &Arc, frame: &Frame, view: &Extent, reach: Opti *pending |= waiting; let bytes = pm.data().len(); let picture = Arc::new(Payload::Image(pm)); - let entry = - Entry { style: Arc::downgrade(r), picture: picture.clone(), bytes, used: tick, waiting: waiting.then_some(generation) }; + let entry = Entry { + style: Arc::downgrade(r), + picture: picture.clone(), + bytes, + used: tick, + waiting: waiting.then_some(generation), + sheets: read.clone(), + }; s.bytes += bytes; if let Some(old) = s.entries.insert(key(slot.0.id), entry) { s.bytes = s.bytes.saturating_sub(old.bytes); @@ -566,6 +601,22 @@ mod tests { panic!("still pending"); } + #[test] + fn a_picture_is_drawn_again_when_other_sprites_are_read() { + let ids = |list: &[&str]| list.iter().map(|id| id.to_string()).collect::>(); + let (none, a, b, both) = (ids(&[]), ids(&["a"]), ids(&["a2"]), ids(&["a", "a2"])); + // No pattern fills: it stands. + assert!(sprites_serve(None, false, None)); + // Drawn from all that could be read: it stands while the other keeps failing... + assert!(sprites_serve(Some(&a), false, Some(&a)) && sprites_serve(Some(&none), false, Some(&none))); + // ...and while that one is asked for again... + assert!(sprites_serve(Some(&a), true, None)); + // ...and is drawn again when it is read, or another is read in its place. + assert!(!sprites_serve(Some(&a), false, Some(&both)) && !sprites_serve(Some(&a), false, Some(&b))); + // Drawn while they were on their way: once they've come. + assert!(!sprites_serve(None, false, Some(&both))); + } + #[test] fn pictures_draw_what_the_style_draws() { let (spec, dir) = spec("same"); diff --git a/crates/tiles/src/shapes.rs b/crates/tiles/src/shapes.rs index 0a4321dcb0..3214359339 100644 --- a/crates/tiles/src/shapes.rs +++ b/crates/tiles/src/shapes.rs @@ -19,7 +19,7 @@ use crate::draw::{Drawn, Frame, Label, Pass, draw_layers, tiles_in}; use crate::mvt::{GeomKind, Tile}; use crate::source::{Resolve, Resolved, Spec, resolve}; use crate::sprite::{self, Load, Sprite}; -use crate::style::{FeatureCtx, LayerKind, LineCap, LineJoin, Rgba, Source, StyleLayer}; +use crate::style::{FeatureCtx, LayerKind, LineCap, LineJoin, PATTERNS, Rgba, Source, StyleLayer}; use crate::template; /// The width of a fill's outline, points (as [`draw`](crate::draw::draw) strokes it). @@ -44,6 +44,8 @@ pub struct VectorTiles { pub attribution: Vec, /// Some tiles (or the sprite) are still on their way. pub pending: bool, + /// What of the style was left out and why, as a drawing's error. + pub error: Option, } /// One data tile placed on the map. @@ -83,7 +85,15 @@ pub fn vector_tiles(spec: &Spec, frame: &Frame, view: &Extent, reach: Option<&Ex draw_layers(None, size, &frame.extent(size.0, size.1), &r, frame, Pass::Labels, &mut d); } let attribution = r.attribution.clone(); - Some(VectorTiles { style: r, source, tiles, level, labels: d.labels, attribution, pending: pending || d.pending }) + let error = crate::draw::left_out(&r, frame, true); + Some(VectorTiles { style: r, source, tiles, level, labels: d.labels, attribution, pending: pending || d.pending, error }) +} + +/// Whether `style` fills with patterns at any zoom of `level`: only then do its meshes need the +/// sprites. +pub fn draws_patterns(style: &Resolved, level: u8) -> bool { + let (lo, hi) = (f32::from(level), f32::from(level) + 1.0); + style.style.layers.iter().any(|l| shown_in(l, lo, hi) && l.draws_patterns()) } /// The one vector source whose shapes are all a style shows at any zoom of `level` (besides its @@ -96,6 +106,9 @@ fn drawn_source(r: &Resolved, level: u8) -> Option { LayerKind::Background | LayerKind::Symbol | LayerKind::Other => {} // Lines painted with a pattern aren't drawn (see `draw::drawable`). LayerKind::Line if l.has_paint("line-pattern") => {} + // A mesh's fill has one pattern's colour for the level: one changing with the zoom + // is drawn zoom by zoom. (Its name may be an `image`, so only the expression tells.) + LayerKind::Fill | LayerKind::FillExtrusion if PATTERNS.iter().any(|p| l.paint_uses_zoom(p)) => return None, LayerKind::Fill | LayerKind::FillExtrusion | LayerKind::Line | LayerKind::Circle => { let at = FeatureCtx::zoom_only; // The level runs up to the next, excluded: what steps there belongs to it. @@ -184,6 +197,9 @@ pub struct TileShapes { pub runs: Vec, /// Pattern fills are left out until the sprite has arrived. pub waiting: bool, + /// The ids of the style's sprites its pattern fills were made from, if it has any: other + /// sprites read (one that failed read after all, say) change them. + pub sheets: Option>, } /// The average colour of a sprite's image (straight RGBA, 0..1). @@ -210,6 +226,11 @@ fn average(img: &tiny_skia::Pixmap) -> Option<[f32; 4]> { /// the next level, in its order. Its background, when it has one, is the first run, filling the /// square. pub fn shapes(style: &Resolved, source: &str, tile: &Tile, level: u8) -> TileShapes { + shapes_with(style, source, tile, level, &|| sprite::load(&style.sprites, false)) +} + +/// [`shapes`], with `load` to load the style's sprites. +fn shapes_with(style: &Resolved, source: &str, tile: &Tile, level: u8, load: &dyn Fn() -> Load) -> TileShapes { // The sprite, loaded the first time a pattern needs it. let mut sheet: Option>> = None; // Each pattern's average colour, found once (a pass over its pixels). @@ -252,7 +273,7 @@ pub fn shapes(style: &Resolved, source: &str, tile: &Tile, level: u8) -> TileSha let free = layer.paint_feature_free(); let mut fixed: [Option>; 4] = Default::default(); for (fi, f) in tl.features.iter().enumerate() { - let ctx = |zoom| FeatureCtx { zoom, kind: f.kind, id: f.id, props: &f.props }; + let ctx = |zoom| FeatureCtx { zoom, kind: f.kind, id: f.id, props: &f.props, images: None }; if !layer.matches(&ctx(lo)) { continue; } @@ -271,21 +292,27 @@ pub fn shapes(style: &Resolved, source: &str, tile: &Tile, level: u8) -> TileSha let (oa, ob) = (layer.fill_opacity(&a), layer.fill_opacity(&b)); let mut color = [rgba(ca, oa), rgba(cb, ob)]; // A pattern names an image of the sprite; one that names none isn't drawn. - let pattern = match ["fill-pattern", "fill-extrusion-pattern"].into_iter().find(|p| layer.has_paint(p)) { + let pattern = match PATTERNS.into_iter().find(|p| layer.has_paint(p)) { Some(p) => { - let Some(crate::style::Val::Str(name)) = - layer.paint_value(p, &a).filter(|v| v.as_str().is_some_and(|n| !n.is_empty())) - else { + // A feature with no name needs no sprite, unless it is the sprite + // that says (an `image` expression). + let named = |v: &crate::style::Val| v.as_str().is_some_and(|n| !n.is_empty()); + if !layer.paint_uses_image(p) && !layer.paint_value(p, &a).is_some_and(|v| named(&v)) { break 'p out; - }; - let sprite = sheet.get_or_insert_with(|| match style.sprite.as_deref().map(|b| sprite::load(b, false)) { - Some(Load::Ready(s)) => Some(s), - Some(Load::Pending) => { + } + let sprite = sheet.get_or_insert_with(|| match load() { + Load::Ready(s) => Some(s), + Load::Pending => { waiting = true; None } - _ => None, + Load::Failed => None, }); + let images = sprite.as_deref(); + let Some(crate::style::Val::Str(name)) = layer.paint_value(p, &FeatureCtx { images, ..a }).filter(named) + else { + break 'p out; + }; let found = match averages.get(&name) { Some(a) => *a, None => { @@ -366,7 +393,9 @@ pub fn shapes(style: &Resolved, source: &str, tile: &Tile, level: u8) -> TileSha runs.push(Run { layer: li, min_zoom: layer.min_zoom, max_zoom: layer.max_zoom, extent: tl.extent, shapes }); } } - TileShapes { runs, waiting } + // (None could be read, or none yet: none.) + let sheets = sheet.map(|s| s.map_or_else(Vec::new, |s| s.sheet_ids())); + TileShapes { runs, waiting, sheets } } #[cfg(test)] @@ -520,6 +549,64 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + #[test] + fn a_pattern_chosen_with_image_asks_the_loaded_sprite() { + let pattern = |name: &str, value: &str| { + let style = STYLE.replacen( + '[', + &format!( + r#"[{{"id": "p", "type": "fill", "source": "x", "source-layer": "parks", "paint": {{"fill-pattern": {value}}}}},"# + ), + 1, + ); + let (spec, dir) = archive(name, &style); + ready(&spec); + (tile(&spec, 2.5), dir) + }; + let shaped = |v: &VectorTiles, load: &dyn Fn() -> Load| { + let Payload::Vector(t) = &*v.tiles[0].payload else { panic!("a vector tile") }; + shapes_with(&v.style, &v.source, t, v.level, load) + }; + let loaded = || Load::Ready(Arc::new(crate::draw::tests::sheet())); + let (v, dir) = pattern("image-pattern", r#"["coalesce", ["image", "nope"], ["image", "red"]]"#); + // With the sprite: the fill is drawn, and says from how many sprites. + let s = shaped(&v, &loaded); + assert!(!s.waiting && s.sheets == Some(vec!["default".to_owned()]) && s.runs.iter().any(|r| r.layer == 0)); + // While it's on its way: left out, and made again. + let s = shaped(&v, &|| Load::Pending); + assert!(s.waiting && s.sheets == Some(Vec::new()) && s.runs.iter().all(|r| r.layer != 0)); + // Failed: left out, and not waiting. + let s = shaped(&v, &|| Load::Failed); + assert!(!s.waiting && s.sheets == Some(Vec::new()) && s.runs.iter().all(|r| r.layer != 0)); + let _ = std::fs::remove_dir_all(dir); + // A name no feature has, with no `image`: nothing asks the sprite, so nothing waits for it. + let (v, dir) = pattern("no-pattern-name", r#"["get", "no-such-field"]"#); + let s = shaped(&v, &|| Load::Pending); + assert!(!s.waiting && s.sheets.is_none() && s.runs.iter().all(|r| r.layer != 0)); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_pattern_changing_with_the_zoom_is_drawn_zoom_by_zoom() { + let source = |name: &str, value: &str| { + let style = STYLE.replacen( + '[', + &format!( + r#"[{{"id": "p", "type": "fill", "source": "x", "source-layer": "parks", "paint": {{"fill-pattern": {value}}}}},"# + ), + 1, + ); + let (spec, dir) = archive(name, &style); + let found = drawn_source(&ready(&spec), 2); + let _ = std::fs::remove_dir_all(dir); + found + }; + // One mesh colour for the level can't show a step within it, whatever names the steps give. + assert!(source("zoom-image-pattern", r#"["step", ["zoom"], ["image", "red"], 2.5, ["image", "blue"]]"#).is_none()); + assert!(source("zoom-named-pattern", r#"["step", ["zoom"], "red", 2.5, "blue"]"#).is_none()); + assert!(source("fixed-pattern", r#""red""#).is_some()); + } + #[test] fn a_step_at_the_next_level_holds_over_this_one() { let style = STYLE.replace(r#""line-width": 2,"#, r#""line-width": ["step", ["zoom"], 2, 3, 6],"#); diff --git a/crates/tiles/src/source.rs b/crates/tiles/src/source.rs index 923a2b481d..81f75c3b1f 100644 --- a/crates/tiles/src/source.rs +++ b/crates/tiles/src/source.rs @@ -75,9 +75,9 @@ impl Spec { /// A style whose sources all have tile addresses. pub struct Resolved { pub style: Style, - /// The style's sprite (an address without `.json`/`.png`), when it has one RustGIS can + /// The style's sprites as (id, address without `.json`/`.png`), those RustGIS can /// fetch. - pub sprite: Option, + pub sprites: Vec<(String, String)>, /// Credits from the layer and its sources, without duplicates. pub attribution: Vec, /// What of the style was left out and why, said with every drawing of it as its error. @@ -104,7 +104,7 @@ fn kept(old: Arc, new: Arc) -> Arc { if old.left_out != new.left_out || old.waiting != new.waiting || old.style != new.style - || old.sprite != new.sprite + || old.sprites != new.sprites || old.attribution != new.attribution { return new; @@ -260,7 +260,7 @@ fn resolve_anew(spec: &Spec, key: String) -> Resolve { } // Sources given by a TileJSON address. let base = spec.url.clone(); - let Sources { left_out, waiting } = match resolve_sources(&mut style, spec, &base) { + let Sources { mut left_out, waiting } = match resolve_sources(&mut style, spec, &base) { Ok(Some(sources)) => sources, Ok(None) => return Resolve::Pending, Err(e) => return Resolve::Failed(e), @@ -278,14 +278,9 @@ fn resolve_anew(spec: &Spec, key: String) -> Resolve { credit(attribution); } } - // The sprite is the style's choice; one that can't be fetched only loses the icons. - let sprite = style - .sprite - .as_deref() - .filter(|s| !s.starts_with("mapbox://")) - .map(|s| template::join(&base, s)) - .filter(|s| address::check(s, Some(&base)).is_ok()); - let r = Arc::new(Resolved { style, attribution, sprite, left_out, made: Mutex::new(Instant::now()), waiting }); + let (sprites, sprites_left_out) = resolve_sprites(&style, &base); + left_out.extend(sprites_left_out); + let r = Arc::new(Resolved { style, attribution, sprites, left_out, made: Mutex::new(Instant::now()), waiting }); let mut all = resolved().lock().unwrap_or_else(|e| e.into_inner()); // A few layers are in use at a time: past that many, start again rather than grow. if all.len() >= MAX_RESOLVED { @@ -295,6 +290,38 @@ fn resolve_anew(spec: &Spec, key: String) -> Resolve { Resolve::Ready(r) } +/// A style's sprites with their addresses resolved against `base`, those RustGIS can fetch, and +/// what was left out of them, and why, if a layer not hidden draws images and so misses them: the +/// sprites are the style's choice, and one that can't be fetched only loses its own icons. +fn resolve_sprites(style: &Style, base: &str) -> (Vec<(String, String)>, Vec) { + let mut sprites = Vec::new(); + let mut left_out = style.sprites_left_out.clone(); + let (mut mapbox, mut refused) = (Vec::new(), Vec::new()); + for (id, s) in &style.sprites { + let address = template::join(base, s); + if s.starts_with("mapbox://") { + mapbox.push(id.as_str()); + } else if address::check(&address, Some(base)).is_err() { + refused.push(id.as_str()); + } else { + sprites.push((id.clone(), address)); + } + } + let total = style.sprites_listed; + let mut say = |ids: &[&str], why: &str| { + if !ids.is_empty() { + let (n, ids) = (ids.len(), ids.join(", ")); + left_out.push(format!("{n} of {total} sprites left out, so their icons and patterns aren't drawn ({why}): {ids}")); + } + }; + say(&mapbox, "mapbox:// addresses need Mapbox's own library"); + say(&refused, "RustGIS won't fetch their addresses"); + if !style.layers.iter().any(|l| l.visible && l.draws_images()) { + left_out.clear(); + } + (sprites, left_out) +} + /// What resolving a style's sources left out of it. #[derive(Debug, Default, PartialEq)] struct Sources { @@ -794,7 +821,7 @@ mod tests { let doc = serde_json::json!({"version": 8, "sources": {}, "layers": [{"id": "bg", "type": "background", "paint": {"background-color": "#f00"}}]}); let r = Resolved { style: Style::parse(&doc).unwrap(), - sprite: None, + sprites: Vec::new(), attribution: Vec::new(), left_out: Vec::new(), made: Mutex::new(Instant::now()), @@ -826,7 +853,7 @@ mod tests { assert!(matches!(style.source("dem"), Some(Source::Other))); let r = Resolved { style, - sprite: None, + sprites: Vec::new(), attribution: Vec::new(), left_out: sources.left_out, made: Mutex::new(Instant::now()), @@ -848,7 +875,7 @@ mod tests { let left_out = vec!["elevation source dem left out, so its relief isn't drawn: gone".to_owned()]; let r = Resolved { style: Style::parse(&doc).unwrap(), - sprite: None, + sprites: Vec::new(), attribution: Vec::new(), left_out, made: Mutex::new(Instant::now()), @@ -866,7 +893,7 @@ mod tests { let Some(long_ago) = Instant::now().checked_sub(cache::RETRY * 2) else { return }; let stale = Resolved { style: Style::parse(&doc).unwrap(), - sprite: None, + sprites: Vec::new(), attribution: Vec::new(), left_out: vec!["x".into()], made: Mutex::new(long_ago), @@ -875,7 +902,7 @@ mod tests { assert!(!stale.current()); let complete = Resolved { style: Style::parse(&doc).unwrap(), - sprite: None, + sprites: Vec::new(), attribution: Vec::new(), left_out: Vec::new(), made: Mutex::new(long_ago), @@ -886,7 +913,7 @@ mod tests { let s = spec(Kind::Raster, "https://expired.example.com/{z}/{x}/{y}.png"); let expired = Arc::new(Resolved { style: Style::parse(&doc).unwrap(), - sprite: None, + sprites: Vec::new(), attribution: Vec::new(), left_out: vec!["x".into()], made: Mutex::new(long_ago), @@ -918,7 +945,7 @@ mod tests { let made = |left_out: &[&str], at: Instant| { Arc::new(Resolved { style: Style::parse(&doc).unwrap(), - sprite: None, + sprites: Vec::new(), attribution: Vec::new(), left_out: left_out.iter().map(|s| s.to_string()).collect(), made: Mutex::new(at), @@ -935,7 +962,7 @@ mod tests { assert!(Arc::ptr_eq(&kept(old.clone(), new.clone()), &new)); let other = Arc::new(Resolved { style: Style::parse(&serde_json::json!({"version": 8, "sources": {}, "layers": [{"id": "bg", "type": "background"}]})).unwrap(), - sprite: None, + sprites: Vec::new(), attribution: Vec::new(), left_out: vec!["dem: gone".into()], made: Mutex::new(Instant::now()), @@ -945,7 +972,7 @@ mod tests { // Still waiting for an elevation source, or no longer: the new one. let arrived = Arc::new(Resolved { style: Style::parse(&doc).unwrap(), - sprite: None, + sprites: Vec::new(), attribution: Vec::new(), left_out: vec!["dem: gone".into()], made: Mutex::new(Instant::now()), @@ -955,7 +982,7 @@ mod tests { // Only its credits changed: the new one too. let recredited = Arc::new(Resolved { style: Style::parse(&doc).unwrap(), - sprite: None, + sprites: Vec::new(), attribution: vec!["© Example".into()], left_out: vec!["dem: gone".into()], made: Mutex::new(Instant::now()), @@ -964,6 +991,58 @@ mod tests { assert!(Arc::ptr_eq(&kept(old, recredited.clone()), &recredited)); } + #[test] + fn sprites_that_cant_be_fetched_are_said() { + let base = "https://t.example.com/style.json"; + let icons = serde_json::json!([{"id": "i", "type": "symbol", "source": "s", "layout": {"icon-image": "x"}}]); + let doc = serde_json::json!({"version": 8, "sources": {}, "layers": icons, "sprite": [ + {"id": "good", "url": "sprites/a"}, + {"id": "box", "url": "mapbox://sprites/x"}, + {"id": "meta", "url": "http://169.254.169.254/s"}, + {"url": "no-id"}]}); + let (sprites, said) = resolve_sprites(&Style::parse(&doc).unwrap(), base); + assert_eq!(sprites, [("good".to_owned(), "https://t.example.com/sprites/a".to_owned())]); + assert_eq!(said.len(), 3, "{said:?}"); + assert!(said[0].starts_with("1 of 4 sprites left out"), "{said:?}"); + assert!(said[1].starts_with("1 of 4 sprites left out") && said[1].contains("mapbox://") && said[1].ends_with(": box"), "{said:?}"); + assert!(said[2].starts_with("1 of 4 sprites left out") && said[2].ends_with(": meta"), "{said:?}"); + // One line per reason, however many: with how many, and which. + let two = |layers: &serde_json::Value| { + let doc = serde_json::json!({"version": 8, "sources": {}, "layers": layers, "sprite": [ + {"id": "a", "url": "mapbox://sprites/a"}, {"id": "b", "url": "mapbox://sprites/b"}]}); + resolve_sprites(&Style::parse(&doc).unwrap(), base).1 + }; + // Said only of a style that misses them: not with no layer drawing images, or one hidden. + assert!(two(&serde_json::json!([])).is_empty()); + let hidden = serde_json::json!([{"id": "i", "type": "symbol", "source": "s", "layout": {"icon-image": "x", "visibility": "none"}}]); + assert!(two(&hidden).is_empty()); + let said = two(&icons); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("2 of 2 sprites left out") && said[0].ends_with(": a, b"), "{said:?}"); + // Clean: nothing to say. + let doc = serde_json::json!({"version": 8, "sources": {}, "layers": [], "sprite": "https://t.example.com/s"}); + assert!(resolve_sprites(&Style::parse(&doc).unwrap(), base).1.is_empty()); + } + + #[test] + fn only_layers_drawing_images_miss_a_sprite() { + let layer = |j: serde_json::Value| crate::style::StyleLayer::parse(&j).unwrap(); + let of = |kind: &str, what: serde_json::Value| { + let mut l = serde_json::json!({"id": "a", "type": kind, "source": "s"}); + l.as_object_mut().unwrap().extend(what.as_object().unwrap().clone()); + layer(l) + }; + assert!(of("symbol", serde_json::json!({"layout": {"icon-image": "x"}})).draws_images()); + assert!(of("fill", serde_json::json!({"paint": {"fill-pattern": "x"}})).draws_images()); + assert!(!of("symbol", serde_json::json!({"layout": {"text-field": "x"}})).draws_images()); + assert!(!of("fill", serde_json::json!({"paint": {"fill-color": "#000"}})).draws_images()); + // A line painted with a pattern isn't drawn, so it misses nothing. + assert!(!of("line", serde_json::json!({"paint": {"line-pattern": "x"}})).draws_images()); + // Nor does another kind of layer naming an icon, or a pattern, that it doesn't draw. + assert!(!of("circle", serde_json::json!({"layout": {"icon-image": "x"}})).draws_images()); + assert!(!of("circle", serde_json::json!({"paint": {"fill-pattern": "x"}})).draws_images()); + } + #[test] fn plain_attribution() { assert_eq!(plain_text("© OpenStreetMap contributors & CARTO"), "© OpenStreetMap contributors & CARTO"); diff --git a/crates/tiles/src/sprite.rs b/crates/tiles/src/sprite.rs index 2f42229d12..17d160726e 100644 --- a/crates/tiles/src/sprite.rs +++ b/crates/tiles/src/sprite.rs @@ -4,6 +4,8 @@ //! picture, its pixel ratio and whether it is an SDF icon) and `
.png`, and their `@2x` //! versions for high-density screens. Both come through the tile cache; images are cut out of //! the picture the first time they are asked for, and SDF icons are coloured as they are drawn. +//! A style may name several sprites, each with an id: one is its `default`, and the images of +//! the others are named `:`. use std::collections::HashMap; use std::sync::{Arc, Mutex, OnceLock}; @@ -11,7 +13,7 @@ use std::sync::{Arc, Mutex, OnceLock}; use tiny_skia::{IntRect, Pixmap}; use crate::cache::{self, Payload, State, Want}; -use crate::style::Rgba; +use crate::style::{MAX_SPRITES, Rgba}; /// Where one image is in the picture. #[derive(Clone, Copy, Debug, PartialEq)] @@ -24,8 +26,19 @@ struct Entry { sdf: bool, } -/// A loaded sprite. +/// A style's loaded sprites, by id. pub struct Sprite { + sheets: Vec<(String, Arc)>, +} + +impl std::fmt::Debug for Sprite { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_list().entries(self.sheets.iter().map(|(id, s)| (id, s.index.len()))).finish() + } +} + +/// One sprite: its picture and index. +struct Sheet { sheet: Pixmap, index: HashMap, /// Images cut out so far, by name and (for SDF icons) colour: looked up by `&str`, so a @@ -45,12 +58,68 @@ pub struct Image { const MAX_IMAGES: usize = 10_000; /// The largest side of one image (icons and patterns are tens of pixels). const MAX_SIDE: f64 = 1024.0; -/// The most bytes of cut images kept. +/// The most bytes of cut images a sheet keeps. const MAX_CUT_BYTES: usize = 32 << 20; +/// The most bytes of decoded pictures the kept sheets hold together. +const MAX_SHEET_BYTES: usize = 256 << 20; +/// The most bytes of cut images the kept sheets hold together: a style may have many sprites. +const MAX_ALL_CUT_BYTES: usize = 64 << 20; impl Sprite { - /// Reads a sprite from its index and picture. + /// A style's one sprite, from its index and picture. pub fn new(index: &serde_json::Value, sheet: Pixmap) -> Sprite { + Sprite { sheets: vec![("default".to_owned(), Arc::new(Sheet::new(index, sheet)))] } + } + + /// A style's sprites, each from its id, index and picture. + #[cfg(test)] + pub(crate) fn of(sheets: Vec<(&str, serde_json::Value, Pixmap)>) -> Sprite { + Sprite { sheets: sheets.into_iter().map(|(id, index, sheet)| (id.to_owned(), Arc::new(Sheet::new(&index, sheet)))).collect() } + } + + /// The sheet with the image `name`, and its name there, as MapLibre names them: a sprite's + /// images are `:`, and the `default` sprite's just ``. Looking anywhere else + /// would draw another sprite's image of that name, and keep `coalesce` from going on to its + /// next choice. An id may hold a colon itself (`harbour:night:light`), so the name is matched + /// against each id, not split, and the longest id that has the image wins. + fn find<'a>(&self, name: &'a str) -> Option<(&Sheet, &'a str)> { + let named = self + .sheets + .iter() + .filter(|(id, _)| id != "default") + .filter_map(|(id, s)| { + let bare = name.strip_prefix(id.as_str())?.strip_prefix(':')?; + s.usable(bare).then_some((id.len(), (&**s, bare))) + }) + .max_by_key(|(len, _)| *len) + .map(|(_, found)| found); + named.or_else(|| { + let (_, s) = self.sheets.iter().find(|(id, _)| id == "default")?; + s.usable(name).then_some((&**s, name)) + }) + } + + /// The ids of the style's sprites that were read. They change when one that failed is read + /// after all, or another fails instead, and what was made from them can then be made again. + pub fn sheet_ids(&self) -> Vec { + self.sheets.iter().map(|(id, _)| id.clone()).collect() + } + + /// Whether a sprite has the image `name`, one that can be drawn. + pub fn has(&self, name: &str) -> bool { + self.find(name).is_some() + } + + /// The image `name`, if a sprite has it. An SDF icon is drawn in `color` (black when none + /// is given). + pub fn image(&self, name: &str, color: Option) -> Option { + let (sheet, name) = self.find(name)?; + sheet.image(name, color) + } +} + +impl Sheet { + fn new(index: &serde_json::Value, sheet: Pixmap) -> Sheet { let num = |v: &serde_json::Value, k: &str| v.get(k).and_then(serde_json::Value::as_f64); let index = index .as_object() @@ -69,28 +138,43 @@ impl Sprite { Some((name.clone(), Entry { x: x as u32, y: y as u32, w: w as u32, h: h as u32, ratio, sdf })) }) .collect(); - Sprite { sheet, index, cut: Mutex::default() } + Sheet { sheet, index, cut: Mutex::default() } + } + + /// Whether the index lists `name` wholly inside the picture: an entry reaching past it can't + /// be cut (cutting would otherwise clip it to a part). + fn usable(&self, name: &str) -> bool { + self.index.get(name).is_some_and(|e| self.fits(e)) + } + + fn fits(&self, e: &Entry) -> bool { + e.x.checked_add(e.w).is_some_and(|r| r <= self.sheet.width()) && e.y.checked_add(e.h).is_some_and(|b| b <= self.sheet.height()) } - fn entry(&self, name: &str) -> Option<(&str, Entry)> { - if let Some((k, e)) = self.index.get_key_value(name) { - return Some((k.as_str(), *e)); + /// The bytes of the images cut so far. + fn cut_bytes(&self) -> usize { + self.cut.lock().unwrap_or_else(|p| p.into_inner()).values().flat_map(HashMap::values).map(|p| p.data().len()).sum() + } + + /// Starts this sheet's and `others`' cut images again if `more` bytes would take them past + /// `budget`: images are cut again when next asked for. + fn make_room(&self, others: &[Arc], more: usize, budget: usize) { + let others = || others.iter().map(|s| &**s).filter(|s| !std::ptr::eq(*s, self)); + if self.cut_bytes() + others().map(Sheet::cut_bytes).sum::() + more > budget { + for s in others().chain([self]) { + s.cut.lock().unwrap_or_else(|p| p.into_inner()).clear(); + } } - // A style with several sprites names their images `:`. - let (_, bare) = name.split_once(':')?; - self.index.get_key_value(bare).map(|(k, e)| (k.as_str(), *e)) } - /// The image `name`, if the sprite has it. An SDF icon is drawn in `color` (black when - /// none is given). - pub fn image(&self, name: &str, color: Option) -> Option { - let (key, e) = self.entry(name)?; + fn image(&self, name: &str, color: Option) -> Option { + let (key, e) = self.index.get_key_value(name).map(|(k, e)| (k.as_str(), *e))?; let color = e.sdf.then(|| color.unwrap_or([0, 0, 0, 255])); if let Some(p) = self.cut.lock().unwrap_or_else(|p| p.into_inner()).get(key).and_then(|by_color| by_color.get(&color)) { return Some(Image { pixmap: p.clone(), ratio: e.ratio }); } - // Cut outside the lock. Wholly inside the picture (cutting would otherwise clip a bad entry to a part). - if e.x.checked_add(e.w)? > self.sheet.width() || e.y.checked_add(e.h)? > self.sheet.height() { + // Cut outside the lock. + if !self.fits(&e) { return None; } let mut p = self.sheet.clone_rect(IntRect::from_xywh(e.x as i32, e.y as i32, e.w, e.h)?)?; @@ -98,6 +182,13 @@ impl Sprite { sdf_fill(&mut p, c); } let p = Arc::new(p); + // One cut at a time from here, so workers can't each see room for theirs and together go + // past the budget. (A cut image is found without this lock. The kept sheets are listed + // before any sheet's images are locked, and each is locked on its own.) + static ROOM: Mutex<()> = Mutex::new(()); + let _room = ROOM.lock().unwrap_or_else(|p| p.into_inner()); + let others: Vec> = sprites().lock().unwrap_or_else(|p| p.into_inner()).values().cloned().collect(); + self.make_room(&others, p.data().len(), MAX_ALL_CUT_BYTES); let mut cut = self.cut.lock().unwrap_or_else(|p| p.into_inner()); // Kept within a byte budget: an SDF icon cut in many colours, or a style naming // thousands of images, starts the cache again rather than growing it. @@ -132,8 +223,8 @@ pub enum Load { Failed, } -fn sprites() -> &'static Mutex>> { - static S: OnceLock>>> = OnceLock::new(); +fn sprites() -> &'static Mutex>> { + static S: OnceLock>>> = OnceLock::new(); S.get_or_init(Mutex::default) } @@ -150,40 +241,94 @@ fn with_suffix(base: &str, suffix: &str) -> String { } } -/// The sprite at `base` (an address without `.json`/`.png`), at high density when `hi_dpi` -/// and the style has one, else at 1×. -pub fn load(base: &str, hi_dpi: bool) -> Load { +/// What to say of `sprites` (of the `listed` a style has, as (id, address)) that `load` couldn't +/// read, if any: they lose only their own images (`what`), but that is said. Nothing while they +/// are on their way. +pub(crate) fn unread_note(sprites: &[(String, String)], listed: usize, load: &Load, what: &str) -> Option { + let read: Vec<&str> = match load { + Load::Pending => return None, + Load::Failed => Vec::new(), + Load::Ready(s) => s.sheets.iter().map(|(id, _)| id.as_str()).collect(), + }; + let unread: Vec<&str> = sprites.iter().map(|(id, _)| id.as_str()).filter(|id| !read.contains(id)).collect(); + (!unread.is_empty()) + .then(|| format!("{} of {listed} sprites couldn't be read, so their {what} aren't drawn: {}", unread.len(), unread.join(", "))) +} + +/// A sheet on its way. +enum SheetLoad { + Ready(Arc), + Pending, + Failed, +} + +/// A style's sprites, as (id, address without `.json`/`.png`), at high density when `hi_dpi` +/// and a sprite has it, else at 1×. Ready once none is on its way, with those that could be +/// read; one that can't only loses its images. +pub fn load(sprites: &[(String, String)], hi_dpi: bool) -> Load { + load_with(sprites, |base| load_sheet(base, hi_dpi)) +} + +fn load_with(sprites: &[(String, String)], sheet: impl Fn(&str) -> SheetLoad) -> Load { + let mut sheets = Vec::new(); + let mut pending = false; + for (id, base) in sprites { + match sheet(base) { + SheetLoad::Ready(s) => sheets.push((id.clone(), s)), + SheetLoad::Pending => pending = true, + SheetLoad::Failed => {} + } + } + if pending { + Load::Pending + } else if sheets.is_empty() { + Load::Failed + } else { + Load::Ready(Arc::new(Sprite { sheets })) + } +} + +/// Keeps a decoded sheet. Room for every sprite of a style at both densities, since the mesh path +/// asks for 1× and a high-density screen's drawing for `@2x` on every frame: fewer would start +/// again each time, and cut the icons again. Past that, or past `budget` bytes of pictures, it +/// starts again rather than grow. +fn keep(all: &mut HashMap>, key: String, sheet: Arc, budget: usize) { + let others = all.iter().filter(|(k, _)| **k != key); + let bytes: usize = others.clone().map(|(_, s)| s.sheet.data().len()).sum(); + if others.count() >= 2 * MAX_SPRITES || bytes + sheet.sheet.data().len() > budget { + all.clear(); + } + all.insert(key, sheet); +} + +fn load_sheet(base: &str, hi_dpi: bool) -> SheetLoad { if hi_dpi { match load_one(base, "@2x") { - Load::Failed => {} + SheetLoad::Failed => {} other => return other, } } load_one(base, "") } -fn load_one(base: &str, density: &str) -> Load { +fn load_one(base: &str, density: &str) -> SheetLoad { let key = format!("{base}|{density}"); if let Some(s) = sprites().lock().unwrap_or_else(|p| p.into_inner()).get(&key) { - return Load::Ready(s.clone()); + return SheetLoad::Ready(s.clone()); } let index = cache::get(&with_suffix(base, &format!("{density}.json")), Want::Json); let sheet = cache::get(&with_suffix(base, &format!("{density}.png")), Want::Image); match (index, sheet) { (State::Ready(i), State::Ready(p)) => match (&*i, &*p) { (Payload::Json(index), Payload::Image(sheet)) => { - let s = Arc::new(Sprite::new(index, sheet.clone())); - let mut all = sprites().lock().unwrap_or_else(|p| p.into_inner()); - if all.len() > 16 { - all.clear(); - } - all.insert(key, s.clone()); - Load::Ready(s) + let s = Arc::new(Sheet::new(index, sheet.clone())); + keep(&mut sprites().lock().unwrap_or_else(|p| p.into_inner()), key, s.clone(), MAX_SHEET_BYTES); + SheetLoad::Ready(s) } - _ => Load::Failed, + _ => SheetLoad::Failed, }, - (State::Failed(_), _) | (_, State::Failed(_)) => Load::Failed, - _ => Load::Pending, + (State::Failed(_), _) | (_, State::Failed(_)) => SheetLoad::Failed, + _ => SheetLoad::Pending, } } @@ -200,7 +345,7 @@ mod tests { #[test] fn forgetting_drops_the_decoded_sheets() { let key = "forget-test|".to_string(); - let sprite = Sprite { sheet: sheet(), index: Default::default(), cut: Default::default() }; + let sprite = Sheet { sheet: sheet(), index: Default::default(), cut: Default::default() }; sprites().lock().unwrap().insert(key.clone(), Arc::new(sprite)); forget(); assert!(!sprites().lock().unwrap().contains_key(&key)); @@ -219,8 +364,12 @@ mod tests { let dot = s.image("dot", None).unwrap(); assert_eq!((dot.pixmap.width(), dot.ratio), (4, 2.0)); // Several sprites: `:`. - assert!(s.image("base:dot", None).is_some()); + // A style's one sprite is `default`: its images are named without an id. + assert!(s.image("base:dot", None).is_none()); assert!(s.image("bad", None).is_none() && s.image("junk", None).is_none() && s.image("nope", None).is_none()); + // Listed, but reaching past the picture: not there for `image` either, so `coalesce` + // goes on to the next. + assert!(!s.has("bad") && s.has("dot")); assert!(s.image("huge", None).is_none(), "over the largest side"); // An SDF icon takes the colour asked for (full alpha is well inside the edge). let blue = s.image("sdf", Some([0, 0, 255, 255])).unwrap(); @@ -228,6 +377,141 @@ mod tests { assert_eq!((px.red(), px.blue(), px.alpha()), (0, 255, 255)); } + #[test] + fn several_sprites_name_their_images_by_id() { + let sheet_of = |names: &[&str]| { + let index: serde_json::Map<_, _> = + names.iter().map(|n| (n.to_string(), serde_json::json!({"x": 0, "y": 0, "width": 4, "height": 4}))).collect(); + Arc::new(Sheet::new(&serde_json::Value::Object(index), sheet())) + }; + let s = Sprite { + sheets: vec![ + ("base".to_owned(), sheet_of(&["icon-bus", "anchor"])), + ("nautical".to_owned(), sheet_of(&["anchor", "light/red"])), + ], + }; + assert!(s.has("nautical:light/red") && s.has("base:icon-bus")); + // The id picks the sprite when both have the name. + let (picked, name) = s.find("nautical:anchor").unwrap(); + assert!(std::ptr::eq(picked, &*s.sheets[1].1) && name == "anchor"); + // Only in the sprite named: not in another that has an image of that name. + assert!(!s.has("base:light/red") && !s.has("nautical:icon-bus") && !s.has("nautical:") && !s.has("")); + // Without an id, only in the `default` sprite, which this style hasn't got. + assert!(!s.has("icon-bus") && !s.has("other:icon-bus")); + let with_default = Sprite { sheets: vec![("default".to_owned(), sheet_of(&["pin"])), ("nautical".to_owned(), sheet_of(&["pin"]))] }; + let (d, name) = with_default.find("pin").unwrap(); + assert!(std::ptr::eq(d, &*with_default.sheets[0].1) && name == "pin"); + assert!(with_default.has("nautical:pin") && !with_default.has("default:missing")); + // Nothing to read is no sprite. + assert!(matches!(load(&[], false), Load::Failed)); + } + + #[test] + fn an_id_may_hold_a_colon() { + let at = serde_json::json!({"x": 0, "y": 0, "width": 4, "height": 4}); + let s = Sprite::of(vec![ + ("harbour:night", serde_json::json!({"light": at}), sheet()), + ("harbour", serde_json::json!({"crane": at}), sheet()), + ("default", serde_json::json!({"pin": at, "other:pin": at}), sheet()), + ]); + let (found, name) = s.find("harbour:night:light").unwrap(); + assert!(std::ptr::eq(found, &*s.sheets[0].1) && name == "light"); + assert!(s.has("harbour:crane")); + // Both ids fit and both have an image of that name: the longest. + let both = Sprite::of(vec![("a", serde_json::json!({"b:icon": at}), sheet()), ("a:b", serde_json::json!({"icon": at}), sheet())]); + let (found, name) = both.find("a:b:icon").unwrap(); + assert!(std::ptr::eq(found, &*both.sheets[1].1) && name == "icon"); + // Named by neither id: a `default` image, whose name may hold one. + assert!(s.has("other:pin") && !s.has("other:crane") && !s.has("harbour:night:crane")); + // The `default` sprite's images have no prefix. + assert!(s.has("pin") && !s.has("default:pin")); + } + + #[test] + fn cut_images_are_kept_within_a_budget_across_sheets() { + let at = serde_json::json!({"x": 0, "y": 0, "width": 4, "height": 4}); + let sheet_of = || Arc::new(Sheet::new(&serde_json::json!({"a": at}), sheet())); + let (one, two) = (sheet_of(), sheet_of()); + one.image("a", None).unwrap(); + two.image("a", None).unwrap(); + let (a, b) = (one.cut_bytes(), two.cut_bytes()); + assert!(a > 0 && b > 0); + // Room left: both stay. (`one` listed too counts once.) + one.make_room(&[one.clone(), two.clone()], 1, a + b + 1); + assert_eq!((one.cut_bytes(), two.cut_bytes()), (a, b)); + // No room: both start again, and cut their images when next asked. + one.make_room(&[one.clone(), two.clone()], 2, a + b + 1); + assert_eq!((one.cut_bytes(), two.cut_bytes()), (0, 0)); + assert!(two.image("a", None).is_some()); + } + + #[test] + fn every_sprite_of_a_style_is_read() { + let one = |name: &str| { + let index = serde_json::json!({ name: {"x": 0, "y": 0, "width": 4, "height": 4} }); + SheetLoad::Ready(Arc::new(Sheet::new(&index, sheet()))) + }; + let style: Vec<_> = ["a", "b"].iter().map(|id| (id.to_string(), id.to_string())).collect(); + // Both read: each with its own images, in the style's order. + let Load::Ready(s) = load_with(&style, |base| one(base)) else { panic!("ready") }; + assert_eq!(s.sheet_ids(), ["a", "b"]); + assert!(s.has("a:a") && s.has("b:b") && !s.has("a:b") && !s.has("b:a")); + // One that fails only loses its own. + let Load::Ready(s) = load_with(&style, |base| if base == "a" { SheetLoad::Failed } else { one(base) }) else { panic!("ready") }; + assert_eq!(s.sheet_ids(), ["b"]); + // One on its way holds back the others, whichever it is. + assert!(matches!(load_with(&style, |base| if base == "a" { SheetLoad::Pending } else { one(base) }), Load::Pending)); + assert!(matches!(load_with(&style, |base| if base == "b" { SheetLoad::Pending } else { one(base) }), Load::Pending)); + // None read. + assert!(matches!(load_with(&style, |_| SheetLoad::Failed), Load::Failed)); + } + + #[test] + fn says_which_sprites_couldnt_be_read() { + let ids = |list: &[&str]| list.iter().map(|id| (id.to_string(), format!("https://x/{id}"))).collect::>(); + let index = serde_json::json!({}); + let read = |list: &[&str]| Load::Ready(Arc::new(Sprite::of(list.iter().map(|id| (*id, index.clone(), sheet())).collect()))); + let style = ids(&["base", "nautical", "roads"]); + // Some read: those that weren't, and how many. + let said = unread_note(&style, 3, &read(&["nautical"]), "icons and patterns").unwrap(); + assert_eq!(said, "2 of 3 sprites couldn't be read, so their icons and patterns aren't drawn: base, roads"); + // None read: all of them. + let said = unread_note(&style, 3, &Load::Failed, "icons").unwrap(); + assert_eq!(said, "3 of 3 sprites couldn't be read, so their icons aren't drawn: base, nautical, roads"); + // All read, on their way, or none to read: nothing to say. + assert_eq!(unread_note(&style, 3, &read(&["base", "nautical", "roads"]), "icons"), None); + assert_eq!(unread_note(&style, 3, &Load::Pending, "icons"), None); + assert_eq!(unread_note(&[], 0, &Load::Failed, "icons"), None); + // Counted among all the style lists, as its other notices are. + let said = unread_note(&style, 5, &Load::Failed, "icons").unwrap(); + assert!(said.starts_with("3 of 5 sprites couldn't be read"), "{said}"); + } + + #[test] + fn keeps_every_sprite_of_a_style_at_both_densities() { + let mut all = HashMap::new(); + let one = || Arc::new(Sheet::new(&serde_json::json!({}), sheet())); + let keys: Vec = (0..MAX_SPRITES).flat_map(|i| [format!("s{i}|"), format!("s{i}|@2x")]).collect(); + for key in &keys { + keep(&mut all, key.clone(), one(), usize::MAX); + } + assert_eq!(all.len(), keys.len(), "none of them evicted"); + // Asked for again, nothing is lost. + keep(&mut all, keys[0].clone(), one(), usize::MAX); + assert_eq!(all.len(), keys.len()); + // Past that, it starts again. + keep(&mut all, "another|".to_owned(), one(), usize::MAX); + assert_eq!(all.len(), 1); + // And past the bytes, however few sheets: each picture here is 8 × 4 × 4 bytes. + let mut all = HashMap::new(); + let side = one().sheet.data().len(); + keep(&mut all, "a|".to_owned(), one(), 2 * side); + keep(&mut all, "b|".to_owned(), one(), 2 * side); + assert_eq!(all.len(), 2); + keep(&mut all, "c|".to_owned(), one(), 2 * side); + assert_eq!(all.len(), 1); + } + #[test] fn suffixes_go_before_the_query() { assert_eq!(with_suffix("https://a/sprite?key=1", "@2x.png"), "https://a/sprite@2x.png?key=1"); diff --git a/crates/tiles/src/style.rs b/crates/tiles/src/style.rs index ef89f7d7a7..e8aa84ca35 100644 --- a/crates/tiles/src/style.rs +++ b/crates/tiles/src/style.rs @@ -22,6 +22,12 @@ const MAX_ARRAY: usize = 4096; const MAX_STR: usize = 1 << 16; const MAX_LAYERS: usize = 10_000; const MAX_SOURCES: usize = 256; +/// The most sprites a style's are read from. +pub(crate) const MAX_SPRITES: usize = 16; +/// The paint properties that fill with an image of a sprite. +pub(crate) const PATTERNS: [&str; 2] = ["fill-pattern", "fill-extrusion-pattern"]; +/// The longest sprite id read: pictures and meshes each keep the ids they were made from. +const MAX_SPRITE_ID: usize = 128; const MAX_PROPS: usize = 256; const MAX_STOPS: usize = 1024; /// The most lights a multidirectional hillshade takes: each shades every pixel again. @@ -62,12 +68,15 @@ pub struct FeatureCtx<'a> { pub kind: GeomKind, pub id: Option, pub props: &'a [(String, Value)], + /// The style's sprite, while an icon is chosen: `["image", name]` is `name` when it has + /// that image, else null. + pub images: Option<&'a crate::sprite::Sprite>, } impl FeatureCtx<'static> { /// Context with no feature (background, raster, zoom-only properties). pub fn zoom_only(zoom: f32) -> Self { - FeatureCtx { zoom, kind: GeomKind::Unknown, id: None, props: &[] } + FeatureCtx { zoom, kind: GeomKind::Unknown, id: None, props: &[], images: None } } } @@ -266,6 +275,16 @@ impl Expr { free(&self.0) } + /// Whether it depends on the zoom. + pub fn uses_zoom(&self) -> bool { + calls(&self.0, Op::Zoom) + } + + /// Whether it asks the sprite for an image (`["image", name]`). + pub fn uses_image(&self) -> bool { + calls(&self.0, Op::Image) + } + /// A `color-relief-color` at `zoom` as colours by height: an `interpolate` or `step` on /// `["elevation"]` whose stops' colours are worked out once, or a single colour. `None` for /// anything else, which a layer can't be drawn from pixel by pixel. @@ -380,6 +399,7 @@ enum Op { Rgb, /// A `color-relief` layer's height (see [`Expr::elevation_ramp`]); null anywhere else. Elevation, + Image, } fn op_of(name: &str) -> Option { @@ -415,6 +435,7 @@ fn op_of(name: &str) -> Option { "typeof" => TypeOf, "concat" => Concat, "upcase" => Upcase, + "image" => Image, "downcase" => Downcase, "+" => Add, "-" => Sub, @@ -464,11 +485,25 @@ enum Node { LegacyIn(Box, Vec), } +/// Whether `n` holds a call of `op`. +fn calls(n: &Node, op: Op) -> bool { + let any = |list: &[(f64, Node)]| list.iter().any(|(_, o)| calls(o, op)); + match n { + Node::Call(o, args) => *o == op || args.iter().any(|a| calls(a, op)), + Node::Match(input, arms, default) => calls(input, op) || arms.iter().any(|(_, o)| calls(o, op)) || calls(default, op), + Node::Step(input, first, stops) => calls(input, op) || calls(first, op) || any(stops), + Node::Interp(_, input, stops) => calls(input, op) || any(stops), + Node::Let(binds, body) => binds.iter().any(|(_, v)| calls(v, op)) || calls(body, op), + Node::Tokens(inner) | Node::LegacyIn(inner, _) => calls(inner, op), + Node::Lit(_) | Node::Var(_) | Node::LegacyGet(_) | Node::LegacyHas(_) => false, + } +} + /// See [`Expr::feature_free`]. fn free(n: &Node) -> bool { match n { Node::Lit(_) | Node::Var(_) => true, - Node::Call(op, args) => !matches!(op, Op::Get | Op::Has | Op::Id | Op::GeomType) && args.iter().all(free), + Node::Call(op, args) => !matches!(op, Op::Get | Op::Has | Op::Id | Op::GeomType | Op::Image) && args.iter().all(free), Node::Match(input, arms, default) => free(input) && arms.iter().all(|(_, o)| free(o)) && free(default), Node::Step(input, first, stops) => free(input) && free(first) && stops.iter().all(|(_, o)| free(o)), Node::Interp(_, input, stops) => free(input) && stops.iter().all(|(_, o)| free(o)), @@ -573,7 +608,7 @@ fn compile_op(name: &str, args: &[Json], depth: usize) -> Option { "number-format" => Node::Call(Op::ToString, vec![arg(0)]), "within" => Node::Lit(Val::Bool(false)), "is-supported-script" => Node::Lit(Val::Bool(true)), - "properties" | "feature-state" | "line-progress" | "accumulated" | "heatmap-density" | "image" | "collator" | "resolved-locale" + "properties" | "feature-state" | "line-progress" | "accumulated" | "heatmap-density" | "collator" | "resolved-locale" | "global-state" | "object" | "distance" => null(), _ => Node::Call(op_of(name)?, args.iter().take(MAX_ARRAY).map(|j| compile(j, d)).collect()), }) @@ -977,6 +1012,10 @@ fn call(op: Op, args: &[Node], f: &FeatureCtx, vars: &mut Vars) -> Val { } Upcase => arg(0).as_str().map_or(Val::Null, |s| Val::Str(s.to_uppercase())), Downcase => arg(0).as_str().map_or(Val::Null, |s| Val::Str(s.to_lowercase())), + Image => match (arg(0).as_str(), f.images) { + (Some(name), Some(sprite)) if sprite.has(name) => Val::Str(name.to_owned()), + _ => Val::Null, + }, Add => nums(&v).map_or(Val::Null, |n| Val::Num(n.iter().sum())), Mul => nums(&v).map_or(Val::Null, |n| Val::Num(n.iter().product())), Sub => match (num(0), num(1), v.len()) { @@ -1085,6 +1124,38 @@ fn substitute_tokens(s: &str, f: &FeatureCtx) -> String { // Style, sources, layers // --------------------------------------------------------------------------------------------------------------- +/// A style's `sprite` array: its sprites as (id, address), at most [`MAX_SPRITES`] of the entries +/// that can be read, each id once; and what was left out, a line per reason. +fn parse_sprites(entries: &[Json]) -> (Vec<(String, String)>, Vec) { + let mut sprites: Vec<(String, String)> = Vec::new(); + let (mut unread, mut repeated, mut past) = (0usize, 0usize, 0usize); + // An empty id or address is none: an empty address would resolve to the style's own folder. + let given = |v: Option<&Json>| str_of(v).filter(|s| !s.is_empty()); + for s in entries { + match (given(s.get("id")).filter(|id| id.len() <= MAX_SPRITE_ID), given(s.get("url"))) { + (Some(id), _) if sprites.iter().any(|(i, _)| *i == id) => repeated += 1, + (Some(_), Some(_)) if sprites.len() >= MAX_SPRITES => past += 1, + (Some(id), Some(url)) => sprites.push((id, url)), + _ => unread += 1, + } + } + let total = entries.len(); + let mut left_out = Vec::new(); + if unread > 0 { + left_out + .push(format!("{unread} of {total} sprites left out, so their icons and patterns aren't drawn: no usable id or no address")); + } + if repeated > 0 { + left_out.push(format!("{repeated} of {total} sprites left out, so their icons and patterns aren't drawn: another has the same id")); + } + if past > 0 { + left_out.push(format!( + "{past} of {total} sprites left out, so their icons and patterns aren't drawn: a style's first {MAX_SPRITES} are read" + )); + } + (sprites, left_out) +} + /// A parsed style. URLs are left as given. #[derive(Clone, Debug, PartialEq)] pub struct Style { @@ -1092,7 +1163,13 @@ pub struct Style { pub sources: Vec<(String, Source)>, pub layers: Vec, pub glyphs: Option, - pub sprite: Option, + /// The style's sprites as (id, address). Images of the sprite with the id `default`, which + /// a style giving just one address has, are named ``; those of the others `:`. + pub sprites: Vec<(String, String)>, + /// What of its `sprite` array couldn't be read, and why. + pub sprites_left_out: Vec, + /// How many sprites it lists, read or not. + pub sprites_listed: usize, /// Where the style places the map, from its root properties. pub view: StyleView, } @@ -1281,19 +1358,20 @@ impl Style { .take(MAX_SOURCES) .map(|(k, v)| (k.clone(), Source::parse(v))) .collect(); - let sprite = match o.get("sprite") { - Some(Json::String(s)) => Some(s.clone()), - Some(Json::Array(a)) => { - a.iter().find(|s| s.get("id").and_then(Json::as_str) == Some("default")).or(a.first()).and_then(|s| str_of(s.get("url"))) - } - _ => None, + let (sprites, sprites_left_out) = match o.get("sprite") { + // (An empty address would resolve to the style's own folder.) + Some(Json::String(s)) if !s.is_empty() => (vec![("default".to_owned(), s.clone())], Vec::new()), + Some(Json::Array(a)) => parse_sprites(a), + _ => (Vec::new(), Vec::new()), }; Ok(Style { name: str_of(o.get("name")).unwrap_or_default(), sources, layers: layers.iter().take(MAX_LAYERS).filter_map(StyleLayer::parse).collect(), glyphs: str_of(o.get("glyphs")), - sprite, + sprites, + sprites_left_out, + sprites_listed: o.get("sprite").map_or(0, |s| s.as_array().map_or(1, Vec::len)), view: StyleView::parse(o), }) } @@ -1478,6 +1556,33 @@ impl StyleLayer { self.paint.contains_key(name) } + /// Whether the paint property `name` depends on the zoom. + pub fn paint_uses_zoom(&self, name: &str) -> bool { + self.paint.get(name).is_some_and(Expr::uses_zoom) + } + + /// Whether the paint property `name` asks the sprite for an image. + pub fn paint_uses_image(&self, name: &str) -> bool { + self.paint.get(name).is_some_and(Expr::uses_image) + } + + /// Whether it draws icons of the style's sprites: a label's. (Another kind of layer may name + /// one, and draw none.) + pub fn draws_icons(&self) -> bool { + self.kind == LayerKind::Symbol && self.has_layout("icon-image") + } + + /// Whether it fills with patterns of the style's sprites. (A line painted with a pattern isn't + /// drawn at all: see `draw::drawable`.) + pub fn draws_patterns(&self) -> bool { + matches!(self.kind, LayerKind::Fill | LayerKind::FillExtrusion) && PATTERNS.iter().any(|p| self.has_paint(p)) + } + + /// Whether it draws images of the style's sprites. + pub fn draws_images(&self) -> bool { + self.draws_icons() || self.draws_patterns() + } + /// Whether every paint and layout property of the layer is the same for every feature at a /// zoom (see [`Expr::feature_free`]). pub fn paint_feature_free(&self) -> bool { @@ -1761,7 +1866,7 @@ mod tests { } fn ctx(zoom: f32, kind: GeomKind, props: &[(String, Value)]) -> FeatureCtx<'_> { - FeatureCtx { zoom, kind, id: Some(42), props } + FeatureCtx { zoom, kind, id: Some(42), props, images: None } } fn ev(j: Json, f: &FeatureCtx) -> Val { @@ -1925,6 +2030,93 @@ mod tests { assert_eq!(ev(json!(["image", "x"]), &f), Val::Null); } + #[test] + fn image_names_a_sprite_by_its_id() { + let at = json!({"x": 0, "y": 0, "width": 2, "height": 2}); + let picture = || tiny_skia::Pixmap::new(2, 2).unwrap(); + let sprite = + crate::sprite::Sprite::of(vec![("nautical", json!({"light/red": at}), picture()), ("base", json!({"bus": at}), picture())]); + let f = FeatureCtx { images: Some(&sprite), ..ctx(10.0, GeomKind::Point, &[]) }; + assert_eq!(ev(json!(["image", "nautical:light/red"]), &f), str_val("nautical:light/red")); + // Not from another sprite, nor with no id: on to the next choice. + assert_eq!(ev(json!(["image", "base:light/red"]), &f), Val::Null); + assert_eq!(ev(json!(["image", "light/red"]), &f), Val::Null); + assert_eq!(ev(json!(["coalesce", ["image", "base:light/red"], ["image", "base:bus"]]), &f), str_val("base:bus")); + } + + #[test] + fn expressions_say_what_they_depend_on() { + let on = |j: Json| Expr::property(&j); + assert!(on(json!(["step", ["zoom"], ["image", "a"], 2.5, ["image", "b"]])).uses_zoom()); + assert!(on(json!({"stops": [[2, "a"], [3, "b"]]})).uses_zoom()); + assert!(!on(json!(["get", "pattern"])).uses_zoom() && !on(json!("a")).uses_zoom()); + assert!(on(json!(["coalesce", ["get", "x"], ["image", "a"]])).uses_image()); + assert!(on(json!(["case", ["has", "x"], ["image", "a"], "b"])).uses_image()); + assert!(!on(json!(["get", "pattern"])).uses_image() && !on(json!("a")).uses_image()); + } + + #[test] + fn reads_a_styles_sprites_and_says_what_it_left_out() { + let parse = |sprite: Json| Style::parse(&json!({"version": 8, "sprite": sprite, "sources": {}, "layers": []})).unwrap(); + // One address is the `default` sprite; a list keeps its ids. + assert_eq!(parse(json!("https://x/s")).sprites, [("default".to_owned(), "https://x/s".to_owned())]); + assert!(parse(json!("")).sprites.is_empty()); + let listed = parse(json!([{"id": "base", "url": "a"}])); + assert_eq!(listed.sprites, [("base".to_owned(), "a".to_owned())]); + assert!(listed.sprites_left_out.is_empty()); + // What can't be read doesn't count towards the limit: a sprite after it is still read. + let mut list: Vec = (0..MAX_SPRITES + 2).map(|_| json!({"url": "no-id"})).collect(); + list.push(json!({"id": "default", "url": "b"})); + let late = parse(Json::Array(list)); + assert_eq!(late.sprites, [("default".to_owned(), "b".to_owned())]); + assert_eq!(late.sprites_left_out.len(), 1); + let total = MAX_SPRITES + 3; + assert!( + late.sprites_left_out[0].starts_with(&format!("{} of {total} sprites left out", MAX_SPRITES + 2)), + "{:?}", + late.sprites_left_out + ); + // A repeated id, and those past the limit, each said with how many. + let mut list: Vec = (0..MAX_SPRITES + 3).map(|i| json!({"id": format!("s{i}"), "url": "u"})).collect(); + list.push(json!({"id": "s0", "url": "again"})); + let many = parse(Json::Array(list)); + assert_eq!(many.sprites.len(), MAX_SPRITES); + assert_eq!(many.sprites[0].1, "u"); + let said = many.sprites_left_out.join("; "); + assert!( + said.contains("1 of 20 sprites left out") && said.contains("same id") && said.contains("3 of 20 sprites left out"), + "{said}" + ); + // An empty id or address is none. + let empty = parse(json!([{"id": "a", "url": ""}, {"id": "", "url": "b"}, {"id": "c", "url": "d"}])); + assert_eq!(empty.sprites, [("c".to_owned(), "d".to_owned())]); + assert!(empty.sprites_left_out[0].starts_with("2 of 3 sprites left out"), "{:?}", empty.sprites_left_out); + // An id too long to keep with every picture and mesh is none either. + let long = parse(json!([{"id": "x".repeat(MAX_SPRITE_ID + 1), "url": "a"}, {"id": "x".repeat(MAX_SPRITE_ID), "url": "b"}])); + assert_eq!(long.sprites.len(), 1); + assert_eq!(long.sprites[0].1, "b"); + } + + #[test] + fn image_is_its_name_when_the_sprite_has_it() { + let index = json!({"light/red": {"x": 0, "y": 0, "width": 2, "height": 2}, "generic": {"x": 0, "y": 0, "width": 2, "height": 2}}); + let Some(sheet) = tiny_skia::Pixmap::new(2, 2) else { panic!("no pixmap") }; + let sprite = crate::sprite::Sprite::new(&index, sheet); + let props = [("colour".to_owned(), Value::String("red".into()))]; + let f = FeatureCtx { images: Some(&sprite), ..ctx(10.0, GeomKind::Point, &props) }; + let light = |colour: &str| json!(["image", ["concat", "light/", colour]]); + assert_eq!(ev(light("red"), &f), str_val("light/red")); + assert_eq!(ev(light("blue"), &f), Val::Null); + // The first image the sprite has, as a style picks a light's icon by its colour. + let pick = |c: Json| ev(json!(["coalesce", ["image", ["concat", "light/", c]], ["image", "generic"]]), &f); + assert_eq!(pick(json!(["get", "colour"])), str_val("light/red")); + assert_eq!(pick(json!("blue")), str_val("generic")); + // Without the sprite, no image is there to be had. + let bare = FeatureCtx { images: None, ..f }; + assert_eq!(ev(light("red"), &bare), Val::Null); + assert!(!Expr::property(&light("red")).feature_free(), "depends on the sprite"); + } + #[test] fn legacy_filters() { let p = props(&[("class", s("park")), ("admin_level", n(4.0))]); @@ -2109,7 +2301,7 @@ mod tests { })) .unwrap(); assert_eq!(st.name, "t"); - assert_eq!(st.sprite.as_deref(), Some("b")); + assert_eq!(st.sprites, vec![("x".to_owned(), "a".to_owned()), ("default".to_owned(), "b".to_owned())]); assert_eq!(st.glyphs.as_deref(), Some("g/{fontstack}/{range}.pbf")); assert_eq!(st.layers.len(), 2); assert_eq!(st.layers[1].kind, LayerKind::Other); @@ -2322,7 +2514,7 @@ mod tests { assert_eq!(counts, want.into_iter().collect()); assert!(matches!(st.source("streets"), Some(Source::Vector { url: Some(_), .. }))); assert!(matches!(st.source("relief"), Some(Source::Raster { tile_size: 256, max_zoom: 6, .. }))); - assert!(st.glyphs.is_some() && st.sprite.is_some()); + assert!(st.glyphs.is_some() && !st.sprites.is_empty()); let feats = sample_features(); let mut labels = 0; @@ -2330,7 +2522,7 @@ mod tests { for z in 0..=20 { for l in &st.layers { for (kind, p) in &feats { - let f = FeatureCtx { zoom: z as f32 + 0.5, kind: *kind, id: Some(1), props: p }; + let f = FeatureCtx { zoom: z as f32 + 0.5, kind: *kind, id: Some(1), props: p, images: None }; labels += touch_all(l, &f); matched += usize::from(l.matches(&f)); } @@ -2471,7 +2663,7 @@ mod tests { for i in 0..5000 { let j = random_json(&mut r, 0); let (kind, p) = &feats[i % feats.len()]; - let f = FeatureCtx { zoom: (i % 23) as f32, kind: *kind, id: Some(i as u64), props: p }; + let f = FeatureCtx { zoom: (i % 23) as f32, kind: *kind, id: Some(i as u64), props: p, images: None }; let _ = Expr::property(&j).eval(&f); let _ = Expr::filter(&j).eval(&f); let l = StyleLayer::parse(&json!({"id": "f", "type": "symbol", "filter": j.clone(), @@ -2650,7 +2842,7 @@ mod feature_free_tests { #[test] fn filters_compare_properties_in_place_as_they_did() { let props = vec![("class".to_string(), Value::String("motorway".into())), ("rank".to_string(), Value::Number(3.0))]; - let f = FeatureCtx { zoom: 10.0, kind: GeomKind::LineString, id: Some(7), props: &props }; + let f = FeatureCtx { zoom: 10.0, kind: GeomKind::LineString, id: Some(7), props: &props, images: None }; let is = |j: Json| Expr::filter(&j).eval(&f) == Val::Bool(true); assert!(is(serde_json::json!(["==", "class", "motorway"]))); assert!(!is(serde_json::json!(["!=", "class", "motorway"]))); diff --git a/crates/tiles/src/symbols.rs b/crates/tiles/src/symbols.rs index 19c9ba20bd..95b8501468 100644 --- a/crates/tiles/src/symbols.rs +++ b/crates/tiles/src/symbols.rs @@ -159,7 +159,7 @@ pub(crate) fn collect( // between zooms is stretched by up to 2. let stretch = 2f32.powf(zoom.rem_euclid(1.0)); for f in &l.features { - let ctx = FeatureCtx { zoom, kind: f.kind, id: f.id, props: &f.props }; + let ctx = FeatureCtx { zoom, kind: f.kind, id: f.id, props: &f.props, images: None }; if !layer.matches(&ctx) { continue; } @@ -349,7 +349,7 @@ fn label_length(l: &Label) -> f32 { /// `icon-offset`; an SDF icon takes `icon-color`. Along a line, an icon turned with the map /// (`icon-rotation-alignment` `map`, or `auto`) gets an angle, `icon-rotate` to begin with. fn icon(sheet: &Sprite, layer: &StyleLayer, ctx: &FeatureCtx, placement: SymbolPlacement) -> Option { - let name = layer.layout_value("icon-image", ctx)?; + let name = layer.layout_value("icon-image", &FeatureCtx { images: Some(sheet), ..*ctx })?; let name = name.as_str().filter(|n| !n.is_empty())?; let img = sheet.image(name, layer.paint_value("icon-color", ctx).and_then(|c| c.as_color()))?; let k = layer.layout_value("icon-size", ctx).and_then(|v| v.as_f64()).filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 8.0) as f32; @@ -684,6 +684,17 @@ mod tests { out } + #[test] + fn an_image_expression_chooses_the_icon() { + let layer = symbol(serde_json::json!({"icon-image": ["coalesce", ["image", "nope"], ["image", "red"]]})); + let out = labels(vec![point("")], &layer, &world_frame(), 64.0); + assert_eq!(out.len(), 1, "an image the sprite has is drawn"); + assert!(out[0].icon.is_some()); + // None of them there: no icon, no label. + let layer = symbol(serde_json::json!({"icon-image": ["image", "nope"]})); + assert!(labels(vec![point("")], &layer, &world_frame(), 64.0).is_empty()); + } + #[test] fn labels_points_with_icons() { let layer = symbol(serde_json::json!({"text-field": "{name}", "icon-image": "{class}", "icon-size": 2, "text-anchor": "left", diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index ccfda2aad3..a5d395603b 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -197,8 +197,13 @@ Ocean, Atlas, Blank), which need no network, and web tile layers over them: - **Map styles**: a MapLibre style document (`style.json`), with its vector, raster and elevation (`raster-dem`: Terrarium, Mapbox or custom encoding) sources. RustGIS draws background, fill, line, circle and raster layers, labels with their icons from - the style's sprite (SDF icons in their `icon-color`), and fill patterns; it evaluates the - style's expressions and zoom functions. From elevation it draws `color-relief` layers (a + the style's sprites (SDF icons in their `icon-color`; the icons of a sprite in the style's + list are named `:`, those of a sprite with the id `default` just ``), and + fill patterns; it evaluates the style's expressions and zoom functions, `image` among them (an + icon's name when a sprite has it, so `coalesce` falls back to the next). When the style draws + images, a notice says why any are missing: a sprite at an address RustGIS won't fetch, an entry + of the list that can't be read, or a sprite whose download failed, which loses only its own + icons and patterns and is tried again. From elevation it draws `color-relief` layers (a `color-relief-color` that is an `interpolate` or `step` on `["elevation"]`) and `hillshade` layers (each `hillshade-method`, lit as the map is drawn, north up; slopes are steepened at small scales so relief stays visible). Its shading follows the style's colours, exaggeration