maps: landcover and landuse, with a minimum area and a kind diff tool
- Commit
6f0e8b93d108c0497faf116c78a00490c40311b7- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 01:14 UTC (3 months ago)
- Parents
5a88784
Diff
scripts/maps/mamaps_build/src/extract.rs
diff --git a/scripts/maps/mamaps_build/src/extract.rs b/scripts/maps/mamaps_build/src/extract.rsindex 30ce21e3a1..f3252ab792 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -60,9 +60,9 @@ struct Relation { /// `(way id, role is inner)`, in the order the relation lists them, which is what /// [`rings::assemble`] stitches. members: Vec<(i64, bool)>,- /// A `type=multipolygon` relation is an area to be stitched into rings. A `type=boundary` one is- /// a **line**: its members are the border itself, and stitching them into a ring would produce a- /// shape that, if it were ever filled, would cover the whole country.+ /// A relation carrying a shape is stitched into rings; one carrying a border is emitted as its+ /// member lines. Which it is comes from [`Class::area`] rather than from the relation's `type`+ /// tag, because both an administrative border and a protected area are `type=boundary`. area: bool, } @@ -96,13 +96,14 @@ pub fn extract(input: &Path, layers: Layers) -> Result<(Vec<Feature>, Stats)> { } } Element::Relation(relation) => {- // Two relation types are carried, and they mean different geometry.- // Anything else — a route, a site, a public_transport — is not a shape.- let area = match relation.tags.get_str("type") {- Some("multipolygon") => true,- Some("boundary") => false,- _ => return Ok(()),- };+ // Two relation types carry a shape. Anything else — a route, a site, a+ // public_transport — does not.+ if !matches!(+ relation.tags.get_str("type"),+ Some("multipolygon" | "boundary")+ ) {+ return Ok(());+ } if !select.matches(|k| relation.tags.get_str(k)) { return Ok(()); }@@ -113,6 +114,11 @@ pub fn extract(input: &Path, layers: Layers) -> Result<(Vec<Feature>, Stats)> { .filter(|m| m.kind == MEMBER_WAY) .map(|m| (m.id, m.role == b"inner")) .collect();+ // **The schema decides**, not the relation's `type` tag. Both an+ // administrative border and a protected area are `type=boundary`, and+ // one is a line while the other is a shape — which is exactly the+ // distinction `Class::area` exists to make.+ let area = class.area; state.1.push(Relation { class, members, area }); } }
scripts/maps/mamaps_build/src/main.rs
diff --git a/scripts/maps/mamaps_build/src/main.rs b/scripts/maps/mamaps_build/src/main.rsindex 950167a5c5..35f6dccfa5 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -204,6 +204,8 @@ fn derive_build_id( u8::from(layers.buildings), u8::from(layers.roads), u8::from(layers.boundaries),+ u8::from(layers.landcover),+ u8::from(layers.landuse), min_zoom, max_zoom, ]);@@ -251,7 +253,7 @@ fn build_report( fn usage() { eprintln!( "usage: mamaps_build --input IN.osm.pbf --out OUT.mamaps\n\- \x20 [--layers water,buildings,roads,boundaries]\n\+ \x20 [--layers water,buildings,roads,boundaries,landcover,landuse]\n\ \x20 [--min-zoom N] [--max-zoom N]\n\ \x20 [--simplification F] [--build-id N] [--report FILE]" );@@ -289,7 +291,7 @@ mod tests { derive_build_id(path, schema::Layers::all(), 0, 14, 1.0, 101), derive_build_id( path,- schema::Layers { water: true, buildings: false, roads: false, boundaries: false },+ schema::Layers { water: true, ..schema::Layers::none() }, 0, 14, 1.0,
scripts/maps/mamaps_build/src/schema/boundaries.rs
diff --git a/scripts/maps/mamaps_build/src/schema/boundaries.rs b/scripts/maps/mamaps_build/src/schema/boundaries.rsindex 72910fd6f1..8a4a714280 100644--- a/scripts/maps/mamaps_build/src/schema/boundaries.rs+++ b/scripts/maps/mamaps_build/src/schema/boundaries.rs@@ -45,6 +45,7 @@ pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> { // over every layer inside the country. area: false, min_zoom: min_zoom_for(level),+ min_area_px: 0.0, }) }
scripts/maps/mamaps_build/src/schema/land.rs
diff --git a/scripts/maps/mamaps_build/src/schema/land.rs b/scripts/maps/mamaps_build/src/schema/land.rsnew file mode 100644index 0000000000..2f243f2768--- /dev/null+++ b/scripts/maps/mamaps_build/src/schema/land.rs@@ -0,0 +1,286 @@+//! `landcover` and `landuse`: the long tail, and where a minimum **area** starts to matter.+//!+//! Two layers with one classifier, because they read the same tags and differ only in what they+//! mean: `landcover` is the natural surface of the world and is drawn at low zoom as a tint over+//! `earth`; `landuse` is what people do with a patch of it and is drawn at high zoom as a shape.+//! Upstream separates them by zoom — the style ramps `landcover` out by z7 and `landuse` in from z6+//! — so the same forest is a green wash on a continent and a named wood in a city.+//!+//! # Minimum area, not just minimum zoom+//!+//! This is the layer that needs both. A `min_zoom` alone cannot separate a national park from a+//! back garden: both are `leisure=park`, and there are four of the first and four million of the+//! second. So a polygon also has to be **big enough to see** — at least a few hundred square pixels+//! of the tile it would be drawn in — and below that it is not carried at all.+//!+//! # Where this will not match upstream+//!+//! Nowhere near exactly, and the plan says so: Planetiler's profile is thousands of lines of+//! accumulated judgement about which of forty `landuse` values is worth a tile at which zoom.+//! `scripts/maps/test/diff_kinds.py` measures the gap per kind. The bar is **visually equivalent**,+//! not count-identical.++use tilecodec::mamaps::dict::{LAYER_LANDCOVER, LAYER_LANDUSE};++use super::{kind, Class, TagSource};++pub const FILTERS: &[&str] =+ &["natural", "landuse", "leisure", "amenity", "tourism", "aeroway", "man_made", "boundary"];++/// Every `kind` this module can emit.+#[cfg_attr(not(test), allow(dead_code))]+pub const KINDS: &[&str] = &[+ // landcover+ "grassland",+ "barren",+ "urban_area",+ "farmland",+ "glacier",+ "scrub",+ "forest",+ "wetland",+ "sand",+ "bare_rock",+ // landuse+ "national_park",+ "park",+ "cemetery",+ "protected_area",+ "nature_reserve",+ "golf_course",+ "wood",+ "grass",+ "meadow",+ "military",+ "naval_base",+ "airfield",+ "allotments",+ "village_green",+ "playground",+ "garden",+ "dog_park",+ "pitch",+ "recreation_ground",+ "hospital",+ "industrial",+ "commercial",+ "residential",+ "railway",+ "school",+ "university",+ "college",+ "kindergarten",+ "beach",+ "zoo",+ "aerodrome",+ "runway",+ "taxiway",+ "pedestrian",+ "dam",+ "pier",+ "platform",+];++/// `natural=*`, which is `landcover`: the surface of the world rather than what is done with it.+///+/// `(OSM value, kind, min_zoom, min_area_px)`. The areas are in square pixels of a 256-unit tile,+/// which is how a threshold stays meaningful across zooms — see [`min_area_for`].+const LANDCOVER: &[(&str, &str, u8, f64)] = &[+ // A glacier or an ice sheet is a continental feature and there are few of them.+ ("glacier", "glacier", 2, 4.0),+ ("wood", "forest", 5, 8.0),+ ("scrub", "scrub", 6, 8.0),+ ("grassland", "grassland", 6, 8.0),+ ("heath", "scrub", 7, 8.0),+ ("wetland", "wetland", 7, 8.0),+ ("sand", "sand", 8, 4.0),+ ("beach", "sand", 10, 2.0),+ ("bare_rock", "bare_rock", 8, 8.0),+ ("scree", "bare_rock", 9, 8.0),+ ("shingle", "bare_rock", 10, 4.0),+ ("desert", "barren", 3, 8.0),+];++/// `landuse=*`, `leisure=*` and the rest, which is `landuse`.+///+/// `(key, OSM value, kind, min_zoom, min_area_px)`. Ordered, and the order is the tie-break for a+/// polygon carrying two of them.+const LANDUSE: &[(&str, &str, &str, u8, f64)] = &[+ // The big protected areas, which carry a continent.+ ("boundary", "national_park", "national_park", 4, 2.0),+ ("boundary", "protected_area", "protected_area", 5, 2.0),+ ("leisure", "nature_reserve", "nature_reserve", 6, 2.0),+ ("landuse", "forest", "forest", 6, 4.0),+ ("landuse", "military", "military", 6, 4.0),+ ("military", "naval_base", "naval_base", 8, 4.0),+ ("aeroway", "aerodrome", "aerodrome", 8, 2.0),+ ("landuse", "farmland", "farmland", 7, 8.0),+ ("landuse", "meadow", "meadow", 8, 8.0),+ ("landuse", "grass", "grass", 10, 4.0),+ ("landuse", "residential", "residential", 10, 8.0),+ ("landuse", "commercial", "commercial", 11, 4.0),+ ("landuse", "industrial", "industrial", 10, 4.0),+ ("landuse", "railway", "railway", 12, 4.0),+ ("landuse", "cemetery", "cemetery", 11, 2.0),+ ("landuse", "allotments", "allotments", 12, 2.0),+ ("landuse", "village_green", "village_green", 12, 2.0),+ ("landuse", "recreation_ground", "recreation_ground", 12, 2.0),+ ("leisure", "park", "park", 8, 2.0),+ ("leisure", "golf_course", "golf_course", 10, 2.0),+ ("leisure", "garden", "garden", 13, 1.0),+ ("leisure", "dog_park", "dog_park", 14, 1.0),+ ("leisure", "playground", "playground", 14, 1.0),+ ("leisure", "pitch", "pitch", 14, 1.0),+ ("amenity", "hospital", "hospital", 12, 2.0),+ ("amenity", "school", "school", 13, 1.0),+ ("amenity", "university", "university", 11, 2.0),+ ("amenity", "college", "college", 12, 2.0),+ ("amenity", "kindergarten", "kindergarten", 14, 1.0),+ ("tourism", "zoo", "zoo", 12, 2.0),+ ("aeroway", "runway", "runway", 11, 1.0),+ ("aeroway", "taxiway", "taxiway", 13, 1.0),+ ("highway", "pedestrian", "pedestrian", 13, 1.0),+ ("man_made", "pier", "pier", 13, 1.0),+ ("waterway", "dam", "dam", 12, 1.0),+ ("public_transport", "platform", "platform", 14, 1.0),+];++/// Classify a landcover or landuse polygon.+///+/// Only areas: a `landuse` line is a tagging mistake, and a `natural=tree_row` is not a surface.+pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> {+ if let Some(natural) = tags.get("natural") {+ if let Some((_, name, min_zoom, area)) =+ LANDCOVER.iter().find(|(value, _, _, _)| *value == natural)+ {+ return Some(with_area(LAYER_LANDCOVER, kind(name), *min_zoom, *area));+ }+ }+ for (key, value, name, min_zoom, area) in LANDUSE {+ if tags.get(key) == Some(value) {+ return Some(with_area(LAYER_LANDUSE, kind(name), *min_zoom, *area));+ }+ }+ None+}++/// A polygon with a minimum drawn area.+///+/// The area is smuggled through the `Class` in the only place it fits — see [`Class::min_area_px`].+fn with_area(layer: u8, kind: u16, min_zoom: u8, min_area_px: f64) -> Class {+ Class { min_area_px, ..Class::area(layer, kind, min_zoom) }+}++/// The minimum area a polygon needs at `extent`, in that tile's own square units.+///+/// Stated in square pixels of a 256-unit tile because that is the only scale that means anything: a+/// shape smaller than a couple of pixels is not detail, it is a speck, and there are millions of+/// them. Converted to the tile's extent here so the threshold is the same *visual* size whatever the+/// extent is.+pub fn min_area_units(min_area_px: f64, extent: u32) -> f64 {+ let scale = extent as f64 / 256.0;+ min_area_px * scale * scale+}++#[cfg(test)]+mod tests {+ use super::*;+ use tilecodec::mamaps::dict;++ fn classify_tags(pairs: &[(&str, &str)]) -> Option<Class> {+ super::classify(pairs)+ }++ fn name(class: &Class) -> &'static str {+ dict::KINDS[class.kind as usize - 1]+ }++ #[test]+ fn natural_surfaces_go_to_landcover_and_human_use_to_landuse() {+ let wood = classify_tags(&[("natural", "wood")]).expect("wood");+ assert_eq!(wood.layer, dict::LAYER_LANDCOVER);+ assert_eq!(name(&wood), "forest");++ let park = classify_tags(&[("leisure", "park")]).expect("park");+ assert_eq!(park.layer, dict::LAYER_LANDUSE);+ assert_eq!(name(&park), "park");+ // Both are areas; neither is ever a line.+ assert!(wood.area && park.area);+ }++ /// The layer's whole difficulty: a national park and a back garden are both green polygons, and+ /// there are four of the first and four million of the second.+ #[test]+ fn the_minimum_zooms_separate_a_national_park_from_a_back_garden() {+ let at = |pairs: &[(&str, &str)]| classify_tags(pairs).expect("classified").min_zoom;+ assert_eq!(at(&[("boundary", "national_park")]), 4);+ assert!(at(&[("boundary", "national_park")]) < at(&[("leisure", "park")]));+ assert!(at(&[("leisure", "park")]) < at(&[("leisure", "garden")]));+ assert_eq!(at(&[("leisure", "garden")]), 13);+ assert_eq!(at(&[("leisure", "pitch")]), 14, "a tennis court is street-level");+ // A glacier carries a world tile.+ assert_eq!(at(&[("natural", "glacier")]), 2);+ }++ /// A minimum **zoom** cannot separate two things tagged identically; a minimum **area** can.+ /// Stated in square pixels of a 256-unit tile, so the threshold is the same visual size at any+ /// extent.+ #[test]+ fn a_minimum_area_is_a_visual_size_not_a_coordinate_count() {+ // 2 px of a 256-unit tile, expressed in a 4096-unit one, is 2 * 16 * 16.+ assert_eq!(min_area_units(2.0, 256), 2.0);+ assert_eq!(min_area_units(2.0, 4096), 512.0);+ assert_eq!(min_area_units(1.0, 4096), 256.0);+ // Every classified polygon carries one.+ for pairs in [+ vec![("natural", "wood")],+ vec![("leisure", "park")],+ vec![("landuse", "residential")],+ ] {+ assert!(classify_tags(&pairs).expect("classified").min_area_px > 0.0);+ }+ }++ /// Several OSM values collapse to one drawn kind, because the style has one colour for them and+ /// inventing more would be paint rather than data.+ #[test]+ fn several_osm_values_can_share_a_drawn_kind() {+ for value in ["bare_rock", "scree", "shingle"] {+ assert_eq!(name(&classify_tags(&[("natural", value)]).expect(value)), "bare_rock");+ }+ for value in ["scrub", "heath"] {+ assert_eq!(name(&classify_tags(&[("natural", value)]).expect(value)), "scrub");+ }+ for value in ["sand", "beach"] {+ assert_eq!(name(&classify_tags(&[("natural", value)]).expect(value)), "sand");+ }+ }++ /// `natural` is asked before everything, and the `landuse` list is ordered, so a polygon+ /// carrying two tags gets the more significant one.+ #[test]+ fn the_rules_are_ordered() {+ // A forest inside a national park is the national park, which is the bigger statement.+ let both = classify_tags(&[("landuse", "forest"), ("boundary", "national_park")])+ .expect("both");+ assert_eq!(name(&both), "national_park");+ // And a natural surface beats a use, because landcover draws under landuse.+ let surface = classify_tags(&[("natural", "wood"), ("leisure", "park")]).expect("surface");+ assert_eq!(surface.layer, dict::LAYER_LANDCOVER);+ }++ #[test]+ fn nothing_untagged_or_unrecognised_is_carried() {+ for pairs in [+ vec![("natural", "tree_row")],+ vec![("natural", "water")],+ vec![("landuse", "quarry")],+ vec![("leisure", "swimming_pool")],+ vec![("amenity", "parking")],+ vec![("building", "yes")],+ vec![],+ ] {+ assert!(classify_tags(&pairs).is_none(), "{pairs:?} should not be carried");+ }+ }+}
scripts/maps/mamaps_build/src/schema/mod.rs
diff --git a/scripts/maps/mamaps_build/src/schema/mod.rs b/scripts/maps/mamaps_build/src/schema/mod.rsindex 2dd981d101..058934ad54 100644--- a/scripts/maps/mamaps_build/src/schema/mod.rs+++ b/scripts/maps/mamaps_build/src/schema/mod.rs@@ -25,6 +25,7 @@ use tilecodec::mamaps::dict; pub mod boundaries; pub mod buildings;+pub mod land; pub mod roads; pub mod water; @@ -63,7 +64,7 @@ impl TagSource for [(&str, &str)] { } /// Where a feature goes and what it is, once classified.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, PartialEq)] pub struct Class { /// An index into [`dict::LAYERS`]. pub layer: u8,@@ -86,17 +87,39 @@ pub struct Class { /// every pond in California. Compared against the tile's zoom, so a feature simply is not /// written above it. pub min_zoom: u8,+ /// The smallest drawn area worth carrying, in square pixels of a 256-unit tile.+ ///+ /// Zero for a line and for anything a zoom gate alone separates. What it is for is the case a+ /// zoom cannot fix: a national park and a back garden are both `leisure=park`, and only a size+ /// tells them apart. Converted to the tile's own units by [`land::min_area_units`].+ pub min_area_px: f64, } impl Class { /// A polygon feature with no detail and no flags. pub const fn area(layer: u8, kind: u16, min_zoom: u8) -> Class {- Class { layer, kind, kind_detail: dict::NONE, flags: 0, area: true, min_zoom }+ Class {+ layer,+ kind,+ kind_detail: dict::NONE,+ flags: 0,+ area: true,+ min_zoom,+ min_area_px: 0.0,+ } } /// A line feature with no detail and no flags. pub const fn line(layer: u8, kind: u16, min_zoom: u8) -> Class {- Class { layer, kind, kind_detail: dict::NONE, flags: 0, area: false, min_zoom }+ Class {+ layer,+ kind,+ kind_detail: dict::NONE,+ flags: 0,+ area: false,+ min_zoom,+ min_area_px: 0.0,+ } } } @@ -129,36 +152,70 @@ pub struct Layers { pub buildings: bool, pub roads: bool, pub boundaries: bool,+ pub landcover: bool,+ pub landuse: bool, } impl Layers { pub fn all() -> Layers {- Layers { water: true, buildings: true, roads: true, boundaries: true }+ Layers {+ water: true,+ buildings: true,+ roads: true,+ boundaries: true,+ landcover: true,+ landuse: true,+ }+ }++ pub fn none() -> Layers {+ Layers {+ water: false,+ buildings: false,+ roads: false,+ boundaries: false,+ landcover: false,+ landuse: false,+ } } /// Parse a comma-separated list, e.g. `water,roads`. pub fn parse(list: &str) -> Result<Layers, String> {- let mut layers =- Layers { water: false, buildings: false, roads: false, boundaries: false };+ let mut layers = Layers::none(); for name in list.split(',').map(str::trim).filter(|s| !s.is_empty()) { match name { "water" => layers.water = true, "buildings" => layers.buildings = true, "roads" => layers.roads = true, "boundaries" => layers.boundaries = true,+ "landcover" => layers.landcover = true,+ "landuse" => layers.landuse = true, other => { return Err(format!(- "unknown layer `{other}`; this generator produces water, buildings, roads \- and boundaries"+ "unknown layer `{other}`; this generator produces water, buildings, roads, \+ boundaries, landcover and landuse" )) } } }- if layers == (Layers { water: false, buildings: false, roads: false, boundaries: false }) {+ if layers == Layers::none() { return Err("no layers selected".to_string()); } Ok(layers) }++ /// Is this the layer a classifier just returned one for?+ fn wants(&self, layer: u8) -> bool {+ match layer {+ dict::LAYER_WATER => self.water,+ dict::LAYER_BUILDINGS => self.buildings,+ dict::LAYER_ROADS => self.roads,+ dict::LAYER_BOUNDARIES => self.boundaries,+ dict::LAYER_LANDCOVER => self.landcover,+ dict::LAYER_LANDUSE => self.landuse,+ _ => false,+ }+ } } /// Classify one element's tags, or `None` for the overwhelming majority that are not drawn.@@ -192,6 +249,15 @@ pub fn classify( return Some(class); } }+ // Last, because it is the layer everything else is drawn on top of. One classifier produces+ // both `landcover` and `landuse`, so which of the two was asked for is checked after the fact.+ if layers.landcover || layers.landuse {+ if let Some(class) = land::classify(tags) {+ if layers.wants(class.layer) {+ return Some(class);+ }+ }+ } None } @@ -214,6 +280,9 @@ pub fn filters(layers: Layers) -> Vec<&'static str> { if layers.boundaries { out.extend_from_slice(boundaries::FILTERS); }+ if layers.landcover || layers.landuse {+ out.extend_from_slice(land::FILTERS);+ } out } @@ -230,6 +299,7 @@ mod tests { .chain(buildings::KINDS) .chain(roads::KINDS) .chain(boundaries::KINDS)+ .chain(land::KINDS) { assert!( dict::KINDS.contains(name),@@ -250,10 +320,13 @@ mod tests { fn a_layer_list_parses_and_rejects_what_this_generator_cannot_build() { assert_eq!( Layers::parse("water").expect("water"),- Layers { water: true, buildings: false, roads: false, boundaries: false },+ Layers { water: true, ..Layers::none() },+ );+ assert_eq!(+ Layers::parse("water,buildings,roads,boundaries,landcover,landuse").expect("all"),+ Layers::all(), );- assert_eq!(Layers::parse("water,buildings,roads,boundaries").expect("all"), Layers::all());- assert!(Layers::parse("landcover").is_err(), "not until phase 7");+ assert!(Layers::parse("earth").is_err(), "not until the coastline work"); assert!(Layers::parse("").is_err(), "nothing selected"); } @@ -269,7 +342,7 @@ mod tests { &[("natural", "water"), ("highway", "residential"), ("building", "yes")]; assert_eq!(classify(water, true, Layers::all()).expect("water").layer, dict::LAYER_WATER); // A layer that is switched off is not consulted, so the next rule wins instead.- let only_buildings = Layers { water: false, buildings: true, roads: false, boundaries: false };+ let only_buildings = Layers { buildings: true, ..Layers::none() }; assert_eq!( classify(both, true, only_buildings).expect("building").layer, dict::LAYER_BUILDINGS,@@ -288,11 +361,14 @@ mod tests { assert!(!filter.contains(' '), "`{filter}` is not a bare tag key"); } assert!(- filters(Layers { water: true, buildings: false, roads: false, boundaries: false }).len()+ filters(Layers { water: true, ..Layers::none() }).len() < all.len() ); // Every key a rule reads for a *decision* has to be in the screen, or the rule never runs.- for key in ["natural", "waterway", "landuse", "building", "highway", "railway", "boundary"] {+ for key in [+ "natural", "waterway", "landuse", "building", "highway", "railway", "boundary",+ "leisure", "amenity",+ ] { assert!(all.contains(&key), "the screen omits `{key}`"); } }
scripts/maps/mamaps_build/src/schema/roads.rs
diff --git a/scripts/maps/mamaps_build/src/schema/roads.rs b/scripts/maps/mamaps_build/src/schema/roads.rsindex d1d772061c..ce6a11a07a 100644--- a/scripts/maps/mamaps_build/src/schema/roads.rs+++ b/scripts/maps/mamaps_build/src/schema/roads.rs@@ -129,6 +129,7 @@ pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> { flags: flags(tags, highway), area: false, min_zoom: *min_zoom,+ min_area_px: 0.0, }); } if let Some(railway) = tags.get("railway") {@@ -140,6 +141,7 @@ pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> { flags: flags(tags, railway), area: false, min_zoom: *min_zoom,+ min_area_px: 0.0, }); } // A runway is a line in this layer and a polygon in `landuse`. Both are drawn, because an@@ -157,6 +159,7 @@ pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> { flags: flags(tags, aeroway), area: false, min_zoom: if aeroway == "runway" { 9 } else { 13 },+ min_area_px: 0.0, }); } // A pier is walkable, so it belongs with the paths rather than with the buildings.@@ -168,6 +171,7 @@ pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> { flags: flags(tags, "pier"), area: false, min_zoom: 13,+ min_area_px: 0.0, }); } // A ferry is a route, and drawing it is what stops a coastal map looking disconnected.
scripts/maps/mamaps_build/src/tiler.rs
diff --git a/scripts/maps/mamaps_build/src/tiler.rs b/scripts/maps/mamaps_build/src/tiler.rsindex 6b9c1cdcd5..66f263e0d0 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -132,7 +132,14 @@ pub fn build(features: &[Feature], settings: &Settings) -> Result<(Vec<u8>, Vec< // and no sort step can be forgotten. A `HashMap` here is the single easiest way to lose // byte-identical rebuilds. for (id, layers) in tiles {- let body = Body { extent: EXTENT as u16, layers: layers.into_values().collect() };+ // A layer that ended up empty \u2014 every feature in it fell below the minimum area after+ // clipping \u2014 costs bytes in the archive and a draw call on device for nothing.+ let layers: Vec<BodyLayer> =+ layers.into_values().filter(|l| !l.features.is_empty()).collect();+ if layers.is_empty() {+ continue;+ }+ let body = Body { extent: EXTENT as u16, layers }; let encoded = tilecodec::mamaps::body::serialize(&body)?; stats.bytes += encoded.len() as u64; stats.tiles += 1;@@ -155,6 +162,11 @@ fn push(layer: &mut BodyLayer, feature: &Feature, geometry: &IntGeometry) -> (u6 let mut added = (0u64, 0u64); match geometry { IntGeometry::Polygons(polygons) => {+ // Below a few square pixels a polygon is a speck rather than detail, and there are+ // millions of them. Measured **after** clipping, on the shape that would actually be+ // drawn, so a large park clipped to a sliver of one tile is kept where it is big and+ // dropped where it is not.+ let floor = crate::schema::land::min_area_units(class.min_area_px, EXTENT); for rings in polygons { // A ring needs three distinct points plus the closing one; anything less bounds no // area. Filtered *before* anything is appended, because a part and its points have@@ -168,6 +180,9 @@ fn push(layer: &mut BodyLayer, feature: &Feature, geometry: &IntGeometry) -> (u6 if !keep.first().is_some_and(|(index, _)| *index == 0) { continue; }+ if floor > 0.0 && ring_area(keep[0].1) < floor {+ continue;+ } let parts_offset = layer.parts.len() as u32; for (index, ring) in &keep { added.1 += push_part(@@ -231,6 +246,20 @@ fn push_part(layer: &mut BodyLayer, points: &[(i32, i32)], winding: u16) -> u64 points.len() as u64 } +/// A ring's absolute area, by the shoelace formula.+///+/// `i64` throughout: a 4096-unit tile's coordinates cross-multiply to about 2^24 per term, and a+/// long ring accumulates thousands of them, which overflows an `i32` and would silently report a+/// huge shape as a tiny one.+fn ring_area(ring: &[(i32, i32)]) -> f64 {+ let mut twice = 0i64;+ for pair in ring.windows(2) {+ let ((x0, y0), (x1, y1)) = (pair[0], pair[1]);+ twice += x0 as i64 * y1 as i64 - x1 as i64 * y0 as i64;+ }+ (twice.abs() as f64) / 2.0+}+ fn is_empty(g: &Geometry<SigPt>) -> bool { match g { Geometry::Points(points) => points.is_empty(),
scripts/maps/test/diff_kinds.py
diff --git a/scripts/maps/test/diff_kinds.py b/scripts/maps/test/diff_kinds.pynew file mode 100644index 0000000000..dc6b3dad0d--- /dev/null+++ b/scripts/maps/test/diff_kinds.py@@ -0,0 +1,167 @@+#!/usr/bin/env python3+"""Compare a generated `.mamaps` archive against the upstream `.pmtiles` it replaces, per kind.++The measurable answer to the dominant risk of the `.mamaps` project. Reproducing the Protomaps+tag->kind mapping from `.osm.pbf` is weeks of work, and "does it look right" is not a way to track+weeks of work. This turns it into a per-kind recall table: for every (layer, kind) upstream draws,+how many features do we draw, and how much total geometry.++**The bar is visually equivalent, not count-identical.** `landcover` and `landuse` will never match:+upstream applies minimum-area thresholds and zoom rules accumulated over years, and a different but+reasonable threshold changes a count by tens of percent without changing what a person sees. What+this catches is the failure that matters -- a kind we emit *none* of, or ten times too many of.++Usage:+ diff_kinds.py --ours OUT.mamaps --theirs UPSTREAM.pmtiles [--layer NAME] [--max-zoom N]+ [--fail-under 0.5]++Both archives are read through their own dump tools, which is the point: the comparison is of the+decoded model, not of bytes. `mamaps_dump --mode summary` and `pmtiles_dump --mode summary` both emit+one tab-separated line per (zoom, layer) with a sorted kind list, so this is a join rather than a+parse.++Exit status is 1 when a kind upstream draws is missing from ours entirely, or when the ratio for a+kind falls below `--fail-under`. Everything else is reported and does not fail, because a difference+is expected and only an absence is a bug.+"""++import argparse+import os+import shutil+import subprocess+import sys+from collections import defaultdict++HERE = os.path.dirname(os.path.abspath(__file__))+TILE_BUILD = os.path.join(HERE, "..", "tile_build")+++def dump_tool(name):+ """The built binary, or a `cargo run` that builds it.++ Same fallback `diff_pmtiles.py` uses: a release binary if one is lying around, otherwise cargo,+ so the harness works in a fresh checkout without a separate build step.+ """+ exe = os.path.join(TILE_BUILD, "target", "release", name + (".exe" if os.name == "nt" else ""))+ if os.path.exists(exe):+ return [exe]+ if shutil.which("cargo") is None:+ sys.exit(f"diff_kinds: {name} is not built and cargo is not on PATH")+ return [+ "cargo",+ "run",+ "--release",+ "--quiet",+ "--manifest-path",+ os.path.join(TILE_BUILD, "Cargo.toml"),+ "--bin",+ name,+ "--",+ ]+++def summarise(tool, archive, layer):+ """`(zoom, layer, kind) -> (features, points)` from a dump's summary mode.++ `points` is absent from `pmtiles_dump`'s output, so it comes back as `None` there and the+ geometry-length column is simply not compared. Counting features is the part that catches a+ missing kind.+ """+ argv = dump_tool(tool) + [archive, "--mode", "summary"]+ if layer:+ argv += ["--layer", layer]+ try:+ out = subprocess.run(argv, capture_output=True, text=True, check=True).stdout+ except subprocess.CalledProcessError as e:+ sys.exit(f"diff_kinds: {tool} failed on {archive}:\n{e.stderr}")++ rows = {}+ for line in out.splitlines():+ parts = line.split("\t")+ if len(parts) < 3 or not parts[0].startswith("z"):+ continue+ zoom = int(parts[0][1:])+ name = parts[1]+ fields = {}+ for field in parts[2:]:+ if "=" in field:+ key, value = field.split("=", 1)+ fields[key] = value+ features = int(fields.get("features", 0))+ points = int(fields["points"]) if "points" in fields else None+ kinds = [k for k in fields.get("kinds", "").split(",") if k and k != "-"]+ if not kinds:+ kinds = ["-"]+ # A summary line gives one feature count for the whole (zoom, layer), not per kind, so the+ # count is spread evenly across the kinds present. That is crude, and it is enough for what+ # this measures: whether a kind appears at all, and whether a layer's volume is in the right+ # order of magnitude. A per-kind count would need `--mode tiles` over the whole archive.+ share = features / len(kinds)+ point_share = points / len(kinds) if points is not None else None+ for kind in kinds:+ # Ours writes `kind:detail`; upstream writes only `kind`. Compared on the kind alone, so+ # a road's OSM class does not make every road look like a mismatch.+ rows[(zoom, name, kind.split(":", 1)[0])] = (share, point_share)+ return rows+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--ours", required=True, help="a .mamaps archive")+ parser.add_argument("--theirs", required=True, help="the upstream .pmtiles archive")+ parser.add_argument("--layer", help="compare one layer only")+ parser.add_argument("--max-zoom", type=int, default=14)+ parser.add_argument(+ "--fail-under",+ type=float,+ default=0.0,+ help="fail when a kind's feature ratio falls below this (0 disables, only absence fails)",+ )+ args = parser.parse_args()++ ours = summarise("mamaps_dump", args.ours, args.layer)+ theirs = summarise("pmtiles_dump", args.theirs, args.layer)++ # Aggregated over zooms, because a one-level difference in a kind's minimum zoom moves every+ # count in a way that says nothing about whether the mapping is right.+ def fold(rows):+ out = defaultdict(lambda: [0.0, 0.0])+ for (zoom, layer, kind), (features, points) in rows.items():+ if zoom > args.max_zoom:+ continue+ out[(layer, kind)][0] += features+ out[(layer, kind)][1] += points or 0.0+ return out++ ours_folded, theirs_folded = fold(ours), fold(theirs)+ keys = sorted(set(ours_folded) | set(theirs_folded))++ print(f"{'layer':<12}{'kind':<24}{'upstream':>12}{'ours':>12}{'ratio':>9} note")+ missing, thin = [], []+ for layer, kind in keys:+ up = theirs_folded.get((layer, kind), [0.0, 0.0])[0]+ us = ours_folded.get((layer, kind), [0.0, 0.0])[0]+ note = ""+ if up > 0 and us == 0:+ note = "MISSING -- upstream draws this and we draw none"+ missing.append((layer, kind))+ elif up == 0 and us > 0:+ note = "extra -- we draw this and upstream does not"+ ratio = us / up if up > 0 else float("inf") if us > 0 else 1.0+ if up > 0 and us > 0 and args.fail_under > 0 and ratio < args.fail_under:+ note = note or f"THIN -- below the {args.fail_under} floor"+ thin.append((layer, kind))+ print(f"{layer:<12}{kind:<24}{up:>12.0f}{us:>12.0f}{ratio:>9.2f} {note}")++ print()+ print(f"{len(keys)} (layer, kind) pair(s) compared, {len(missing)} missing, {len(thin)} thin")+ if missing:+ print("missing: " + ", ".join(f"{l}/{k}" for l, k in missing))+ if thin:+ print("thin: " + ", ".join(f"{l}/{k}" for l, k in thin))+ # A difference is expected; an absence is a bug. Only the second fails.+ return 1 if missing or thin else 0+++if __name__ == "__main__":+ sys.exit(main())