Modern Apps git

← Modern-Apps.git

maps: port maxspeed and transit_lines to Rust, dropping the GDAL step

Commit
727d204493458e08522fc9e345afe5d543bba0e0
Author
vayun-mathur <[email protected]>
When
2026-08-21 06:34 UTC (3 months ago)
Parents
22fbc4a

Diff

scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex 2fa4d6c884..850ef2bf44 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -169,8 +169,8 @@ mutually consistent (same POI set, same coordinates). See | `build_v5_pmtiles.sh` | Tile orchestrator: base + safety + maxspeed + transit_lines + ma_pois + admin + transit_stops → merge → `v5.pmtiles` | | `build_base_layers.sh` | Base tiles (Planetiler build **or** reuse upstream `v4.pmtiles`) | | `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` | osmium → GeoJSON → `normalize_maxspeed.py` → tippecanoe → `maxspeed.pmtiles` |-| `build_transit_lines_layer.sh` | osmium + ogr2ogr → GeoJSON → `normalize_transit_lines.py` → tippecanoe → `transit_lines.pmtiles` |+| `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_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). 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++) |@@ -181,8 +181,8 @@ mutually consistent (same POI set, same coordinates). See | `tile_build/` | Rust MVT + PMTiles v3 crate (detached), **replacing tippecanoe and tile-join**. Bins: `tile_points` / `tile_lines` / `tile_polygons` (one per geometry kind), `tile_join` (merge archives), `pmtiles_dump` (canonical text dump, for the differential harness). Library: `geojson` (the shared GeoJSONSeq reader), `geom` (web-mercator projection, tile ranges, quantisation), `clip` (Liang-Barsky for lines, Sutherland-Hodgman for polygons), `simplify` (Douglas-Peucker in integer tile coordinates), `pyramid` (the tile pyramid driver and the drop policy), `mvt` (line and polygon encoders beside the opaque passthrough that keeps `tile_join` lossless). Container layout documented in `src/pmtiles.rs`, the pipeline order in `src/geom.rs`, the drop policy in `src/pyramid.rs` | | `publish_r2.sh` | Upload built artifacts to Cloudflare R2 (creds from env vars only) | | `normalize_safety.py` | OSM tags → `safety` layer schema (pure stdlib, unit-tested). **Superseded** by `osm_ingest/src/safety.rs`; kept as the contract of record and as `--engine legacy` for the differential harness |-| `normalize_maxspeed.py` | OSM maxspeed ways → `maxspeed` layer schema (pure stdlib, unit-tested) |-| `normalize_transit_lines.py` | OSM railway ways + route relations → `transit_lines` schema (pure stdlib, unit-tested) |+| `normalize_maxspeed.py` | OSM maxspeed ways → `maxspeed` layer schema (pure stdlib, unit-tested). **Superseded** by `osm_ingest/src/maxspeed.rs`; kept as the contract of record and as `--engine legacy` |+| `normalize_transit_lines.py` | OSM railway ways + route relations → `transit_lines` schema (pure stdlib, unit-tested). **Superseded** by `osm_ingest/src/transit_lines.rs`; kept as the contract of record and as `--engine legacy` | | `normalize_admin.py` | NE/OSM attrs → admin layer schema (pure stdlib, unit-tested) | | `test/test_normalize.py` | Dry-run unit test of the schema mapping (no external tools) | | `test/diff_geojsonseq.py` | **Differential harness**, extraction half: diffs a legacy GeoJSONSeq against a Rust one. Properties exact, points exact, lines/polygons within an epsilon |@@ -277,6 +277,27 @@ bridges them onto the first set. what makes a re-run cheap. `--keep-work` only silences the reminder; it does not change the behaviour. +### 7. `transit_lines` relation `osm_id` changed form++The legacy chain got relation geometry from `ogr2ogr … multilinestrings`, whose+`osm_id` field is a bare number, while railway ways came through `osmium export`+as `way/5001`. The two sources disagreeing was an artefact of the toolchain rather+than a decision, so the rust engine emits `<kind>/<id>` throughout and a relation+is now `relation/9001`.++This is the one schema difference the differential harness will report on a+`transit_lines` run. Nothing in the app styles on `osm_id` — it is carried for+dedup and debugging — but if you are diffing the two engines, expect it.++### 8. The superseded Python normalisers are still in the tree++`normalize_safety.py`, `normalize_maxspeed.py` and `normalize_transit_lines.py`+have Rust replacements that the unit tests show agree with them, but they are kept,+along with their assertions in `test/test_normalize.py`, because they **are** the+`--engine legacy` path and therefore the only way to run the differential harness+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.+ ---  ## Prerequisites (tools)@@ -294,28 +315,30 @@ here is Rust and Python):   * [`tile_build`](tile_build/) — MVT and PMTiles v3 read/write, which **replaces     tippecanoe and tile-join**. The final merge and the `transit_stops` layer both     go through it, so they run on **Windows**.-* **tippecanoe** ≥ 2.x — still required by the maxspeed, transit_lines and admin-  layer scripts, which pipe GeoJSON through it. The merge no longer uses its-  `tile-join`, and `safety` and `ma_pois` no longer use it at all.-* **osmium-tool** (`osmium`) — still required by those same OSM-derived layers, and-  by any `--bbox` run of `build_all.sh` (which clips once for every stage).-* **GDAL** (`ogr2ogr`) — transit_lines and admin only.-* **python3** (stdlib only) — the remaining `normalize_*.py` schema mappers, the-  schema unit test, and the differential harness.+* **tippecanoe** ≥ 2.x — now only the admin layer scripts, and any+  `--engine legacy` run. The merge does not use its `tile-join`, and `safety`,+  `maxspeed`, `transit_lines` and `ma_pois` do not use it at all.+* **osmium-tool** (`osmium`) — the admin layer and `--engine legacy`, plus any+  `--bbox` run of `build_all.sh` (which clips once for every stage).+* **GDAL** (`ogr2ogr`) — the admin layer, and `transit_lines --engine legacy`. The+  rust `transit_lines` engine reads route relations out of the PBF directly, so it+  needs no GDAL at all.+* **python3** (stdlib only) — `normalize_admin.py`, the superseded normalisers kept+  for `--engine legacy`, the schema unit test, and the differential harness. * Base build mode only: **Java 21** + the Protomaps basemap jar   (build once from `github.com/protomaps/basemaps`, `tiles/` → `mvn package`) * Base reuse mode only: `curl`, and `go-pmtiles` (`pmtiles`) if using `--bbox`  ### What builds on Windows -Everything that is cargo-only: the routing graph (`build_graph.ps1`), the POI-layer and its side files, the `safety` layer, the offline transit pack-(`build_ca_transit.ps1`), the `transit_stops` layer-(`build_transit_stops_layer.ps1`) and the final merge (`tile_join`).-`build_all.ps1` chains those. The remaining OSM-derived vector layers (maxspeed,-transit_lines, admin) still need tippecanoe + osmium + python3 + GDAL and-therefore a Linux box or WSL, which is why the Windows tiles stage composites onto-a `-BaseArchive` instead of building a complete `v5.pmtiles`.+Everything that is cargo-only, which is now every layer except `admin`: the routing+graph (`build_graph.ps1`), the POI layer and its side files, `safety`, `maxspeed`,+`transit_lines`, the offline transit pack (`build_ca_transit.ps1`), the+`transit_stops` layer (`build_transit_stops_layer.ps1`) and the final merge+(`tile_join`). `build_all.ps1` chains those. Only the admin layers still need+tippecanoe + osmium + python3 + GDAL, and the Planetiler base build still needs+Java — which is why the Windows tiles stage composites onto a `-BaseArchive`+instead of building a complete `v5.pmtiles`.  That is why `tile_build` exists rather than shelling out to tippecanoe: there is no Windows path for it (see the note at `build_graph.ps1:29`), which would@@ -369,28 +392,31 @@ unlike the per-layer scripts, the routing graph honours it too. That needs  Per-layer `--engine rust|legacy` flags exist for every layer so a ported layer can be rolled back with one flag. Asking for an engine that has not landed is an-error, never a silent fall-back. `safety` and `ma_pois` default to `rust`; the-rest still default to `legacy`.+error, never a silent fall-back. `safety`, `maxspeed`, `transit_lines` and+`ma_pois` default to `rust`; `base` and `admin` still default to `legacy`. -> **Validate a flipped engine before trusting it.** Each layer that moves to Rust-> has unit tests mirroring the Python normaliser's assertions, but those pin the-> schema, not the extraction over real data. Run both engines over the same PBF-> and diff them before publishing:+> **Validate a flipped engine before trusting it.** Each ported layer has unit+> tests mirroring the Python normaliser's assertions, but those pin the schema, not+> the extraction over real data. Run both engines over the same PBF and diff them+> before publishing: > > ```bash-> ./build_safety_layer.sh --pbf norcal.osm.pbf --bbox -122.6,37.2,-121.7,37.9 \->     --engine legacy --out /tmp/safety-legacy.pmtiles \->     --geojson-out /tmp/safety-legacy.geojsonseq-> ./build_safety_layer.sh --pbf norcal.osm.pbf --bbox -122.6,37.2,-121.7,37.9 \->     --engine rust --out /tmp/safety-rust.pmtiles \->     --geojson-out /tmp/safety-rust.geojsonseq-> python3 test/diff_geojsonseq.py /tmp/safety-legacy.geojsonseq /tmp/safety-rust.geojsonseq-> python3 test/diff_pmtiles.py    /tmp/safety-legacy.pmtiles    /tmp/safety-rust.pmtiles+> for engine in legacy rust; do+>   ./build_maxspeed_layer.sh --pbf norcal.osm.pbf --bbox -122.6,37.2,-121.7,37.9 \+>       --engine $engine --out /tmp/maxspeed-$engine.pmtiles \+>       --geojson-out /tmp/maxspeed-$engine.geojsonseq+> done+> python3 test/diff_geojsonseq.py /tmp/maxspeed-legacy.geojsonseq /tmp/maxspeed-rust.geojsonseq+> python3 test/diff_pmtiles.py    /tmp/maxspeed-legacy.pmtiles    /tmp/maxspeed-rust.pmtiles > ``` >-> The extraction diff must be clean: properties exactly, point geometry exactly.-> The tile diff is allowed a feature-count delta (see-> [Caveats](#caveats--known-limitations) §3).+> The extraction diff must be clean: properties exactly, point geometry exactly,+> line and polygon geometry within `--epsilon`. The tile diff is allowed a+> feature-count delta (see [Caveats](#caveats--known-limitations) §3).+>+> 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.  ### 1. Dry run (single metro — validates safety + border layers) 
scripts/maps/build_all.ps1
diff --git a/scripts/maps/build_all.ps1 b/scripts/maps/build_all.ps1index bf9d713f55..3c0b14c2fd 100644--- a/scripts/maps/build_all.ps1+++ b/scripts/maps/build_all.ps1@@ -4,13 +4,13 @@ # artifacts, with every bytes-to-bytes transformation done by our own Rust crates # and only network I/O and process orchestration here. #-# WHAT THIS TWIN CAN AND CANNOT DO. The layers that still go through osmium,-# tippecanoe, GDAL and python3 (maxspeed, transit_lines, admin) have no Windows-# path, and neither does the Planetiler base build. So the tiles stage here-# composites only the cargo-only layers -- safety, ma_pois and transit_stops -- on-# top of a base archive you point it at with -BaseArchive. It says so loudly-# rather than quietly emitting an archive with layers missing. For a complete v5,-# run build_all.sh under WSL. Stages graph, pois and transit are complete.+# WHAT THIS TWIN CAN AND CANNOT DO. Only the `admin` layers still go through+# osmium, tippecanoe, GDAL and python3, and the Planetiler base build still needs+# Java. So the tiles stage here composites the cargo-only layers -- safety,+# maxspeed, transit_lines, ma_pois and transit_stops -- on top of a base archive you+# point it at with -BaseArchive. It says so loudly rather than quietly emitting an+# archive with layers missing. For a complete v5, run build_all.sh under WSL.+# Stages graph, pois and transit are complete. # # THE 9 ARTIFACTS, all landing in -OutDir: #   graph    metadata.bin road_names.bin nodes.bin edges.bin lanes.bin@@ -66,6 +66,8 @@ param(     # is refused until that layer is actually ported.     [ValidateSet("rust", "legacy")] [string] $EnginePois = "rust",     [ValidateSet("rust", "legacy")] [string] $EngineSafety = "rust",+    [ValidateSet("rust", "legacy")] [string] $EngineMaxspeed = "rust",+    [ValidateSet("rust", "legacy")] [string] $EngineTransitLines = "rust",      # Publishing. Delegates to publish_r2.sh, which needs bash (WSL or Git Bash).     [switch] $Publish,@@ -127,6 +129,11 @@ if ($EnginePois -eq "legacy") { if ($EngineSafety -eq "legacy") {     throw "-EngineSafety legacy needs osmium, tippecanoe and python3, none of which have a Windows path; use rust (the default), or build under WSL" }+foreach ($pair in @(@("EngineMaxspeed", $EngineMaxspeed), @("EngineTransitLines", $EngineTransitLines))) {+    if ($pair[1] -eq "legacy") {+        throw "-$($pair[0]) legacy needs osmium, tippecanoe, python3 (and GDAL for transit_lines), none of which have a Windows path; use rust (the default), or build under WSL"+    }+}  New-Item -ItemType Directory -Force -Path $OutDir | Out-Null $OutDir = (Resolve-Path $OutDir).Path@@ -165,6 +172,8 @@ if ($Geofabrik) {  $PoisTile    = Join-Path $Work "ma_pois.pmtiles" $SafetyTile  = Join-Path $Work "safety.pmtiles"+$MaxspeedTile = Join-Path $Work "maxspeed.pmtiles"+$TransitLinesTile = Join-Path $Work "transit_lines.pmtiles" $StopsTile   = Join-Path $Work "transit_stops.pmtiles" $TransitWork = Join-Path $Work "transit" @@ -251,8 +260,7 @@ if (Test-Stage "tiles") {             throw @" the tiles stage needs -BaseArchive on Windows. -Only safety, ma_pois and transit_stops are cargo-only today; maxspeed,-transit_lines and admin still need osmium/tippecanoe/GDAL/python3, and the+Only the admin layers still need osmium/tippecanoe/GDAL/python3, and the Planetiler base build needs Java. So this twin composites the cargo-only layers onto an existing archive rather than building one: @@ -279,19 +287,26 @@ For a complete v5 with every layer, run build_all.sh under WSL.             throw "-BaseArchive not found: $base"         } -        # safety is cargo-only: osm_extract reads the PBF directly and-        # tile_points tiles it, so no osmium, tippecanoe or python3 is involved.+        # safety, maxspeed and transit_lines are all cargo-only: osm_extract reads+        # the PBF directly and the tile_build tilers tile it, so no osmium,+        # tippecanoe, GDAL or python3 is involved.         if ($Pbf) {-            $safetyGeo = Join-Path $Work "safety.geojsonseq"-            Write-Host "=== tiles: safety -> $SafetyTile ==="-            Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $OsmManifest,-                "--bin", "osm_extract", "--", $Pbf, "--layer", "safety", "--out", $safetyGeo)-            Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $TileManifest,-                "--bin", "tile_points", "--",-                "--geojson", $safetyGeo, "--out", $SafetyTile, "--layer", "safety",-                "--minzoom", "10", "--maxzoom", "16")+            foreach ($spec in @(+                @{ Layer = "safety";        Tile = $SafetyTile;       Bin = "tile_points"; Min = 10; Max = 16 },+                @{ Layer = "maxspeed";      Tile = $MaxspeedTile;     Bin = "tile_lines";  Min = 12; Max = 16 },+                @{ Layer = "transit_lines"; Tile = $TransitLinesTile; Bin = "tile_lines";  Min = 9;  Max = 16 }+            )) {+                $geo = Join-Path $Work "$($spec.Layer).geojsonseq"+                Write-Host "=== tiles: $($spec.Layer) -> $($spec.Tile) ==="+                Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $OsmManifest,+                    "--bin", "osm_extract", "--", $Pbf, "--layer", $spec.Layer, "--out", $geo)+                Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $TileManifest,+                    "--bin", $spec.Bin, "--",+                    "--geojson", $geo, "--out", $spec.Tile, "--layer", $spec.Layer,+                    "--minzoom", "$($spec.Min)", "--maxzoom", "$($spec.Max)")+            }         } else {-            Write-Warning "no -Pbf given; skipping the safety layer"+            Write-Warning "no -Pbf given; skipping the safety, maxspeed and transit_lines layers"         }          # transit_stops needs the same feed manifest world.transit was built from,@@ -312,14 +327,14 @@ For a complete v5 with every layer, run build_all.sh under WSL.          # Later inputs win a layer-name collision, so the overlays go after base.         $inputs = @($base)-        foreach ($t in @($SafetyTile, $PoisTile, $StopsTile)) {+        foreach ($t in @($SafetyTile, $MaxspeedTile, $TransitLinesTile, $PoisTile, $StopsTile)) {             if ((Test-Path $t) -or $DryRun) { $inputs += $t }         }         Write-Host "=== tiles: merging $($inputs.Count) source(s) -> $Out ==="         $inputs | ForEach-Object { Write-Host "  + $_" }         Invoke-Step "cargo" (@("run", "--release", "--quiet", "--manifest-path", $TileManifest,             "--bin", "tile_join", "--", "--out", $Out) + $inputs)-        Write-Warning "maxspeed, transit_lines and admin are NOT in $Out (they need osmium/tippecanoe/GDAL/python3 -- build under WSL for a complete archive)"+        Write-Warning "the admin layers are NOT in $Out (they need osmium/tippecanoe/GDAL/python3 -- build under WSL for a complete archive)"         Set-Stamp "tiles"     } }
scripts/maps/build_all.sh
diff --git a/scripts/maps/build_all.sh b/scripts/maps/build_all.shindex a128f16070..a8d1b22fe7 100644--- a/scripts/maps/build_all.sh+++ b/scripts/maps/build_all.sh@@ -63,8 +63,9 @@ set -euo pipefail #     --engine-base E     rust|legacy    (default legacy) #     --engine-safety E   rust|legacy    (default rust: osm_extract + tile_points, #                                         no osmium/tippecanoe/python3)-#     --engine-maxspeed E rust|legacy    (default legacy)-#     --engine-transit-lines E           (default legacy)+#     --engine-maxspeed E rust|legacy    (default rust: osm_extract + tile_lines)+#     --engine-transit-lines E           (default rust: ways AND route relations+#                                         read straight from the PBF, no GDAL) #     --engine-admin E    rust|legacy    (default legacy) #     --engine-pois E     rust|legacy    (default rust: tile_points, no tippecanoe) #   Publishing@@ -102,8 +103,8 @@ PUBLISH=0 PUBLISH_DRY_RUN=0 ENGINE_BASE="legacy" ENGINE_SAFETY="rust"-ENGINE_MAXSPEED="legacy"-ENGINE_TRANSIT_LINES="legacy"+ENGINE_MAXSPEED="rust"+ENGINE_TRANSIT_LINES="rust" ENGINE_ADMIN="legacy" ENGINE_POIS="rust" @@ -136,7 +137,7 @@ while [[ $# -gt 0 ]]; do         --engine-transit-lines) ENGINE_TRANSIT_LINES="$2"; shift 2 ;;         --engine-admin) ENGINE_ADMIN="$2"; shift 2 ;;         --engine-pois) ENGINE_POIS="$2"; shift 2 ;;-        -h|--help) sed -n '4,78p' "$0" | sed 's/^# \?//'; exit 0 ;;+        -h|--help) sed -n '4,79p' "$0" | sed 's/^# \?//'; exit 0 ;;         *) echo "Unknown arg: $1" >&2; exit 1 ;;     esac done@@ -161,8 +162,8 @@ engine_check() { } engine_check base           "$ENGINE_BASE"           0 engine_check safety         "$ENGINE_SAFETY"         1-engine_check maxspeed       "$ENGINE_MAXSPEED"       0-engine_check transit-lines  "$ENGINE_TRANSIT_LINES"  0+engine_check maxspeed       "$ENGINE_MAXSPEED"       1+engine_check transit-lines  "$ENGINE_TRANSIT_LINES"  1 engine_check admin          "$ENGINE_ADMIN"          0 engine_check pois           "$ENGINE_POIS"           1 
scripts/maps/build_maxspeed_layer.sh
diff --git a/scripts/maps/build_maxspeed_layer.sh b/scripts/maps/build_maxspeed_layer.shindex 7de2947119..adf115602f 100644--- a/scripts/maps/build_maxspeed_layer.sh+++ b/scripts/maps/build_maxspeed_layer.sh@@ -1,14 +1,27 @@ #!/bin/bash set -euo pipefail -# build_maxspeed_layer.sh — bake the `maxspeed` layer (posted speed limits)+# build_maxspeed_layer.sh — bake the `maxspeed` layer (P5b) into a .pmtiles #-# Produces a line-geometry PMTiles layer of OSM ways that carry a maxspeed tag,-# so the app's posted-speed-limit feature (P5b MaxspeedSource) can read it via-# queryRenderedFeatures from v5.pmtiles instead of a separate host.+# Extracts posted speed limits from OSM ways and tiles them into a single-layer+# PMTiles file, so the app's MaxspeedSource reads them from the basemap instead of+# querying anything at runtime. #-# Source layer produced:  maxspeed   (attr: maxspeed, highway?, name?, osm_id)-#   maxspeed = raw OSM value, e.g. "35 mph", "50", "50 km/h" (parsed app-side)+# Source layer produced:  maxspeed  (attr: maxspeed, highway?, name?, osm_id)+#+# THE VALUE IS A RAW STRING. `maxspeed` is the OSM tag verbatim -- "25 mph",+# "100 km/h", "50", "none", "walk", "signals" -- because OsmMaxspeed.kt parses it+# itself and the distinctions matter: `none` on an autobahn is not an absent limit,+# and `walk` is not a number. Do NOT put it through osm_ingest's+# `tags::parse_maxspeed`, which is the routing graph's parser and normalises to a+# u8 of km/h.+#+# TWO ENGINES. `--engine rust` (the default) is cargo-only: `osm_extract` reads the+# .osm.pbf directly and `tile_lines` tiles it, so this layer needs neither osmium,+# nor tippecanoe, nor python3, and runs on Windows. `--engine legacy` is the+# original `osmium | normalize_maxspeed.py | tippecanoe` chain, kept so the two can+# be diffed against each other with `test/diff_geojsonseq.py` and+# `test/diff_pmtiles.py`. # # Usage: #   ./build_maxspeed_layer.sh --pbf planet.osm.pbf --out maxspeed.pmtiles@@ -18,11 +31,15 @@ set -euo pipefail #   --pbf FILE     Input OSM .pbf (required) #   --out FILE     Output .pmtiles (default: maxspeed.pmtiles) #   --bbox BOX     Optional "minlon,minlat,maxlon,maxlat" metro extract (dry runs)-#   --minzoom N    tippecanoe minzoom (default 12 — where roads appear)-#   --maxzoom N    tippecanoe maxzoom (default 16)+#   --minzoom N    tiler minzoom (default 12)+#   --maxzoom N    tiler maxzoom (default 16)+#   --engine E     rust|legacy (default rust)+#   --geojson-out F  also keep the intermediate geojsonseq here (for the+#                    differential harness, which needs both engines' output) #   --keep-tmp     Don't delete intermediate files #-# Tools required: osmium (osmium-tool), tippecanoe, python3+# Tools required: cargo. `--engine legacy` additionally needs osmium, tippecanoe+# and python3; `--engine rust --bbox` needs none of them (the clip is inline).  HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PBF=""@@ -30,6 +47,8 @@ OUT="maxspeed.pmtiles" BBOX="" MINZOOM=12 MAXZOOM=16+ENGINE="rust"+GEOJSON_OUT="" KEEP_TMP=0  while [[ $# -gt 0 ]]; do@@ -39,50 +58,81 @@ while [[ $# -gt 0 ]]; do         --bbox) BBOX="$2"; shift 2 ;;         --minzoom) MINZOOM="$2"; shift 2 ;;         --maxzoom) MAXZOOM="$2"; shift 2 ;;+        --engine) ENGINE="$2"; shift 2 ;;+        --geojson-out) GEOJSON_OUT="$2"; shift 2 ;;         --keep-tmp) KEEP_TMP=1; shift ;;-        -h|--help) sed -n '4,30p' "$0" | sed 's/^# \?//'; exit 0 ;;+        -h|--help) sed -n '4,42p' "$0" | sed 's/^# \?//'; exit 0 ;;         *) echo "Unknown arg: $1" >&2; exit 1 ;;     esac done  [[ -n "$PBF" ]] || { echo "ERROR: --pbf required" >&2; exit 1; } [[ -f "$PBF" ]] || { echo "ERROR: pbf not found: $PBF" >&2; exit 1; }-command -v osmium     >/dev/null || { echo "ERROR: osmium-tool not installed" >&2; exit 1; }-command -v tippecanoe >/dev/null || { echo "ERROR: tippecanoe not installed" >&2; exit 1; }+case "$ENGINE" in+    rust|legacy) : ;;+    *) echo "ERROR: --engine must be rust|legacy (got '$ENGINE')" >&2; exit 1 ;;+esac+command -v cargo >/dev/null || { echo "ERROR: cargo not installed (https://rustup.rs)" >&2; exit 1; }+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; }+fi  TMP="$(mktemp -d)" cleanup() { [[ "$KEEP_TMP" == "1" ]] || rm -rf "$TMP"; } trap cleanup EXIT -SRC="$PBF"-if [[ -n "$BBOX" ]]; then-    echo "[maxspeed] extracting metro bbox $BBOX"-    osmium extract --overwrite -b "$BBOX" "$PBF" -o "$TMP/metro.osm.pbf"-    SRC="$TMP/metro.osm.pbf"-fi+GEOJSON="${GEOJSON_OUT:-$TMP/maxspeed.geojsonseq}"+[[ -z "$GEOJSON_OUT" ]] || mkdir -p "$(dirname "$GEOJSON_OUT")" -echo "[maxspeed] filtering ways with a maxspeed tag"-osmium tags-filter --overwrite "$SRC" \-    w/maxspeed w/maxspeed:forward w/maxspeed:backward \-    -o "$TMP/maxspeed_raw.osm.pbf"+if [[ "$ENGINE" == "rust" ]]; then+    echo "[maxspeed] extracting speed-limit ways -> $GEOJSON (osm_extract)"+    EXTRACT_ARGS=("$PBF" --layer maxspeed --out "$GEOJSON")+    [[ -n "$BBOX" ]] && EXTRACT_ARGS+=(--bbox "$BBOX")+    cargo run --release --quiet --manifest-path "$HERE/osm_ingest/Cargo.toml" \+        --bin osm_extract -- "${EXTRACT_ARGS[@]}"+else+    SRC="$PBF"+    if [[ -n "$BBOX" ]]; then+        echo "[maxspeed] extracting metro bbox $BBOX"+        osmium extract --overwrite -b "$BBOX" "$PBF" -o "$TMP/metro.osm.pbf"+        SRC="$TMP/metro.osm.pbf"+    fi -echo "[maxspeed] exporting to GeoJSON + normalizing"-osmium export -f geojsonseq --overwrite "$TMP/maxspeed_raw.osm.pbf" \-    | python3 "$HERE/normalize_maxspeed.py" \-    > "$TMP/maxspeed.geojsonseq"+    echo "[maxspeed] filtering ways with a posted limit"+    osmium tags-filter --overwrite "$SRC" \+        w/maxspeed w/maxspeed:forward w/maxspeed:backward \+        -o "$TMP/maxspeed_raw.osm.pbf" -FEATURES="$(wc -l < "$TMP/maxspeed.geojsonseq" | tr -d ' ')"-echo "[maxspeed] $FEATURES normalized feature(s)"+    echo "[maxspeed] exporting to GeoJSON + normalizing"+    osmium export -f geojsonseq --overwrite "$TMP/maxspeed_raw.osm.pbf" \+        | python3 "$HERE/normalize_maxspeed.py" \+        > "$GEOJSON"+fi++FEATURES="$(wc -l < "$GEOJSON" | tr -d ' ')"+echo "[maxspeed] $FEATURES feature(s)" [[ "$FEATURES" -gt 0 ]] || echo "[maxspeed] WARNING: 0 features — check bbox/extract" -echo "[maxspeed] tiling -> $OUT (z$MINZOOM-$MAXZOOM)"-tippecanoe --force \-    -o "$OUT" \-    -l maxspeed \-    --minimum-zoom="$MINZOOM" \-    --maximum-zoom="$MAXZOOM" \-    --drop-densest-as-needed \-    --extend-zooms-if-still-dropping \-    "$TMP/maxspeed.geojsonseq"+echo "[maxspeed] tiling -> $OUT (z$MINZOOM-$MAXZOOM, engine: $ENGINE)"+if [[ "$ENGINE" == "rust" ]]; then+    cargo run --release --quiet --manifest-path "$HERE/tile_build/Cargo.toml" \+        --bin tile_lines -- \+        --geojson "$GEOJSON" \+        --out "$OUT" \+        --layer maxspeed \+        --minzoom "$MINZOOM" \+        --maxzoom "$MAXZOOM"+else+    tippecanoe --force \+        -o "$OUT" \+        -l maxspeed \+        --minimum-zoom="$MINZOOM" \+        --maximum-zoom="$MAXZOOM" \+        --drop-densest-as-needed \+        --extend-zooms-if-still-dropping \+        "$GEOJSON"+fi  echo "[maxspeed] done: $OUT"
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 0bf583cbbd..922db9df36 100644--- a/scripts/maps/build_transit_lines_layer.sh+++ b/scripts/maps/build_transit_lines_layer.sh@@ -1,39 +1,58 @@ #!/bin/bash set -euo pipefail -# build_transit_lines_layer.sh — bake the `transit_lines` layer (OSM rail/transit)+# build_transit_lines_layer.sh — bake the `transit_lines` layer (P22) into a .pmtiles #-# Produces a line-geometry PMTiles layer of OSM transit lines so the app's-# transit-line highlight (P22) can render/highlight them via queryRenderedFeatures-# on v5.pmtiles — no runtime Overpass query.+# Extracts OSM rail/subway/tram/light_rail/monorail geometry and tiles it into a+# single-layer PMTiles file, so the app's transit-line highlight reads it from the+# basemap with no runtime Overpass query. #-# Source layer produced:  transit_lines-#   geometry : LineString / MultiLineString-#   attrs    : kind, name?, ref?, colour?, osm_id+# Source layer produced:  transit_lines  (attr: kind, name?, ref?, colour?, osm_id) #   kind ∈ { rail, subway, light_rail, tram, monorail, train } #-# Two OSM inputs are combined:-#   * railway WAYS       railway ∈ {rail,subway,light_rail,tram,monorail,narrow_gauge}-#                        (exported by osmium; kind derived from `railway`)-#   * route RELATIONS    route ∈ {subway,tram,light_rail,train,monorail}-#                        (assembled by ogr2ogr's OSM `multilinestrings` layer, which-#                        carries the relation `colour`; kind derived from `route`)-# ogr2ogr is optional: if it is missing the relation colour is skipped and the-# layer is built from railway ways only (a WARNING is printed).+# TWO SOURCES, and each can only produce some of the kinds. Railway WAYS give+# rail/subway/light_rail/tram/monorail (narrow_gauge folds into rail); route+# RELATIONS give subway/tram/light_rail/train/monorail. So `rail` is only reachable+# from a way and `train` only from a relation, and `route=bus` is in neither map --+# this layer is the rail-like modes the highlight styles. `railway` wins over+# `route`: a way carrying both is track, and the route is a service over it.+#+# TWO ENGINES. `--engine rust` (the default) is cargo-only: `osm_extract` reads+# ways AND relations straight out of the .osm.pbf and `tile_lines` tiles them.+# `--engine legacy` is the original chain, which needed osmium for the ways,+# GDAL's `ogr2ogr … multilinestrings` for the relations, and+# normalize_transit_lines.py to unpack the `other_tags` HSTORE that GDAL folded the+# relation's tags into. Reading relations directly makes all of that moot -- the+# GDAL dependency and the HSTORE parsing both disappear.+#+# ONE SCHEMA CHANGE. A relation's `osm_id` is now `relation/9001`; the GDAL path+# emitted a bare `9001` while ways came through as `way/5001`. That disagreement+# was an artefact of the toolchain, so the rust engine uses `<kind>/<id>`+# throughout. `test/diff_geojsonseq.py` will report it on relation features.+#+# Relation geometry is an unordered MultiLineString of the member ways, deliberately+# unstitched: branches, loops and split platforms mean a route's ways often do not+# form one continuous path, and the layer's contract allows the multi- form. # # Usage: #   ./build_transit_lines_layer.sh --pbf planet.osm.pbf --out transit_lines.pmtiles-#   ./build_transit_lines_layer.sh --pbf planet.osm.pbf --bbox -122.6,37.2,-121.7,37.9 --out transit_lines.pmtiles+#   ./build_transit_lines_layer.sh --pbf planet.osm.pbf --bbox -122.6,37.2,-121.7,37.9 \+#       --out transit_lines.pmtiles # # Options: #   --pbf FILE     Input OSM .pbf (required) #   --out FILE     Output .pmtiles (default: transit_lines.pmtiles) #   --bbox BOX     Optional "minlon,minlat,maxlon,maxlat" metro extract (dry runs)-#   --minzoom N    tippecanoe minzoom (default 9)-#   --maxzoom N    tippecanoe maxzoom (default 16)+#   --minzoom N    tiler minzoom (default 9)+#   --maxzoom N    tiler maxzoom (default 16)+#   --engine E     rust|legacy (default rust)+#   --geojson-out F  also keep the intermediate geojsonseq here (for the+#                    differential harness, which needs both engines' output) #   --keep-tmp     Don't delete intermediate files #-# Tools required: osmium (osmium-tool), tippecanoe, python3; ogr2ogr (GDAL) optional+# 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.  HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PBF=""@@ -41,6 +60,8 @@ OUT="transit_lines.pmtiles" BBOX="" MINZOOM=9 MAXZOOM=16+ENGINE="rust"+GEOJSON_OUT="" KEEP_TMP=0  while [[ $# -gt 0 ]]; do@@ -50,69 +71,97 @@ while [[ $# -gt 0 ]]; do         --bbox) BBOX="$2"; shift 2 ;;         --minzoom) MINZOOM="$2"; shift 2 ;;         --maxzoom) MAXZOOM="$2"; shift 2 ;;+        --engine) ENGINE="$2"; shift 2 ;;+        --geojson-out) GEOJSON_OUT="$2"; shift 2 ;;         --keep-tmp) KEEP_TMP=1; shift ;;-        -h|--help) sed -n '4,36p' "$0" | sed 's/^# \?//'; exit 0 ;;+        -h|--help) sed -n '4,55p' "$0" | sed 's/^# \?//'; exit 0 ;;         *) echo "Unknown arg: $1" >&2; exit 1 ;;     esac done  [[ -n "$PBF" ]] || { echo "ERROR: --pbf required" >&2; exit 1; } [[ -f "$PBF" ]] || { echo "ERROR: pbf not found: $PBF" >&2; exit 1; }-command -v osmium     >/dev/null || { echo "ERROR: osmium-tool not installed" >&2; exit 1; }-command -v tippecanoe >/dev/null || { echo "ERROR: tippecanoe not installed" >&2; exit 1; }+case "$ENGINE" in+    rust|legacy) : ;;+    *) echo "ERROR: --engine must be rust|legacy (got '$ENGINE')" >&2; exit 1 ;;+esac+command -v cargo >/dev/null || { echo "ERROR: cargo not installed (https://rustup.rs)" >&2; exit 1; }+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; }+fi  TMP="$(mktemp -d)" cleanup() { [[ "$KEEP_TMP" == "1" ]] || rm -rf "$TMP"; } trap cleanup EXIT -SRC="$PBF"-if [[ -n "$BBOX" ]]; then-    echo "[transit_lines] extracting metro bbox $BBOX"-    osmium extract --overwrite -b "$BBOX" "$PBF" -o "$TMP/metro.osm.pbf"-    SRC="$TMP/metro.osm.pbf"-fi+GEOJSON="${GEOJSON_OUT:-$TMP/transit_lines.geojsonseq}"+[[ -z "$GEOJSON_OUT" ]] || mkdir -p "$(dirname "$GEOJSON_OUT")"++if [[ "$ENGINE" == "rust" ]]; then+    echo "[transit_lines] extracting railway ways + route relations -> $GEOJSON (osm_extract)"+    # Three passes over the PBF in one process: relations decide which ways matter,+    # ways decide which node coordinates matter, nodes supply them.+    EXTRACT_ARGS=("$PBF" --layer transit_lines --out "$GEOJSON")+    [[ -n "$BBOX" ]] && EXTRACT_ARGS+=(--bbox "$BBOX")+    cargo run --release --quiet --manifest-path "$HERE/osm_ingest/Cargo.toml" \+        --bin osm_extract -- "${EXTRACT_ARGS[@]}"+else+    SRC="$PBF"+    if [[ -n "$BBOX" ]]; then+        echo "[transit_lines] extracting metro bbox $BBOX"+        osmium extract --overwrite -b "$BBOX" "$PBF" -o "$TMP/metro.osm.pbf"+        SRC="$TMP/metro.osm.pbf"+    fi -echo "[transit_lines] filtering railway ways + route relations"-# Keep the railway ways we bake AND route relations (with their referenced-# members so both way and relation geometries assemble).-osmium tags-filter --overwrite "$SRC" \-    w/railway=rail,subway,light_rail,tram,monorail,narrow_gauge \-    r/route=subway,tram,light_rail,train,monorail \-    -o "$TMP/transit_raw.osm.pbf"+    echo "[transit_lines] filtering railway ways + route relations"+    osmium tags-filter --overwrite "$SRC" \+        w/railway=rail,subway,light_rail,tram,monorail,narrow_gauge \+        r/route=subway,tram,light_rail,train,monorail \+        -o "$TMP/transit_raw.osm.pbf" -echo "[transit_lines] exporting railway ways (osmium)"-osmium export -f geojsonseq --overwrite "$TMP/transit_raw.osm.pbf" \-    > "$TMP/ways.geojsonseq"+    echo "[transit_lines] exporting ways to GeoJSON"+    osmium export -f geojsonseq --overwrite "$TMP/transit_raw.osm.pbf" > "$TMP/ways.geojsonseq" -# Route relations carry the line `colour`; osmium export does not emit linear-# relations as geometry, so use GDAL's OSM `multilinestrings` layer for those.-: > "$TMP/relations.geojsonseq"-if command -v ogr2ogr >/dev/null; then-    echo "[transit_lines] exporting route relations (ogr2ogr multilinestrings)"-    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"-else-    echo "[transit_lines] WARNING: ogr2ogr (GDAL) not found; route-relation colour omitted (railway ways only)"-fi+    # 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"+    else+        echo "[transit_lines] WARNING: ogr2ogr (GDAL) not found; route-relation colour omitted (railway ways only)"+    fi -echo "[transit_lines] normalizing kinds + colour"-cat "$TMP/ways.geojsonseq" "$TMP/relations.geojsonseq" \-    | python3 "$HERE/normalize_transit_lines.py" \-    > "$TMP/transit_lines.geojsonseq"+    echo "[transit_lines] normalizing kinds"+    cat "$TMP/ways.geojsonseq" "$TMP/relations.geojsonseq" \+        | python3 "$HERE/normalize_transit_lines.py" \+        > "$GEOJSON"+fi -FEATURES="$(wc -l < "$TMP/transit_lines.geojsonseq" | tr -d ' ')"-echo "[transit_lines] $FEATURES normalized feature(s)"+FEATURES="$(wc -l < "$GEOJSON" | tr -d ' ')"+echo "[transit_lines] $FEATURES feature(s)" [[ "$FEATURES" -gt 0 ]] || echo "[transit_lines] WARNING: 0 features — check bbox/extract" -echo "[transit_lines] tiling -> $OUT (z$MINZOOM-$MAXZOOM)"-tippecanoe --force \-    -o "$OUT" \-    -l transit_lines \-    --minimum-zoom="$MINZOOM" \-    --maximum-zoom="$MAXZOOM" \-    --drop-densest-as-needed \-    --extend-zooms-if-still-dropping \-    "$TMP/transit_lines.geojsonseq"+echo "[transit_lines] tiling -> $OUT (z$MINZOOM-$MAXZOOM, engine: $ENGINE)"+if [[ "$ENGINE" == "rust" ]]; then+    cargo run --release --quiet --manifest-path "$HERE/tile_build/Cargo.toml" \+        --bin tile_lines -- \+        --geojson "$GEOJSON" \+        --out "$OUT" \+        --layer transit_lines \+        --minzoom "$MINZOOM" \+        --maxzoom "$MAXZOOM"+else+    tippecanoe --force \+        -o "$OUT" \+        -l transit_lines \+        --minimum-zoom="$MINZOOM" \+        --maximum-zoom="$MAXZOOM" \+        --drop-densest-as-needed \+        --extend-zooms-if-still-dropping \+        "$GEOJSON"+fi  echo "[transit_lines] done: $OUT"
scripts/maps/build_v5_pmtiles.sh
diff --git a/scripts/maps/build_v5_pmtiles.sh b/scripts/maps/build_v5_pmtiles.shindex 14320b063d..dc4fee491c 100644--- a/scripts/maps/build_v5_pmtiles.sh+++ b/scripts/maps/build_v5_pmtiles.sh@@ -59,11 +59,11 @@ set -euo pipefail #   --extra-layer F   fold an already-built .pmtiles into the final merge #                     (repeatable). Lets a caller that built a layer itself skip #                     the matching step here instead of building it twice.-#   --engine-base E       rust|legacy per-layer engine. `safety` defaults to rust-#   --engine-safety E     (cargo-only); the rest default to legacy, and asking for-#   --engine-maxspeed E   rust before a layer is ported is an error rather than a-#   --engine-transit-lines E  silent no-op, so a rollback is always one flag.-#   --engine-admin E+#   --engine-base E       rust|legacy per-layer engine. `safety`, `maxspeed` and+#   --engine-safety E     `transit_lines` default to rust (cargo-only); the rest+#   --engine-maxspeed E   default to legacy, and asking for rust before a layer is+#   --engine-transit-lines E  ported is an error rather than a silent no-op, so a+#   --engine-admin E          rollback is always one flag. #   --dry-run         print each step's command instead of running it #   --skip-base       don't (re)build base; expects <workdir>/base.pmtiles present #   --skip-safety     omit safety layer@@ -94,8 +94,8 @@ BASE_SOURCE="" EXTRA_LAYERS=() ENGINE_BASE="legacy" ENGINE_SAFETY="rust"-ENGINE_MAXSPEED="legacy"-ENGINE_TRANSIT_LINES="legacy"+ENGINE_MAXSPEED="rust"+ENGINE_TRANSIT_LINES="rust" ENGINE_ADMIN="legacy" DRY_RUN=0 SKIP_BASE=0@@ -159,8 +159,8 @@ engine_check() { } engine_check base          "$ENGINE_BASE"          0 engine_check safety        "$ENGINE_SAFETY"        1-engine_check maxspeed      "$ENGINE_MAXSPEED"      0-engine_check transit-lines "$ENGINE_TRANSIT_LINES" 0+engine_check maxspeed      "$ENGINE_MAXSPEED"      1+engine_check transit-lines "$ENGINE_TRANSIT_LINES" 1 engine_check admin         "$ENGINE_ADMIN"         0  run() {@@ -209,7 +209,7 @@ fi # --- 3. maxspeed --- if [[ "$SKIP_MAXSPEED" == "0" ]]; then     [[ -n "$PBF" ]] || { echo "ERROR: --pbf required for maxspeed layer (or --skip-maxspeed)" >&2; exit 1; }-    MS_ARGS=(--pbf "$PBF" --out "$WORK/maxspeed.pmtiles")+    MS_ARGS=(--pbf "$PBF" --out "$WORK/maxspeed.pmtiles" --engine "$ENGINE_MAXSPEED")     [[ -n "$BBOX" ]] && MS_ARGS+=(--bbox "$BBOX")     run "$HERE/build_maxspeed_layer.sh" "${MS_ARGS[@]}"     INPUTS+=("$WORK/maxspeed.pmtiles")@@ -218,7 +218,7 @@ fi # --- 4. transit_lines --- if [[ "$SKIP_TRANSIT_LINES" == "0" ]]; then     [[ -n "$PBF" ]] || { echo "ERROR: --pbf required for transit_lines layer (or --skip-transit-lines)" >&2; exit 1; }-    TL_ARGS=(--pbf "$PBF" --out "$WORK/transit_lines.pmtiles")+    TL_ARGS=(--pbf "$PBF" --out "$WORK/transit_lines.pmtiles" --engine "$ENGINE_TRANSIT_LINES")     [[ -n "$BBOX" ]] && TL_ARGS+=(--bbox "$BBOX")     run "$HERE/build_transit_lines_layer.sh" "${TL_ARGS[@]}"     INPUTS+=("$WORK/transit_lines.pmtiles")
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 ae543ca35a..20c580f947 100644--- a/scripts/maps/osm_ingest/src/extract.rs+++ b/scripts/maps/osm_ingest/src/extract.rs@@ -30,27 +30,34 @@ //! on California. The sorted-`Vec` form costs 16 bytes per *needed* node, which //! for a selected subset is orders of magnitude smaller. +use std::collections::HashMap; use std::fs::File; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf};  use crate::bbox::{self, BBox};-use crate::geojson::{self, Feature};-use crate::osm::{visit_block, Element};-use crate::pbf::{self, KIND_NODES};+use crate::geojson::{self, Coord, Feature, Geometry};+use crate::maxspeed::{self, MaxspeedTags};+use crate::osm::{visit_block, Element, Member, MEMBER_WAY};+use crate::pbf::{self, KIND_NODES, KIND_RELATIONS, KIND_WAYS}; use crate::proto::{Error, Result}; use crate::safety::{self, Kind, SafetyTags}; use crate::select::Select;+use crate::transit_lines::{self, TransitTags};  #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Layer {     Safety,+    Maxspeed,+    TransitLines, }  impl Layer {     pub fn parse(s: &str) -> std::result::Result<Layer, String> {         match s {             "safety" => Ok(Layer::Safety),+            "maxspeed" => Ok(Layer::Maxspeed),+            "transit_lines" => Ok(Layer::TransitLines),             other => Err(format!(                 "unknown --layer '{other}'; supported: {}",                 Layer::names().join(", ")@@ -59,12 +66,14 @@ impl Layer {     }      pub fn names() -> Vec<&'static str> {-        vec!["safety"]+        vec!["safety", "maxspeed", "transit_lines"]     }      pub fn name(self) -> &'static str {         match self {             Layer::Safety => "safety",+            Layer::Maxspeed => "maxspeed",+            Layer::TransitLines => "transit_lines",         }     } }@@ -97,9 +106,110 @@ pub fn build(input: &Path, out: &Path, opts: &Options) -> Result<Stats> {      match opts.layer {         Layer::Safety => build_safety(input, &blobs, out, opts),+        Layer::Maxspeed => build_maxspeed(input, &blobs, out, opts),+        Layer::TransitLines => build_transit_lines(input, &blobs, out, opts),     } } +// --- the node coordinate table --------------------------------------------++/// Sentinel latitude for "this node's location was never seen".+const NO_LOC: i32 = i32::MIN;++/// Coordinates for a known set of node ids: a sorted id table plus an+/// index-aligned coordinate array, looked up by `binary_search`.+///+/// **This, and not [`crate::graph_build`]'s bitset.** That module allocates+/// `BITSET_SIZE = 20e9` bits -- 2.5 GB keyed by raw OSM node id, whatever the+/// extract -- and peaks around 10 GB on California. This form costs 16 bytes per+/// *needed* node, so a layer that wants a few hundred thousand nodes pays a few+/// megabytes. Same pattern as [`crate::poi_build`], which worked it out first.+pub struct NodeLocations {+    ids: Vec<i64>,+    locs: Vec<(i32, i32)>,+}++impl NodeLocations {+    /// `ids` need not be sorted or unique; both are done here.+    pub fn new(mut ids: Vec<i64>) -> NodeLocations {+        ids.sort_unstable();+        ids.dedup();+        let locs = vec![(NO_LOC, NO_LOC); ids.len()];+        NodeLocations { ids, locs }+    }++    pub fn len(&self) -> usize {+        self.ids.len()+    }++    pub fn is_empty(&self) -> bool {+        self.ids.is_empty()+    }++    fn index_of(&self, id: i64) -> Option<u32> {+        self.ids.binary_search(&id).ok().map(|i| i as u32)+    }++    pub fn get(&self, id: i64) -> Option<(i32, i32)> {+        let (lat, lon) = self.locs[self.index_of(id)? as usize];+        (lat != NO_LOC).then_some((lat, lon))+    }++    /// A way's geometry in lon/lat order, with unresolved refs skipped.+    ///+    /// A ref can be unresolved for a legitimate reason: an extract cut through the+    /// way, so some of its nodes are simply not in the file. Skipping the gap keeps+    /// the rest of the line rather than discarding the whole way, which is what+    /// `osmium extract`'s `complete_ways` produces for the same input.+    pub fn line(&self, refs: &[i64]) -> Vec<Coord> {+        refs.iter()+            .filter_map(|id| self.get(*id))+            .map(|(lat_e7, lon_e7)| (lon_e7 as f64 * 1e-7, lat_e7 as f64 * 1e-7))+            .collect()+    }+}++/// The node pass: fill in every coordinate the earlier passes asked for.+fn resolve_nodes(+    input: &Path,+    blobs: &[pbf::BlobLoc],+    blob_kinds: &[u8],+    label: &str,+    mut table: NodeLocations,+) -> Result<NodeLocations> {+    if table.is_empty() {+        return Ok(table);+    }+    let ids = std::mem::take(&mut table.ids);+    let (chunks, _) = pbf::run_pass(+        input,+        blobs,+        Some(blob_kinds),+        KIND_NODES,+        label,+        Vec::<(u32, i32, i32)>::new,+        |state: &mut Vec<(u32, i32, i32)>, block| {+            let mut kinds = 0u8;+            visit_block(block, KIND_NODES, &mut kinds, &mut |el: Element| {+                if let Element::Node(n) = el {+                    if let Ok(idx) = ids.binary_search(&n.id) {+                        state.push((idx as u32, n.lat_e7, n.lon_e7));+                    }+                }+                Ok(())+            })?;+            Ok(kinds)+        },+    )?;+    table.ids = ids;+    for chunk in chunks {+        for (idx, lat, lon) in chunk {+            table.locs[idx as usize] = (lat, lon);+        }+    }+    Ok(table)+}+ // --- safety ---------------------------------------------------------------  /// One classified node, with the attributes it carries copied out of the block.@@ -252,6 +362,417 @@ fn safety_blob(     Ok(kinds) } +// --- maxspeed -------------------------------------------------------------++/// One way with a posted limit, with its tag values copied out of the block.+struct MaxspeedRow {+    id: i64,+    refs: Vec<i64>,+    maxspeed: String,+    highway: Option<String>,+    name: Option<String>,+}++fn build_maxspeed(+    input: &Path,+    blobs: &[pbf::BlobLoc],+    out: &Path,+    opts: &Options,+) -> Result<Stats> {+    let select = Select::parse(&maxspeed::FILTERS)?;++    // Pass 1 runs with `blob_kinds = None`, which is what makes run_pass build the+    // per-blob kind mask the node pass then uses to skip node-only blobs.+    let (chunks, blob_kinds) = pbf::run_pass(+        input,+        blobs,+        None,+        KIND_WAYS,+        "Pass 1: ways",+        Vec::<MaxspeedRow>::new,+        |state: &mut Vec<MaxspeedRow>, block| maxspeed_blob(state, block, &select),+    )?;+    let mut rows: Vec<MaxspeedRow> = Vec::new();+    for chunk in chunks {+        rows.extend(chunk);+    }+    println!("{} way(s) with a posted limit", rows.len());++    let table = NodeLocations::new(rows.iter().flat_map(|r| r.refs.iter().copied()).collect());+    println!("{} node location(s) needed", table.len());+    let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 2: nodes", table)?;++    let mut lines: Vec<LineFeature> = Vec::with_capacity(rows.len());+    let mut outside_bbox = 0usize;+    for row in &rows {+        let coords = table.line(&row.refs);+        if coords.len() < 2 {+            continue;+        }+        if !parts_touch_bbox(std::slice::from_ref(&coords), opts.bbox.as_ref()) {+            outside_bbox += 1;+            continue;+        }+        let t = MaxspeedTags {+            maxspeed: Some(row.maxspeed.as_str()),+            highway: row.highway.as_deref(),+            name: row.name.as_deref(),+            ..Default::default()+        };+        let f = maxspeed::feature(&row.maxspeed, &t, Geometry::LineString(coords), row.id);+        lines.push(LineFeature { sort: ("way", row.id), rendered: render(&f) });+    }++    let written = write_lines(out, lines)?;+    println!("Wrote {} maxspeed feature(s) to {}", written, out.display());+    if outside_bbox > 0 {+        println!("{outside_bbox} feature(s) dropped by --bbox");+    }+    Ok(Stats {+        features: written,+        from_nodes: 0,+        from_ways: written,+        from_relations: 0,+        outside_bbox,+    })+}++fn maxspeed_blob(+    state: &mut Vec<MaxspeedRow>,+    block: &pbf::PrimitiveBlock,+    select: &Select,+) -> Result<u8> {+    let mut kinds = 0u8;+    visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {+        if let Element::Way(w) = el {+            if w.refs.len() < 2 || w.tags.is_empty() {+                return Ok(());+            }+            if !select.matches(|k| w.tags.get_str(k)) {+                return Ok(());+            }+            let t = MaxspeedTags {+                maxspeed: w.tags.get_str("maxspeed"),+                maxspeed_forward: w.tags.get_str("maxspeed:forward"),+                maxspeed_backward: w.tags.get_str("maxspeed:backward"),+                highway: w.tags.get_str("highway"),+                name: w.tags.get_str("name"),+            };+            if let Some(value) = maxspeed::extract(&t) {+                state.push(MaxspeedRow {+                    id: w.id,+                    refs: w.refs.to_vec(),+                    maxspeed: value.to_string(),+                    highway: t.highway.map(str::to_string),+                    name: t.name.map(str::to_string),+                });+            }+        }+        Ok(())+    })?;+    Ok(kinds)+}++// --- transit_lines --------------------------------------------------------++/// One classified way or relation, with its tag values copied out of the block.+struct TransitRow {+    /// `"way"` or `"relation"`, for the `osm_id` and for the sort.+    element: &'static str,+    id: i64,+    kind: &'static str,+    name: Option<String>,+    reference: Option<String>,+    colour: Option<String>,+    /// A way has one part. A relation has one per member way, in member order.+    /// Empty until the way pass fills a relation's in.+    parts: Vec<Vec<i64>>,+    /// A relation's member way ids, in member order.+    member_ways: Vec<i64>,+}++#[derive(Default)]+struct TransitWayPass {+    rows: Vec<TransitRow>,+    /// `(way id, its refs)` for ways a relation claimed. A per-chunk assoc list+    /// rather than a map: cheap to push, and the merge is single-threaded anyway.+    wanted: Vec<(i64, Vec<i64>)>,+}++fn build_transit_lines(+    input: &Path,+    blobs: &[pbf::BlobLoc],+    out: &Path,+    opts: &Options,+) -> Result<Stats> {+    let way_select = Select::parse(&transit_lines::WAY_FILTERS)?;+    let rel_select = Select::parse(&transit_lines::RELATION_FILTERS)?;++    // Pass 1: relations, which decide which ways matter.+    let (chunks, blob_kinds) = pbf::run_pass(+        input,+        blobs,+        None,+        KIND_RELATIONS,+        "Pass 1: relations",+        Vec::<TransitRow>::new,+        |state: &mut Vec<TransitRow>, block| transit_relation_blob(state, block, &rel_select),+    )?;+    let mut rel_rows: Vec<TransitRow> = Vec::new();+    for chunk in chunks {+        rel_rows.extend(chunk);+    }+    let mut wanted_ways: Vec<i64> = rel_rows+        .iter()+        .flat_map(|r| r.member_ways.iter().copied())+        .collect();+    wanted_ways.sort_unstable();+    wanted_ways.dedup();+    println!(+        "{} route relation(s), {} member way(s)",+        rel_rows.len(),+        wanted_ways.len()+    );++    // Pass 2: ways, which are both features in their own right and the geometry+    // the relations need.+    let (chunks, _) = pbf::run_pass(+        input,+        blobs,+        Some(&blob_kinds),+        KIND_WAYS,+        "Pass 2: ways",+        TransitWayPass::default,+        |state, block| transit_way_blob(state, block, &way_select, &wanted_ways),+    )?;+    let mut way_rows: Vec<TransitRow> = Vec::new();+    let mut member_refs: HashMap<i64, Vec<i64>> = HashMap::new();+    for chunk in chunks {+        way_rows.extend(chunk.rows);+        member_refs.extend(chunk.wanted);+    }+    println!("{} railway way(s)", way_rows.len());++    // A relation's parts, in member order. Members whose way is missing from the+    // extract are simply absent, which is the same thing GDAL produced.+    for row in &mut rel_rows {+        row.parts = row+            .member_ways+            .iter()+            .filter_map(|w| member_refs.get(w).cloned())+            .collect();+    }++    // Pass 3: node coordinates for everything both earlier passes collected.+    let table = NodeLocations::new(+        way_rows+            .iter()+            .chain(rel_rows.iter())+            .flat_map(|r| r.parts.iter().flat_map(|p| p.iter().copied()))+            .collect(),+    );+    println!("{} node location(s) needed", table.len());+    let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 3: nodes", table)?;++    let mut lines: Vec<LineFeature> = Vec::new();+    let mut outside_bbox = 0usize;+    let mut from_ways = 0usize;+    let mut from_relations = 0usize;+    for row in way_rows.iter().chain(rel_rows.iter()) {+        let parts: Vec<Vec<Coord>> = row+            .parts+            .iter()+            .map(|refs| table.line(refs))+            .filter(|p| p.len() >= 2)+            .collect();+        if parts.is_empty() {+            continue;+        }+        if !parts_touch_bbox(&parts, opts.bbox.as_ref()) {+            outside_bbox += 1;+            continue;+        }+        // A way is one line; a relation is a MultiLineString of its member ways,+        // deliberately unstitched. See the module docs in `transit_lines`.+        let geometry = if row.element == "way" {+            Geometry::LineString(parts.into_iter().next().expect("non-empty"))+        } else {+            Geometry::MultiLineString(parts)+        };+        let t = TransitTags {+            name: row.name.as_deref(),+            reference: row.reference.as_deref(),+            colour: row.colour.as_deref(),+            ..Default::default()+        };+        let f = transit_lines::feature(row.kind, &t, geometry, row.element, row.id);+        lines.push(LineFeature {+            sort: (row.element, row.id),+            rendered: render(&f),+        });+        if row.element == "way" {+            from_ways += 1;+        } else {+            from_relations += 1;+        }+    }++    let written = write_lines(out, lines)?;+    println!(+        "Wrote {written} transit_lines feature(s) to {} ({from_ways} way, {from_relations} relation)",+        out.display()+    );+    if outside_bbox > 0 {+        println!("{outside_bbox} feature(s) dropped by --bbox");+    }+    Ok(Stats {+        features: written,+        from_nodes: 0,+        from_ways,+        from_relations,+        outside_bbox,+    })+}++fn transit_relation_blob(+    state: &mut Vec<TransitRow>,+    block: &pbf::PrimitiveBlock,+    select: &Select,+) -> Result<u8> {+    let mut kinds = 0u8;+    visit_block(block, KIND_RELATIONS, &mut kinds, &mut |el: Element| {+        if let Element::Relation(r) = el {+            if !select.matches(|k| r.tags.get_str(k)) {+                return Ok(());+            }+            let t = TransitTags {+                railway: r.tags.get_str("railway"),+                type_: r.tags.get_str("type"),+                route: r.tags.get_str("route"),+                name: r.tags.get_str("name"),+                reference: r.tags.get_str("ref"),+                colour: r.tags.get_str("colour"),+                color: r.tags.get_str("color"),+            };+            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.+            let member_ways: Vec<i64> = r+                .members+                .iter()+                .filter(|m: &&Member| m.kind == MEMBER_WAY)+                .map(|m| m.id)+                .collect();+            if member_ways.is_empty() {+                return Ok(());+            }+            state.push(TransitRow {+                element: "relation",+                id: r.id,+                kind,+                name: t.name.map(str::to_string),+                reference: t.reference.map(str::to_string),+                colour: transit_lines::colour(&t).map(str::to_string),+                parts: Vec::new(),+                member_ways,+            });+        }+        Ok(())+    })?;+    Ok(kinds)+}++fn transit_way_blob(+    state: &mut TransitWayPass,+    block: &pbf::PrimitiveBlock,+    select: &Select,+    wanted: &[i64],+) -> Result<u8> {+    let mut kinds = 0u8;+    visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {+        if let Element::Way(w) = el {+            if w.refs.len() < 2 {+                return Ok(());+            }+            if wanted.binary_search(&w.id).is_ok() {+                state.wanted.push((w.id, w.refs.to_vec()));+            }+            if w.tags.is_empty() || !select.matches(|k| w.tags.get_str(k)) {+                return Ok(());+            }+            let t = TransitTags {+                railway: w.tags.get_str("railway"),+                type_: w.tags.get_str("type"),+                route: w.tags.get_str("route"),+                name: w.tags.get_str("name"),+                reference: w.tags.get_str("ref"),+                colour: w.tags.get_str("colour"),+                color: w.tags.get_str("color"),+            };+            if let Some(kind) = transit_lines::classify(&t) {+                state.rows.push(TransitRow {+                    element: "way",+                    id: w.id,+                    kind,+                    name: t.name.map(str::to_string),+                    reference: t.reference.map(str::to_string),+                    colour: transit_lines::colour(&t).map(str::to_string),+                    parts: vec![w.refs.to_vec()],+                    member_ways: Vec::new(),+                });+            }+        }+        Ok(())+    })?;+    Ok(kinds)+}++// --- shared output --------------------------------------------------------++/// A rendered feature plus the key it sorts on.+///+/// Rendering before the sort means the sort moves one `Vec<u8>` per feature rather+/// than a geometry, and the writer then has nothing left to decide.+struct LineFeature {+    sort: (&'static str, i64),+    rendered: Vec<u8>,+}++fn render(f: &Feature) -> Vec<u8> {+    let mut line = Vec::new();+    geojson::render_feature(f, &mut line);+    line+}++/// `true` when there is no bbox, or any vertex of any part is inside it.+///+/// Whole-element, matching `osmium extract`'s default `complete_ways` strategy: a+/// way with one node in the box is kept entire, overspill included. Truncating it+/// at the boundary would invent a vertex that is not in OSM, and the tiler clips+/// properly per tile later anyway.+fn parts_touch_bbox(parts: &[Vec<Coord>], bbox: Option<&BBox>) -> bool {+    let Some(b) = bbox else { return true };+    parts+        .iter()+        .flatten()+        .any(|(lon, lat)| b.contains(*lon, *lat))+}++/// Sort by `(element kind, id)` and write. Deterministic, so two runs of the same+/// input are byte-identical and a diff against the previous build shows only real+/// changes.+fn write_lines(out: &Path, mut lines: Vec<LineFeature>) -> Result<usize> {+    lines.sort_by_key(|l| l.sort);+    let mut writer = BufWriter::new(create(out)?);+    for l in &lines {+        writer.write_all(&l.rendered).map_err(io_err)?;+    }+    writer.flush().map_err(io_err)?;+    Ok(lines.len())+}+ fn create(path: &Path) -> Result<File> {     File::create(path).map_err(|e| Error(format!("cannot write {}: {e}", path.display()))) }@@ -421,6 +942,160 @@ mod tests {         assert_eq!(stats.outside_bbox, 0);     } +    // --- maxspeed ---------------------------------------------------------++    fn extract_layer(tag: &str, layer: Layer) -> (Vec<String>, Stats) {+        let (pbf_path, dir) = testpbf::write_layers_sample(tag);+        let out = dir.join(format!("{}.geojsonseq", layer.name()));+        let stats = build(&pbf_path, &out, &Options { layer, bbox: None }).unwrap();+        (features(&out), stats)+    }++    #[test]+    fn extracts_the_maxspeed_layer_with_its_raw_values() {+        let (lines, stats) = extract_layer("extract_maxspeed", Layer::Maxspeed);+        // Two of the fixture's three highway ways carry a limit; the third does not.+        assert_eq!((stats.features, stats.from_ways), (2, 2));+        assert_eq!(stats.from_nodes, 0);+        assert_eq!(lines.len(), 2);++        // The whole point of the layer: the string survives verbatim.+        let mph = lines.iter().find(|l| l.contains("way/3001")).unwrap();+        assert!(mph.contains("\"maxspeed\":\"25 mph\""), "{mph}");+        assert!(mph.contains("\"highway\":\"residential\""), "{mph}");+        assert!(mph.contains("\"name\":\"Main St\""), "{mph}");+        assert!(mph.contains("\"type\":\"LineString\""), "{mph}");++        // maxspeed=none is kept as "none", and beats the directional tag.+        let none = lines.iter().find(|l| l.contains("way/3002")).unwrap();+        assert!(none.contains("\"maxspeed\":\"none\""), "{none}");+        assert!(!none.contains("30 mph"), "the direction-agnostic tag wins: {none}");++        // The way with no limit is absent.+        assert!(!lines.iter().any(|l| l.contains("way/3003")));++        // Geometry came from resolved node coordinates, not from nowhere.+        assert!(mph.contains("-122.43"), "{mph}");+    }++    // --- transit_lines ----------------------------------------------------++    #[test]+    fn extracts_the_transit_lines_layer_from_ways_and_relations() {+        let (lines, stats) = extract_layer("extract_transit", Layer::TransitLines);+        // Two railway ways plus one route relation. The platform way and the bus+        // route are both dropped.+        assert_eq!(stats.features, 3);+        assert_eq!((stats.from_ways, stats.from_relations), (2, 1));+        assert_eq!(lines.len(), 3);++        let subway = lines.iter().find(|l| l.contains("way/5001")).unwrap();+        assert!(subway.contains("\"kind\":\"subway\""), "{subway}");+        assert!(subway.contains("\"name\":\"Market St Subway\""), "{subway}");+        assert!(subway.contains("\"type\":\"LineString\""), "{subway}");++        // narrow_gauge folds into rail.+        let ng = lines.iter().find(|l| l.contains("way/5002")).unwrap();+        assert!(ng.contains("\"kind\":\"rail\""), "{ng}");++        assert!(!lines.iter().any(|l| l.contains("way/5003")), "no platform");+        assert!(!lines.iter().any(|l| l.contains("relation/9002")), "no bus route");+    }++    #[test]+    fn a_route_relation_becomes_an_unstitched_multilinestring() {+        let (lines, _) = extract_layer("extract_transit_rel", Layer::TransitLines);+        let route = lines.iter().find(|l| l.contains("relation/9001")).unwrap();+        assert!(route.contains("\"type\":\"MultiLineString\""), "{route}");+        assert!(route.contains("\"kind\":\"subway\""), "{route}");+        // The tags GDAL used to bury in an `other_tags` HSTORE are now just tags.+        assert!(route.contains("\"name\":\"Red Line\""), "{route}");+        assert!(route.contains("\"ref\":\"Red\""), "{route}");+        assert!(route.contains("\"colour\":\"#DA291C\""), "{route}");++        // Two member ways, so two parts: `[[[...]],[[...]]]` is three opening+        // brackets before the first coordinate pair.+        let at = route.find("\"coordinates\":").unwrap();+        assert!(route[at..].starts_with("\"coordinates\":[[["), "{route}");+        // Counting the part separators: two parts means one `]],[[`.+        assert_eq!(route.matches("]],[[").count(), 1, "two parts: {route}");+    }++    #[test]+    fn the_line_layers_are_deterministic_and_bbox_filtered() {+        for layer in [Layer::Maxspeed, Layer::TransitLines] {+            let (pbf_path, dir) = testpbf::write_layers_sample(&format!("det_{}", layer.name()));+            let run = |suffix: &str| {+                let out = dir.join(format!("{}{suffix}.geojsonseq", layer.name()));+                build(&pbf_path, &out, &Options { layer, bbox: None }).unwrap();+                std::fs::read(out).unwrap()+            };+            assert_eq!(run("a"), run("b"), "{} is not deterministic", layer.name());++            // The fixture's ways sit near 37.79N 122.42W; this box is Atlantic.+            let out = dir.join("empty.geojsonseq");+            let stats = build(+                &pbf_path,+                &out,+                &Options {+                    layer,+                    bbox: Some(BBox::parse("-30,20,-20,30").unwrap()),+                },+            )+            .unwrap();+            assert_eq!(stats.features, 0, "{}", layer.name());+            assert!(stats.outside_bbox > 0, "{}", layer.name());++            // And a box that contains them changes nothing.+            let out = dir.join("all.geojsonseq");+            let all = build(+                &pbf_path,+                &out,+                &Options {+                    layer,+                    bbox: Some(BBox::parse("-123,36,-121,38").unwrap()),+                },+            )+            .unwrap();+            assert_eq!(all.outside_bbox, 0, "{}", layer.name());+            assert!(all.features > 0, "{}", layer.name());+        }+    }++    // --- the coordinate table ---------------------------------------------++    #[test]+    fn node_locations_are_keyed_by_a_sorted_table_not_by_raw_node_id() {+        // The point of the pattern: memory is O(needed), so ids can be as large as+        // OSM's real ones without allocating anything proportional to them.+        let huge = 12_345_678_901i64;+        let mut table = NodeLocations::new(vec![huge, 5, 5, 1]);+        assert_eq!(table.len(), 3, "sorted and deduped");+        assert_eq!(table.get(5), None, "unresolved until the node pass fills it");+        // Fill by index, as the merge does.+        let idx = table.index_of(5).unwrap() as usize;+        table.locs[idx] = (377_900_000, -1_224_200_000);+        assert_eq!(table.get(5), Some((377_900_000, -1_224_200_000)));+        assert_eq!(table.get(huge), None);+        assert_eq!(table.get(999), None, "not in the table at all");+    }++    #[test]+    fn an_unresolved_ref_leaves_a_gap_rather_than_dropping_the_way() {+        // An extract that cuts through a way leaves some of its nodes out of the+        // file. Keeping the rest is what osmium's complete_ways produces too.+        let mut table = NodeLocations::new(vec![1, 2, 3]);+        for (id, lat, lon) in [(1i64, 370_000_000, -1_220_000_000), (3, 370_020_000, -1_220_020_000)] {+            let idx = table.index_of(id).unwrap() as usize;+            table.locs[idx] = (lat, lon);+        }+        let line = table.line(&[1, 2, 3]);+        assert_eq!(line.len(), 2, "the middle vertex is missing, not the way");+        // lon/lat order, as GeoJSON wants.+        assert!((line[0].0 - -122.0).abs() < 1e-9);+        assert!((line[0].1 - 37.0).abs() < 1e-9);+    }+     #[test]     fn args_need_a_layer_and_an_out() {         let ok = parse_args(&[
scripts/maps/osm_ingest/src/lib.rs
diff --git a/scripts/maps/osm_ingest/src/lib.rs b/scripts/maps/osm_ingest/src/lib.rsindex 14aa5512d3..291fb10baa 100644--- a/scripts/maps/osm_ingest/src/lib.rs+++ b/scripts/maps/osm_ingest/src/lib.rs@@ -20,6 +20,7 @@ pub mod bbox; pub mod extract; pub mod geojson; pub mod graph_build;+pub mod maxspeed; pub mod names; pub mod osm; pub mod par;@@ -30,6 +31,7 @@ pub mod safety; pub mod select; pub mod spatial; pub mod tags;+pub mod transit_lines;  #[cfg(test)] mod testpbf;
scripts/maps/osm_ingest/src/maxspeed.rs
diff --git a/scripts/maps/osm_ingest/src/maxspeed.rs b/scripts/maps/osm_ingest/src/maxspeed.rsnew file mode 100644index 0000000000..b863632ad4--- /dev/null+++ b/scripts/maps/osm_ingest/src/maxspeed.rs@@ -0,0 +1,211 @@+//! The `maxspeed` layer: posted speed limits, for the app's `MaxspeedSource`.+//!+//! A port of `normalize_maxspeed.py`, which is the contract of record.+//!+//! ## The value is a RAW STRING and must stay one+//!+//! The emitted `maxspeed` property is the OSM tag verbatim: `"25 mph"`,+//! `"100 km/h"`, `"50"`, `"none"`, `"walk"`, `"signals"`. The app parses it itself,+//! in `OsmMaxspeed.kt::parseMaxspeed`, because the distinctions matter to it --+//! `none` on an autobahn is not the same as an absent limit, and `walk` is not a+//! number at all.+//!+//! **Do not route this through [`crate::tags::parse_maxspeed`].** That function+//! exists for the routing graph, where a speed has to become a `u8` of km/h to go+//! in an edge record, so it normalises units and collapses everything+//! non-numeric to `0`. Sending the layer through it would turn `"25 mph"` into+//! `40`, `"none"` into `0`, and `"walk"` into `0` -- three different facts about a+//! road becoming the same one, with nothing in the pipeline to notice.+//!+//! ## Tag precedence+//!+//! First non-empty of `maxspeed`, `maxspeed:forward`, `maxspeed:backward`. The+//! direction-agnostic tag wins; the directional ones are a fallback, and the layer+//! does not record which one it used. That is a known simplification -- a road with+//! different limits each way is rendered with one of them -- and it is what the+//! Python did.++use crate::geojson::{osm_ref, Feature, Geometry, Value};++/// The keys `osmium tags-filter` narrowed on for this layer.+pub const FILTERS: [&str; 3] = ["maxspeed", "maxspeed:forward", "maxspeed:backward"];++#[derive(Debug, Default, Clone, Copy)]+pub struct MaxspeedTags<'a> {+    pub maxspeed: Option<&'a str>,+    pub maxspeed_forward: Option<&'a str>,+    pub maxspeed_backward: Option<&'a str>,+    pub highway: Option<&'a str>,+    pub name: Option<&'a str>,+}++/// The raw tag value to emit, or `None` when the way has no usable limit.+pub fn extract<'a>(t: &MaxspeedTags<'a>) -> Option<&'a str> {+    [t.maxspeed, t.maxspeed_forward, t.maxspeed_backward]+        .into_iter()+        .flatten()+        .find(|v| !v.is_empty())+}++/// Build the emitted feature. Property order matches the Python's insertion order:+/// `maxspeed`, then `highway`, then `name`, then `osm_id`.+///+/// `highway` and `name` are kept on plain emptiness, **not** on the `_truthy` test+/// the safety layer uses: `normalize_maxspeed.py` has no `_truthy` at all, so+/// `highway=no` survives here where `direction=no` would not survive there. An+/// inconsistency in the original, reproduced deliberately rather than tidied, since+/// tidying it would change what the layer contains.+pub fn feature<'a>(+    maxspeed: &'a str,+    t: &MaxspeedTags<'a>,+    geometry: Geometry,+    way_id: i64,+) -> Feature<'a> {+    let mut props: Vec<(&'a str, Value)> = vec![("maxspeed", Value::str(maxspeed))];+    if let Some(v) = t.highway.filter(|v| !v.is_empty()) {+        props.push(("highway", Value::str(v)));+    }+    if let Some(v) = t.name.filter(|v| !v.is_empty()) {+        props.push(("name", Value::str(v)));+    }+    props.push(("osm_id", osm_ref("way", way_id)));+    Feature { geometry, props }+}++#[cfg(test)]+mod tests {+    use super::*;++    fn tags<'a>(ms: Option<&'a str>, fwd: Option<&'a str>, bwd: Option<&'a str>) -> MaxspeedTags<'a> {+        MaxspeedTags {+            maxspeed: ms,+            maxspeed_forward: fwd,+            maxspeed_backward: bwd,+            ..Default::default()+        }+    }++    /// The seven emitted features of+    /// `scripts/maps/test/fixtures/maxspeed_sample.geojsonseq`, as tag sets. The+    /// fixture also holds a way with no maxspeed and a Point that has one; both are+    /// dropped, the first by [`extract`] and the second by the geometry filter.+    fn fixture_values() -> Vec<&'static str> {+        [+            tags(Some("25 mph"), None, None),+            tags(Some("50"), None, None),+            tags(Some("100 km/h"), None, None),+            tags(None, Some("30 mph"), None),+            tags(Some("none"), None, None),+            tags(Some("walk"), None, None),+            tags(Some("signals"), None, None),+        ]+        .iter()+        .filter_map(extract)+        .collect()+    }++    #[test]+    fn emits_seven_values() {+        assert_eq!(fixture_values().len(), 7);+    }++    #[test]+    fn every_raw_form_survives_verbatim() {+        // This is the whole point of the layer: the app parses these itself.+        let values = fixture_values();+        for want in ["25 mph", "50", "100 km/h", "30 mph", "none", "walk", "signals"] {+            assert!(values.contains(&want), "{want:?} was lost: {values:?}");+        }+    }++    #[test]+    fn tags_rs_parse_maxspeed_would_destroy_every_one_of_them() {+        // Not a test of this module so much as a guard on the wiring: if anyone+        // routes the layer through the graph's parser, these are the answers they+        // get instead. "25 mph" becomes 40, and the three non-numeric forms all+        // become the same 0.+        assert_eq!(crate::tags::parse_maxspeed(Some("25 mph")), 40);+        assert_eq!(crate::tags::parse_maxspeed(Some("100 km/h")), 100);+        for lossy in ["none", "walk", "signals"] {+            assert_eq!(crate::tags::parse_maxspeed(Some(lossy)), 0, "{lossy}");+        }+    }++    #[test]+    fn precedence_is_maxspeed_then_forward_then_backward() {+        assert_eq!(extract(&tags(Some("50"), Some("30"), Some("20"))), Some("50"));+        assert_eq!(extract(&tags(None, Some("30"), Some("20"))), Some("30"));+        assert_eq!(extract(&tags(None, None, Some("20"))), Some("20"));+        assert_eq!(extract(&tags(None, None, None)), None);+    }++    #[test]+    fn an_empty_tag_falls_through_to_the_next() {+        // A present-but-empty tag is not a speed limit.+        assert_eq!(extract(&tags(Some(""), Some("30"), None)), Some("30"));+        assert_eq!(extract(&tags(Some(""), Some(""), Some(""))), None);+    }++    #[test]+    fn the_emitted_schema_is_maxspeed_highway_name_osm_id() {+        let t = MaxspeedTags {+            maxspeed: Some("25 mph"),+            highway: Some("residential"),+            name: Some("Main St"),+            ..Default::default()+        };+        let f = feature("25 mph", &t, Geometry::LineString(vec![(0.0, 0.0), (1.0, 1.0)]), 3001);+        let keys: Vec<&str> = f.props.iter().map(|(k, _)| *k).collect();+        assert_eq!(keys, ["maxspeed", "highway", "name", "osm_id"]);+        match &f.props[3].1 {+            Value::Str(s) => assert_eq!(s, b"way/3001"),+            _ => panic!("osm_id must be the way/N string form"),+        }+    }++    #[test]+    fn highway_and_name_are_omitted_only_when_empty() {+        let bare = MaxspeedTags { maxspeed: Some("50"), ..Default::default() };+        assert_eq!(+            feature("50", &bare, Geometry::LineString(vec![]), 1).props.len(),+            2,+            "maxspeed + osm_id only"+        );+        let empty = MaxspeedTags {+            maxspeed: Some("50"),+            highway: Some(""),+            name: Some(""),+            ..Default::default()+        };+        assert_eq!(feature("50", &empty, Geometry::LineString(vec![]), 1).props.len(), 2);++        // `highway=no` IS kept: normalize_maxspeed.py used plain truthiness, not+        // its own `_truthy`, unlike the safety layer.+        let no = MaxspeedTags {+            maxspeed: Some("50"),+            highway: Some("no"),+            ..Default::default()+        };+        assert_eq!(feature("50", &no, Geometry::LineString(vec![]), 1).props.len(), 3);+    }++    #[test]+    fn the_pbf_filters_cover_every_tag_extract_reads() {+        let select = crate::select::Select::parse(&FILTERS).unwrap();+        for (ms, fwd, bwd) in [+            (Some("50"), None, None),+            (None, Some("30 mph"), None),+            (None, None, Some("20")),+        ] {+            let t = tags(ms, fwd, bwd);+            let get = |k: &str| match k {+                "maxspeed" => t.maxspeed,+                "maxspeed:forward" => t.maxspeed_forward,+                "maxspeed:backward" => t.maxspeed_backward,+                _ => None,+            };+            assert!(extract(&t).is_some());+            assert!(select.matches(get), "extract accepts what the filter rejects");+        }+    }+}
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 f8a1abfc61..7b19424c18 100644--- a/scripts/maps/osm_ingest/src/testpbf.rs+++ b/scripts/maps/osm_ingest/src/testpbf.rs@@ -362,6 +362,27 @@ pub const SIGNALS_NODE_ID: i64 = 1007; /// A named cafe: tagged, but not road furniture. The negative control. pub const LAYERS_CAFE_NODE_ID: i64 = 1008; +/// `highway=residential` + `maxspeed=25 mph`, the raw-string case.+pub const MAXSPEED_WAY_ID: i64 = 3001;+/// `highway=motorway` + `maxspeed=none`, which the graph's parser would collapse+/// to 0 and this layer must keep verbatim.+pub const MAXSPEED_NONE_WAY_ID: i64 = 3002;+/// `highway=service` with no speed limit at all. The negative control.+pub const NO_MAXSPEED_WAY_ID: i64 = 3003;+/// `railway=subway`, a transit line in its own right.+pub const RAILWAY_WAY_ID: i64 = 5001;+/// `railway=narrow_gauge`, which folds into `rail`.+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.+pub const ROUTE_RELATION_ID: i64 = 9001;+/// `type=route` + `route=bus`, which this layer drops.+pub const BUS_RELATION_ID: i64 = 9002;++/// Node ids the vector-layer fixture's ways are built from.+const WAY_NODE_IDS: [i64; 6] = [2001, 2002, 2003, 2004, 2005, 2006];+ /// One node in the vector-layer fixture: `(id, lat_e7, lon_e7, tags)`. type FixtureNode = (i64, i32, i32, Vec<(u32, u32)>); @@ -397,6 +418,13 @@ pub fn layers_block() -> Vec<u8> {     let k_direction = st.id("direction");     let k_amenity = st.id("amenity");     let k_name = st.id("name");+    let k_maxspeed = st.id("maxspeed");+    let k_maxspeed_forward = st.id("maxspeed:forward");+    let k_railway = st.id("railway");+    let k_type = st.id("type");+    let k_route = st.id("route");+    let k_ref = st.id("ref");+    let k_colour = st.id("colour");      let v_speed_camera = st.id("speed_camera");     let v_surveillance = st.id("surveillance");@@ -407,7 +435,26 @@ pub fn layers_block() -> Vec<u8> {     let v_traffic_signals = st.id("traffic_signals");     let v_cafe = st.id("cafe");     let v_corner_cafe = st.id("Corner Cafe");-+    let v_residential = st.id("residential");+    let v_motorway = st.id("motorway");+    let v_service = st.id("service");+    let v_25mph = st.id("25 mph");+    let v_none = st.id("none");+    let v_30mph = st.id("30 mph");+    let v_main_st = st.id("Main St");+    let v_subway = st.id("subway");+    let v_narrow_gauge = st.id("narrow_gauge");+    let v_platform = st.id("platform");+    let v_market_st = st.id("Market St Subway");+    let v_route = st.id("route");+    let v_bus = st.id("bus");+    let v_red_line = st.id("Red Line");+    let v_red = st.id("Red");+    let v_da291c = st.id("#DA291C");+    // An empty member role is string-table index 0, per the PBF spec.+    let role_empty = ST_EMPTY;++    // Ids ascend, as they do in a real PBF.     let nodes: Vec<FixtureNode> = vec![         (             CAMERA_NODE_ID,@@ -443,15 +490,96 @@ pub fn layers_block() -> Vec<u8> {             -1_224_130_000,             vec![(k_amenity, v_cafe), (k_name, v_corner_cafe)],         ),+        // Untagged nodes the ways are built from, laid out along 37.79N.+        (WAY_NODE_IDS[0], 377_900_000, -1_224_300_000, vec![]),+        (WAY_NODE_IDS[1], 377_900_000, -1_224_200_000, vec![]),+        (WAY_NODE_IDS[2], 377_900_000, -1_224_100_000, vec![]),+        (WAY_NODE_IDS[3], 377_910_000, -1_224_100_000, vec![]),+        (WAY_NODE_IDS[4], 377_920_000, -1_224_100_000, vec![]),+        (WAY_NODE_IDS[5], 377_930_000, -1_224_100_000, vec![]),     ];     let dense = dense_group(&nodes); +    let ways = [+        // maxspeed: a raw "25 mph", with a highway and a name to carry.+        way(+            MAXSPEED_WAY_ID,+            &[+                (k_highway, v_residential),+                (k_maxspeed, v_25mph),+                (k_name, v_main_st),+            ],+            &WAY_NODE_IDS[..3],+        ),+        // maxspeed=none, plus a directional tag that must NOT win over it.+        way(+            MAXSPEED_NONE_WAY_ID,+            &[+                (k_highway, v_motorway),+                (k_maxspeed, v_none),+                (k_maxspeed_forward, v_30mph),+            ],+            &WAY_NODE_IDS[2..5],+        ),+        // No speed limit at all.+        way(NO_MAXSPEED_WAY_ID, &[(k_highway, v_service)], &WAY_NODE_IDS[..2]),+        // transit_lines: a subway way with a name, and a member of the route below.+        way(+            RAILWAY_WAY_ID,+            &[(k_railway, v_subway), (k_name, v_market_st)],+            &WAY_NODE_IDS[..3],+        ),+        // narrow_gauge folds into rail; also the route's second member.+        way(+            NARROW_GAUGE_WAY_ID,+            &[(k_railway, v_narrow_gauge)],+            &WAY_NODE_IDS[3..6],+        ),+        // A platform is not a line.+        way(PLATFORM_WAY_ID, &[(k_railway, v_platform)], &WAY_NODE_IDS[..2]),+    ];++    let rels = [+        // A route relation over two member ways, so its geometry is a genuine+        // MultiLineString rather than a single part.+        relation(+            ROUTE_RELATION_ID,+            &[+                (k_type, v_route),+                (k_route, v_subway),+                (k_name, v_red_line),+                (k_ref, v_red),+                (k_colour, v_da291c),+            ],+            &[+                (RAILWAY_WAY_ID, role_empty, 1),+                (NARROW_GAUGE_WAY_ID, role_empty, 1),+            ],+        ),+        // A bus route: this layer is the rail-like modes only.+        relation(+            BUS_RELATION_ID,+            &[(k_type, v_route), (k_route, v_bus)],+            &[(RAILWAY_WAY_ID, role_empty, 1)],+        ),+    ];+     let mut node_group = Vec::new();     bytes_field(2, &dense, &mut node_group);+    let mut way_group = Vec::new();+    for w in &ways {+        bytes_field(3, w, &mut way_group);+    }+    let mut rel_group = Vec::new();+    for r in &rels {+        bytes_field(4, r, &mut rel_group);+    }      let mut block = Vec::new();     bytes_field(1, &st.encode(), &mut block);     bytes_field(2, &node_group, &mut block);+    bytes_field(2, &way_group, &mut block);+    bytes_field(2, &rel_group, &mut block);     varint_field(17, 100, &mut block); // granularity     block }
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.rsnew file mode 100644index 0000000000..9bda55489a--- /dev/null+++ b/scripts/maps/osm_ingest/src/transit_lines.rs@@ -0,0 +1,374 @@+//! The `transit_lines` layer: OSM rail/subway/tram/… geometry for the app's+//! transit-line highlight.+//!+//! A port of `normalize_transit_lines.py`. Two sources feed it, and each can only+//! produce some of the kinds:+//!+//! * **railway ways** -- `railway=rail|subway|light_rail|tram|monorail|narrow_gauge`+//! * **route relations** -- `type=route` with `route=subway|tram|light_rail|train|monorail`+//!+//! The asymmetry is deliberate and encoded in the two maps. `rail` is only+//! reachable from a way, because `route=rail` is not a tagging convention; `train`+//! is only reachable from a relation, because that is how national rail services+//! are tagged; `narrow_gauge` folds into `rail`; and `route=bus` is in neither map,+//! so bus routes are dropped -- this layer is for the rail-like modes the highlight+//! styles.+//!+//! `railway` wins over `route`: a way carrying both is a physical piece of track,+//! and the route is a service running over it.+//!+//! ## The HSTORE parsing is gone, and why that is not a regression+//!+//! The Python spent a third of its length on `parse_hstore` and `merged_tags`,+//! unpacking a `"route"=>"subway","colour"=>"#DA291C"` string back into tags. That+//! existed for exactly one reason: relation geometry came from+//! `ogr2ogr -f GeoJSONSeq … multilinestrings`, and GDAL's OSM driver exposes a few+//! named fields and folds every other tag into an `other_tags` HSTORE. Reading+//! relations out of the PBF directly gives their tags as tags, so there is nothing+//! to unpack. The GDAL dependency goes with it.+//!+//! ## Relation geometry is an unordered MultiLineString+//!+//! A route relation's member ways are emitted as separate parts, in member order,+//! with no attempt to stitch them into a single continuous line. The layer's+//! contract allows it -- `MultiLineString` is what the Python emitted too, since+//! that is what GDAL produced -- and it is the right answer for a route: branches,+//! loops and split platforms mean the ways often do not form one path at all.+//!+//! ## One deliberate schema change+//!+//! `osm_id` for a relation is now `relation/9001`, where the GDAL path emitted a+//! bare `9001` (its `osm_id` field) while ways came through as `way/5001`. The two+//! sources disagreeing was an artefact of the toolchain, not a decision, so the+//! port uses the `<kind>/<id>` form throughout. The differential harness will show+//! this as a property difference on relation features; that is expected.++use crate::geojson::{osm_ref, Feature, Geometry, Value};++/// `railway=<value>` on a way -> the layer's `kind`.+pub const RAILWAY_KIND: [(&str, &str); 6] = [+    ("rail", "rail"),+    ("subway", "subway"),+    ("light_rail", "light_rail"),+    ("tram", "tram"),+    ("monorail", "monorail"),+    // Folded in: the highlight styles gauge-agnostic heavy rail the same way.+    ("narrow_gauge", "rail"),+];++/// `route=<value>` on a `type=route` relation -> the layer's `kind`.+pub const ROUTE_KIND: [(&str, &str); 5] = [+    ("subway", "subway"),+    ("tram", "tram"),+    ("light_rail", "light_rail"),+    ("train", "train"),+    ("monorail", "monorail"),+];++/// The `osmium tags-filter` expression for the way half of the layer.+pub const WAY_FILTERS: [&str; 1] = ["railway=rail,subway,light_rail,tram,monorail,narrow_gauge"];++/// The `osmium tags-filter` expression for the relation half.+pub const RELATION_FILTERS: [&str; 1] = ["route=subway,tram,light_rail,train,monorail"];++#[derive(Debug, Default, Clone, Copy)]+pub struct TransitTags<'a> {+    pub railway: Option<&'a str>,+    /// The relation's `type`. Absent is accepted, matching the Python's+    /// `tags.get("type") in (None, "route")`.+    pub type_: Option<&'a str>,+    pub route: Option<&'a str>,+    pub name: Option<&'a str>,+    pub reference: Option<&'a str>,+    pub colour: Option<&'a str>,+    /// The American spelling, accepted as a fallback.+    pub color: Option<&'a str>,+}++fn lookup(map: &[(&str, &'static str)], v: Option<&str>) -> Option<&'static str> {+    let v = v?;+    map.iter().find(|(k, _)| *k == v).map(|(_, kind)| *kind)+}++pub fn railway_kind(v: Option<&str>) -> Option<&'static str> {+    lookup(&RAILWAY_KIND, v)+}++pub fn route_kind(v: Option<&str>) -> Option<&'static str> {+    lookup(&ROUTE_KIND, v)+}++pub fn classify(t: &TransitTags) -> Option<&'static str> {+    // A way carrying both tags is track, not a service.+    if let Some(kind) = railway_kind(t.railway) {+        return Some(kind);+    }+    if matches!(t.type_, None | Some("route")) {+        return route_kind(t.route);+    }+    None+}++/// `normalize_transit_lines.py`'s `_truthy`.+pub fn truthy(v: Option<&str>) -> bool {+    !matches!(v, None | Some("") | Some("no") | Some("false") | Some("0"))+}++/// 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()+}++/// Build the emitted feature. Property order matches the Python's insertion order:+/// `kind`, `name`, `ref`, `colour`, `osm_id`.+pub fn feature<'a>(+    kind: &'a str,+    t: &TransitTags<'a>,+    geometry: Geometry,+    element: &'a str,+    id: i64,+) -> Feature<'a> {+    let mut props: Vec<(&'a str, Value)> = vec![("kind", Value::str(kind))];+    if truthy(t.name) {+        props.push(("name", Value::str(t.name.unwrap())));+    }+    if truthy(t.reference) {+        props.push(("ref", Value::str(t.reference.unwrap())));+    }+    if let Some(c) = colour(t) {+        props.push(("colour", Value::str(c)));+    }+    props.push(("osm_id", osm_ref(element, id)));+    Feature { geometry, props }+}++#[cfg(test)]+mod tests {+    use super::*;++    fn way(railway: &str) -> TransitTags<'_> {+        TransitTags { railway: Some(railway), ..Default::default() }+    }++    fn relation<'a>(route: &'a str) -> TransitTags<'a> {+        TransitTags {+            type_: Some("route"),+            route: Some(route),+            ..Default::default()+        }+    }++    /// The eight emitted features of+    /// `scripts/maps/test/fixtures/transit_lines_sample.geojsonseq`: six railway+    /// ways and two route relations. The fixture's platform way, highway way, bus+    /// route relation and station point are all dropped.+    fn fixture_kinds() -> Vec<&'static str> {+        [+            way("subway"),        // way/5001 Market St Subway+            way("light_rail"),    // way/5002+            way("tram"),          // way/5003+            way("monorail"),      // way/5004+            way("rail"),          // way/5005+            way("narrow_gauge"),  // way/5006 -> rail+            relation("subway"),   // relation 9001 Red Line+            relation("tram"),     // relation 9002 N Judah+        ]+        .iter()+        .filter_map(classify)+        .collect()+    }++    fn count(kinds: &[&str], want: &str) -> usize {+        kinds.iter().filter(|k| **k == want).count()+    }++    #[test]+    fn emits_eight_features() {+        assert_eq!(fixture_kinds().len(), 8);+    }++    #[test]+    fn a_way_and_a_relation_can_both_produce_the_same_kind() {+        let kinds = fixture_kinds();+        assert_eq!(count(&kinds, "subway"), 2, "railway=subway and route=subway");+        assert_eq!(count(&kinds, "tram"), 2, "railway=tram and route=tram");+    }++    #[test]+    fn light_rail_and_monorail_come_through() {+        let kinds = fixture_kinds();+        assert!(kinds.contains(&"light_rail"));+        assert!(kinds.contains(&"monorail"));+    }++    #[test]+    fn narrow_gauge_folds_into_rail() {+        // Two rail features from one railway=rail and one railway=narrow_gauge.+        assert_eq!(count(&fixture_kinds(), "rail"), 2);+        assert_eq!(classify(&way("narrow_gauge")), Some("rail"));+    }++    #[test]+    fn platforms_highways_and_bus_routes_are_dropped() {+        assert_eq!(classify(&way("platform")), None);+        assert_eq!(classify(&TransitTags::default()), None);+        // A highway way carries no railway tag at all.+        assert_eq!(+            classify(&TransitTags { route: None, ..Default::default() }),+            None+        );+        // route=bus is in neither map: this layer is the rail-like modes.+        assert_eq!(classify(&relation("bus")), None);+        assert_eq!(classify(&relation("ferry")), None);+    }++    #[test]+    fn train_is_only_reachable_from_a_relation_and_rail_only_from_a_way() {+        assert_eq!(classify(&relation("train")), Some("train"));+        // There is no railway=train convention, so a way cannot make one.+        assert_eq!(classify(&way("train")), None);+        assert_eq!(classify(&way("rail")), Some("rail"));+        // And route=rail is not a convention either.+        assert_eq!(classify(&relation("rail")), None);+    }++    #[test]+    fn railway_wins_over_route() {+        // Track carrying a service is track.+        let both = TransitTags {+            railway: Some("rail"),+            type_: Some("route"),+            route: Some("subway"),+            ..Default::default()+        };+        assert_eq!(classify(&both), Some("rail"));+    }++    #[test]+    fn an_absent_type_is_accepted_but_a_wrong_one_is_not() {+        // The Python tested `type in (None, "route")`.+        assert_eq!(+            classify(&TransitTags { route: Some("subway"), ..Default::default() }),+            Some("subway")+        );+        assert_eq!(+            classify(&TransitTags {+                type_: Some("multipolygon"),+                route: Some("subway"),+                ..Default::default()+            }),+            None+        );+    }++    #[test]+    fn the_relations_colour_and_ref_come_through() {+        // The Red Line fixture: colour "#DA291C", ref "Red", kind subway. These+        // arrived via GDAL's HSTORE before; now they are just tags.+        let t = TransitTags {+            type_: Some("route"),+            route: Some("subway"),+            name: Some("Red Line"),+            reference: Some("Red"),+            colour: Some("#DA291C"),+            ..Default::default()+        };+        assert_eq!(classify(&t), Some("subway"));+        let f = feature("subway", &t, Geometry::MultiLineString(vec![]), "relation", 9001);+        let keys: Vec<&str> = f.props.iter().map(|(k, _)| *k).collect();+        assert_eq!(keys, ["kind", "name", "ref", "colour", "osm_id"]);+        match &f.props[3].1 {+            Value::Str(s) => assert_eq!(s, b"#DA291C"),+            _ => panic!("colour must be a string"),+        }+    }++    #[test]+    fn the_american_colour_spelling_is_accepted() {+        // The N Judah fixture uses `color`.+        let t = TransitTags { color: Some("blue"), ..Default::default() };+        assert_eq!(colour(&t), Some("blue"));+        // British wins when both are set.+        let t = TransitTags {+            colour: Some("#DA291C"),+            color: Some("blue"),+            ..Default::default()+        };+        assert_eq!(colour(&t), Some("#DA291C"));+        // A falsey British value falls through to the American one.+        let t = TransitTags {+            colour: Some("no"),+            color: Some("blue"),+            ..Default::default()+        };+        assert_eq!(colour(&t), Some("blue"));+        assert_eq!(colour(&TransitTags::default()), None);+    }++    #[test]+    fn a_ways_ref_comes_through_too() {+        // The fixture has a way with ref "F".+        let t = TransitTags {+            railway: Some("tram"),+            reference: Some("F"),+            ..Default::default()+        };+        let f = feature("tram", &t, Geometry::LineString(vec![]), "way", 5003);+        assert!(f.props.iter().any(|(k, v)| *k == "ref"+            && matches!(v, Value::Str(s) if s == b"F")));+    }++    #[test]+    fn osm_id_uses_the_element_kind_for_both_sources() {+        // The one deliberate schema change: GDAL emitted a bare number for+        // relations, so the two sources disagreed. See the module docs.+        let t = way("rail");+        let f = feature("rail", &t, Geometry::LineString(vec![]), "way", 5005);+        match &f.props.last().unwrap().1 {+            Value::Str(s) => assert_eq!(s, b"way/5005"),+            _ => panic!(),+        }+        let t = relation("train");+        let f = feature("train", &t, Geometry::MultiLineString(vec![]), "relation", 9003);+        match &f.props.last().unwrap().1 {+            Value::Str(s) => assert_eq!(s, b"relation/9003"),+            _ => panic!(),+        }+    }++    #[test]+    fn falsey_names_and_refs_are_dropped() {+        for v in ["", "no", "false", "0"] {+            let t = TransitTags {+                railway: Some("rail"),+                name: Some(v),+                reference: Some(v),+                colour: Some(v),+                ..Default::default()+            };+            let f = feature("rail", &t, Geometry::LineString(vec![]), "way", 1);+            assert_eq!(f.props.len(), 2, "kind + osm_id only, but {v:?} survived");+        }+    }++    #[test]+    fn the_pbf_filters_cover_both_halves_of_the_layer() {+        let ways = crate::select::Select::parse(&WAY_FILTERS).unwrap();+        for (_, kind) in RAILWAY_KIND {+            let value = RAILWAY_KIND.iter().find(|(_, k)| *k == kind).unwrap().0;+            assert!(+                ways.matches(|k| if k == "railway" { Some(value) } else { None }),+                "railway={value} classifies but is pre-filtered out"+            );+        }+        let rels = crate::select::Select::parse(&RELATION_FILTERS).unwrap();+        for (value, _) in ROUTE_KIND {+            assert!(+                rels.matches(|k| if k == "route" { Some(value) } else { None }),+                "route={value} classifies but is pre-filtered out"+            );+        }+        // And the filters do not let bus through.+        assert!(!rels.matches(|k| if k == "route" { Some("bus") } else { None }));+    }+}