Modern Apps git

← Modern-Apps.git

maps: assemble admin_city boundary rings in Rust

Commit
ea971d878aea983899cb29c4dc9eb32e58a47f9e
Author
vayun-mathur <[email protected]>
When
2026-08-21 06:44 UTC (3 months ago)
Parents
bb6c7ed

Diff

scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex 850ef2bf44..6d7a7116aa 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -172,9 +172,9 @@ mutually consistent (same POI set, same coordinates). See | `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) |+| `osm_ingest/` | Rust OSM ingest crate (detached, `.osm.pbf` read natively): `poi_extract` (POI layer + side files), `road_graph` (routing graph) and `osm_extract` (one geojsonseq per baked vector layer, with its own boundary ring assembler in `src/rings.rs`). Full TYPE MAP and on-disk layouts in `src/poi_build.rs` / `src/graph_build.rs`; see [`osm_ingest/README.md`](osm_ingest/README.md) | | `build_graph.ps1` | Windows entry point for the routing-graph build (no WSL, no g++) |-| `build_admin_layers.sh` | Natural Earth / OSM → `normalize_admin.py` → tippecanoe → `admin_*.pmtiles` |+| `build_admin_layers.sh` | `admin_city`: **`--engine-city rust`** (default) is `osm_extract`'s own ring assembler → `tile_polygons`, cargo-only; `legacy` is osmium → `normalize_admin.py` → tippecanoe. `admin_country`/`admin_region`: Natural Earth → `normalize_admin.py` → tippecanoe, with **no rust engine** — OSM cannot supply them. `--only-city` builds the one admin layer a cargo-only box can | | `build_transit_stops_layer.sh` | GTFS dirs → `gtfs_ingest` `transit_stops` → geojsonseq → `tile_build` `tile_points` → `transit_stops.pmtiles`. **No tippecanoe, no osmium** | | `build_transit_stops_layer.ps1` | **Windows** entry point for the same layer (cargo-only) | | `gtfs_ingest/` | Rust GTFS crate (detached): `gtfs_ingest` (the on-device `.transit` pack) and `transit_stops` (the basemap stop layer). TRX2 on-disk format documented in `src/index.rs` |@@ -183,7 +183,7 @@ mutually consistent (same POI set, same coordinates). See | `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). **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) |+| `normalize_admin.py` | NE/OSM attrs → admin layer schema (pure stdlib, unit-tested). Still the **only** producer for `admin_country`/`admin_region`; the city level is superseded by `osm_ingest/src/admin.rs` | | `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 | | `test/diff_pmtiles.py` | **Differential harness**, tiling half: diffs a tippecanoe archive against ours via `pmtiles_dump` — layer presence, property key sets, extent, geometry mix, and feature counts against a stated drop budget |@@ -207,11 +207,27 @@ archive with `curl` (plus `go-pmtiles` today for a `--bbox` extract). ### 2. Natural Earth is a third input  `admin_country` and `admin_region` come from `ne_10m_admin_0_countries` and-`ne_10m_admin_1_states_provinces`. They are **not derivable from OSM**, so the-default is to carry those two layers forward from the published archive rather-than rebuild them. "OSM + GTFS only" therefore holds for every layer that-actually changes between builds; it does not hold for national and state borders,-which change on a different clock and from a different source.+`ne_10m_admin_1_states_provinces`. They are **not derivable from OSM**, so those two+layers have no rust engine and are not going to get one from this pipeline: they+still need `ogr2ogr`, `tippecanoe` and `python3`, and the default is to carry them+forward from the published archive rather than rebuild them at all.++`admin_city` is different — OSM is the only source for it, Natural Earth has no+cities — and it is fully ported: `osm_extract` assembles the boundary relations'+member ways into rings itself (`osm_ingest/src/rings.rs`) and `tile_polygons` tiles+them. `build_admin_layers.sh --only-city` builds just that one, which is the one+admin layer a cargo-only box can do.++So "OSM + GTFS only" holds for every layer that actually changes between builds; it+does not hold for national and state borders, which change on a different clock and+from a different source.++**Two things the ring assembler does that are worth knowing.** A ring that will not+close — a member missing from the extract, a genuine tagging error — is **dropped and+reported**, not emitted open, because an open ring renders as a wedge of fill+reaching to wherever the renderer chose to close it. And a ring with an unresolvable+vertex is dropped whole, where a *line* with one keeps its remaining vertices:+bridging a gap in an area changes what is inside it.  ### 3. Output is not byte-identical to tippecanoe, by design @@ -315,30 +331,32 @@ 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 — now only the admin layer scripts, and any+* **tippecanoe** ≥ 2.x — now only `admin_country`/`admin_region`, 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.+  `maxspeed`, `transit_lines`, `admin_city` and `ma_pois` do not use it at all.+* **osmium-tool** (`osmium`) — `--engine legacy` runs, plus any `--bbox` run of+  `build_all.sh` (which clips once for every stage).+* **GDAL** (`ogr2ogr`) — `admin_country`/`admin_region`, and+  `transit_lines --engine legacy`. The rust engines read relations out of the PBF+  directly, so they need no GDAL at all.+* **python3** (stdlib only) — `normalize_admin.py` for the two Natural Earth levels,+  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, 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`.+Everything that is cargo-only, which is now every layer except `admin_country` and+`admin_region`: the routing graph (`build_graph.ps1`), the POI layer and its side+files, `safety`, `maxspeed`, `transit_lines`, `admin_city`, 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 two Natural Earth levels need ogr2ogr ++tippecanoe + python3, and the Planetiler base build 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@@ -392,8 +410,9 @@ 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`, `maxspeed`, `transit_lines` and-`ma_pois` default to `rust`; `base` and `admin` still default to `legacy`.+error, never a silent fall-back. `safety`, `maxspeed`, `transit_lines`,+`admin-city` and `ma_pois` default to `rust`; `base` and `admin` (meaning the two+Natural Earth levels) still default to `legacy`.  > **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
scripts/maps/build_admin_layers.sh
diff --git a/scripts/maps/build_admin_layers.sh b/scripts/maps/build_admin_layers.shindex 36bc2f6764..ac7be68163 100644--- a/scripts/maps/build_admin_layers.sh+++ b/scripts/maps/build_admin_layers.sh@@ -18,11 +18,35 @@ set -euo pipefail #   country/region -> Natural Earth 10m (matches .fgb schema, clean geometry) #   city           -> OSM boundary=administrative admin_level=8 (NE has no cities) #+# THE CITY LAYER HAS TWO ENGINES. `--engine-city rust` (the default) is cargo-only:+# `osm_extract` reads the boundary relations out of the .osm.pbf and assembles their+# member ways into rings itself, then `tile_polygons` tiles them. `--engine-city+# legacy` is the original `osmium export | normalize_admin.py | tippecanoe` chain,+# where libosmium did the ring assembly.+#+# THE COUNTRY AND REGION LAYERS HAVE NO RUST ENGINE, and are not going to get one+# from OSM: they come from Natural Earth shapefiles, which OSM cannot supply. That+# is the third input the README's caveats section describes. They still need+# ogr2ogr, tippecanoe and python3.+# # Usage: #   ./build_admin_layers.sh --outdir out/ [--pbf planet.osm.pbf] [--ne-dir ne/] \-#                           [--bbox minlon,minlat,maxlon,maxlat] [--no-city]+#                           [--bbox minlon,minlat,maxlon,maxlat] [--no-city] \+#                           [--engine-city rust|legacy] [--only-city]+#+# Options:+#   --outdir DIR       Where the .pmtiles land (default .)+#   --pbf FILE         OSM extract, required for the city layer+#   --ne-dir DIR       Natural Earth download cache (default ne)+#   --bbox BOX         "minlon,minlat,maxlon,maxlat"+#   --no-city          Omit the city layer+#   --only-city        Build ONLY the city layer, so a cargo-only box can do the+#                      one admin layer it is able to+#   --engine-city E    rust|legacy (default rust) #-# Tools required: ogr2ogr (GDAL), tippecanoe, python3; osmium + a --pbf for cities.+# Tools required: cargo. The country and region layers additionally need ogr2ogr+# (GDAL), tippecanoe and python3; `--engine-city legacy` needs osmium, tippecanoe+# and python3 as well.  HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" OUTDIR="."@@ -30,6 +54,8 @@ PBF="" NE_DIR="ne" BBOX="" WITH_CITY=1+ONLY_CITY=0+ENGINE_CITY="rust"  NE_COUNTRIES_URL="https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_0_countries.zip" NE_REGIONS_URL="https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_1_states_provinces.zip"@@ -41,13 +67,23 @@ while [[ $# -gt 0 ]]; do         --ne-dir) NE_DIR="$2"; shift 2 ;;         --bbox) BBOX="$2"; shift 2 ;;         --no-city) WITH_CITY=0; shift ;;-        -h|--help) sed -n '4,32p' "$0" | sed 's/^# \?//'; exit 0 ;;+        --only-city) ONLY_CITY=1; shift ;;+        --engine-city) ENGINE_CITY="$2"; shift 2 ;;+        -h|--help) sed -n '4,49p' "$0" | sed 's/^# \?//'; exit 0 ;;         *) echo "Unknown arg: $1" >&2; exit 1 ;;     esac done -command -v ogr2ogr    >/dev/null || { echo "ERROR: ogr2ogr (GDAL) not installed" >&2; exit 1; }-command -v tippecanoe >/dev/null || { echo "ERROR: tippecanoe not installed" >&2; exit 1; }+case "$ENGINE_CITY" in+    rust|legacy) : ;;+    *) echo "ERROR: --engine-city must be rust|legacy (got '$ENGINE_CITY')" >&2; exit 1 ;;+esac+command -v cargo >/dev/null || { echo "ERROR: cargo not installed (https://rustup.rs)" >&2; exit 1; }+if [[ "$ONLY_CITY" == "0" ]]; then+    command -v ogr2ogr    >/dev/null || { echo "ERROR: ogr2ogr (GDAL) needed for the country/region layers (or --only-city)" >&2; exit 1; }+    command -v tippecanoe >/dev/null || { echo "ERROR: tippecanoe needed for the country/region layers (or --only-city)" >&2; exit 1; }+    command -v python3    >/dev/null || { echo "ERROR: python3 needed for the country/region layers (or --only-city)" >&2; exit 1; }+fi mkdir -p "$OUTDIR" "$NE_DIR"  # --- Fetch Natural Earth shapefiles if missing ---@@ -58,8 +94,10 @@ fetch_ne() {     curl -fL --retry 3 -o "$NE_DIR/$zip" "$url"     ( cd "$NE_DIR" && unzip -o "$zip" >/dev/null ) }-fetch_ne "$NE_COUNTRIES_URL" ne_admin0.zip ne_10m_admin_0_countries.shp-fetch_ne "$NE_REGIONS_URL"   ne_admin1.zip ne_10m_admin_1_states_provinces.shp+if [[ "$ONLY_CITY" == "0" ]]; then+    fetch_ne "$NE_COUNTRIES_URL" ne_admin0.zip ne_10m_admin_0_countries.shp+    fetch_ne "$NE_REGIONS_URL"   ne_admin1.zip ne_10m_admin_1_states_provinces.shp+fi  # ogr2ogr optional bbox clip: -spat minx miny maxx maxy SPAT=()@@ -86,37 +124,65 @@ build_layer() {  # level  layer_name  minzoom  maxzoom  input_geojson         "$geojson" } -echo "[admin] country (Natural Earth admin_0)"-ogr2ogr -f GeoJSON "${SPAT[@]}" /vsistdout/ "$NE_DIR/ne_10m_admin_0_countries.shp" \-    | python3 "$HERE/normalize_admin.py" --level country > "$OUTDIR/admin_country.geojsonseq"-build_layer 2 admin_country 0 8 "$OUTDIR/admin_country.geojsonseq"+if [[ "$ONLY_CITY" == "0" ]]; then+    echo "[admin] country (Natural Earth admin_0)"+    ogr2ogr -f GeoJSON "${SPAT[@]}" /vsistdout/ "$NE_DIR/ne_10m_admin_0_countries.shp" \+        | python3 "$HERE/normalize_admin.py" --level country > "$OUTDIR/admin_country.geojsonseq"+    build_layer 2 admin_country 0 8 "$OUTDIR/admin_country.geojsonseq" -echo "[admin] region (Natural Earth admin_1)"-ogr2ogr -f GeoJSON "${SPAT[@]}" /vsistdout/ "$NE_DIR/ne_10m_admin_1_states_provinces.shp" \-    | python3 "$HERE/normalize_admin.py" --level region > "$OUTDIR/admin_region.geojsonseq"-build_layer 4 admin_region 3 9 "$OUTDIR/admin_region.geojsonseq"+    echo "[admin] region (Natural Earth admin_1)"+    ogr2ogr -f GeoJSON "${SPAT[@]}" /vsistdout/ "$NE_DIR/ne_10m_admin_1_states_provinces.shp" \+        | python3 "$HERE/normalize_admin.py" --level region > "$OUTDIR/admin_region.geojsonseq"+    build_layer 4 admin_region 3 9 "$OUTDIR/admin_region.geojsonseq"+fi  if [[ "$WITH_CITY" == "1" ]]; then     if [[ -z "$PBF" ]]; then         echo "[admin] --no-city not set but no --pbf given; skipping city layer" >&2     else-        command -v osmium >/dev/null || { echo "ERROR: osmium needed for city layer" >&2; exit 1; }         [[ -f "$PBF" ]] || { echo "ERROR: pbf not found: $PBF" >&2; exit 1; }-        TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT-        SRC="$PBF"-        if [[ -n "$BBOX" ]]; then-            osmium extract --overwrite -b "$BBOX" "$PBF" -o "$TMP/metro.osm.pbf"-            SRC="$TMP/metro.osm.pbf"+        GEOJSON="$OUTDIR/admin_city.geojsonseq"+        if [[ "$ENGINE_CITY" == "rust" ]]; then+            echo "[admin] city (OSM admin_level=8 boundaries, osm_extract)"+            # Three passes over the PBF in one process, with our own ring assembler:+            # relations decide which ways matter, ways give ordered node refs, nodes+            # give coordinates. Rings that will not close are dropped and reported.+            EXTRACT_ARGS=("$PBF" --layer admin_city --out "$GEOJSON")+            [[ -n "$BBOX" ]] && EXTRACT_ARGS+=(--bbox "$BBOX")+            cargo run --release --quiet --manifest-path "$HERE/osm_ingest/Cargo.toml" \+                --bin osm_extract -- "${EXTRACT_ARGS[@]}"+            echo "[admin] tiling admin_city (z6-12, tile_polygons)"+            # No per-tile byte budget: an admin polygon must stay whole enough to+            # reassemble for the dimming mask, which is why the legacy path passed+            # --no-tile-size-limit --no-feature-limit.+            cargo run --release --quiet --manifest-path "$HERE/tile_build/Cargo.toml" \+                --bin tile_polygons -- \+                --geojson "$GEOJSON" \+                --out "$OUTDIR/admin_city.pmtiles" \+                --layer admin_city \+                --minzoom 6 --maxzoom 12 \+                --simplification 4 \+                --max-tile-bytes 100000000+        else+            command -v osmium     >/dev/null || { echo "ERROR: --engine-city legacy needs osmium" >&2; exit 1; }+            command -v tippecanoe >/dev/null || { echo "ERROR: --engine-city legacy needs tippecanoe" >&2; exit 1; }+            command -v python3    >/dev/null || { echo "ERROR: --engine-city legacy needs python3" >&2; exit 1; }+            TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT+            SRC="$PBF"+            if [[ -n "$BBOX" ]]; then+                osmium extract --overwrite -b "$BBOX" "$PBF" -o "$TMP/metro.osm.pbf"+                SRC="$TMP/metro.osm.pbf"+            fi+            echo "[admin] city (OSM admin_level=8 boundaries, osmium)"+            # Keep boundary relations/ways; osmium export assembles the polygon areas+            # from closed ways + multipolygon/boundary relations automatically.+            osmium tags-filter --overwrite "$SRC" \+                r/boundary=administrative w/boundary=administrative \+                -o "$TMP/admin_raw.osm.pbf"+            osmium export -f geojsonseq --overwrite "$TMP/admin_raw.osm.pbf" \+                | python3 "$HERE/normalize_admin.py" --level city > "$GEOJSON"+            build_layer 8 admin_city 6 12 "$GEOJSON"         fi-        echo "[admin] city (OSM admin_level=8 boundaries)"-        # Keep boundary relations/ways; osmium export assembles the polygon areas-        # from closed ways + multipolygon/boundary relations automatically.-        osmium tags-filter --overwrite "$SRC" \-            r/boundary=administrative w/boundary=administrative \-            -o "$TMP/admin_raw.osm.pbf"-        osmium export -f geojsonseq --overwrite "$TMP/admin_raw.osm.pbf" \-            | python3 "$HERE/normalize_admin.py" --level city > "$OUTDIR/admin_city.geojsonseq"-        build_layer 8 admin_city 6 12 "$OUTDIR/admin_city.geojsonseq"     fi fi 
scripts/maps/build_all.ps1
diff --git a/scripts/maps/build_all.ps1 b/scripts/maps/build_all.ps1index 3c0b14c2fd..a305fc9db8 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. 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.+# WHAT THIS TWIN CAN AND CANNOT DO. Only `admin_country` and `admin_region` cannot+# be built here, and never will be from OSM: they come from Natural Earth+# shapefiles. Everything else is cargo-only, so the tiles stage composites safety,+# maxspeed, transit_lines, admin_city, 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@@ -68,6 +68,7 @@ param(     [ValidateSet("rust", "legacy")] [string] $EngineSafety = "rust",     [ValidateSet("rust", "legacy")] [string] $EngineMaxspeed = "rust",     [ValidateSet("rust", "legacy")] [string] $EngineTransitLines = "rust",+    [ValidateSet("rust", "legacy")] [string] $EngineAdminCity = "rust",      # Publishing. Delegates to publish_r2.sh, which needs bash (WSL or Git Bash).     [switch] $Publish,@@ -129,7 +130,7 @@ 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))) {+foreach ($pair in @(@("EngineMaxspeed", $EngineMaxspeed), @("EngineTransitLines", $EngineTransitLines), @("EngineAdminCity", $EngineAdminCity))) {     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"     }@@ -174,6 +175,7 @@ $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"+$AdminCityTile = Join-Path $Work "admin_city.pmtiles" $StopsTile   = Join-Path $Work "transit_stops.pmtiles" $TransitWork = Join-Path $Work "transit" @@ -260,9 +262,9 @@ if (Test-Stage "tiles") {             throw @" the tiles stage needs -BaseArchive on Windows. -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:+Only admin_country and admin_region cannot be built here -- they come from Natural+Earth shapefiles, not OSM -- and the Planetiler base build needs Java. So this twin+composites the cargo-only layers onto an existing archive rather than building one:    .\build_all.ps1 ... -BaseArchive https://data.vayunmathur.com/v5.pmtiles @@ -287,26 +289,32 @@ For a complete v5 with every layer, run build_all.sh under WSL.             throw "-BaseArchive not found: $base"         } -        # 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.+        # safety, maxspeed, transit_lines and admin_city are all cargo-only:+        # osm_extract reads the PBF directly -- assembling boundary rings itself for+        # admin_city -- and the tile_build tilers tile it. No osmium, tippecanoe,+        # GDAL or python3 is involved.         if ($Pbf) {             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 }+                @{ Layer = "safety";        Tile = $SafetyTile;       Bin = "tile_points";   Min = 10; Max = 16; Extra = @() },+                @{ Layer = "maxspeed";      Tile = $MaxspeedTile;     Bin = "tile_lines";    Min = 12; Max = 16; Extra = @() },+                @{ Layer = "transit_lines"; Tile = $TransitLinesTile; Bin = "tile_lines";    Min = 9;  Max = 16; Extra = @() },+                # Admin polygons must stay whole enough to reassemble for the+                # dimming mask, so the per-tile byte budget is effectively lifted --+                # the same reason the legacy path passed --no-tile-size-limit.+                @{ Layer = "admin_city";    Tile = $AdminCityTile;    Bin = "tile_polygons"; Min = 6;  Max = 12;+                   Extra = @("--simplification", "4", "--max-tile-bytes", "100000000") }             )) {                 $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,+                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)")+                    "--minzoom", "$($spec.Min)", "--maxzoom", "$($spec.Max)") + $spec.Extra)             }         } else {-            Write-Warning "no -Pbf given; skipping the safety, maxspeed and transit_lines layers"+            Write-Warning "no -Pbf given; skipping the safety, maxspeed, transit_lines and admin_city layers"         }          # transit_stops needs the same feed manifest world.transit was built from,@@ -327,14 +335,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, $MaxspeedTile, $TransitLinesTile, $PoisTile, $StopsTile)) {+        foreach ($t in @($SafetyTile, $MaxspeedTile, $TransitLinesTile, $AdminCityTile, $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 "the admin layers are NOT in $Out (they need osmium/tippecanoe/GDAL/python3 -- build under WSL for a complete archive)"+        Write-Warning "admin_country and admin_region are NOT in $Out (they come from Natural Earth shapefiles, not OSM -- 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 a8d1b22fe7..9340487413 100644--- a/scripts/maps/build_all.sh+++ b/scripts/maps/build_all.sh@@ -66,7 +66,11 @@ set -euo pipefail #     --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-admin E    rust|legacy    (default legacy: admin_country and+#                                         admin_region come from Natural Earth,+#                                         which OSM cannot supply)+#     --engine-admin-city E              (default rust: osm_extract's own ring+#                                         assembler + tile_polygons) #     --engine-pois E     rust|legacy    (default rust: tile_points, no tippecanoe) #   Publishing #     --publish           upload every built artifact via publish_r2.sh@@ -106,6 +110,7 @@ ENGINE_SAFETY="rust" ENGINE_MAXSPEED="rust" ENGINE_TRANSIT_LINES="rust" ENGINE_ADMIN="legacy"+ENGINE_ADMIN_CITY="rust" ENGINE_POIS="rust"  while [[ $# -gt 0 ]]; do@@ -136,8 +141,9 @@ while [[ $# -gt 0 ]]; do         --engine-maxspeed) ENGINE_MAXSPEED="$2"; shift 2 ;;         --engine-transit-lines) ENGINE_TRANSIT_LINES="$2"; shift 2 ;;         --engine-admin) ENGINE_ADMIN="$2"; shift 2 ;;+        --engine-admin-city) ENGINE_ADMIN_CITY="$2"; shift 2 ;;         --engine-pois) ENGINE_POIS="$2"; shift 2 ;;-        -h|--help) sed -n '4,79p' "$0" | sed 's/^# \?//'; exit 0 ;;+        -h|--help) sed -n '4,83p' "$0" | sed 's/^# \?//'; exit 0 ;;         *) echo "Unknown arg: $1" >&2; exit 1 ;;     esac done@@ -165,6 +171,7 @@ engine_check safety         "$ENGINE_SAFETY"         1 engine_check maxspeed       "$ENGINE_MAXSPEED"       1 engine_check transit-lines  "$ENGINE_TRANSIT_LINES"  1 engine_check admin          "$ENGINE_ADMIN"          0+engine_check admin-city     "$ENGINE_ADMIN_CITY"     1 engine_check pois           "$ENGINE_POIS"           1  command -v cargo >/dev/null || { echo "ERROR: cargo not installed (https://rustup.rs)" >&2; exit 1; }@@ -331,7 +338,8 @@ if want_stage tiles; then                   --engine-safety "$ENGINE_SAFETY"                   --engine-maxspeed "$ENGINE_MAXSPEED"                   --engine-transit-lines "$ENGINE_TRANSIT_LINES"-                  --engine-admin "$ENGINE_ADMIN")+                  --engine-admin "$ENGINE_ADMIN"+                  --engine-admin-city "$ENGINE_ADMIN_CITY")         [[ "$DRY_RUN" == "1" ]] && V5_ARGS+=(--dry-run)         "$HERE/build_v5_pmtiles.sh" "${V5_ARGS[@]}"         mark_done tiles
scripts/maps/build_v5_pmtiles.sh
diff --git a/scripts/maps/build_v5_pmtiles.sh b/scripts/maps/build_v5_pmtiles.shindex dc4fee491c..883053a1e4 100644--- a/scripts/maps/build_v5_pmtiles.sh+++ b/scripts/maps/build_v5_pmtiles.sh@@ -59,11 +59,13 @@ 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`, `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.+#   --engine-base E       rust|legacy per-layer engine. `safety`, `maxspeed`,+#   --engine-safety E     `transit_lines` and `admin-city` default to rust+#   --engine-maxspeed E   (cargo-only); the rest default to legacy, and asking for+#   --engine-transit-lines E  rust before a layer is ported is an error rather than+#   --engine-admin E          a silent no-op, so a rollback is always one flag.+#   --engine-admin-city E     `admin-country`/`admin-region` come from Natural+#                             Earth and will never have a rust engine. #   --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@@ -97,6 +99,7 @@ ENGINE_SAFETY="rust" ENGINE_MAXSPEED="rust" ENGINE_TRANSIT_LINES="rust" ENGINE_ADMIN="legacy"+ENGINE_ADMIN_CITY="rust" DRY_RUN=0 SKIP_BASE=0 SKIP_SAFETY=0@@ -126,6 +129,7 @@ while [[ $# -gt 0 ]]; do         --engine-maxspeed) ENGINE_MAXSPEED="$2"; shift 2 ;;         --engine-transit-lines) ENGINE_TRANSIT_LINES="$2"; shift 2 ;;         --engine-admin) ENGINE_ADMIN="$2"; shift 2 ;;+        --engine-admin-city) ENGINE_ADMIN_CITY="$2"; shift 2 ;;         --dry-run) DRY_RUN=1; shift ;;         --skip-base) SKIP_BASE=1; shift ;;         --skip-safety) SKIP_SAFETY=1; shift ;;@@ -138,7 +142,7 @@ while [[ $# -gt 0 ]]; do         --keep-work) KEEP_WORK=1; shift ;;         --publish) PUBLISH=1; shift ;;         --publish-key) PUBLISH_KEY="$2"; shift 2 ;;-        -h|--help) sed -n '4,83p' "$0" | sed 's/^# \?//'; exit 0 ;;+        -h|--help) sed -n '4,85p' "$0" | sed 's/^# \?//'; exit 0 ;;         *) echo "Unknown arg: $1" >&2; exit 1 ;;     esac done@@ -162,6 +166,7 @@ engine_check safety        "$ENGINE_SAFETY"        1 engine_check maxspeed      "$ENGINE_MAXSPEED"      1 engine_check transit-lines "$ENGINE_TRANSIT_LINES" 1 engine_check admin         "$ENGINE_ADMIN"         0+engine_check admin-city    "$ENGINE_ADMIN_CITY"    1  run() {     if [[ "$DRY_RUN" == "1" ]]; then@@ -236,7 +241,7 @@ fi  # --- 6. admin --- if [[ "$SKIP_ADMIN" == "0" ]]; then-    ADMIN_ARGS=(--outdir "$WORK/admin")+    ADMIN_ARGS=(--outdir "$WORK/admin" --engine-city "$ENGINE_ADMIN_CITY")     [[ -n "$PBF" ]] && ADMIN_ARGS+=(--pbf "$PBF")     [[ -n "$BBOX" ]] && ADMIN_ARGS+=(--bbox "$BBOX")     [[ -z "$PBF" ]] && ADMIN_ARGS+=(--no-city)
scripts/maps/osm_ingest/src/admin.rs
diff --git a/scripts/maps/osm_ingest/src/admin.rs b/scripts/maps/osm_ingest/src/admin.rsnew file mode 100644index 0000000000..f4df2e5cae--- /dev/null+++ b/scripts/maps/osm_ingest/src/admin.rs@@ -0,0 +1,232 @@+//! The `admin_city` layer: OSM `admin_level=8` boundaries, for the app's border+//! masks and labels.+//!+//! A port of `normalize_admin.py --level city`. Only the city level comes from OSM;+//! `admin_country` and `admin_region` come from Natural Earth, which is not+//! derivable from OSM and is handled elsewhere. See the README's caveats.+//!+//! ## `name_en` has no fallback to plain `name` here+//!+//! The three levels disagree, and the disagreement is in the Python:+//!+//! | level | `name` from | `name_en` from |+//! |---|---|---|+//! | country | `NAME_EN, name:en, NAME, name` | `NAME_EN, name:en` |+//! | region | `name_en, NAME_EN, name, NAME` | `name_en, NAME_EN, name:en` |+//! | **city** | `name:en, name, NAME_EN, NAME` | **`name:en, NAME_EN`** |+//!+//! So a city tagged only `name=Oakland` gets `name` and **no** `name_en`, where a+//! region tagged only `name=California` would get both. Adding the fallback would+//! be a defensible schema decision and a silent change to what the layer contains,+//! so it is not made here.+//!+//! ## The level filter+//!+//! `boundary=administrative` (absent counts as administrative) **and**+//! `admin_level=8`. A relation with neither key is accepted -- that branch existed+//! for Natural Earth rows, which carry no OSM admin tagging -- but a PBF relation+//! always has both, so in practice both must match.++use crate::geojson::{osm_ref, Feature, Geometry, Value};++/// The admin level this layer takes.+pub const CITY_LEVEL: i64 = 8;++/// The `osmium tags-filter` expression for the layer.+pub const FILTERS: [&str; 1] = ["boundary=administrative"];++#[derive(Debug, Default, Clone, Copy)]+pub struct AdminTags<'a> {+    pub boundary: Option<&'a str>,+    pub admin_level: Option<&'a str>,+    pub name_en_tag: Option<&'a str>,+    pub name: Option<&'a str>,+    /// The relation `type`, which must be `boundary` for a boundary relation.+    pub type_: Option<&'a str>,+}++/// `normalize_admin.py`'s `_get`: the first key whose value is neither absent nor+/// empty.+fn first<const N: usize>(values: [Option<&str>; N]) -> Option<&str> {+    values.into_iter().flatten().find(|v| !v.is_empty())+}++/// `is_admin_level(tags, 8)`.+pub fn is_city(t: &AdminTags) -> bool {+    if t.admin_level.is_none() && t.boundary.is_none() {+        // Natural Earth rows have no OSM admin tagging. A PBF relation always has+        // both, so this branch is unreachable from a PBF.+        return true;+    }+    if t.boundary.unwrap_or("administrative") != "administrative" {+        return false;+    }+    match t.admin_level {+        None => true,+        // A non-numeric admin_level is a tagging error, not level 8.+        Some(v) => v.trim().parse::<i64>() == Ok(CITY_LEVEL),+    }+}++/// `build_city`, plus the `"name" not in props` drop the Python applied afterwards:+/// `None` when the boundary is unnamed, since an unnamed border is useless for both+/// the mask and the labels.+pub fn feature<'a>(+    t: &AdminTags<'a>,+    geometry: Geometry,+    relation_id: i64,+) -> Option<Feature<'a>> {+    let name = first([t.name_en_tag, t.name])?;+    // No fallback to plain `name` -- see the module docs.+    let name_en = first([t.name_en_tag]);++    let mut props: Vec<(&'a str, Value)> = vec![+        ("admin_level", Value::num(CITY_LEVEL)),+        ("name", Value::str(name)),+    ];+    if let Some(v) = name_en {+        props.push(("name_en", Value::str(v)));+    }+    props.push(("osm_id", osm_ref("relation", relation_id)));+    Some(Feature { geometry, props })+}++#[cfg(test)]+mod tests {+    use super::*;++    fn city<'a>(name: Option<&'a str>, name_en: Option<&'a str>) -> AdminTags<'a> {+        AdminTags {+            boundary: Some("administrative"),+            admin_level: Some("8"),+            name,+            name_en_tag: name_en,+            type_: Some("boundary"),+        }+    }++    fn poly() -> Geometry {+        Geometry::Polygon(vec![vec![+            (0.0, 0.0),+            (1.0, 0.0),+            (1.0, 1.0),+            (0.0, 1.0),+            (0.0, 0.0),+        ]])+    }++    fn props_of(t: &AdminTags) -> Vec<(String, String)> {+        feature(t, poly(), 1)+            .expect("a named city")+            .props+            .iter()+            .map(|(k, v)| {+                let rendered = match v {+                    Value::Str(s) => String::from_utf8_lossy(s).to_string(),+                    Value::Raw(r) => r.clone(),+                };+                (k.to_string(), rendered)+            })+            .collect()+    }++    /// `scripts/maps/test/fixtures/admin_city_sample.geojsonseq` holds San+    /// Francisco and Oakland at `admin_level=8`, plus a county at `admin_level=6`+    /// that must be dropped.+    #[test]+    fn only_admin_level_8_is_kept() {+        assert!(is_city(&city(Some("San Francisco"), None)));+        assert!(is_city(&city(Some("Oakland"), None)));+        let county = AdminTags {+            admin_level: Some("6"),+            ..city(Some("Alameda County"), None)+        };+        assert!(!is_city(&county), "a county is not a city");+    }++    #[test]+    fn admin_level_is_emitted_as_the_number_8() {+        let p = props_of(&city(Some("Oakland"), None));+        assert_eq!(p[0], ("admin_level".to_string(), "8".to_string()));+        // A number, not a string: the app's mask code reads it as one.+        match &feature(&city(Some("Oakland"), None), poly(), 1).unwrap().props[0].1 {+            Value::Raw(r) => assert_eq!(r, "8"),+            _ => panic!("admin_level must be a JSON number"),+        }+    }++    #[test]+    fn name_prefers_the_english_tag_then_falls_back() {+        // name:en wins.+        let p = props_of(&city(Some("Ciudad de México"), Some("Mexico City")));+        assert_eq!(p[1].1, "Mexico City");+        // Only `name`: that is the name.+        let p = props_of(&city(Some("Oakland"), None));+        assert_eq!(p[1].1, "Oakland");+    }++    #[test]+    fn name_en_has_no_fallback_to_plain_name() {+        // The city level's one asymmetry, and the trap: a region tagged only `name`+        // gets a `name_en` too, a city does not. Adding the fallback would be a+        // silent change to what the layer contains.+        let keys: Vec<String> = props_of(&city(Some("Oakland"), None))+            .into_iter()+            .map(|(k, _)| k)+            .collect();+        assert_eq!(keys, ["admin_level", "name", "osm_id"]);+        assert!(!keys.contains(&"name_en".to_string()));++        // With name:en, both appear.+        let keys: Vec<String> = props_of(&city(Some("Ciudad de México"), Some("Mexico City")))+            .into_iter()+            .map(|(k, _)| k)+            .collect();+        assert_eq!(keys, ["admin_level", "name", "name_en", "osm_id"]);+    }++    #[test]+    fn an_unnamed_boundary_is_dropped() {+        assert!(feature(&city(None, None), poly(), 1).is_none());+        assert!(feature(&city(Some(""), None), poly(), 1).is_none());+        // An empty name:en falls through to `name`.+        let f = feature(&city(Some("Oakland"), Some("")), poly(), 1).unwrap();+        assert_eq!(f.props.len(), 3, "name from `name`, and no name_en");+    }++    #[test]+    fn a_non_administrative_boundary_is_rejected() {+        for b in ["postal_code", "political", "maritime"] {+            let t = AdminTags { boundary: Some(b), ..city(Some("X"), None) };+            assert!(!is_city(&t), "boundary={b}");+        }+        // An absent boundary key defaults to administrative.+        let t = AdminTags { boundary: None, ..city(Some("X"), None) };+        assert!(is_city(&t));+    }++    #[test]+    fn a_malformed_admin_level_is_not_level_eight() {+        for v in ["", "eight", "8a", "8.0", "-8"] {+            let t = AdminTags { admin_level: Some(v), ..city(Some("X"), None) };+            assert!(!is_city(&t), "admin_level={v:?}");+        }+        // Whitespace around a good value is tolerated.+        let t = AdminTags { admin_level: Some(" 8 "), ..city(Some("X"), None) };+        assert!(is_city(&t));+    }++    #[test]+    fn osm_id_is_the_relation_form() {+        let p = props_of(&city(Some("Oakland"), None));+        assert_eq!(p.last().unwrap(), &("osm_id".to_string(), "relation/1".to_string()));+    }++    #[test]+    fn the_pbf_filter_covers_what_the_level_test_accepts() {+        let select = crate::select::Select::parse(&FILTERS).unwrap();+        let t = city(Some("Oakland"), None);+        assert!(is_city(&t));+        assert!(select.matches(|k| if k == "boundary" { t.boundary } else { None }));+    }+}
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 20c580f947..f5446bed74 100644--- a/scripts/maps/osm_ingest/src/extract.rs+++ b/scripts/maps/osm_ingest/src/extract.rs@@ -35,12 +35,14 @@ use std::fs::File; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; +use crate::admin::{self, AdminTags}; use crate::bbox::{self, BBox}; 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::rings::{self, MemberWay, RingStats}; use crate::safety::{self, Kind, SafetyTags}; use crate::select::Select; use crate::transit_lines::{self, TransitTags};@@ -50,6 +52,7 @@ pub enum Layer {     Safety,     Maxspeed,     TransitLines,+    AdminCity, }  impl Layer {@@ -58,6 +61,7 @@ impl Layer {             "safety" => Ok(Layer::Safety),             "maxspeed" => Ok(Layer::Maxspeed),             "transit_lines" => Ok(Layer::TransitLines),+            "admin_city" => Ok(Layer::AdminCity),             other => Err(format!(                 "unknown --layer '{other}'; supported: {}",                 Layer::names().join(", ")@@ -66,7 +70,7 @@ impl Layer {     }      pub fn names() -> Vec<&'static str> {-        vec!["safety", "maxspeed", "transit_lines"]+        vec!["safety", "maxspeed", "transit_lines", "admin_city"]     }      pub fn name(self) -> &'static str {@@ -74,6 +78,7 @@ impl Layer {             Layer::Safety => "safety",             Layer::Maxspeed => "maxspeed",             Layer::TransitLines => "transit_lines",+            Layer::AdminCity => "admin_city",         }     } }@@ -108,6 +113,7 @@ pub fn build(input: &Path, out: &Path, opts: &Options) -> Result<Stats> {         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),+        Layer::AdminCity => build_admin_city(input, &blobs, out, opts),     } } @@ -729,6 +735,226 @@ fn transit_way_blob(     Ok(kinds) } +// --- admin_city -----------------------------------------------------------++/// One `admin_level=8` boundary relation, with its member ways and tags copied out.+struct AdminRow {+    id: i64,+    name: Option<String>,+    name_en: Option<String>,+    /// `(way id, is_outer)` in member order.+    members: Vec<(i64, bool)>,+}++#[derive(Default)]+struct AdminWayPass {+    /// `(way id, its refs)` for ways a boundary relation claimed.+    wanted: Vec<(i64, Vec<i64>)>,+}++fn build_admin_city(+    input: &Path,+    blobs: &[pbf::BlobLoc],+    out: &Path,+    opts: &Options,+) -> Result<Stats> {+    let select = Select::parse(&admin::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::<AdminRow>::new,+        |state: &mut Vec<AdminRow>, block| admin_relation_blob(state, block, &select),+    )?;+    let mut rows: Vec<AdminRow> = Vec::new();+    for chunk in chunks {+        rows.extend(chunk);+    }+    let mut wanted_ways: Vec<i64> = rows.iter().flat_map(|r| r.members.iter().map(|m| m.0)).collect();+    wanted_ways.sort_unstable();+    wanted_ways.dedup();+    println!(+        "{} admin_level=8 relation(s), {} member way(s)",+        rows.len(),+        wanted_ways.len()+    );++    // Pass 2: the member ways' node refs, IN ORDER. Nothing sorts or dedups them:+    // vertex order is the geometry. See the `rings` module docs.+    let (chunks, _) = pbf::run_pass(+        input,+        blobs,+        Some(&blob_kinds),+        KIND_WAYS,+        "Pass 2: ways",+        AdminWayPass::default,+        |state, block| admin_way_blob(state, block, &wanted_ways),+    )?;+    let mut member_refs: HashMap<i64, Vec<i64>> = HashMap::new();+    for chunk in chunks {+        member_refs.extend(chunk.wanted);+    }++    // Pass 3: node coordinates.+    let table = NodeLocations::new(+        member_refs.values().flat_map(|r| r.iter().copied()).collect(),+    );+    println!("{} node location(s) needed", table.len());+    let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 3: nodes", table)?;++    let locate = |id: i64| -> Option<Coord> {+        table+            .get(id)+            .map(|(lat_e7, lon_e7)| (lon_e7 as f64 * 1e-7, lat_e7 as f64 * 1e-7))+    };++    let mut lines: Vec<LineFeature> = Vec::new();+    let mut stats = RingStats::default();+    let mut outside_bbox = 0usize;+    let mut no_geometry = 0usize;+    for row in &rows {+        let members: Vec<MemberWay> = row+            .members+            .iter()+            .filter_map(|(way, outer)| {+                member_refs.get(way).map(|refs| MemberWay {+                    refs: refs.clone(),+                    outer: *outer,+                })+            })+            .collect();+        let polygons = rings::assemble(&members, locate, &mut stats);+        if polygons.is_empty() {+            no_geometry += 1;+            continue;+        }+        if !parts_touch_bbox(+            &polygons.iter().flatten().cloned().collect::<Vec<_>>(),+            opts.bbox.as_ref(),+        ) {+            outside_bbox += 1;+            continue;+        }+        // A relation with one ring is a Polygon; several are a MultiPolygon. Both+        // are what `keep_geometry` accepted, and the tiler takes either.+        let geometry = if polygons.len() == 1 {+            Geometry::Polygon(polygons.into_iter().next().expect("non-empty"))+        } else {+            Geometry::MultiPolygon(polygons)+        };+        let t = AdminTags {+            name: row.name.as_deref(),+            name_en_tag: row.name_en.as_deref(),+            ..Default::default()+        };+        let Some(f) = admin::feature(&t, geometry, row.id) else {+            continue;+        };+        lines.push(LineFeature {+            sort: ("relation", row.id),+            rendered: render(&f),+        });+    }++    let written = write_lines(out, lines)?;+    println!(+        "Wrote {written} admin_city feature(s) to {} ({} outer, {} inner ring(s))",+        out.display(),+        stats.outer_rings,+        stats.inner_rings+    );+    // Loud, because an unclosed ring is a data problem the operator can act on --+    // usually a member missing from the extract.+    if stats.unclosed > 0 || stats.orphan_inner > 0 || no_geometry > 0 {+        println!(+            "{} ring(s) would not close, {} orphan hole(s) dropped, {} relation(s) yielded no geometry",+            stats.unclosed, stats.orphan_inner, no_geometry+        );+    }+    if outside_bbox > 0 {+        println!("{outside_bbox} feature(s) dropped by --bbox");+    }+    Ok(Stats {+        features: written,+        from_nodes: 0,+        from_ways: 0,+        from_relations: written,+        outside_bbox,+    })+}++fn admin_relation_blob(+    state: &mut Vec<AdminRow>,+    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 = AdminTags {+                boundary: r.tags.get_str("boundary"),+                admin_level: r.tags.get_str("admin_level"),+                name_en_tag: r.tags.get_str("name:en"),+                name: r.tags.get_str("name"),+                type_: r.tags.get_str("type"),+            };+            if !admin::is_city(&t) {+                return Ok(());+            }+            // An empty role means outer, per the OSM boundary convention: most real+            // members are unroled, and treating them as holes would leave nearly+            // every boundary with no exterior at all.+            let members: Vec<(i64, bool)> = r+                .members+                .iter()+                .filter(|m: &&Member| m.kind == MEMBER_WAY)+                .filter_map(|m| match m.role {+                    b"outer" | b"" => Some((m.id, true)),+                    b"inner" => Some((m.id, false)),+                    // Anything else (`label`, `admin_centre`, a subarea) is not part+                    // of the edge.+                    _ => None,+                })+                .collect();+            if members.is_empty() {+                return Ok(());+            }+            state.push(AdminRow {+                id: r.id,+                name: t.name.map(str::to_string),+                name_en: t.name_en_tag.map(str::to_string),+                members,+            });+        }+        Ok(())+    })?;+    Ok(kinds)+}++fn admin_way_blob(+    state: &mut AdminWayPass,+    block: &pbf::PrimitiveBlock,+    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 && wanted.binary_search(&w.id).is_ok() {+                state.wanted.push((w.id, w.refs.to_vec()));+            }+        }+        Ok(())+    })?;+    Ok(kinds)+}+ // --- shared output --------------------------------------------------------  /// A rendered feature plus the key it sorts on.@@ -1096,6 +1322,82 @@ mod tests {         assert!((line[0].1 - 37.0).abs() < 1e-9);     } +    // --- admin_city -------------------------------------------------------++    #[test]+    fn assembles_an_admin_city_boundary_from_its_member_ways() {+        let (lines, stats) = extract_layer("extract_admin", Layer::AdminCity);+        // Only the admin_level=8 relation. The county at level 6 is dropped.+        assert_eq!(stats.features, 1, "{lines:?}");+        assert_eq!((stats.from_relations, stats.from_ways), (1, 0));++        let f = &lines[0];+        assert!(f.contains("\"admin_level\":8"), "a number, not a string: {f}");+        assert!(f.contains("\"name\":\"Oakland\""), "{f}");+        assert!(f.contains("\"osm_id\":\"relation/9101\""), "{f}");+        // No name:en on the fixture, and the city level has no fallback to `name`.+        assert!(!f.contains("name_en"), "{f}");+        assert!(!lines.iter().any(|l| l.contains("Alameda County")));+    }++    #[test]+    fn an_admin_outer_ring_is_stitched_and_its_hole_is_kept() {+        let (lines, _) = extract_layer("extract_admin_rings", Layer::AdminCity);+        let f = &lines[0];+        // One outer ring plus one hole: a Polygon, not a MultiPolygon.+        assert!(f.contains("\"type\":\"Polygon\""), "{f}");+        // Two rings means one `]],[[` separator between them.+        assert_eq!(f.matches("]],[[").count(), 1, "exterior plus one hole: {f}");++        // The exterior came from two ways -- one roled `outer`, one unroled, and one+        // of them traversed backwards -- so all four corners must be present and the+        // ring must close on the corner it started from.+        let at = f.find("\"coordinates\":[[").unwrap() + "\"coordinates\":[".len();+        let end = at + f[at..].find("]],").unwrap() + 1;+        let outer = &f[at..end];+        for corner in [+            "[-122.4000000,37.8000000]",+            "[-122.3600000,37.8000000]",+            "[-122.3600000,37.8400000]",+            "[-122.4000000,37.8400000]",+        ] {+            assert!(outer.contains(corner), "missing outer corner {corner}: {outer}");+        }+        assert_eq!(outer.matches("[-122.4000000,37.8000000]").count(), 2, "closed: {outer}");++        // The hole is the second ring, and is inside the first.+        let hole = &f[end..];+        assert!(hole.contains("[-122.3900000,37.8100000]"), "{hole}");+    }++    #[test]+    fn admin_city_is_deterministic_and_bbox_filtered() {+        let (pbf_path, dir) = testpbf::write_layers_sample("det_admin");+        let run = |suffix: &str| {+            let out = dir.join(format!("admin{suffix}.geojsonseq"));+            build(+                &pbf_path,+                &out,+                &Options { layer: Layer::AdminCity, bbox: None },+            )+            .unwrap();+            std::fs::read(out).unwrap()+        };+        assert_eq!(run("a"), run("b"));++        let stats = build(+            &pbf_path,+            &dir.join("empty.geojsonseq"),+            &Options {+                layer: Layer::AdminCity,+                bbox: Some(BBox::parse("-30,20,-20,30").unwrap()),+            },+        )+        .unwrap();+        assert_eq!(stats.features, 0);+        assert_eq!(stats.outside_bbox, 1);+    }+     #[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 291fb10baa..514743396c 100644--- a/scripts/maps/osm_ingest/src/lib.rs+++ b/scripts/maps/osm_ingest/src/lib.rs@@ -16,6 +16,7 @@ //! plus a pure-Rust inflate — makes them native on every platform the app is //! built on, and the third never had a Windows path at all. +pub mod admin; pub mod bbox; pub mod extract; pub mod geojson;@@ -27,6 +28,7 @@ pub mod par; pub mod pbf; pub mod poi_build; pub mod proto;+pub mod rings; pub mod safety; pub mod select; pub mod spatial;
scripts/maps/osm_ingest/src/rings.rs
diff --git a/scripts/maps/osm_ingest/src/rings.rs b/scripts/maps/osm_ingest/src/rings.rsnew file mode 100644index 0000000000..b13c742242--- /dev/null+++ b/scripts/maps/osm_ingest/src/rings.rs@@ -0,0 +1,465 @@+//! Assembling a boundary relation's member ways into closed rings, and those rings+//! into polygons.+//!+//! This is the piece [`crate::poi_build`] deliberately did not do. It approximated a+//! relation's outer ring by **sorting and deduplicating** the member ways' node ids,+//! which is exact for a centroid -- averaging is order-independent -- and destroys+//! the ring. Its own comment says so. Nothing built on that approximation can have+//! an area, a winding order, or a point-in-polygon test.+//!+//! Two things follow, and both are load-bearing:+//!+//! * **This module must not sort or dedup refs.** Vertex order *is* the geometry.+//! * **`poi_build` must be left alone.** Its centroids match the libosmium C++ they+//!   replaced, to within a documented 3.1 m worst case, and `poi_index.bin` is a+//!   published artefact. Changing how it derives a centroid would move POIs for no+//!   benefit to this layer.+//!+//! # The assembler+//!+//! 1. **Bucket members by role.** `outer` and the **empty role** are both outer:+//!    the OSM boundary convention is that an unroled way in a `boundary` relation is+//!    part of the outer edge, and in real data most of them are unroled. `inner` is+//!    a hole. Any other role is ignored.+//! 2. **Stitch.** Ways in a relation are in no particular order and no particular+//!    direction, so a ring is found by walking an endpoint -> way multimap,+//!    reversing a way whenever its far end is the one that matches. This is what+//!    libosmium's `Assembler` does.+//! 3. **Drop and log what will not close.** A ring that runs out of candidate ways+//!    before returning to its start is a data error -- a missing member, a way+//!    clipped away by the extract, a genuine tagging mistake. Emitting it as an+//!    open ring would render as a wedge of fill reaching to wherever the renderer+//!    decides to close it, which is far worse than the boundary being absent.+//! 4. **Classify into polygons.** Inner rings are matched to the outer ring that+//!    contains them, by point-in-ring containment, and the outer ring is chosen by+//!    smallest area among those that contain the hole -- nesting means several may.++use crate::geojson::Coord;++/// A member way's ordered node refs, and the role it had in the relation.+pub struct MemberWay {+    pub refs: Vec<i64>,+    pub outer: bool,+}++/// One assembled polygon: its exterior ring first, then its holes. Every ring is+/// explicitly closed.+pub type Polygon = Vec<Vec<Coord>>;++/// What an assembly cost, for the report the operator is owed.+#[derive(Debug, Default, Clone, PartialEq)]+pub struct RingStats {+    pub outer_rings: usize,+    pub inner_rings: usize,+    /// Rings that ran out of ways before closing, and were dropped.+    pub unclosed: usize,+    /// Holes with no containing outer ring, and were dropped.+    pub orphan_inner: usize,+}++/// Assemble `members` into polygons. `locate` resolves a node id to `(lon, lat)`.+///+/// Returns the polygons and a report. An empty result means nothing closed.+pub fn assemble<L>(members: &[MemberWay], locate: L, stats: &mut RingStats) -> Vec<Polygon>+where+    L: Fn(i64) -> Option<Coord>,+{+    let outer = stitch(members.iter().filter(|m| m.outer), stats);+    let inner = stitch(members.iter().filter(|m| !m.outer), stats);+    stats.outer_rings += outer.len();+    stats.inner_rings += inner.len();++    // Resolve to coordinates only once the topology is settled: stitching is about+    // node identity, and comparing coordinates instead would weld two distinct+    // nodes that happen to share a position.+    let outer: Vec<Vec<Coord>> = outer.iter().filter_map(|r| resolve(r, &locate)).collect();+    let inner: Vec<Vec<Coord>> = inner.iter().filter_map(|r| resolve(r, &locate)).collect();++    let mut polygons: Vec<Polygon> = outer.into_iter().map(|r| vec![r]).collect();+    for hole in inner {+        match containing(&polygons, &hole) {+            Some(i) => polygons[i].push(hole),+            // A hole with nothing around it is not a shape, and emitting it would+            // render as solid fill in the layer's colour.+            None => stats.orphan_inner += 1,+        }+    }+    polygons+}++/// Walk the ways into closed rings of node ids. Each returned ring is explicitly+/// closed (first == last).+fn stitch<'a, I>(ways: I, stats: &mut RingStats) -> Vec<Vec<i64>>+where+    I: Iterator<Item = &'a MemberWay>,+{+    // Index by both endpoints, since a way may be traversed either way round.+    let mut pool: Vec<Option<Vec<i64>>> = ways+        .filter(|w| w.refs.len() >= 2)+        .map(|w| Some(w.refs.clone()))+        .collect();++    let mut rings: Vec<Vec<i64>> = Vec::new();+    for start in 0..pool.len() {+        let Some(first) = pool[start].take() else {+            continue;+        };+        let mut ring = first;+        loop {+            if ring.len() > 2 && ring.first() == ring.last() {+                rings.push(ring);+                break;+            }+            let tail = *ring.last().expect("non-empty");+            // Find any unused way starting or ending at the current tail.+            let next = pool.iter().position(|w| {+                w.as_ref()+                    .is_some_and(|r| r.first() == Some(&tail) || r.last() == Some(&tail))+            });+            let Some(i) = next else {+                // Nothing joins on: this ring cannot close.+                stats.unclosed += 1;+                break;+            };+            let mut piece = pool[i].take().expect("just found");+            if piece.first() != Some(&tail) {+                piece.reverse();+            }+            // The shared endpoint is already the ring's tail.+            ring.extend_from_slice(&piece[1..]);++            // A way that closed the ring on its own, or a degenerate self-loop, is+            // caught by the check at the top of the loop.+            if ring.len() > 100_000_000 {+                // Cannot happen with real data; guards against a pathological+                // multimap cycle turning into an OOM rather than an error.+                stats.unclosed += 1;+                break;+            }+        }+    }+    rings+}++/// Resolve a ring of node ids to coordinates. `None` when too few resolve to+/// enclose an area.+///+/// Unlike a line, a ring with a missing vertex is **not** kept with a gap: closing+/// across the gap invents an edge, and for an area that changes what is inside it.+fn resolve<L>(ring: &[i64], locate: &L) -> Option<Vec<Coord>>+where+    L: Fn(i64) -> Option<Coord>,+{+    let coords: Vec<Coord> = ring.iter().map(|id| locate(*id)).collect::<Option<_>>()?;+    // Three distinct vertices plus the repeated close.+    if coords.len() < 4 {+        return None;+    }+    Some(coords)+}++/// Index of the smallest outer ring containing `hole`, if any.+///+/// Smallest, because boundaries nest: a city inside a county inside a state means+/// several outer rings may contain the same hole, and the hole belongs to the+/// tightest one.+fn containing(polygons: &[Polygon], hole: &[Coord]) -> Option<usize> {+    let probe = *hole.first()?;+    let mut best: Option<(usize, f64)> = None;+    for (i, poly) in polygons.iter().enumerate() {+        let outer = &poly[0];+        if !point_in_ring(probe, outer) {+            continue;+        }+        let area = ring_area(outer).abs();+        if best.is_none_or(|(_, b)| area < b) {+            best = Some((i, area));+        }+    }+    best.map(|(i, _)| i)+}++/// Twice the signed area of a ring, by the surveyor's formula.+///+/// In lon/lat degrees, so it is not an area on the ground -- but every use here is a+/// comparison or a sign test, and for that a consistent planar measure is the right+/// tool. A spherical area would cost a lot and change no decision.+pub fn ring_area(ring: &[Coord]) -> f64 {+    let n = ring.len();+    if n < 3 {+        return 0.0;+    }+    let mut sum = 0.0;+    for i in 0..n {+        let (x1, y1) = ring[i];+        let (x2, y2) = ring[(i + 1) % n];+        sum += x1 * y2 - x2 * y1;+    }+    sum+}++/// Ray-casting point-in-polygon. `true` when `p` is inside `ring`.+///+/// The half-open `(y1 > y) != (y2 > y)` test is what makes a vertex exactly at the+/// probe's latitude count once rather than twice, so a ray grazing a vertex does not+/// flip the answer.+pub fn point_in_ring((x, y): Coord, ring: &[Coord]) -> bool {+    let mut inside = false;+    let n = ring.len();+    if n < 3 {+        return false;+    }+    for i in 0..n {+        let (x1, y1) = ring[i];+        let (x2, y2) = ring[(i + 1) % n];+        if (y1 > y) != (y2 > y) {+            let t = (y - y1) / (y2 - y1);+            if x < x1 + t * (x2 - x1) {+                inside = !inside;+            }+        }+    }+    inside+}++#[cfg(test)]+mod tests {+    use super::*;++    fn way(refs: &[i64], outer: bool) -> MemberWay {+        MemberWay { refs: refs.to_vec(), outer }+    }++    /// A 4x4 grid of nodes, ids 1..=16, so a ring can be described by ids alone.+    /// Node `n` sits at `(lon, lat) = ((n-1) % 4, (n-1) / 4)`.+    fn grid(id: i64) -> Option<Coord> {+        (1..=16).contains(&id).then(|| {+            let i = (id - 1) as f64;+            ((i % 4.0), (i / 4.0).floor())+        })+    }++    /// The unit square's corners, and a smaller square inside it.+    fn square(min: f64, max: f64) -> Vec<Coord> {+        vec![(min, min), (max, min), (max, max), (min, max), (min, min)]+    }++    #[test]+    fn a_single_closed_way_is_already_a_ring() {+        let mut stats = RingStats::default();+        let polys = assemble(&[way(&[1, 4, 16, 13, 1], true)], grid, &mut stats);+        assert_eq!(polys.len(), 1);+        assert_eq!(polys[0].len(), 1, "no holes");+        assert_eq!(polys[0][0].len(), 5);+        assert_eq!(polys[0][0].first(), polys[0][0].last());+        assert_eq!(stats, RingStats { outer_rings: 1, ..Default::default() });+    }++    #[test]+    fn several_ways_stitch_into_one_ring() {+        // The square 1-4-16-13 split into four ways, in a scrambled order and with+        // two of them pointing the wrong way. This is what real boundary relations+        // look like.+        let mut stats = RingStats::default();+        let members = vec![+            way(&[16, 13], true),  // reversed+            way(&[1, 4], true),+            way(&[13, 1], true),+            way(&[16, 4], true),   // reversed+        ];+        let polys = assemble(&members, grid, &mut stats);+        assert_eq!(polys.len(), 1, "{stats:?}");+        assert_eq!(stats.unclosed, 0);+        // Four corners plus the close, whichever way round it came out.+        assert_eq!(polys[0][0].len(), 5, "{:?}", polys[0][0]);+        assert!(ring_area(&polys[0][0]).abs() > 0.0);+    }++    #[test]+    fn a_way_is_reversed_when_its_far_end_is_the_match() {+        // Two ways that only join if the second is flipped.+        let mut stats = RingStats::default();+        let members = vec![way(&[1, 4, 16], true), way(&[1, 13, 16], true)];+        let polys = assemble(&members, grid, &mut stats);+        assert_eq!(polys.len(), 1, "{stats:?}");+        assert_eq!(polys[0][0].len(), 5);+    }++    #[test]+    fn an_unclosed_ring_is_dropped_and_counted() {+        // Three sides of a square: it cannot close, so emitting it would render as+        // a wedge reaching to wherever the renderer chose to close it.+        let mut stats = RingStats::default();+        let members = vec![way(&[1, 4], true), way(&[4, 16], true)];+        let polys = assemble(&members, grid, &mut stats);+        assert!(polys.is_empty(), "{polys:?}");+        assert_eq!(stats.unclosed, 1);+        assert_eq!(stats.outer_rings, 0);+    }++    #[test]+    fn one_bad_ring_does_not_take_a_good_one_with_it() {+        let mut stats = RingStats::default();+        let members = vec![+            way(&[1, 4, 16, 13, 1], true), // closed on its own+            way(&[2, 3], true),            // a dangling fragment+        ];+        let polys = assemble(&members, grid, &mut stats);+        assert_eq!(polys.len(), 1);+        assert_eq!(stats.unclosed, 1);+        assert_eq!(stats.outer_rings, 1);+    }++    #[test]+    fn an_empty_role_counts_as_outer() {+        // The OSM boundary convention, and what most real members carry. Treating an+        // unroled way as "not outer" would leave nearly every boundary with no+        // exterior at all.+        let mut stats = RingStats::default();+        let polys = assemble(&[way(&[1, 4, 16, 13, 1], true)], grid, &mut stats);+        assert_eq!(polys.len(), 1);+    }++    #[test]+    fn a_hole_attaches_to_the_ring_that_contains_it() {+        let locate = |id: i64| -> Option<Coord> {+            match id {+                // Outer: a 10x10 square.+                1 => Some((0.0, 0.0)),+                2 => Some((10.0, 0.0)),+                3 => Some((10.0, 10.0)),+                4 => Some((0.0, 10.0)),+                // Inner: a 2x2 square well inside it.+                11 => Some((4.0, 4.0)),+                12 => Some((6.0, 4.0)),+                13 => Some((6.0, 6.0)),+                14 => Some((4.0, 6.0)),+                _ => None,+            }+        };+        let mut stats = RingStats::default();+        let members = vec![+            way(&[1, 2, 3, 4, 1], true),+            way(&[11, 12, 13, 14, 11], false),+        ];+        let polys = assemble(&members, locate, &mut stats);+        assert_eq!(polys.len(), 1);+        assert_eq!(polys[0].len(), 2, "exterior plus its hole");+        assert!(ring_area(&polys[0][0]).abs() > ring_area(&polys[0][1]).abs());+        assert_eq!(stats.inner_rings, 1);+        assert_eq!(stats.orphan_inner, 0);+    }++    #[test]+    fn a_hole_outside_every_outer_ring_is_dropped() {+        let locate = |id: i64| -> Option<Coord> {+            match id {+                1 => Some((0.0, 0.0)),+                2 => Some((10.0, 0.0)),+                3 => Some((10.0, 10.0)),+                4 => Some((0.0, 10.0)),+                // Miles away.+                21 => Some((100.0, 100.0)),+                22 => Some((102.0, 100.0)),+                23 => Some((102.0, 102.0)),+                24 => Some((100.0, 102.0)),+                _ => None,+            }+        };+        let mut stats = RingStats::default();+        let members = vec![+            way(&[1, 2, 3, 4, 1], true),+            way(&[21, 22, 23, 24, 21], false),+        ];+        let polys = assemble(&members, locate, &mut stats);+        assert_eq!(polys.len(), 1);+        assert_eq!(polys[0].len(), 1, "the orphan hole is not emitted");+        assert_eq!(stats.orphan_inner, 1);+    }++    #[test]+    fn a_hole_in_nested_outers_goes_to_the_smallest_containing_one() {+        // Boundaries nest, so several outer rings can contain the same hole. It+        // belongs to the tightest.+        let big = square(0.0, 100.0);+        let small = square(10.0, 50.0);+        let hole = square(20.0, 30.0);+        let polys = vec![vec![big], vec![small.clone()]];+        let i = containing(&polys, &hole).expect("contained by both");+        assert_eq!(polys[i][0], small, "the smaller outer ring wins");+        // And order does not matter.+        let polys = vec![vec![square(10.0, 50.0)], vec![square(0.0, 100.0)]];+        assert_eq!(containing(&polys, &hole), Some(0));+    }++    #[test]+    fn a_ring_with_an_unresolvable_vertex_is_dropped_not_bridged() {+        // For a line, skipping a missing vertex keeps the rest. For an area, closing+        // across the gap invents an edge and changes what is inside.+        let mut stats = RingStats::default();+        let polys = assemble(&[way(&[1, 4, 99, 13, 1], true)], grid, &mut stats);+        assert!(polys.is_empty(), "{polys:?}");+    }++    #[test]+    fn a_ring_too_small_to_enclose_anything_is_dropped() {+        let mut stats = RingStats::default();+        // Two distinct vertices, closed: a line, not an area.+        let polys = assemble(&[way(&[1, 4, 1], true)], grid, &mut stats);+        assert!(polys.is_empty());+        // A single-vertex way is not even a way.+        let polys = assemble(&[way(&[1], true)], grid, &mut stats);+        assert!(polys.is_empty());+        let polys = assemble(&[], grid, &mut stats);+        assert!(polys.is_empty());+    }++    #[test]+    fn vertex_order_is_preserved_which_is_the_whole_point() {+        // poi_build sorts and dedups a relation's refs, which is fine for a centroid+        // and fatal for geometry. This assembler must not: the two rings below have+        // the same vertex SET and different shapes, and sorting would make them+        // indistinguishable.+        let mut stats = RingStats::default();+        let convex = assemble(&[way(&[1, 4, 16, 13, 1], true)], grid, &mut stats);+        let crossed = assemble(&[way(&[1, 16, 4, 13, 1], true)], grid, &mut stats);+        assert_eq!(convex[0][0].len(), crossed[0][0].len());+        assert_ne!(+            convex[0][0], crossed[0][0],+            "the same vertices in a different order are a different ring"+        );+        // The bow-tie encloses no net area; the square encloses 9.+        assert!((ring_area(&convex[0][0]).abs() / 2.0 - 9.0).abs() < 1e-9);+        assert!(ring_area(&crossed[0][0]).abs() < 1e-9);+    }++    #[test]+    fn point_in_ring_handles_edges_and_vertices_without_double_counting() {+        let sq = square(0.0, 10.0);+        assert!(point_in_ring((5.0, 5.0), &sq));+        assert!(!point_in_ring((15.0, 5.0), &sq));+        assert!(!point_in_ring((5.0, 15.0), &sq));+        // A ray leaving a vertex at exactly the probe's latitude must not flip the+        // answer twice.+        assert!(!point_in_ring((-1.0, 0.0), &sq));+        assert!(!point_in_ring((-1.0, 10.0), &sq));+        assert!(point_in_ring((5.0, 0.000001), &sq));+        // Degenerate rings contain nothing.+        assert!(!point_in_ring((0.0, 0.0), &[]));+        assert!(!point_in_ring((0.0, 0.0), &[(0.0, 0.0), (1.0, 1.0)]));+    }++    #[test]+    fn ring_area_signs_and_magnitudes() {+        let ccw = square(0.0, 10.0);+        let mut cw = ccw.clone();+        cw.reverse();+        assert!(ring_area(&ccw) > 0.0);+        assert!(ring_area(&cw) < 0.0);+        assert_eq!(ring_area(&ccw), -ring_area(&cw));+        // Twice the area of a 10x10 square.+        assert!((ring_area(&ccw).abs() - 200.0).abs() < 1e-9);+        assert_eq!(ring_area(&[]), 0.0);+        assert_eq!(ring_area(&[(0.0, 0.0), (1.0, 1.0)]), 0.0);+    }+}
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 7b19424c18..4cd195b445 100644--- a/scripts/maps/osm_ingest/src/testpbf.rs+++ b/scripts/maps/osm_ingest/src/testpbf.rs@@ -379,10 +379,33 @@ pub const PLATFORM_WAY_ID: i64 = 5003; pub const ROUTE_RELATION_ID: i64 = 9001; /// `type=route` + `route=bus`, which this layer drops. pub const BUS_RELATION_ID: i64 = 9002;+/// `type=boundary` + `boundary=administrative` + `admin_level=8`, with an outer+/// ring split across two ways and one inner ring (a hole).+pub const ADMIN_CITY_RELATION_ID: i64 = 9101;+/// The same, but `admin_level=6`: a county, which the city layer drops.+pub const ADMIN_COUNTY_RELATION_ID: i64 = 9102;++/// Way ids the admin boundary is assembled from.+pub const ADMIN_OUTER_WAY_A: i64 = 7001;+pub const ADMIN_OUTER_WAY_B: i64 = 7002;+pub const ADMIN_INNER_WAY: i64 = 7003;  /// Node ids the vector-layer fixture's ways are built from. const WAY_NODE_IDS: [i64; 6] = [2001, 2002, 2003, 2004, 2005, 2006]; +/// The admin boundary's outer ring corners, then its hole's corners. A 0.04-degree+/// square near the other fixture geometry, with a 0.01-degree hole inside it.+const ADMIN_NODES: [(i64, i32, i32); 8] = [+    (2101, 378_000_000, -1_224_000_000),+    (2102, 378_000_000, -1_223_600_000),+    (2103, 378_400_000, -1_223_600_000),+    (2104, 378_400_000, -1_224_000_000),+    (2111, 378_100_000, -1_223_900_000),+    (2112, 378_100_000, -1_223_800_000),+    (2113, 378_200_000, -1_223_800_000),+    (2114, 378_200_000, -1_223_900_000),+];+ /// One node in the vector-layer fixture: `(id, lat_e7, lon_e7, tags)`. type FixtureNode = (i64, i32, i32, Vec<(u32, u32)>); @@ -425,6 +448,8 @@ pub fn layers_block() -> Vec<u8> {     let k_route = st.id("route");     let k_ref = st.id("ref");     let k_colour = st.id("colour");+    let k_boundary = st.id("boundary");+    let k_admin_level = st.id("admin_level");      let v_speed_camera = st.id("speed_camera");     let v_surveillance = st.id("surveillance");@@ -451,6 +476,14 @@ pub fn layers_block() -> Vec<u8> {     let v_red_line = st.id("Red Line");     let v_red = st.id("Red");     let v_da291c = st.id("#DA291C");+    let v_boundary = st.id("boundary");+    let v_administrative = st.id("administrative");+    let v_eight = st.id("8");+    let v_six = st.id("6");+    let v_oakland = st.id("Oakland");+    let v_alameda = st.id("Alameda County");+    let role_outer = st.id("outer");+    let role_inner = st.id("inner");     // An empty member role is string-table index 0, per the PBF spec.     let role_empty = ST_EMPTY; @@ -498,6 +531,10 @@ pub fn layers_block() -> Vec<u8> {         (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 mut nodes = nodes;+    for (id, lat, lon) in ADMIN_NODES {+        nodes.push((id, lat, lon, vec![]));+    }     let dense = dense_group(&nodes);      let ways = [@@ -537,6 +574,12 @@ pub fn layers_block() -> Vec<u8> {         ),         // A platform is not a line.         way(PLATFORM_WAY_ID, &[(k_railway, v_platform)], &WAY_NODE_IDS[..2]),+        // admin_city: the outer ring split across two ways, so the assembler has to+        // stitch them, and one of them is reversed so it has to flip one too.+        way(ADMIN_OUTER_WAY_A, &[], &[2101, 2102, 2103]),+        way(ADMIN_OUTER_WAY_B, &[], &[2101, 2104, 2103]),+        // The hole, closed on its own.+        way(ADMIN_INNER_WAY, &[], &[2111, 2112, 2113, 2114, 2111]),     ];      let rels = [@@ -562,6 +605,34 @@ pub fn layers_block() -> Vec<u8> {             &[(k_type, v_route), (k_route, v_bus)],             &[(RAILWAY_WAY_ID, role_empty, 1)],         ),+        // An admin_level=8 boundary. One member is unroled, which the OSM boundary+        // convention says is outer -- the case that matters most, since most real+        // members are unroled.+        relation(+            ADMIN_CITY_RELATION_ID,+            &[+                (k_type, v_boundary),+                (k_boundary, v_administrative),+                (k_admin_level, v_eight),+                (k_name, v_oakland),+            ],+            &[+                (ADMIN_OUTER_WAY_A, role_outer, 1),+                (ADMIN_OUTER_WAY_B, role_empty, 1),+                (ADMIN_INNER_WAY, role_inner, 1),+            ],+        ),+        // A county: same shape, wrong level.+        relation(+            ADMIN_COUNTY_RELATION_ID,+            &[+                (k_type, v_boundary),+                (k_boundary, v_administrative),+                (k_admin_level, v_six),+                (k_name, v_alameda),+            ],+            &[(ADMIN_OUTER_WAY_A, role_outer, 1), (ADMIN_OUTER_WAY_B, role_empty, 1)],+        ),     ];      let mut node_group = Vec::new();