Modern Apps git

← Modern-Apps.git

maps: draw only a route's path, and fail loudly without GDAL

Commit
40ad1977efec7ed247b4d5159f58937370647a35
Author
vayun-mathur <[email protected]>
When
2026-08-25 01:55 UTC (3 months ago)
Parents
68aa18b

Diff

scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex ca404e7f4f..b7a5f9a1f1 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -130,11 +130,15 @@ mutually consistent (same POI set, same coordinates). See     Exported by `osmium export` (ways export cleanly as LineStrings).   * route **relations** where `route` ∈ {`subway`,`tram`,`light_rail`,`train`,     `monorail`} (bus is intentionally excluded) → `kind`, and the relation-    `colour`/`color` is carried onto the geometry. `osmium export` does not emit-    linear relations as geometry, so these are assembled by GDAL's OSM-    `multilinestrings` layer (`ogr2ogr`), whose `other_tags` HSTORE is parsed by-    the normalizer to recover `route`/`colour`/`ref`. If `ogr2ogr` is not-    installed the layer is still built from railway ways alone (colour omitted).+    `colour`/`color` is carried onto the geometry. Only the way members that are+    the route's **path** contribute geometry: `platform*` and `stop*` roles are+    excluded, because a PTv2 platform is usually a closed way and drawing it as+    track puts a box around every station. `osmium export` does not emit+    linear relations as geometry, so on `--engine legacy` these are assembled by+    GDAL's OSM `multilinestrings` layer (`ogr2ogr`), whose `other_tags` HSTORE is+    parsed by the normalizer to recover `route`/`colour`/`ref`. That engine now+    **fails** without `ogr2ogr` rather than quietly building the way half alone —+    see [Caveats](#caveats--known-limitations) 9. * **POIs (`ma_pois`)** — OpenStreetMap. Any node OR way/relation-area that has   BOTH a `name` tag AND one of the recognised POI keys   (`amenity`/`shop`/`tourism`/`leisure`/`office`/`healthcare`) becomes a POI. The@@ -171,7 +175,7 @@ mutually consistent (same POI set, same coordinates). See | `build_base_layers.sh` | Base tiles (Planetiler build **or** reuse a published archive). A `--bbox` reuse extract now uses our own `pmtiles_extract`; `--extractor go-pmtiles` is still accepted, and is the only practical way to clip the 137 GB planet base | | `build_safety_layer.sh` | **`--engine rust`** (default): `osm_ingest` `osm_extract` → geojsonseq → `tile_build` `tile_points` → `safety.pmtiles`, cargo-only. `--engine legacy`: osmium → GeoJSON → `normalize_safety.py` → tippecanoe | | `build_maxspeed_layer.sh` | **`--engine rust`** (default): `osm_extract` → geojsonseq → `tile_lines`, cargo-only. `--engine legacy`: osmium → GeoJSON → `normalize_maxspeed.py` → tippecanoe |-| `build_transit_lines_layer.sh` | **`--engine rust`** (default): `osm_extract` reads railway ways **and** route relations straight from the PBF → `tile_lines`, cargo-only, **no GDAL**. `--engine legacy`: osmium + ogr2ogr → GeoJSON → `normalize_transit_lines.py` → tippecanoe |+| `build_transit_lines_layer.sh` | **`--engine rust`** (default): `osm_extract` reads railway ways **and** route relations straight from the PBF → `tile_lines`, cargo-only, **no GDAL**. `--engine legacy`: osmium + ogr2ogr → GeoJSON → `normalize_transit_lines.py` → tippecanoe, and **requires** ogr2ogr (see [Caveats](#caveats--known-limitations) 9) | | `build_pois_layer.sh` | `osm_ingest` `poi_extract` → geojsonseq + `poi_names.bin` + `poi_index.bin` → `tile_points` (or tippecanoe with `--engine legacy`) → `ma_pois.pmtiles` | | `osm_ingest/` | Rust OSM ingest crate (detached, `.osm.pbf` read natively): `poi_extract` (POI layer + side files), `road_graph` (routing graph) and `osm_extract` (one geojsonseq per baked vector layer, with its own boundary ring assembler in `src/rings.rs`). Full TYPE MAP and on-disk layouts in `src/poi_build.rs` / `src/graph_build.rs`; see [`osm_ingest/README.md`](osm_ingest/README.md) | | `build_graph.ps1` | Windows entry point for the routing-graph build (no WSL, no g++) |@@ -355,6 +359,31 @@ along with their assertions in `test/test_normalize.py`, because they **are** th on real data. Delete each one once a full-region diff against its Rust engine is clean; deleting them sooner would remove the evidence that the port is right. +### 9. A `transit_lines` layer without its relation half renders grey++A rail corridor is covered by *two* features: a `railway=*` way and a `type=route`+relation. Only the relation carries `colour`, `ref` and the route's `name` — a+plain way emits `kind` + `osm_id` and nothing else. The app's line paint is+`coalesce(feature["colour"], byKind)`, so losing the relation half leaves a layer+with a plausible feature count in which every line falls through to the grey+`rail` fallback.++`--engine rust` cannot produce that shape: it reads relations out of the PBF+directly. `--engine legacy` can, because the relation half is the only part that+needs `ogr2ogr`. So the legacy engine now **exits 1** when `ogr2ogr` is absent or+its export fails; `--allow-ways-only` is the opt-in if that is genuinely what you+want. `osm_extract` additionally warns when it finds railway ways and zero route+relations, which is the same shape arrived at from any other direction.++### 10. The differential harness cannot detect a missing GDAL++`test/diff_geojsonseq.py` diffs a legacy GeoJSONSeq against a Rust one, so running+it needs the legacy engine — which for `transit_lines` needs `ogr2ogr`. The+detector and the failure it would catch share a dependency: on a box without GDAL+there is no legacy output to diff, so the harness cannot be the thing that tells+you the relation half went missing. That is why the check lives in the build script+as a hard failure instead.+ ---  ## Prerequisites (tools)@@ -486,6 +515,8 @@ Natural Earth levels) still default to `legacy`. > One expected difference: `transit_lines` relation features now carry > `osm_id: "relation/9001"` where the GDAL path emitted a bare `9001`. Pass > `--ignore-prop osm_id` to look past it, or read [Caveats](#caveats--known-limitations) §7.+> And on a box without GDAL there is nothing to diff at all for `transit_lines`:+> see [Caveats](#caveats--known-limitations) §10.  ### 1. Dry run (single metro — validates safety + border layers) 
scripts/maps/build_transit_lines_layer.sh
diff --git a/scripts/maps/build_transit_lines_layer.sh b/scripts/maps/build_transit_lines_layer.shindex 150581cf30..50dfb1b218 100644--- a/scripts/maps/build_transit_lines_layer.sh+++ b/scripts/maps/build_transit_lines_layer.sh@@ -48,11 +48,18 @@ set -euo pipefail #   --engine E     rust|legacy (default rust) #   --geojson-out F  also keep the intermediate geojsonseq here (for the #                    differential harness, which needs both engines' output)+#   --allow-ways-only  Let `--engine legacy` proceed without ogr2ogr, producing a+#                    layer with no route relations. See the warning below. #   --keep-tmp     Don't delete intermediate files # # Tools required: cargo. `--engine legacy` additionally needs osmium, tippecanoe-# and python3, plus ogr2ogr (GDAL) for the route-relation half -- without it that-# engine silently produces railway ways only.+# and python3, plus ogr2ogr (GDAL) for the route-relation half.+#+# A LAYER WITHOUT ITS RELATION HALF IS BROKEN, NOT MERELY SMALLER. `colour`, `ref`+# and the route `name` live on the relation and essentially never on the way, so+# dropping relations leaves a full-looking layer of colourless track and the app+# renders every line in its grey `rail` fallback. Missing GDAL is therefore fatal+# here, and `--allow-ways-only` is the deliberate opt-in.  HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PBF=""@@ -62,6 +69,7 @@ MINZOOM=8 MAXZOOM=16 ENGINE="rust" GEOJSON_OUT=""+ALLOW_WAYS_ONLY=0 KEEP_TMP=0  while [[ $# -gt 0 ]]; do@@ -73,8 +81,9 @@ while [[ $# -gt 0 ]]; do         --maxzoom) MAXZOOM="$2"; shift 2 ;;         --engine) ENGINE="$2"; shift 2 ;;         --geojson-out) GEOJSON_OUT="$2"; shift 2 ;;+        --allow-ways-only) ALLOW_WAYS_ONLY=1; shift ;;         --keep-tmp) KEEP_TMP=1; shift ;;-        -h|--help) sed -n '4,55p' "$0" | sed 's/^# \?//'; exit 0 ;;+        -h|--help) sed -n '4,62p' "$0" | sed 's/^# \?//'; exit 0 ;;         *) echo "Unknown arg: $1" >&2; exit 1 ;;     esac done@@ -90,6 +99,14 @@ if [[ "$ENGINE" == "legacy" ]]; then     command -v osmium     >/dev/null || { echo "ERROR: --engine legacy needs osmium-tool" >&2; exit 1; }     command -v tippecanoe >/dev/null || { echo "ERROR: --engine legacy needs tippecanoe" >&2; exit 1; }     command -v python3    >/dev/null || { echo "ERROR: --engine legacy needs python3" >&2; exit 1; }+    if [[ "$ALLOW_WAYS_ONLY" != "1" ]] && ! command -v ogr2ogr >/dev/null; then+        echo "ERROR: --engine legacy needs ogr2ogr (GDAL) for the route-relation half." >&2+        echo "       Without it the layer is railway ways only, which carry no colour," >&2+        echo "       so every transit line renders grey. Use --engine rust (no GDAL" >&2+        echo "       needed at all), or pass --allow-ways-only if that is really what" >&2+        echo "       you want." >&2+        exit 1+    fi fi  TMP="$(mktemp -d)"@@ -127,11 +144,14 @@ else     # Relations need GDAL: osmium export cannot assemble relation geometry.     : > "$TMP/relations.geojsonseq"     if command -v ogr2ogr >/dev/null; then-        ogr2ogr -f GeoJSONSeq "$TMP/relations.geojsonseq" \-            "$TMP/transit_raw.osm.pbf" multilinestrings 2>/dev/null \-            || echo "[transit_lines] WARNING: ogr2ogr relation export failed; railway ways only"+        if ! ogr2ogr -f GeoJSONSeq "$TMP/relations.geojsonseq" \+            "$TMP/transit_raw.osm.pbf" multilinestrings 2>/dev/null; then+            echo "[transit_lines] ERROR: ogr2ogr relation export failed" >&2+            [[ "$ALLOW_WAYS_ONLY" == "1" ]] || exit 1+            echo "[transit_lines] --allow-ways-only: continuing with railway ways only" >&2+        fi     else-        echo "[transit_lines] WARNING: ogr2ogr (GDAL) not found; route-relation colour omitted (railway ways only)"+        echo "[transit_lines] --allow-ways-only: no ogr2ogr, railway ways only (no colour)" >&2     fi      echo "[transit_lines] normalizing kinds"
scripts/maps/osm_ingest/src/bin/osm_extract.rs
diff --git a/scripts/maps/osm_ingest/src/bin/osm_extract.rs b/scripts/maps/osm_ingest/src/bin/osm_extract.rsindex 63b9c30996..a48c405313 100644--- a/scripts/maps/osm_ingest/src/bin/osm_extract.rs+++ b/scripts/maps/osm_ingest/src/bin/osm_extract.rs@@ -48,6 +48,9 @@ fn main() -> ExitCode {                     "WARNING: 0 features. Check --bbox and that the PBF covers the area."                 );             }+            if let Some(why) = stats.missing_half(args.layer) {+                eprintln!("WARNING: {}: {why}", args.layer.name());+            }             ExitCode::SUCCESS         }         Err(e) => {
scripts/maps/osm_ingest/src/extract.rs
diff --git a/scripts/maps/osm_ingest/src/extract.rs b/scripts/maps/osm_ingest/src/extract.rsindex f5446bed74..4aff0ba00a 100644--- a/scripts/maps/osm_ingest/src/extract.rs+++ b/scripts/maps/osm_ingest/src/extract.rs@@ -99,6 +99,28 @@ pub struct Stats {     pub outside_bbox: usize, } +impl Stats {+    /// A layer assembled from two element kinds, reporting none of one of them.+    ///+    /// `transit_lines` is the case that matters: a rail corridor is covered by both+    /// a `railway=*` way and a `type=route` relation, and only the relation carries+    /// `colour`, `ref` and the route's `name`. A ways-only layer therefore looks+    /// full, has the right feature count, and renders every line in the app's grey+    /// `rail` fallback. It is not proof of a broken build -- a rural extract really+    /// can hold track that no PTv2 route covers -- so this is a warning, and the+    /// build scripts own the checks that can be certain.+    pub fn missing_half(&self, layer: Layer) -> Option<String> {+        if layer != Layer::TransitLines || self.from_relations > 0 || self.from_ways == 0 {+            return None;+        }+        Some(format!(+            "{} railway way(s) but 0 route relation(s). Only relations carry `colour`, \+             `ref` and the route `name`, so every line will render grey.",+            self.from_ways+        ))+    }+}+ pub fn build(input: &Path, out: &Path, opts: &Options) -> Result<Stats> {     // Fail before the passes rather than after them if the output is unwritable.     if let Some(parent) = out.parent().filter(|p| !p.as_os_str().is_empty()) {@@ -663,12 +685,14 @@ fn transit_relation_blob(             let Some(kind) = transit_lines::classify(&t) else {                 return Ok(());             };-            // Every way member, whatever its role: a route's `forward`/`backward`-            // members are as much of the line as its unroled ones.+            // Way members that are the route's path. `forward`/`backward` count;+            // `platform*` and `stop*` do not - see [`transit_lines::member_is_path`].             let member_ways: Vec<i64> = r                 .members                 .iter()-                .filter(|m: &&Member| m.kind == MEMBER_WAY)+                .filter(|m: &&Member| {+                    m.kind == MEMBER_WAY && transit_lines::member_is_path(m.role)+                })                 .map(|m| m.id)                 .collect();             if member_ways.is_empty() {@@ -1247,6 +1271,22 @@ mod tests {         assert_eq!(route.matches("]],[[").count(), 1, "two parts: {route}");     } +    #[test]+    fn a_routes_platform_members_are_not_drawn_as_track() {+        // The fixture's route relation carries a third member: a *closed*+        // `railway=platform` way, `role=platform`. Assembling geometry from every+        // member drew a box around the station.+        let (lines, stats) = extract_layer("extract_transit_platform", Layer::TransitLines);+        let route = lines.iter().find(|l| l.contains("relation/9001")).unwrap();+        assert_eq!(route.matches("]],[[").count(), 1, "the two path members only: {route}");+        // The platform's corners sit at 122.404-122.405W, nowhere near the path.+        assert!(!route.contains("-122.4050000"), "platform outline drawn: {route}");+        assert!(!route.contains("-122.4040000"), "platform outline drawn: {route}");+        // And it is not a feature in its own right either, roled or not.+        assert!(!lines.iter().any(|l| l.contains("way/5004")));+        assert_eq!((stats.from_ways, stats.from_relations), (2, 1));+    }+     #[test]     fn the_line_layers_are_deterministic_and_bbox_filtered() {         for layer in [Layer::Maxspeed, Layer::TransitLines] {@@ -1288,6 +1328,25 @@ mod tests {         }     } +    #[test]+    fn a_transit_lines_layer_with_no_relations_is_reported() {+        // Ways-only is the shape a GDAL-less legacy build produces: the right+        // feature count, and no `colour` anywhere, so every line renders grey.+        let ways_only = Stats { features: 900, from_ways: 900, ..Default::default() };+        assert!(ways_only.missing_half(Layer::TransitLines).is_some());+        // Both halves present, or nothing at all, are both fine.+        let both = Stats {+            features: 900,+            from_ways: 800,+            from_relations: 100,+            ..Default::default()+        };+        assert_eq!(both.missing_half(Layer::TransitLines), None);+        assert_eq!(Stats::default().missing_half(Layer::TransitLines), None);+        // And the check is specific to the two-source layer.+        assert_eq!(ways_only.missing_half(Layer::Maxspeed), None);+    }+     // --- the coordinate table ---------------------------------------------      #[test]
scripts/maps/osm_ingest/src/testpbf.rs
diff --git a/scripts/maps/osm_ingest/src/testpbf.rs b/scripts/maps/osm_ingest/src/testpbf.rsindex a2eed53032..bb77c34510 100644--- a/scripts/maps/osm_ingest/src/testpbf.rs+++ b/scripts/maps/osm_ingest/src/testpbf.rs@@ -383,7 +383,11 @@ pub const RAILWAY_WAY_ID: i64 = 5001; pub const NARROW_GAUGE_WAY_ID: i64 = 5002; /// `railway=platform`, which is not a line. The negative control. pub const PLATFORM_WAY_ID: i64 = 5003;-/// `type=route` + `route=subway`, with a colour and a ref, over two member ways.+/// A **closed** `railway=platform` way, carried by the route relation below as a+/// `role=platform` member. The shape that drew a box around every station.+pub const ROUTE_PLATFORM_WAY_ID: i64 = 5004;+/// `type=route` + `route=subway`, with a colour and a ref, over two member ways+/// plus a `role=platform` member that is not part of the line. pub const ROUTE_RELATION_ID: i64 = 9001; /// `type=route` + `route=bus`, which this layer drops. pub const BUS_RELATION_ID: i64 = 9002;@@ -393,6 +397,15 @@ pub const ADMIN_CITY_RELATION_ID: i64 = 9101; /// The same, but `admin_level=6`: a county, which the city layer drops. pub const ADMIN_COUNTY_RELATION_ID: i64 = 9102; +/// The corners of [`ROUTE_PLATFORM_WAY_ID`], well clear of every other fixture+/// coordinate so its absence from the route's geometry can be asserted directly.+const ROUTE_PLATFORM_NODES: [(i64, i32, i32); 4] = [+    (2201, 377_950_000, -1_224_050_000),+    (2202, 377_950_000, -1_224_040_000),+    (2203, 377_960_000, -1_224_040_000),+    (2204, 377_960_000, -1_224_050_000),+];+ /// Way ids the admin boundary is assembled from. pub const ADMIN_OUTER_WAY_A: i64 = 7001; pub const ADMIN_OUTER_WAY_B: i64 = 7002;@@ -492,6 +505,7 @@ pub fn layers_block() -> Vec<u8> {     let v_alameda = st.id("Alameda County");     let role_outer = st.id("outer");     let role_inner = st.id("inner");+    let role_platform = st.id("platform");     // An empty member role is string-table index 0, per the PBF spec.     let role_empty = ST_EMPTY; @@ -540,7 +554,7 @@ pub fn layers_block() -> Vec<u8> {         (WAY_NODE_IDS[5], 377_930_000, -1_224_100_000, vec![]),     ];     let mut nodes = nodes;-    for (id, lat, lon) in ADMIN_NODES {+    for (id, lat, lon) in ADMIN_NODES.into_iter().chain(ROUTE_PLATFORM_NODES) {         nodes.push((id, lat, lon, vec![]));     }     let dense = dense_group(&nodes);@@ -582,6 +596,12 @@ pub fn layers_block() -> Vec<u8> {         ),         // A platform is not a line.         way(PLATFORM_WAY_ID, &[(k_railway, v_platform)], &WAY_NODE_IDS[..2]),+        // And a closed one, which the route relation below claims as `role=platform`.+        way(+            ROUTE_PLATFORM_WAY_ID,+            &[(k_railway, v_platform)],+            &[2201, 2202, 2203, 2204, 2201],+        ),         // admin_city: the outer ring split across two ways, so the assembler has to         // stitch them, and one of them is reversed so it has to flip one too.         way(ADMIN_OUTER_WAY_A, &[], &[2101, 2102, 2103]),@@ -605,6 +625,7 @@ pub fn layers_block() -> Vec<u8> {             &[                 (RAILWAY_WAY_ID, role_empty, 1),                 (NARROW_GAUGE_WAY_ID, role_empty, 1),+                (ROUTE_PLATFORM_WAY_ID, role_platform, 1),             ],         ),         // A bus route: this layer is the rail-like modes only.
scripts/maps/osm_ingest/src/transit_lines.rs
diff --git a/scripts/maps/osm_ingest/src/transit_lines.rs b/scripts/maps/osm_ingest/src/transit_lines.rsindex 9bda55489a..7b4c106733 100644--- a/scripts/maps/osm_ingest/src/transit_lines.rs+++ b/scripts/maps/osm_ingest/src/transit_lines.rs@@ -114,6 +114,20 @@ pub fn truthy(v: Option<&str>) -> bool {     !matches!(v, None | Some("") | Some("no") | Some("false") | Some("0")) } +/// Whether a route relation's way member with this `role` is part of the line.+///+/// A PTv2 route relation carries more than its path: `platform` and `stop` members+/// describe where passengers board, and a platform is very often a **closed way**.+/// Including those drew every platform's outline as if it were track, which is what+/// put station-shaped boxes all over the transit layer.+///+/// Unroled members are the path, and `forward`/`backward` are as much of it — only+/// boarding infrastructure is excluded, by prefix, because PTv2 spells it+/// `platform_entry_only`, `stop_exit_only` and so on.+pub fn member_is_path(role: &[u8]) -> bool {+    !role.starts_with(b"platform") && !role.starts_with(b"stop")+}+ /// British spelling first, then American. pub fn colour<'a>(t: &TransitTags<'a>) -> Option<&'a str> {     [t.colour, t.color].into_iter().find(|v| truthy(*v)).flatten()@@ -351,6 +365,27 @@ mod tests {         }     } +    #[test]+    fn only_boarding_infrastructure_roles_are_excluded_from_the_path() {+        // The PTv2 role table. `platform*` and `stop*` describe where passengers+        // board; a platform is usually a closed way, and including it drew a box+        // around every station.+        for role in [+            "platform",+            "platform_entry_only",+            "platform_exit_only",+            "stop",+            "stop_entry_only",+            "stop_exit_only",+        ] {+            assert!(!member_is_path(role.as_bytes()), "{role} is not the path");+        }+        // Unroled members are the path, and a direction is still the path.+        for role in ["", "forward", "backward"] {+            assert!(member_is_path(role.as_bytes()), "{role} is the path");+        }+    }+     #[test]     fn the_pbf_filters_cover_both_halves_of_the_layer() {         let ways = crate::select::Select::parse(&WAY_FILTERS).unwrap();