Modern Apps git

← Modern-Apps.git

maps: roads and boundaries, with the three flags and a numeric level

Commit
5a887841d05c4d7fd915677da67f10c100fdd415
Author
vayun-mathur <[email protected]>
When
2026-08-28 01:07 UTC (3 months ago)
Parents
169c5c6

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 ad92014edc..30ce21e3a1 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -60,6 +60,10 @@ 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.+    area: bool, }  /// Read `input` and return every feature the schema classifies.@@ -92,11 +96,13 @@ pub fn extract(input: &Path, layers: Layers) -> Result<(Vec<Feature>, Stats)> {                         }                     }                     Element::Relation(relation) => {-                        // `type=multipolygon` is what makes a relation an area. A route or a-                        // boundary relation carrying a water tag is not a lake.-                        if relation.tags.get_str("type") != Some("multipolygon") {-                            return Ok(());-                        }+                        // 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(()),+                        };                         if !select.matches(|k| relation.tags.get_str(k)) {                             return Ok(());                         }@@ -107,7 +113,7 @@ 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();-                            state.1.push(Relation { class, members });+                            state.1.push(Relation { class, members, area });                         }                     }                     Element::Node(_) => {}@@ -203,12 +209,31 @@ pub fn extract(input: &Path, layers: Layers) -> Result<(Vec<Feature>, Stats)> {         }     }     for relation in &relations {+        let refs_of = |id: &i64| ways.get(id).map(|w| &w.refs).or_else(|| members.get(id));+        // A boundary relation's members are the border. Each is emitted as its own line rather than+        // stitched: the renderer strokes them, and a gap between two member ways is invisible in a+        // stroke while a failed stitch would drop the whole border.+        if !relation.area {+            let lines: Vec<Vec<(f64, f64)>> = relation+                .members+                .iter()+                .filter_map(|(id, _)| refs_of(id))+                .map(|refs| table.line(refs))+                .filter(|line| line.len() >= 2)+                .collect();+            if lines.is_empty() {+                stats.geometry_failed += 1;+                continue;+            }+            out.push(Feature { class: relation.class, geometry: Geometry::Lines(lines) });+            stats.features += 1;+            continue;+        }         let member_ways: Vec<MemberWay> = relation             .members             .iter()             .filter_map(|(id, inner)| {-                let refs = ways.get(id).map(|w| &w.refs).or_else(|| members.get(id))?;-                Some(MemberWay { refs: refs.clone(), outer: !inner })+                Some(MemberWay { refs: refs_of(id)?.clone(), outer: !inner })             })             .collect();         let polygons = rings::assemble(&member_ways, |id| locate(&table, id), &mut stats.rings);@@ -216,10 +241,7 @@ pub fn extract(input: &Path, layers: Layers) -> Result<(Vec<Feature>, Stats)> {             stats.geometry_failed += 1;             continue;         }-        out.push(Feature {-            class: relation.class,-            geometry: Geometry::Polygons(polygons),-        });+        out.push(Feature { class: relation.class, geometry: Geometry::Polygons(polygons) });         stats.features += 1;     }     Ok((out, stats))
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 9bb6fd6525..950167a5c5 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -199,7 +199,14 @@ fn derive_build_id(             }         }     }-    eat(&[u8::from(layers.water), u8::from(layers.buildings), min_zoom, max_zoom]);+    eat(&[+        u8::from(layers.water),+        u8::from(layers.buildings),+        u8::from(layers.roads),+        u8::from(layers.boundaries),+        min_zoom,+        max_zoom,+    ]);     eat(&simplification.to_le_bytes());     eat(&features.to_le_bytes());     // The schema table's own version, so a remapped kind invalidates every cache even when the@@ -244,7 +251,8 @@ fn build_report( fn usage() {     eprintln!(         "usage: mamaps_build --input IN.osm.pbf --out OUT.mamaps\n\-         \x20                   [--layers water,buildings] [--min-zoom N] [--max-zoom N]\n\+         \x20                   [--layers water,buildings,roads,boundaries]\n\+         \x20                   [--min-zoom N] [--max-zoom N]\n\          \x20                   [--simplification F] [--build-id N] [--report FILE]"     ); }@@ -281,7 +289,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 },+                schema::Layers { water: true, buildings: false, roads: false, boundaries: false },                 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.rsnew file mode 100644index 0000000000..72910fd6f1--- /dev/null+++ b/scripts/maps/mamaps_build/src/schema/boundaries.rs@@ -0,0 +1,178 @@+//! `boundaries`: the one layer whose detail is a number.+//!+//! An administrative boundary's whole meaning is its **level** — 2 is a country, 4 a state, 6 a+//! county, 8 a city — and the style compares it with `<=` rather than matching a name: one layer for+//! country borders and another for everything below. So the level is carried as a plain integer in+//! the `kind_detail` field under [`FLAG_DETAIL_NUMERIC`], rather than interned. Interning it would+//! mean interning every integer, and comparing `<=` against an id that is not ordered like the value+//! would be worse than useless.+//!+//! A `kind` is carried too, for the differential harness and for a future style that wants a county+//! line dashed differently from a state line. It is derivable from the level, which is exactly why+//! the level is what the style reads.++use tilecodec::mamaps::body::FLAG_DETAIL_NUMERIC;+use tilecodec::mamaps::dict::LAYER_BOUNDARIES;++use super::{kind, Class, TagSource};++pub const FILTERS: &[&str] = &["boundary", "admin_level"];++/// Every `kind` this module can emit.+#[cfg_attr(not(test), allow(dead_code))]+pub const KINDS: &[&str] = &["country", "region", "county", "locality"];++/// The deepest administrative level worth drawing.+///+/// Below 8 is a ward or a neighbourhood: real data, and a line nobody has ever wanted on a basemap.+const MAX_LEVEL: u16 = 8;++pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> {+    if tags.get("boundary") != Some("administrative") {+        return None;+    }+    let level: u16 = tags.get("admin_level")?.trim().parse().ok()?;+    if level == 0 || level > MAX_LEVEL {+        return None;+    }+    Some(Class {+        layer: LAYER_BOUNDARIES,+        kind: kind(kind_for(level)),+        // The level itself, not an id. This is the only field in the format that is a number.+        kind_detail: level,+        flags: FLAG_DETAIL_NUMERIC,+        // A border is a line even when it closes: the style strokes it, and filling it would paint+        // over every layer inside the country.+        area: false,+        min_zoom: min_zoom_for(level),+    })+}++/// The name for an administrative level, as upstream spells it.+fn kind_for(level: u16) -> &'static str {+    match level {+        0..=2 => "country",+        3..=4 => "region",+        5..=6 => "county",+        _ => "locality",+    }+}++/// How shallow a level is worth drawing.+///+/// A country border carries a world tile. A city limit at z4 is noise — and there are a hundred+/// thousand of them.+fn min_zoom_for(level: u16) -> u8 {+    match level {+        0..=2 => 0,+        3..=4 => 3,+        5..=6 => 6,+        _ => 9,+    }+}++#[cfg(test)]+mod tests {+    use super::*;+    use tilecodec::mamaps::dict;++    fn classify_tags(pairs: &[(&str, &str)]) -> Option<Class> {+        super::classify(pairs)+    }++    /// **What the style actually reads.** `boundaries_country` filters `kind_detail <= 2`, so the+    /// level has to arrive as a number that compares correctly — not as an interned id whose+    /// ordering is an accident of table position.+    #[test]+    fn the_level_is_carried_as_a_number_not_an_id() {+        for level in 1..=8u16 {+            let class =+                classify_tags(&[("boundary", "administrative"), ("admin_level", &level.to_string())])+                    .expect("a level");+            assert_eq!(class.kind_detail, level, "the field holds the level itself");+            assert_eq!(class.flags, FLAG_DETAIL_NUMERIC, "and says so");+        }+        // The comparison the style makes.+        let country = classify_tags(&[("boundary", "administrative"), ("admin_level", "2")])+            .expect("country");+        let city = classify_tags(&[("boundary", "administrative"), ("admin_level", "8")])+            .expect("city");+        assert!(country.kind_detail <= 2, "drawn by boundaries_country");+        assert!(city.kind_detail > 2, "drawn by the other layer");+    }++    #[test]+    fn a_level_maps_to_the_name_upstream_uses() {+        let name = |level: &str| {+            let class = classify_tags(&[("boundary", "administrative"), ("admin_level", level)])+                .expect(level);+            dict::KINDS[class.kind as usize - 1]+        };+        assert_eq!(name("2"), "country");+        assert_eq!(name("4"), "region");+        assert_eq!(name("6"), "county");+        assert_eq!(name("8"), "locality");+    }++    /// A border is a line even when it closes. Filling it would paint over every layer inside the+    /// country.+    #[test]+    fn a_boundary_is_never_an_area() {+        let class = classify_tags(&[("boundary", "administrative"), ("admin_level", "2")])+            .expect("country");+        assert!(!class.area);+        assert_eq!(class.layer, dict::LAYER_BOUNDARIES);+    }++    #[test]+    fn a_country_border_is_carried_at_world_zoom_and_a_city_limit_is_not() {+        let at = |level: &str| {+            classify_tags(&[("boundary", "administrative"), ("admin_level", level)])+                .expect(level)+                .min_zoom+        };+        assert_eq!(at("2"), 0, "a country border carries a world tile");+        assert!(at("2") < at("4"));+        assert!(at("4") < at("6"));+        assert!(at("6") < at("8"));+        assert_eq!(at("8"), 9, "there are a hundred thousand city limits");+    }++    #[test]+    fn a_level_below_a_city_is_not_drawn() {+        // Level 9 and 10 are wards and neighbourhoods: real data, and a line nobody wants.+        for level in ["9", "10", "11"] {+            assert!(+                classify_tags(&[("boundary", "administrative"), ("admin_level", level)]).is_none(),+                "level {level} should not be drawn",+            );+        }+        assert!(+            classify_tags(&[("boundary", "administrative"), ("admin_level", "0")]).is_none(),+            "level 0 is not a level",+        );+    }++    #[test]+    fn only_an_administrative_boundary_with_a_readable_level_counts() {+        for tags in [+            // A protected area or a maritime boundary is a boundary and not an administrative one.+            vec![("boundary", "protected_area"), ("admin_level", "2")],+            vec![("boundary", "maritime"), ("admin_level", "2")],+            // Administrative but with no level, or an unreadable one.+            vec![("boundary", "administrative")],+            vec![("boundary", "administrative"), ("admin_level", "")],+            vec![("boundary", "administrative"), ("admin_level", "two")],+            vec![("boundary", "administrative"), ("admin_level", "4;6")],+            vec![("admin_level", "2")],+            vec![],+        ] {+            assert!(classify_tags(&tags).is_none(), "{tags:?} should not be a boundary");+        }+        // Whitespace around a level is common in real data and is not a reason to drop a border.+        assert!(+            classify_tags(&[("boundary", "administrative"), ("admin_level", " 4 ")]).is_some(),+            "a padded level still parses",+        );+    }+}
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 40b56c977f..2dd981d101 100644--- a/scripts/maps/mamaps_build/src/schema/mod.rs+++ b/scripts/maps/mamaps_build/src/schema/mod.rs@@ -23,7 +23,9 @@  use tilecodec::mamaps::dict; +pub mod boundaries; pub mod buildings;+pub mod roads; pub mod water;  /// Tag lookup, so a rule is a pure function of its tags.@@ -112,33 +114,47 @@ pub fn kind(name: &str) -> u16 {     } } +/// Look up a `kind_detail` name's id.+pub fn detail(name: &str) -> u16 {+    match dict::DETAILS.iter().position(|d| *d == name) {+        Some(index) => index as u16 + 1,+        None => panic!("the schema names detail `{name}`, which the dictionary has no id for"),+    }+}+ /// Which layers a build is producing. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Layers {     pub water: bool,     pub buildings: bool,+    pub roads: bool,+    pub boundaries: bool, }  impl Layers {     pub fn all() -> Layers {-        Layers { water: true, buildings: true }+        Layers { water: true, buildings: true, roads: true, boundaries: true }     } -    /// Parse a comma-separated list, e.g. `water,buildings`.+    /// 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 };+        let mut layers =+            Layers { water: false, buildings: false, roads: false, boundaries: false };         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,                 other => {                     return Err(format!(-                        "unknown layer `{other}`; this generator produces water and buildings"+                        "unknown layer `{other}`; this generator produces water, buildings, roads \+                         and boundaries"                     ))                 }             }         }-        if !layers.water && !layers.buildings {+        if layers == (Layers { water: false, buildings: false, roads: false, boundaries: false }) {             return Err("no layers selected".to_string());         }         Ok(layers)@@ -150,17 +166,32 @@ impl Layers { /// Ordered and first-match-wins. `is_way` distinguishes a way from a relation, which matters /// because a closed way's area-ness is a tag question while a multipolygon relation is always an /// area.-pub fn classify(tags: &(impl TagSource + ?Sized), is_way: bool, layers: Layers) -> Option<Class> {+pub fn classify(+    tags: &(impl TagSource + ?Sized),+    is_way: bool,+    layers: Layers,+) -> Option<Class> {     if layers.water {         if let Some(class) = water::classify(tags, is_way) {             return Some(class);         }     }+    // Before buildings, because a road bridge over a building passage is a road.+    if layers.roads {+        if let Some(class) = roads::classify(tags) {+            return Some(class);+        }+    }     if layers.buildings {         if let Some(class) = buildings::classify(tags) {             return Some(class);         }     }+    if layers.boundaries {+        if let Some(class) = boundaries::classify(tags) {+            return Some(class);+        }+    }     None } @@ -174,9 +205,15 @@ pub fn filters(layers: Layers) -> Vec<&'static str> {     if layers.water {         out.extend_from_slice(water::FILTERS);     }+    if layers.roads {+        out.extend_from_slice(roads::FILTERS);+    }     if layers.buildings {         out.extend_from_slice(buildings::FILTERS);     }+    if layers.boundaries {+        out.extend_from_slice(boundaries::FILTERS);+    }     out } @@ -184,29 +221,61 @@ pub fn filters(layers: Layers) -> Vec<&'static str> { mod tests {     use super::*; -    /// Every name this crate writes has to be in the dictionary, or [`kind`] panics at runtime on-    /// whichever feature happens to hit that rule first.+    /// Every name this crate writes has to be in the dictionary, or [`kind`] and [`detail`] panic+    /// at runtime on whichever feature happens to hit that rule first.     #[test]-    fn every_kind_this_schema_names_is_in_the_dictionary() {-        for name in water::KINDS.iter().chain(buildings::KINDS) {+    fn every_name_this_schema_uses_is_in_the_dictionary() {+        for name in water::KINDS+            .iter()+            .chain(buildings::KINDS)+            .chain(roads::KINDS)+            .chain(boundaries::KINDS)+        {             assert!(                 dict::KINDS.contains(name),-                "the schema names `{name}`, which the dictionary has no id for",+                "the schema names kind `{name}`, which the dictionary has no id for",             );-            // And the lookup really resolves rather than merely being present.             assert_eq!(dict::KINDS[kind(name) as usize - 1], *name);         }+        for name in roads::DETAILS {+            assert!(+                dict::DETAILS.contains(name),+                "the schema names detail `{name}`, which the dictionary has no id for",+            );+            assert_eq!(dict::DETAILS[detail(name) as usize - 1], *name);+        }     }      #[test]     fn a_layer_list_parses_and_rejects_what_this_generator_cannot_build() {-        assert_eq!(Layers::parse("water").expect("water"), Layers { water: true, buildings: false });-        assert_eq!(Layers::parse("water,buildings").expect("both"), Layers::all());-        assert_eq!(Layers::parse(" buildings , water ").expect("spaces"), Layers::all());-        assert!(Layers::parse("roads").is_err(), "not until phase 6");+        assert_eq!(+            Layers::parse("water").expect("water"),+            Layers { water: true, buildings: false, roads: false, boundaries: false },+        );+        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("").is_err(), "nothing selected");     } +    /// Order is load-bearing and first match wins. A way tagged as both a road and a building is a+    /// road, because a building passage is something you drive through.+    #[test]+    fn the_rules_are_ordered_and_the_first_match_wins() {+        let both: &[(&str, &str)] = &[("highway", "residential"), ("building", "yes")];+        let class = classify(both, true, Layers::all()).expect("classified");+        assert_eq!(class.layer, dict::LAYER_ROADS);+        // And water is asked before either.+        let water: &[(&str, &str)] =+            &[("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 };+        assert_eq!(+            classify(both, true, only_buildings).expect("building").layer,+            dict::LAYER_BUILDINGS,+        );+    }+     #[test]     fn the_pre_screen_is_a_superset_of_what_the_rules_accept() {         // Not provable in general, so this pins the shape: the screen is a list of tag *keys* the@@ -218,9 +287,12 @@ mod tests {             assert!(!filter.is_empty(), "an empty screen matches everything");             assert!(!filter.contains(' '), "`{filter}` is not a bare tag key");         }-        assert!(filters(Layers { water: true, buildings: false }).len() < all.len());+        assert!(+            filters(Layers { water: true, buildings: false, roads: false, boundaries: false }).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"] {+        for key in ["natural", "waterway", "landuse", "building", "highway", "railway", "boundary"] {             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.rsnew file mode 100644index 0000000000..d1d772061c--- /dev/null+++ b/scripts/maps/mamaps_build/src/schema/roads.rs@@ -0,0 +1,328 @@+//! `roads`: six kinds, thirty details, and three booleans.+//!+//! **This is where roads finally become correct.** The MVT overlay this replaces carried a road's+//! class and nothing else, so a bridge drew as road-coloured tarmac laid over a river and a tunnel+//! drew as though it were on the surface. The three flags are the whole fix, and they cost three+//! bits.+//!+//! # kind versus kind_detail+//!+//! `kind` is the six-way class the style paints — one colour and one width ramp per class. It is+//! deliberately coarse: a map that gave `tertiary` its own colour would be unreadable.+//!+//! `kind_detail` is the OSM `highway` value itself, unreduced. Nothing in the style filters on more+//! than four of them today, and carrying the rest is what lets a future style draw a track+//! differently from a motorway link without a rebuild — and what lets the differential harness+//! compare this generator against upstream value for value rather than class for class.+//!+//! # Minimum zoom is the whole game+//!+//! A motorway belongs on a continent and a service road does not. Six thousand miles of residential+//! street at z8 is not detail, it is a grey wash — and it is also most of the bytes. The `min_zoom`+//! column below is the single most consequential table in this crate.++use tilecodec::mamaps::body::{FLAG_IS_BRIDGE, FLAG_IS_LINK, FLAG_IS_TUNNEL};+use tilecodec::mamaps::dict::LAYER_ROADS;++use super::{detail, kind, Class, TagSource};++pub const FILTERS: &[&str] = &["highway", "railway", "aeroway", "route", "man_made"];++/// Every `kind` this module can emit.+#[cfg_attr(not(test), allow(dead_code))]+pub const KINDS: &[&str] =+    &["highway", "major_road", "minor_road", "path", "other", "rail", "ferry", "aerialway"];++/// Every `kind_detail` this module can emit.+#[cfg_attr(not(test), allow(dead_code))]+pub const DETAILS: &[&str] = &[+    "motorway",+    "motorway_link",+    "trunk",+    "trunk_link",+    "primary",+    "primary_link",+    "secondary",+    "secondary_link",+    "tertiary",+    "tertiary_link",+    "residential",+    "unclassified",+    "living_street",+    "alley",+    "service",+    "track",+    "path",+    "footway",+    "sidewalk",+    "crossing",+    "steps",+    "corridor",+    "cycleway",+    "pedestrian",+    "rail",+    "subway",+    "tram",+    "light_rail",+    "turntable",+    "runway",+    "taxiway",+    "pier",+];++/// `(OSM highway value, kind, kind_detail, min_zoom)`, ordered by importance.+///+/// The `min_zoom` column is the accumulated judgement: a motorway carries a continent, a trunk road+/// a country, a residential street a neighbourhood. Wrong by two levels either way and a mid-zoom+/// tile is either empty or a grey wash.+const HIGHWAYS: &[(&str, &str, &str, u8)] = &[+    ("motorway", "highway", "motorway", 3),+    ("motorway_link", "highway", "motorway_link", 11),+    ("trunk", "major_road", "trunk", 5),+    ("trunk_link", "major_road", "trunk_link", 11),+    ("primary", "major_road", "primary", 7),+    ("primary_link", "major_road", "primary_link", 12),+    ("secondary", "major_road", "secondary", 9),+    ("secondary_link", "major_road", "secondary_link", 12),+    ("tertiary", "major_road", "tertiary", 10),+    ("tertiary_link", "major_road", "tertiary_link", 13),+    ("residential", "minor_road", "residential", 12),+    ("unclassified", "minor_road", "unclassified", 12),+    ("living_street", "minor_road", "living_street", 13),+    // A service road is every driveway and car-park aisle in the world. There are more of them+    // than of every other class combined, and they are street-level detail at best.+    ("service", "minor_road", "service", 14),+    ("road", "other", "unclassified", 13),+    ("track", "path", "track", 14),+    ("path", "path", "path", 14),+    ("footway", "path", "footway", 14),+    ("cycleway", "path", "cycleway", 14),+    ("bridleway", "path", "path", 14),+    ("steps", "path", "steps", 14),+    ("corridor", "path", "corridor", 15),+    ("pedestrian", "path", "pedestrian", 13),+];++/// `(OSM railway value, kind_detail, min_zoom)`.+///+/// One `kind` between them: the style draws every rail the same, and a map that coloured a tram+/// differently from a subway would be a transit diagram rather than a basemap.+const RAILWAYS: &[(&str, &str, u8)] = &[+    ("rail", "rail", 8),+    ("subway", "subway", 12),+    ("light_rail", "light_rail", 12),+    ("tram", "tram", 13),+    ("narrow_gauge", "rail", 11),+    ("monorail", "light_rail", 13),+    ("funicular", "light_rail", 13),+    ("turntable", "turntable", 15),+];++pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> {+    if let Some(highway) = tags.get("highway") {+        let (_, kind_name, detail_name, min_zoom) =+            HIGHWAYS.iter().find(|(value, _, _, _)| *value == highway)?;+        return Some(Class {+            layer: LAYER_ROADS,+            kind: kind(kind_name),+            kind_detail: detail(detail_name),+            flags: flags(tags, highway),+            area: false,+            min_zoom: *min_zoom,+        });+    }+    if let Some(railway) = tags.get("railway") {+        let (_, detail_name, min_zoom) = RAILWAYS.iter().find(|(value, _, _)| *value == railway)?;+        return Some(Class {+            layer: LAYER_ROADS,+            kind: kind("rail"),+            kind_detail: detail(detail_name),+            flags: flags(tags, railway),+            area: false,+            min_zoom: *min_zoom,+        });+    }+    // A runway is a line in this layer and a polygon in `landuse`. Both are drawn, because an+    // airport reads as a shape with a stripe down it.+    if let Some(aeroway) = tags.get("aeroway") {+        let detail_name = match aeroway {+            "runway" => "runway",+            "taxiway" => "taxiway",+            _ => return None,+        };+        return Some(Class {+            layer: LAYER_ROADS,+            kind: kind("other"),+            kind_detail: detail(detail_name),+            flags: flags(tags, aeroway),+            area: false,+            min_zoom: if aeroway == "runway" { 9 } else { 13 },+        });+    }+    // A pier is walkable, so it belongs with the paths rather than with the buildings.+    if tags.get("man_made") == Some("pier") {+        return Some(Class {+            layer: LAYER_ROADS,+            kind: kind("path"),+            kind_detail: detail("pier"),+            flags: flags(tags, "pier"),+            area: false,+            min_zoom: 13,+        });+    }+    // A ferry is a route, and drawing it is what stops a coastal map looking disconnected.+    if tags.get("route") == Some("ferry") {+        return Some(Class::line(LAYER_ROADS, kind("ferry"), 9));+    }+    None+}++/// The three booleans, and the reason this layer was worth redoing.+///+/// `is_link` is derived from the class name rather than read from a tag, because OSM spells a slip+/// road as `highway=motorway_link` and there is no `link=yes`. That matches what upstream emits and+/// what the style filters with `!has is_link`.+fn flags(tags: &(impl TagSource + ?Sized), value: &str) -> u8 {+    let mut flags = 0u8;+    // `tunnel=building_passage` is a tunnel; only `no` is not. Same for a bridge tagged `viaduct`+    // or `boardwalk`.+    if tags.truthy("tunnel") || tags.get("covered") == Some("yes") {+        flags |= FLAG_IS_TUNNEL;+    }+    if tags.truthy("bridge") {+        flags |= FLAG_IS_BRIDGE;+    }+    if value.ends_with("_link") {+        flags |= FLAG_IS_LINK;+    }+    flags+}++#[cfg(test)]+mod tests {+    use super::*;+    use tilecodec::mamaps::dict;++    fn classify_tags(pairs: &[(&str, &str)]) -> Option<Class> {+        super::classify(pairs)+    }++    fn names(class: &Class) -> (&'static str, &'static str) {+        (+            dict::KINDS[class.kind as usize - 1],+            dict::DETAILS[class.kind_detail as usize - 1],+        )+    }++    #[test]+    fn a_road_carries_a_coarse_kind_and_its_exact_osm_class() {+        let motorway = classify_tags(&[("highway", "motorway")]).expect("motorway");+        assert_eq!(names(&motorway), ("highway", "motorway"));+        assert_eq!(motorway.layer, dict::LAYER_ROADS);+        assert!(!motorway.area, "a road is a line");++        // Four OSM classes collapse to one drawn colour, and each keeps its own detail.+        for (value, detail) in+            [("trunk", "trunk"), ("primary", "primary"), ("secondary", "secondary"), ("tertiary", "tertiary")]+        {+            let class = classify_tags(&[("highway", value)]).expect(value);+            assert_eq!(names(&class), ("major_road", detail));+        }+    }++    /// **The fix this layer was redone for.** Without these three bits a bridge is tarmac laid over+    /// a river and a tunnel is a road on the surface.+    #[test]+    fn a_bridge_a_tunnel_and_a_slip_road_are_all_flagged() {+        let bridge = classify_tags(&[("highway", "primary"), ("bridge", "yes")]).expect("bridge");+        assert_eq!(bridge.flags, FLAG_IS_BRIDGE);+        let tunnel = classify_tags(&[("highway", "primary"), ("tunnel", "yes")]).expect("tunnel");+        assert_eq!(tunnel.flags, FLAG_IS_TUNNEL);+        // A slip road is spelled in the class, not in a tag of its own.+        let link = classify_tags(&[("highway", "motorway_link")]).expect("link");+        assert_eq!(link.flags, FLAG_IS_LINK);+        assert_eq!(names(&link), ("highway", "motorway_link"));+        // And they combine: a flyover slip road is both.+        let both = classify_tags(&[("highway", "motorway_link"), ("bridge", "viaduct")])+            .expect("both");+        assert_eq!(both.flags, FLAG_IS_LINK | FLAG_IS_BRIDGE);+        // Only `no` is not a bridge. `bridge=viaduct` and `bridge=boardwalk` are.+        let flat = classify_tags(&[("highway", "primary"), ("bridge", "no")]).expect("flat");+        assert_eq!(flat.flags, 0);+    }++    #[test]+    fn a_covered_way_counts_as_a_tunnel() {+        // `covered=yes` is how an arcade or a building passage is tagged when it is not a tunnel+        // proper, and it draws the same way.+        let covered = classify_tags(&[("highway", "footway"), ("covered", "yes")]).expect("covered");+        assert_eq!(covered.flags, FLAG_IS_TUNNEL);+    }++    /// The most consequential column in this crate. A motorway carries a continent; a service road+    /// is every driveway in the world and there are more of them than of everything else combined.+    #[test]+    fn the_minimum_zooms_run_from_continent_to_street() {+        let at = |value: &str| classify_tags(&[("highway", value)]).expect(value).min_zoom;+        assert_eq!(at("motorway"), 3, "a motorway is a continental feature");+        assert!(at("trunk") < at("primary"));+        assert!(at("primary") < at("secondary"));+        assert!(at("secondary") < at("tertiary"));+        assert!(at("tertiary") < at("residential"));+        assert!(at("residential") < at("service"));+        assert_eq!(at("service"), 14, "a driveway is street-level at best");+        // A slip road is not carried shallower than the road it joins, which would draw a+        // disembodied stub.+        assert!(at("motorway_link") > at("motorway"));+        assert!(at("primary_link") > at("primary"));+    }++    #[test]+    fn every_railway_draws_as_one_kind_with_its_own_detail() {+        for (value, expected) in+            [("rail", "rail"), ("subway", "subway"), ("tram", "tram"), ("narrow_gauge", "rail")]+        {+            let class = classify_tags(&[("railway", value)]).expect(value);+            assert_eq!(names(&class), ("rail", expected));+        }+        // A rail line is a country-scale feature; a tram is not.+        let rail = classify_tags(&[("railway", "rail")]).expect("rail");+        let tram = classify_tags(&[("railway", "tram")]).expect("tram");+        assert!(rail.min_zoom < tram.min_zoom);+    }++    #[test]+    fn a_runway_a_pier_and_a_ferry_are_carried_in_this_layer() {+        let runway = classify_tags(&[("aeroway", "runway")]).expect("runway");+        assert_eq!(names(&runway), ("other", "runway"));+        let pier = classify_tags(&[("man_made", "pier")]).expect("pier");+        assert_eq!(names(&pier), ("path", "pier"), "a pier is walkable");+        let ferry = classify_tags(&[("route", "ferry")]).expect("ferry");+        assert_eq!(dict::KINDS[ferry.kind as usize - 1], "ferry");+    }++    /// `highway` is asked before `railway`, which matters at a level crossing: a way tagged both is+    /// the road, because that is what carries traffic.+    #[test]+    fn highway_is_asked_before_railway() {+        let crossing = classify_tags(&[("railway", "rail"), ("highway", "residential")])+            .expect("crossing");+        assert_eq!(names(&crossing).0, "minor_road");+    }++    #[test]+    fn an_unrecognised_value_is_not_a_road() {+        for tags in [+            vec![("highway", "bus_stop")],+            vec![("highway", "street_lamp")],+            vec![("railway", "abandoned")],+            vec![("aeroway", "gate")],+            vec![("man_made", "tower")],+            vec![("route", "bicycle")],+            vec![("building", "yes")],+            vec![],+        ] {+            assert!(classify_tags(&tags).is_none(), "{tags:?} should not be a road");+        }+    }+}