Modern Apps git

← Modern-Apps.git

mamaps: water-as-background tiles + barren subtree pruning

Commit
65cfae732c52fcc68757c6a8f2b63a33f101304c
Author
vayun-mathur <[email protected]>
When
2026-10-10 04:38 UTC (1 month ago)
Parents
011aad2

Diff

scripts/maps/mamaps_build/src/tiler_part1.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part1.rs b/scripts/maps/mamaps_build/src/tiler_part1.rsindex 7ef4735615..f5cf1d4fa8 100644--- a/scripts/maps/mamaps_build/src/tiler_part1.rs+++ b/scripts/maps/mamaps_build/src/tiler_part1.rs@@ -163,8 +163,17 @@ fn tile_zooms(                 let _ = std::io::Write::flush(&mut std::io::stderr());             }             let encoding = std::time::Instant::now();-            let done = encode_batch(batch, &settings.dem, store.conventions(), &settings.region_links)?;+            let mut done = encode_batch(batch, &settings.dem, store.conventions(), &settings.region_links)?;             stats.encode_ms += encoding.elapsed().as_millis() as u64;+            // Phase B: prune barren subtrees. A tile whose four children all came back+            // empty (`None` — genuinely featureless, or full-bleed water background) is+            // itself the end of the tree: drop the children and let the reader stop at+            // the parent (overzoom). Applies recursively up the pyramid, so a z13 tile+            // whose z14 children are all ocean ends the tree at z13. Only above z0 (the+            // world tile is never pruned) and only when all four children of a parent+            // are present-and-empty in this batch — never across batch boundaries, so+            // the archive stays independent of batching and thread count.+            prune_barren_subtree(z, &mut done);             let appending = std::time::Instant::now();             for (id, encoded, rings, lines) in done {                 stats.rings.add(rings);@@ -210,6 +219,11 @@ fn tile_zooms( /// own still makes progress. The pulled prefix is contiguous merge order, so feeding it to /// `encode_batch` (which preserves tile order) keeps the archive byte-identical: the only /// change is how many tiles one batch holds.+///+/// Contiguity is also what [`prune_barren_subtree`] relies on: four siblings of one parent+/// occupy consecutive tile ids, so a parent's whole child set is either inside one batch or+/// split across a batch boundary — and only the first case prunes, which keeps the archive+/// independent of where the batcher cut. fn merge_batch(     merged: &mut Merged<'_>,     max_tiles: usize,@@ -229,6 +243,79 @@ fn merge_batch(     Ok(batch) } +/// Prune barren subtrees within one encoded batch: drop the four empty children of a+/// tile whose whole child set came back `None`.+///+/// A `None` child is a tile with nothing drawable — genuinely featureless, or full-bleed+/// water background (Phase B). The reader's miss path already overzooms: a missing tile+/// falls back to its parent, whose background (or whose own body) shows through. So four+/// empty siblings carry no information their parent does not, and storing them buys index+/// entries, leaf span and fetches for zero pixels.+///+/// The conditions are deliberately strict, because a wrong prune deletes drawable map:+///+/// * `z == 0` never prunes: the world tile has no parent to overzoom to.+/// * All four children of a parent must be present **in this batch** and all `None`.+///   A parent split across a batch boundary keeps its children — the archive must not+///   depend on where the cost-batcher cut, and a partial set cannot prove barrenness.+/// * Only `None` children prune. A stored child (even a tiny one) means drawable content.+/// * The parent itself is untouched: it was merged and encoded in its own zoom pass (zooms+///   tile independently), so pruning children never orphans a stored parent.+///+/// Recursion across zooms falls out of the zoom loop: a z13 tile whose z14 children were+/// all pruned is itself absent-or-water, so when z13 encodes, *its* parent sees four empty+/// children and prunes again — the tree ends where the content does.+///+/// Runs on the serial append thread over the encoded batch (not in the parallel encode+/// workers): it inspects batch adjacency, which only the ordered batch has. Pure function+/// of the batch's `(id, Option)` pairs, so thread count and chunk boundaries cannot move it.+fn prune_barren_subtree(z: u8, done: &mut Vec<Encoded>) {+    if z == 0 || done.len() < 4 {+        return;+    }+    // Index by tile id for sibling lookup. The batch is ascending by id (merge order+    // through `encode_batch`'s positional collect), so positions are found by search+    // rather than assumed adjacent: siblings are consecutive ids but not necessarily+    // consecutive positions (a stored neighbour may sit between them — which itself+    // vetoes the prune, correctly).+    let mut drop_ids: std::collections::BTreeSet<u64> = std::collections::BTreeSet::new();+    let mut at: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();+    for (index, (id, _, _, _)) in done.iter().enumerate() {+        at.insert(*id, index);+    }+    for (index, (id, encoded, _, _)) in done.iter().enumerate() {+        let _ = index;+        if encoded.is_some() {+            continue;+        }+        let (tz, tx, ty) = tilecodec::pmtiles::tile_zxy(*id);+        if tz != z {+            continue;+        }+        // Only the top-left child starts the check, so each parent is considered once.+        if tx % 2 != 0 || ty % 2 != 0 {+            continue;+        }+        let (px, py) = (tx / 2, ty / 2);+        let mut siblings: Vec<u64> = Vec::with_capacity(4);+        for (dx, dy) in [(0u64, 0u64), (1, 0), (0, 1), (1, 1)] {+            siblings.push(tilecodec::pmtiles::tile_id(z, px * 2 + dx, py * 2 + dy));+        }+        // All four present in this batch and all empty: the parent covers them.+        let all_empty = siblings.iter().all(|sib| {+            at.get(sib).is_some_and(|&i| done[i].1.is_none())+        });+        if all_empty {+            for sib in siblings {+                drop_ids.insert(sib);+            }+        }+    }+    if !drop_ids.is_empty() {+        done.retain(|(id, _, _, _)| !drop_ids.contains(id));+    }+}+ /// Cap on one merge pull's merged-geometry cost, in `tile_cost` units (features + coordinates). /// /// 8 M units is ~64 MB of merged tile geometry per batch at typical z14 density -- small against@@ -392,3 +479,111 @@ static READ_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64:: pub fn read_seconds() -> f64 {     READ_NANOS.swap(0, Ordering::Relaxed) as f64 / 1e9 }++#[cfg(test)]+mod tests_part1 {+    use super::*;++    fn empty_entry(id: u64) -> Encoded {+        (id, None, crate::rings::Stats::default(), crate::coalesce::Stats::default())+    }++    fn stored_entry(id: u64) -> Encoded {+        (+            id,+            Some((vec![7u8; 32], 32, tilecodec::mamaps::write::hash64(&[7u8; 32]))),+            crate::rings::Stats::default(),+            crate::coalesce::Stats::default(),+        )+    }++    fn ids_of(done: &[Encoded]) -> Vec<u64> {+        done.iter().map(|(id, _, _, _)| *id).collect()+    }++    /// **Phase B subtree pruning: four empty siblings end the tree at the parent.**+    /// All four children of one z12 parent arrive `None` in one batch: all four are+    /// dropped, so the reader stops at the z11 parent (overzoom) instead of fetching+    /// four empty bodies.+    #[test]+    fn four_empty_siblings_are_pruned_to_the_parent() {+        use tilecodec::pmtiles::tile_id;+        let (px, py) = (1_200u64, 1_500u64);+        let z = 12u8;+        let mut done = vec![+            empty_entry(tile_id(z, px * 2, py * 2)),+            empty_entry(tile_id(z, px * 2 + 1, py * 2)),+            empty_entry(tile_id(z, px * 2, py * 2 + 1)),+            empty_entry(tile_id(z, px * 2 + 1, py * 2 + 1)),+        ];+        prune_barren_subtree(z, &mut done);+        assert!(done.is_empty(), "all four empty siblings must go: {done:?}");+    }++    /// **A stored sibling vetoes the prune.** One child carries drawable content, so the+    /// parent cannot cover the set — dropping the other three would delete the map's+    /// answer for their ground (the reader would overzoom a parent that draws coarsely).+    #[test]+    fn a_stored_sibling_vetoes_the_prune() {+        use tilecodec::pmtiles::tile_id;+        let (px, py) = (1_200u64, 1_500u64);+        let z = 12u8;+        let mut done = vec![+            empty_entry(tile_id(z, px * 2, py * 2)),+            stored_entry(tile_id(z, px * 2 + 1, py * 2)),+            empty_entry(tile_id(z, px * 2, py * 2 + 1)),+            empty_entry(tile_id(z, px * 2 + 1, py * 2 + 1)),+        ];+        prune_barren_subtree(z, &mut done);+        assert_eq!(done.len(), 4, "a stored child keeps the whole set");+    }++    /// **A partial set never prunes.** The parent split across a batch boundary keeps its+    /// children: the archive must not depend on where the cost-batcher cut, and three+    /// empties cannot prove the fourth is barren.+    #[test]+    fn a_partial_child_set_never_prunes() {+        use tilecodec::pmtiles::tile_id;+        let (px, py) = (1_200u64, 1_500u64);+        let z = 12u8;+        let mut done = vec![+            empty_entry(tile_id(z, px * 2, py * 2)),+            empty_entry(tile_id(z, px * 2 + 1, py * 2)),+            empty_entry(tile_id(z, px * 2, py * 2 + 1)),+        ];+        prune_barren_subtree(z, &mut done);+        assert_eq!(done.len(), 3, "a split parent keeps its children");+    }++    /// **z0 never prunes.** The world tile has no parent to overzoom to; dropping it+    /// would delete the map's coarsest answer.+    #[test]+    fn the_world_tile_is_never_pruned() {+        use tilecodec::pmtiles::tile_id;+        let mut done = vec![+            empty_entry(tile_id(0, 0, 0)),+            empty_entry(tile_id(0, 1, 0)),+            empty_entry(tile_id(0, 0, 1)),+            empty_entry(tile_id(0, 1, 1)),+        ];+        let before = ids_of(&done);+        prune_barren_subtree(0, &mut done);+        assert_eq!(ids_of(&done), before, "z0 keeps everything");+    }++    /// **Unrelated tiles are untouched.** A batch of four empties from different parents+    /// prunes nothing — the check is per-parent, not per-batch.+    #[test]+    fn empties_from_different_parents_do_not_prune() {+        use tilecodec::pmtiles::tile_id;+        let z = 12u8;+        let mut done = vec![+            empty_entry(tile_id(z, 0, 0)),+            empty_entry(tile_id(z, 100, 100)),+            empty_entry(tile_id(z, 200, 200)),+            empty_entry(tile_id(z, 300, 300)),+        ];+        prune_barren_subtree(z, &mut done);+        assert_eq!(done.len(), 4, "no parent has its full set here");+    }+}
scripts/maps/mamaps_build/src/tiler_part10.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part10.rs b/scripts/maps/mamaps_build/src/tiler_part10.rsindex 4c6d4a933d..61a2b246ed 100644--- a/scripts/maps/mamaps_build/src/tiler_part10.rs+++ b/scripts/maps/mamaps_build/src/tiler_part10.rs@@ -324,4 +324,110 @@ mod tests_part10 {         set_chunk_vertices(0);         release_threads();     }++    /// **Phase B: a full-bleed single-water-polygon tile is water background, not a tile.**+    /// A tile whose only content is one water polygon covering the whole tile draws exactly+    /// what the style's water background already paints, so it is `None` (not stored) like+    /// an emptied tile — and the reader overzooms the parent instead of fetching a body.+    #[test]+    fn a_full_bleed_water_tile_is_not_stored() {+        use tilecodec::pmtiles::{tile_id, tile_zxy};+        // A water square far larger than one tile, so interior tiles clip full-bleed while the+        // build still has edge tiles carrying real geometry (the writer refuses an empty archive).+        let sea = Feature {+            class: Class::area(dict::LAYER_LANDTYPE, crate::schema::kind("sea"), 0),+            geometry: square(-10.0, -10.0, 20.0),+            name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0,+            turn_fwd: Vec::new(),+            turn_bwd: Vec::new(),+            building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),+        };+        let (bytes, _) = build(&spilled(&[sea]), &settings(0, 6)).expect("build");+        let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read");+        // Every stored tile must carry something drawable beyond a full-bleed water fill:+        // either a second feature/layer, a hole (island), or a partial-bleed ring.+        let extent = crate::tiler::EXTENT as f64;+        for (id, _, body) in &entries {+            let body = Body::parse(body).expect("parse");+            let Some(layer) = body.layer(dict::LAYER_LANDTYPE) else { continue };+            if layer.features.len() != 1 {+                continue;+            }+            let feature = &layer.features[0];+            let water = matches!(+                tilecodec::mamaps::dict::KINDS.get(feature.kind as usize - 1).copied(),+                Some(+                    "ocean" | "sea" | "lake" | "water" | "river" | "stream" | "bay"+                        | "strait" | "fjord" | "reef" | "canal" | "dock",+                ),+            );+            if !water || feature.geom_type != GEOM_POLYGON || feature.part_count != 1 {+                continue;+            }+            let part = &layer.parts[feature.parts_offset as usize];+            let start = part.coord_start as usize;+            let points = &layer.coords[start..start + part.point_count as usize];+            let (mut min_x, mut min_y) = (i16::MAX, i16::MAX);+            let (mut max_x, mut max_y) = (i16::MIN, i16::MIN);+            for &(x, y) in points {+                min_x = min_x.min(x);+                min_y = min_y.min(y);+                max_x = max_x.max(x);+                max_y = max_y.max(y);+            }+            let full = min_x as f64 <= 0.5+                && min_y as f64 <= 0.5+                && max_x as f64 >= extent - 0.5+                && max_y as f64 >= extent - 0.5;+            let (z, x, y) = tile_zxy(*id);+            assert!(+                !full,+                "z{z}/{x}/{y} is a full-bleed single-water-polygon tile and must not be stored",+            );+        }+        // And the interior really is empty: a tile strictly inside the square resolves to no+        // body, so the reader overzooms the parent whose background shows through.+        let _ = tile_id(0, 0, 0);+    }++    /// **Phase B: a water tile with an island hole is drawable land and stays stored.**+    /// The narrow check must not fire when the polygon carries a hole — that hole is an+    /// island, and dropping the tile would delete land.+    #[test]+    fn a_water_tile_with_a_hole_stays_stored() {+        // A sea square with a smaller land square punched out of its middle is modelled here+        // as two features: the sea polygon plus a land-base polygon inside it. The tile+        // covering both carries two features, so `is_water_background` refuses it.+        let sea = Feature {+            class: Class::area(dict::LAYER_LANDTYPE, crate::schema::kind("sea"), 0),+            geometry: square(-10.0, -10.0, 20.0),+            name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0,+            turn_fwd: Vec::new(),+            turn_bwd: Vec::new(),+            building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),+        };+        let island = Feature {+            class: Class::area(dict::LAYER_LANDTYPE, tilecodec::mamaps::dict::NONE, 0),+            geometry: square(-1.0, -1.0, 2.0),+            name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0,+            turn_fwd: Vec::new(),+            turn_bwd: Vec::new(),+            building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),+        };+        let (bytes, _) = build(&spilled(&[sea, island]), &settings(0, 6)).expect("build");+        let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read");+        let mut saw_land = false;+        for (_, _, body) in &entries {+            let body = Body::parse(body).expect("parse");+            if let Some(layer) = body.layer(dict::LAYER_LANDTYPE) {+                if layer.features.iter().any(|f| f.kind == tilecodec::mamaps::dict::NONE) {+                    saw_land = true;+                }+            }+        }+        assert!(saw_land, "the island's land base must survive Phase B");+    } }
scripts/maps/mamaps_build/src/tiler_part5.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part5.rs b/scripts/maps/mamaps_build/src/tiler_part5.rsindex 6f66f8a06b..11c59c76c6 100644--- a/scripts/maps/mamaps_build/src/tiler_part5.rs+++ b/scripts/maps/mamaps_build/src/tiler_part5.rs@@ -107,6 +107,14 @@ fn encode_tile(     if layers.is_empty() {         return Ok((id, None, rings, lines));     }+    // Phase B: a full-bleed single-water-polygon tile is water, not a tile. One+    // water polygon covering the whole tile draws exactly what the style's water+    // background already paints, so storing it buys a body, an index entry and a+    // fetch for zero pixels. `None` (not stored) like an emptied tile, and the+    // reader overzooms the parent whose background shows through.+    if is_water_background(&layers) {+        return Ok((id, None, rings, lines));+    }     // What the `u16` feature index in the body format has to hold. Sampled here because this is the     // shape that reaches the encoder: after coalescing merged the line fragments and after stage C     // dropped what it drops.
scripts/maps/mamaps_build/src/tiler_part6.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part6.rs b/scripts/maps/mamaps_build/src/tiler_part6.rsindex bde9f469dd..842a9502ff 100644--- a/scripts/maps/mamaps_build/src/tiler_part6.rs+++ b/scripts/maps/mamaps_build/src/tiler_part6.rs@@ -206,6 +206,73 @@ fn is_empty(g: &Geometry<SigPt>) -> bool {     } } +/// Whether a merged tile is pure water background: one `landtype` layer, one polygon+/// feature of a water kind, one exterior ring covering the whole tile, no holes.+///+/// Such a tile draws exactly what the style's water background already paints, so+/// [`encode_tile`](super::tiler_part5::encode_tile) drops it (`None`, not stored) and the+/// reader overzooms the parent. The checks are deliberately narrow — one layer, one+/// feature, one part, water kind, full bleed, no holes — so a tile carrying anything+/// drawable (an island hole, a named water label, a second layer) keeps its body.+///+/// `extent` is the tile grid ([`super::EXTENT`]); the full-bleed bar is half a unit, the+/// same sub-pixel magnitude as [`super::BUILDING_TOLERANCE`]. Clipped water rings run along+/// the tile edge but rarely exactly on it, so exact equality would never fire.+fn is_water_background(layers: &[ChunkEntry]) -> bool {+    use tilecodec::mamaps::dict;+    let [entry] = layers else { return false };+    if entry.layer.layer_id != dict::LAYER_LANDTYPE || entry.layer.features.len() != 1 {+        return false;+    }+    let feature = &entry.layer.features[0];+    if feature.geom_type != GEOM_POLYGON || feature.part_count != 1 {+        return false;+    }+    if !is_water_kind_id(feature.kind) {+        return false;+    }+    // No holes: a holed polygon is an island (or a lake ring), which is drawable land.+    let part = &entry.layer.parts[feature.parts_offset as usize];+    if part.winding != WINDING_OUTER {+        return false;+    }+    let start = part.coord_start as usize;+    let points = &entry.layer.coords[start..start + part.point_count as usize];+    if points.len() < 4 {+        return false;+    }+    let extent = EXTENT as f64;+    let (mut min_x, mut min_y) = (f64::MAX, f64::MAX);+    let (mut max_x, mut max_y) = (f64::MIN, f64::MIN);+    for &(x, y) in points {+        min_x = min_x.min(x as f64);+        min_y = min_y.min(y as f64);+        max_x = max_x.max(x as f64);+        max_y = max_y.max(y as f64);+    }+    const BLEED: f64 = 0.5;+    min_x <= BLEED && min_y <= BLEED && max_x >= extent - BLEED && max_y >= extent - BLEED+}++/// Whether an interned `landtype` kind id is one the style paints as water.+///+/// Name-resolved (not hard-coded ids) so the check cannot drift when the dictionary+/// grows. Mirrors the renderer's own water list (`tile::geometry::terrain::WATER_KINDS`)+/// minus `fountain`/`swimming_pool`: those are street furniture, never full-bleed tiles.+fn is_water_kind_id(kind: u16) -> bool {+    use tilecodec::mamaps::dict;+    if kind == dict::NONE {+        return false;+    }+    matches!(+        dict::KINDS.get(kind as usize - 1).copied(),+        Some(+            "ocean" | "sea" | "lake" | "water" | "river" | "stream" | "bay" | "strait"+                | "fjord" | "reef" | "canal" | "dock",+        ),+    )+}+   /// A build that produced nothing is a build whose schema matched nothing, which is worth failing on