maps: port the safety layer to Rust with a new osm_extract bin
- Commit
aa42c75666d907cdd67e1ec0cdba85695559a6ba- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 05:59 UTC (3 months ago)
- Parents
6506c56
Diff
scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex 82137a4005..2c689ce88b 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -168,11 +168,11 @@ mutually consistent (same POI set, same coordinates). See | `run_generator.sh` | **Deprecated** thin wrapper over `build_all.sh` (graph + pois + publish) | | `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` | osmium → GeoJSON → `normalize_safety.py` → tippecanoe → `safety.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_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) and `road_graph` (routing graph). 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). 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_transit_stops_layer.sh` | GTFS dirs → `gtfs_ingest` `transit_stops` → geojsonseq → `tile_build` `tile_points` → `transit_stops.pmtiles`. **No tippecanoe, no osmium** |@@ -180,7 +180,7 @@ mutually consistent (same POI set, same coordinates). See | `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` | | `tile_build/` | Rust MVT + PMTiles v3 crate (detached), **replacing tippecanoe and tile-join**: `tile_points` (tile a point geojsonseq), `tile_join` (merge archives) and `pmtiles_dump` (canonical text dump, for the differential harness). Container layout documented in `src/pmtiles.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) |+| `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_admin.py` | NE/OSM attrs → admin layer schema (pure stdlib, unit-tested) |@@ -270,19 +270,22 @@ here is Rust and Python): * **cargo** (https://rustup.rs) — and for a growing share of the pipeline, the *only* thing needed. It builds:- * [`osm_ingest`](osm_ingest/) — the `ma_pois` extractor and the routing graph.+ * [`osm_ingest`](osm_ingest/) — the `ma_pois` extractor, the routing graph, and+ `osm_extract` for the baked vector layers. No C/C++ toolchain and no libosmium: it reads `.osm.pbf` natively. * [`gtfs_ingest`](gtfs_ingest/) — the on-device `.transit` pack and the `transit_stops` basemap layer. * [`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 safety, maxspeed, transit_lines,- ma_pois and admin layer scripts, which pipe GeoJSON through it. The merge no- longer uses its `tile-join`.-* **osmium-tool** (`osmium`) — still required by those same OSM-derived layers.-* **GDAL** (`ogr2ogr`) — transit_lines only.-* **python3** (stdlib only) — the `normalize_*.py` schema mappers.+* **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. * 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`@@ -290,12 +293,17 @@ here is Rust and Python): ### What builds on Windows Everything that is cargo-only: the routing graph (`build_graph.ps1`), the POI-layer and its side files, 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 OSM-derived vector layers-(safety, 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`.+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`.++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+otherwise have left `transit_stops` unbuildable on the dev box. 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@@ -345,7 +353,28 @@ 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.+error, never a silent fall-back. `safety` and `ma_pois` default to `rust`; the+rest 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:+>+> ```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+> ```+>+> 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). ### 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 d8483ce882..bf9d713f55 100644--- a/scripts/maps/build_all.ps1+++ b/scripts/maps/build_all.ps1@@ -5,9 +5,9 @@ # 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 (safety, 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 -- ma_pois and transit_stops -- on+# 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.@@ -65,6 +65,7 @@ param( # Engines, per layer, so a ported layer rolls back with a flag. A 'rust' value # is refused until that layer is actually ported. [ValidateSet("rust", "legacy")] [string] $EnginePois = "rust",+ [ValidateSet("rust", "legacy")] [string] $EngineSafety = "rust", # Publishing. Delegates to publish_r2.sh, which needs bash (WSL or Git Bash). [switch] $Publish,@@ -123,6 +124,9 @@ if ($EnginePois -ne "rust" -and $EnginePois -ne "legacy") { if ($EnginePois -eq "legacy") { throw "-EnginePois legacy needs tippecanoe, which has no Windows build; use rust (the default)" }+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"+} New-Item -ItemType Directory -Force -Path $OutDir | Out-Null $OutDir = (Resolve-Path $OutDir).Path@@ -160,6 +164,7 @@ if ($Geofabrik) { } $PoisTile = Join-Path $Work "ma_pois.pmtiles"+$SafetyTile = Join-Path $Work "safety.pmtiles" $StopsTile = Join-Path $Work "transit_stops.pmtiles" $TransitWork = Join-Path $Work "transit" @@ -246,7 +251,7 @@ if (Test-Stage "tiles") { throw @" the tiles stage needs -BaseArchive on Windows. -Only ma_pois and transit_stops are cargo-only today; safety, maxspeed,+Only safety, ma_pois and transit_stops are cargo-only today; maxspeed, transit_lines and admin 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:@@ -274,6 +279,21 @@ 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.+ 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")+ } else {+ Write-Warning "no -Pbf given; skipping the safety layer"+ }+ # transit_stops needs the same feed manifest world.transit was built from, # so the pins and the schedules agree on stop ids. if ($script:EffectiveGtfsManifest -and (Test-Path $script:EffectiveGtfsManifest)) {@@ -292,14 +312,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 @($PoisTile, $StopsTile)) {+ foreach ($t in @($SafetyTile, $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 "safety, maxspeed, transit_lines and admin are NOT in $Out (they need osmium/tippecanoe/GDAL/python3 -- build under WSL for a complete archive)"+ Write-Warning "maxspeed, transit_lines and admin 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 025dcc28fc..a128f16070 100644--- a/scripts/maps/build_all.sh+++ b/scripts/maps/build_all.sh@@ -61,7 +61,8 @@ set -euo pipefail # --dry-run print what each stage would run; change nothing # Engines, per layer, so a ported layer rolls back with a flag # --engine-base E rust|legacy (default legacy)-# --engine-safety 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-admin E rust|legacy (default legacy)@@ -100,7 +101,7 @@ DRY_RUN=0 PUBLISH=0 PUBLISH_DRY_RUN=0 ENGINE_BASE="legacy"-ENGINE_SAFETY="legacy"+ENGINE_SAFETY="rust" ENGINE_MAXSPEED="legacy" ENGINE_TRANSIT_LINES="legacy" ENGINE_ADMIN="legacy"@@ -135,7 +136,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,77p' "$0" | sed 's/^# \?//'; exit 0 ;;+ -h|--help) sed -n '4,78p' "$0" | sed 's/^# \?//'; exit 0 ;; *) echo "Unknown arg: $1" >&2; exit 1 ;; esac done@@ -159,7 +160,7 @@ engine_check() { fi } engine_check base "$ENGINE_BASE" 0-engine_check safety "$ENGINE_SAFETY" 0+engine_check safety "$ENGINE_SAFETY" 1 engine_check maxspeed "$ENGINE_MAXSPEED" 0 engine_check transit-lines "$ENGINE_TRANSIT_LINES" 0 engine_check admin "$ENGINE_ADMIN" 0
scripts/maps/build_safety_layer.sh
diff --git a/scripts/maps/build_safety_layer.sh b/scripts/maps/build_safety_layer.shindex 645295733b..3c1033e0cc 100644--- a/scripts/maps/build_safety_layer.sh+++ b/scripts/maps/build_safety_layer.sh@@ -7,22 +7,41 @@ set -euo pipefail # signals from an OSM extract and tiles them into a single-layer PMTiles file. # These are baked at build time so the app never needs a runtime Overpass query. #-# Source layer produced: safety (attr: kind, name?, direction?, operator?, ref?)+# Source layer produced: safety (attr: kind, name?, direction?, operator?, ref?,+# surveillance_type?, osm_id) # kind ∈ { speed_camera, alpr, surveillance, stop_sign, traffic_signals } #+# TWO ENGINES. `--engine rust` (the default) is cargo-only: osm_ingest's+# `osm_extract` reads the .osm.pbf directly and tile_build's `tile_points` tiles+# it, so this layer needs neither osmium, nor tippecanoe, nor python3, and runs on+# Windows. `--engine legacy` is the original+# `osmium tags-filter | osmium export | normalize_safety.py | tippecanoe` chain,+# kept so the two can be diffed against each other with+# `test/diff_geojsonseq.py` and `test/diff_pmtiles.py`.+#+# The Rust classifier mirrors normalize_safety.py exactly, including the two+# things easiest to get wrong: `enforcement=maxspeed` is checked BEFORE the+# surveillance branch, and the ALPR heuristic matches `surveillance:type` by+# substring but `camera:type` by exact equality. See osm_ingest/src/safety.rs.+# # Usage: # ./build_safety_layer.sh --pbf planet.osm.pbf --out safety.pmtiles # ./build_safety_layer.sh --pbf planet.osm.pbf --bbox -122.6,37.2,-121.7,37.9 --out safety.pmtiles+# ./build_safety_layer.sh --pbf planet.osm.pbf --engine legacy --out safety-legacy.pmtiles # # Options: # --pbf FILE Input OSM .pbf (required) # --out FILE Output .pmtiles (default: safety.pmtiles) # --bbox BOX Optional "minlon,minlat,maxlon,maxlat" metro extract (dry runs)-# --minzoom N tippecanoe minzoom (default 10)-# --maxzoom N tippecanoe maxzoom (default 16)+# --minzoom N tiler minzoom (default 10)+# --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 (>=2.x, writes .pmtiles), 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 +49,8 @@ OUT="safety.pmtiles" BBOX="" MINZOOM=10 MAXZOOM=16+ENGINE="rust"+GEOJSON_OUT="" KEEP_TMP=0 while [[ $# -gt 0 ]]; do@@ -39,54 +60,87 @@ 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,44p' "$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 "[safety] 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/safety.geojsonseq}"+[[ -z "$GEOJSON_OUT" ]] || mkdir -p "$(dirname "$GEOJSON_OUT")" -echo "[safety] filtering safety/road-furniture nodes"-# Keep only the node types we bake. `enforcement=maxspeed` catches speed-camera-# nodes tagged via the enforcement relation scheme.-osmium tags-filter --overwrite "$SRC" \- n/highway=speed_camera,stop,traffic_signals \- n/man_made=surveillance \- n/enforcement=maxspeed \- -o "$TMP/safety_raw.osm.pbf"+if [[ "$ENGINE" == "rust" ]]; then+ echo "[safety] extracting safety nodes -> $GEOJSON (osm_extract)"+ # One pass over the PBF, with the bbox applied inline: no tags-filter+ # intermediate, no GeoJSON round trip through python.+ EXTRACT_ARGS=("$PBF" --layer safety --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 "[safety] extracting metro bbox $BBOX"+ osmium extract --overwrite -b "$BBOX" "$PBF" -o "$TMP/metro.osm.pbf"+ SRC="$TMP/metro.osm.pbf"+ fi -echo "[safety] exporting to GeoJSON + normalizing kinds"-osmium export -f geojsonseq --overwrite "$TMP/safety_raw.osm.pbf" \- | python3 "$HERE/normalize_safety.py" \- > "$TMP/safety.geojsonseq"+ echo "[safety] filtering safety/road-furniture nodes"+ # Keep only the node types we bake. `enforcement=maxspeed` catches speed-camera+ # nodes tagged via the enforcement relation scheme.+ osmium tags-filter --overwrite "$SRC" \+ n/highway=speed_camera,stop,traffic_signals \+ n/man_made=surveillance \+ n/enforcement=maxspeed \+ -o "$TMP/safety_raw.osm.pbf" -FEATURES="$(wc -l < "$TMP/safety.geojsonseq" | tr -d ' ')"-echo "[safety] $FEATURES normalized feature(s)"+ echo "[safety] exporting to GeoJSON + normalizing kinds"+ osmium export -f geojsonseq --overwrite "$TMP/safety_raw.osm.pbf" \+ | python3 "$HERE/normalize_safety.py" \+ > "$GEOJSON"+fi++FEATURES="$(wc -l < "$GEOJSON" | tr -d ' ')"+echo "[safety] $FEATURES feature(s)" [[ "$FEATURES" -gt 0 ]] || echo "[safety] WARNING: 0 features — check bbox/extract" -echo "[safety] tiling -> $OUT (z$MINZOOM-$MAXZOOM)"-tippecanoe --force \- -o "$OUT" \- -l safety \- --minimum-zoom="$MINZOOM" \- --maximum-zoom="$MAXZOOM" \- --drop-densest-as-needed \- --extend-zooms-if-still-dropping \- "$TMP/safety.geojsonseq"+echo "[safety] tiling -> $OUT (z$MINZOOM-$MAXZOOM, engine: $ENGINE)"+if [[ "$ENGINE" == "rust" ]]; then+ cargo run --release --quiet --manifest-path "$HERE/tile_build/Cargo.toml" \+ --bin tile_points -- \+ --geojson "$GEOJSON" \+ --out "$OUT" \+ --layer safety \+ --minzoom "$MINZOOM" \+ --maxzoom "$MAXZOOM"+else+ tippecanoe --force \+ -o "$OUT" \+ -l safety \+ --minimum-zoom="$MINZOOM" \+ --maximum-zoom="$MAXZOOM" \+ --drop-densest-as-needed \+ --extend-zooms-if-still-dropping \+ "$GEOJSON"+fi echo "[safety] done: $OUT"
scripts/maps/build_v5_pmtiles.sh
diff --git a/scripts/maps/build_v5_pmtiles.sh b/scripts/maps/build_v5_pmtiles.shindex c072fcd1e5..14320b063d 100644--- a/scripts/maps/build_v5_pmtiles.sh+++ b/scripts/maps/build_v5_pmtiles.sh@@ -59,10 +59,10 @@ 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 (all default legacy; a-# --engine-safety E `rust` value is rejected until that layer is ported,-# --engine-maxspeed E so a rollback is one flag and never a silent no-op)-# --engine-transit-lines E+# --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 # --dry-run print each step's command instead of running it # --skip-base don't (re)build base; expects <workdir>/base.pmtiles present@@ -93,7 +93,7 @@ BASE_AREA="planet" BASE_SOURCE="" EXTRA_LAYERS=() ENGINE_BASE="legacy"-ENGINE_SAFETY="legacy"+ENGINE_SAFETY="rust" ENGINE_MAXSPEED="legacy" ENGINE_TRANSIT_LINES="legacy" ENGINE_ADMIN="legacy"@@ -158,7 +158,7 @@ engine_check() { fi } engine_check base "$ENGINE_BASE" 0-engine_check safety "$ENGINE_SAFETY" 0+engine_check safety "$ENGINE_SAFETY" 1 engine_check maxspeed "$ENGINE_MAXSPEED" 0 engine_check transit-lines "$ENGINE_TRANSIT_LINES" 0 engine_check admin "$ENGINE_ADMIN" 0@@ -200,7 +200,7 @@ INPUTS+=("$BASE") # --- 2. safety --- if [[ "$SKIP_SAFETY" == "0" ]]; then [[ -n "$PBF" ]] || { echo "ERROR: --pbf required for safety layer (or --skip-safety)" >&2; exit 1; }- SAFETY_ARGS=(--pbf "$PBF" --out "$WORK/safety.pmtiles")+ SAFETY_ARGS=(--pbf "$PBF" --out "$WORK/safety.pmtiles" --engine "$ENGINE_SAFETY") [[ -n "$BBOX" ]] && SAFETY_ARGS+=(--bbox "$BBOX") run "$HERE/build_safety_layer.sh" "${SAFETY_ARGS[@]}" INPUTS+=("$WORK/safety.pmtiles")
scripts/maps/osm_ingest/Cargo.toml
diff --git a/scripts/maps/osm_ingest/Cargo.toml b/scripts/maps/osm_ingest/Cargo.tomlindex 2b7886b344..7f2a252603 100644--- a/scripts/maps/osm_ingest/Cargo.toml+++ b/scripts/maps/osm_ingest/Cargo.toml@@ -2,8 +2,9 @@ # # Replaces the former `scripts/maps/generator.cpp` (road graph) and # `scripts/maps/poi_extract.cpp` (POI layer), which needed g++ + libosmium and-# therefore WSL. This crate reads `.osm.pbf` natively, so both tools run on-# Windows.+# therefore WSL, plus the `osmium tags-filter | osmium export | normalize_*.py`+# chain that built the baked vector layers. This crate reads `.osm.pbf` natively,+# so all three tools run on Windows. # # Deliberately DETACHED from the Android Rust workspace (the empty [workspace] # table below), exactly like `scripts/maps/gtfs_ingest`: it is a host binary, so@@ -17,7 +18,7 @@ version = "0.1.0" edition = "2021" publish = false license = "GPL-2.0-only"-description = "OSM .osm.pbf -> Maps routing graph + POI side files (replaces the libosmium C++ tools)"+description = "OSM .osm.pbf -> Maps routing graph, POI side files and baked vector layers" [lib] name = "osm_ingest"@@ -31,6 +32,10 @@ path = "src/bin/road_graph.rs" name = "poi_extract" path = "src/bin/poi_extract.rs" +[[bin]]+name = "osm_extract"+path = "src/bin/osm_extract.rs"+ [dependencies] # Pure-Rust inflate. We only ever DECOMPRESS the zlib blobs inside a .osm.pbf, # so a decode-only crate is enough and keeps the C toolchain out of the build.
scripts/maps/osm_ingest/README.md
diff --git a/scripts/maps/osm_ingest/README.md b/scripts/maps/osm_ingest/README.mdindex 6e15d8ae83..1a5cf2e78b 100644--- a/scripts/maps/osm_ingest/README.md+++ b/scripts/maps/osm_ingest/README.md@@ -1,12 +1,13 @@ # osm_ingest Host-side Rust tools that turn an OpenStreetMap `.osm.pbf` extract into the-Maps app's offline artifacts. Two binaries share one library:+Maps app's offline artifacts. Three binaries share one library: | Binary | Replaces | Emits | |---|---|---| | `road_graph` | `scripts/maps/generator.cpp` | `metadata.bin`, `nodes.bin`, `edges.bin`, `lanes.bin`, `road_names.bin` | | `poi_extract` | `scripts/maps/poi_extract.cpp` | `<name>.geojsonseq`, `poi_names.bin`, `poi_index.bin` |+| `osm_extract` | `osmium tags-filter \| osmium export \| normalize_*.py` | one `<layer>.geojsonseq` per baked vector layer | ## Why Rust (LANGUAGE RULE) @@ -36,11 +37,69 @@ cargo run --release --bin road_graph -- california-latest.osm.pbf --out map_data # POI layer side files + the geojsonseq tippecanoe consumes cargo run --release --bin poi_extract -- california-latest.osm.pbf \ --geojson pois.geojsonseq --names poi_names.bin --index poi_index.bin++# One baked vector layer, with the bbox clip done inline (no osmium extract)+cargo run --release --bin osm_extract -- california-latest.osm.pbf \+ --layer safety --out safety.geojsonseq --bbox -122.6,37.2,-121.7,37.9 ``` From Windows, `scripts/maps/build_graph.ps1` wraps the road-graph build in one-command. `scripts/maps/run_generator.sh` and `scripts/maps/build_pois_layer.sh`-call these binaries for the full pipelines.+command and `scripts/maps/build_all.ps1` chains every cargo-only stage.+`scripts/maps/build_all.sh` and the per-layer `build_*_layer.sh` scripts call+these binaries for the full pipelines.++## `osm_extract` and the vector layers++One 3-pass driver ([`src/extract.rs`](src/extract.rs)) for every baked layer,+with each layer's schema in its own module. Supported today: `safety`+([`src/safety.rs`](src/safety.rs)).++Three pieces are shared:++* [`src/geojson.rs`](src/geojson.rs) — the writer. Reproduces+ `json.dumps(..., separators=(",", ":"), ensure_ascii=False)`: no whitespace,+ fixed key order, UTF-8 passthrough.+* [`src/bbox.rs`](src/bbox.rs) — the `osmium extract -b` equivalent, reproducing+ osmium's `complete_ways` strategy (any vertex inside keeps the whole element).+ Containment is compared in 1e-7 **integers**, not degrees, because+ `-1_226_000_000 * 1e-7` lands a hair west of `-122.6` and would drop a node+ sitting exactly on its own box edge.+* [`src/select.rs`](src/select.rs) — the `osmium tags-filter` equivalent, as a+ cheap pre-filter. Tag lookup is a linear scan, so screening on three keys+ before the classifier reads ten is worth doing at planet scale.++### Pass ordering++A PBF stores nodes before the ways that reference them, so any layer needing way+or relation geometry has to traverse **relations, then ways, then nodes** —+relations decide which ways matter, ways decide which node coordinates matter,+nodes supply them. Only the passes a layer needs are run; `safety` is node-based,+so it runs one.++When the way and relation layers land, their node coordinates must be stored the+way `poi_build.rs` does it — a sorted `Vec` of needed ids plus an index-aligned+coordinate array, looked up by `binary_search`, 16 bytes per *needed* node — and+**not** the way `graph_build.rs` does it. That module's bitset is sized from+`BITSET_SIZE = 20e9`, i.e. 2.5 GB keyed by raw node id, and peaks around 10 GB on+California.++### The Python normalisers are still the contract of record++Each `normalize_*.py` stays in the tree until its layer is ported, and the layer+script keeps an `--engine legacy` so both can be run over the same PBF and diffed+with `scripts/maps/test/diff_geojsonseq.py`. For `safety` the two agree exactly:+same properties, same order, same coordinates.++The two rules easiest to break in that port, both pinned by tests in+`src/safety.rs`:++* `enforcement=maxspeed` is checked **before** the `man_made=surveillance`+ branch. A camera tagged both ways is a speed camera, and swapping the order+ silently reclassifies every enforcement camera.+* The ALPR heuristic is **asymmetric**: `surveillance:type` matches by substring+ (real values include `ALPR;camera`), `camera:type` matches by exact equality+ (it is an enumerated field, and a substring rule would corrupt it), and+ `operator`/`manufacturer` match `flock` by substring. ## Output contracts
scripts/maps/osm_ingest/src/bbox.rs
diff --git a/scripts/maps/osm_ingest/src/bbox.rs b/scripts/maps/osm_ingest/src/bbox.rsnew file mode 100644index 0000000000..f252f08738--- /dev/null+++ b/scripts/maps/osm_ingest/src/bbox.rs@@ -0,0 +1,186 @@+//! Bounding-box filtering: the `osmium extract -b` equivalent.+//!+//! The layer scripts clip a PBF with `osmium extract --overwrite -b BOX` before+//! reading it. Doing the clip inline instead removes both the osmium dependency+//! and the intermediate file, at the cost of still walking the whole PBF -- which+//! the extractor has to do anyway to resolve way and relation members.+//!+//! ## Which strategy this reproduces+//!+//! `osmium extract`'s default is `complete_ways`: a way is kept if **any** of its+//! nodes falls inside the box, and then *all* of that way's nodes are kept, even+//! the ones outside. That is why a clipped extract has geometry hanging past the+//! box edge, and it is the right behaviour here too -- truncating a way at the box+//! boundary would invent a vertex that is not in OSM, and the tiler clips+//! properly per tile later anyway.+//!+//! So [`BBox`] only ever answers "is this coordinate inside", and the callers+//! decide what that means for a multi-node element: keep the whole thing if one+//! vertex qualifies.++use crate::proto::{Error, Result};++/// A geographic bounding box in degrees.+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct BBox {+ pub min_lon: f64,+ pub min_lat: f64,+ pub max_lon: f64,+ pub max_lat: f64,+}++impl BBox {+ /// Parse the `minlon,minlat,maxlon,maxlat` form every script in this+ /// directory uses for `--bbox`.+ ///+ /// Reversed bounds are an error rather than being silently swapped: a+ /// transposed box usually means lat and lon were entered the wrong way round,+ /// and normalising it would produce a plausible-looking extract of the wrong+ /// place.+ pub fn parse(s: &str) -> Result<BBox> {+ let parts: Vec<&str> = s.split(',').map(str::trim).collect();+ if parts.len() != 4 {+ return Err(Error(format!(+ "--bbox wants minlon,minlat,maxlon,maxlat, got {} field(s): {s}",+ parts.len()+ )));+ }+ let mut v = [0.0f64; 4];+ for (i, p) in parts.iter().enumerate() {+ v[i] = p+ .parse()+ .map_err(|_| Error(format!("--bbox field {} is not a number: {p}", i + 1)))?;+ }+ let bbox = BBox {+ min_lon: v[0],+ min_lat: v[1],+ max_lon: v[2],+ max_lat: v[3],+ };+ if bbox.min_lon >= bbox.max_lon || bbox.min_lat >= bbox.max_lat {+ return Err(Error(format!(+ "--bbox is empty or reversed: min ({}, {}) is not below max ({}, {})",+ bbox.min_lon, bbox.min_lat, bbox.max_lon, bbox.max_lat+ )));+ }+ if !(-180.0..=180.0).contains(&bbox.min_lon)+ || !(-180.0..=180.0).contains(&bbox.max_lon)+ || !(-90.0..=90.0).contains(&bbox.min_lat)+ || !(-90.0..=90.0).contains(&bbox.max_lat)+ {+ return Err(Error(format!("--bbox is outside the world: {s}")));+ }+ Ok(bbox)+ }++ /// Inclusive on every edge, matching osmium: a node exactly on the boundary+ /// is inside.+ pub fn contains(&self, lon: f64, lat: f64) -> bool {+ self.contains_e7(to_e7(lat), to_e7(lon))+ }++ /// The same test against the 1e-7 integers the PBF decoder produces, which is+ /// what the hot paths have.+ ///+ /// Both entry points compare **integers**, not degrees. Going the other way+ /// -- widening `lat_e7` to a float and comparing against the parsed bounds --+ /// loses a coordinate that sits exactly on an edge: `1e-7` is not+ /// representable in binary, so `-1_226_000_000 * 1e-7` lands a hair below+ /// `-122.6` and falls out of a box whose western edge is exactly that. OSM+ /// coordinates are 1e-7 integers to begin with, so rounding the bounds into+ /// that space instead is both exact and the comparison the data deserves.+ pub fn contains_e7(&self, lat_e7: i32, lon_e7: i32) -> bool {+ lon_e7 >= to_e7(self.min_lon)+ && lon_e7 <= to_e7(self.max_lon)+ && lat_e7 >= to_e7(self.min_lat)+ && lat_e7 <= to_e7(self.max_lat)+ }+}++fn to_e7(deg: f64) -> i32 {+ (deg * 1e7).round() as i32+}++/// `true` when there is no box, or the point is inside it. The shape callers+/// actually want, since `--bbox` is optional everywhere.+pub fn keep_e7(bbox: Option<&BBox>, lat_e7: i32, lon_e7: i32) -> bool {+ bbox.is_none_or(|b| b.contains_e7(lat_e7, lon_e7))+}++#[cfg(test)]+mod tests {+ use super::*;++ const SF: &str = "-122.6,37.2,-121.7,37.9";++ #[test]+ fn parses_the_script_form() {+ let b = BBox::parse(SF).unwrap();+ assert_eq!(+ b,+ BBox {+ min_lon: -122.6,+ min_lat: 37.2,+ max_lon: -121.7,+ max_lat: 37.9,+ }+ );+ // Whitespace around the fields is tolerated.+ assert_eq!(BBox::parse(" -122.6 , 37.2 , -121.7 , 37.9 ").unwrap(), b);+ }++ #[test]+ fn rejects_malformed_boxes() {+ for bad in [+ "",+ "1,2,3",+ "1,2,3,4,5",+ "a,2,3,4",+ // Reversed rather than silently swapped: this is the lat/lon+ // transposition mistake, and normalising it hides a wrong extract.+ "-121.7,37.2,-122.6,37.9",+ "-122.6,37.9,-121.7,37.2",+ // Degenerate.+ "-122.6,37.2,-122.6,37.9",+ // Off the world.+ "-200,37.2,-121.7,37.9",+ "-122.6,-95,-121.7,37.9",+ ] {+ assert!(BBox::parse(bad).is_err(), "{bad:?} should not parse");+ }+ }++ #[test]+ fn containment_is_inclusive_on_every_edge() {+ let b = BBox::parse(SF).unwrap();+ assert!(b.contains(-122.4194, 37.7749)); // San Francisco+ assert!(b.contains(-122.6, 37.2)); // min corner+ assert!(b.contains(-121.7, 37.9)); // max corner+ assert!(!b.contains(-122.61, 37.7)); // just west+ assert!(!b.contains(-122.4, 38.0)); // just north+ assert!(!b.contains(-74.0, 40.7)); // New York+ }++ #[test]+ fn the_e7_path_agrees_with_the_float_path() {+ let b = BBox::parse(SF).unwrap();+ assert!(b.contains_e7(377_749_000, -1_224_194_000));+ assert!(!b.contains_e7(407_000_000, -740_000_000));+ // Exactly on both corners, expressed as integers. This is the case that+ // a float comparison gets wrong: -1_226_000_000 * 1e-7 is very slightly+ // west of -122.6, so the node falls out of its own bounding box.+ assert!(b.contains_e7(372_000_000, -1_226_000_000));+ assert!(b.contains_e7(379_000_000, -1_217_000_000));+ // One unit outside is outside.+ assert!(!b.contains_e7(372_000_000, -1_226_000_001));+ assert!(!b.contains_e7(371_999_999, -1_226_000_000));+ }++ #[test]+ fn no_box_keeps_everything() {+ assert!(keep_e7(None, 407_000_000, -740_000_000));+ let b = BBox::parse(SF).unwrap();+ assert!(!keep_e7(Some(&b), 407_000_000, -740_000_000));+ assert!(keep_e7(Some(&b), 377_749_000, -1_224_194_000));+ }+}
scripts/maps/osm_ingest/src/bin/osm_extract.rs
diff --git a/scripts/maps/osm_ingest/src/bin/osm_extract.rs b/scripts/maps/osm_ingest/src/bin/osm_extract.rsnew file mode 100644index 0000000000..63b9c30996--- /dev/null+++ b/scripts/maps/osm_ingest/src/bin/osm_extract.rs@@ -0,0 +1,58 @@+//! `osm_extract IN.osm.pbf --layer NAME --out FILE [--bbox BOX]`+//!+//! One 3-pass driver for the baked vector layers, replacing the+//! `osmium tags-filter | osmium export | normalize_*.py` chain for each of them.+//! See `osm_ingest::extract` for the pass ordering and each layer's own module+//! for its schema.++use std::process::ExitCode;++const USAGE: &str = "Usage: osm_extract IN.osm.pbf --layer NAME --out FILE [--bbox BOX]";++fn main() -> ExitCode {+ let argv: Vec<String> = std::env::args().skip(1).collect();+ let args = match osm_ingest::extract::parse_args(&argv) {+ Ok(v) => v,+ Err(e) => {+ eprintln!("error: {e}\n{USAGE}");+ eprintln!(+ "Layers: {}",+ osm_ingest::extract::Layer::names().join(", ")+ );+ return ExitCode::FAILURE;+ }+ };++ let options = osm_ingest::extract::Options {+ layer: args.layer,+ bbox: args.bbox,+ };+ let started = std::time::Instant::now();+ match osm_ingest::extract::build(&args.input, &args.out, &options) {+ Ok(stats) => {+ println!(+ "{}: {} feature(s) ({} node, {} way, {} relation) in {:.1}s",+ args.layer.name(),+ stats.features,+ stats.from_nodes,+ stats.from_ways,+ stats.from_relations,+ started.elapsed().as_secs_f64()+ );+ println!("Wrote {}", args.out.display());+ if stats.features == 0 {+ // Not an error -- an extract really can hold no cameras -- but an+ // empty layer is nearly always a wrong --bbox or a wrong PBF, and+ // the tiler downstream only warns about it.+ eprintln!(+ "WARNING: 0 features. Check --bbox and that the PBF covers the area."+ );+ }+ ExitCode::SUCCESS+ }+ Err(e) => {+ eprintln!("error: {e}");+ ExitCode::FAILURE+ }+ }+}
scripts/maps/osm_ingest/src/extract.rs
diff --git a/scripts/maps/osm_ingest/src/extract.rs b/scripts/maps/osm_ingest/src/extract.rsnew file mode 100644index 0000000000..ae543ca35a--- /dev/null+++ b/scripts/maps/osm_ingest/src/extract.rs@@ -0,0 +1,466 @@+//! Vector-layer extraction: `.osm.pbf` -> one geojsonseq per layer.+//!+//! The `osmium tags-filter | osmium export | normalize_*.py` chain, done in one+//! pass over the PBF with no external tools. Each layer's schema lives in its own+//! module ([`crate::safety`] and so on); this module owns the PBF traversal, the+//! bbox filter, the deterministic ordering and the output file.+//!+//! ## Pass ordering is fixed, and reversed+//!+//! Layers that need way or relation geometry cannot be done in one pass, because+//! a PBF stores nodes before the ways that reference them. So the traversal runs+//! **relations, then ways, then nodes** -- the reverse of the file order:+//!+//! 1. **Relations** decide which ways matter (a boundary's member ways, a route's+//! member ways).+//! 2. **Ways** decide which node coordinates matter -- both their own refs and the+//! refs of the ways relations claimed.+//! 3. **Nodes** supply those coordinates, and any node-based features.+//!+//! Only the passes a layer actually needs are run. `safety` is node-based, so it+//! runs one. The first pass to run is given `blob_kinds = None`, which is what+//! makes [`crate::pbf::run_pass`] build the per-blob kind mask that later passes+//! use to skip whole blobs.+//!+//! When way and relation layers land here, their node coordinates must be stored+//! the way [`crate::poi_build`] does it -- a sorted `Vec` of the needed ids plus an+//! index-aligned coordinate array, looked up by `binary_search` -- and **not** the+//! way [`crate::graph_build`] does it. That module allocates a bitset sized from+//! `BITSET_SIZE = 20e9`, i.e. 2.5 GB keyed by raw node id, and peaks around 10 GB+//! on California. The sorted-`Vec` form costs 16 bytes per *needed* node, which+//! for a selected subset is orders of magnitude smaller.++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::proto::{Error, Result};+use crate::safety::{self, Kind, SafetyTags};+use crate::select::Select;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Layer {+ Safety,+}++impl Layer {+ pub fn parse(s: &str) -> std::result::Result<Layer, String> {+ match s {+ "safety" => Ok(Layer::Safety),+ other => Err(format!(+ "unknown --layer '{other}'; supported: {}",+ Layer::names().join(", ")+ )),+ }+ }++ pub fn names() -> Vec<&'static str> {+ vec!["safety"]+ }++ pub fn name(self) -> &'static str {+ match self {+ Layer::Safety => "safety",+ }+ }+}++pub struct Options {+ pub layer: Layer,+ pub bbox: Option<BBox>,+}++#[derive(Debug, Default, PartialEq)]+pub struct Stats {+ pub features: usize,+ pub from_nodes: usize,+ pub from_ways: usize,+ pub from_relations: usize,+ /// Classified, but outside `--bbox`. Reported so an empty layer can be told+ /// apart from a badly placed box.+ pub outside_bbox: usize,+}++pub fn build(input: &Path, out: &Path, opts: &Options) -> Result<Stats> {+ // Fail before the passes rather than after them if the output is unwritable.+ if let Some(parent) = out.parent().filter(|p| !p.as_os_str().is_empty()) {+ std::fs::create_dir_all(parent)+ .map_err(|e| Error(format!("cannot create {}: {e}", parent.display())))?;+ }++ let blobs = pbf::scan_blobs(input)?;+ println!("Scanned {} data blob(s) in {}", blobs.len(), input.display());++ match opts.layer {+ Layer::Safety => build_safety(input, &blobs, out, opts),+ }+}++// --- safety ---------------------------------------------------------------++/// One classified node, with the attributes it carries copied out of the block.+///+/// The pass borrows tag values from the `PrimitiveBlock` it is reading, which is+/// dropped when the blob is, so anything kept has to be owned.+struct SafetyRow {+ lat_e7: i32,+ lon_e7: i32,+ id: i64,+ kind: Kind,+ name: Option<String>,+ direction: Option<String>,+ operator: Option<String>,+ reference: Option<String>,+ surveillance_type: Option<String>,+}++#[derive(Default)]+struct SafetyPass {+ rows: Vec<SafetyRow>,+ outside_bbox: usize,+}++fn build_safety(+ input: &Path,+ blobs: &[pbf::BlobLoc],+ out: &Path,+ opts: &Options,+) -> Result<Stats> {+ // The `osmium tags-filter` expression this layer used, as a cheap screen: it+ // reads three tags to reject almost every node, instead of the ten the+ // classifier and the property builder would read between them. Tag lookup is+ // a linear scan, so that matters at planet scale.+ let select = Select::parse(&safety::FILTERS)?;+ let bbox = opts.bbox.as_ref();++ let (chunks, _) = pbf::run_pass(+ input,+ blobs,+ None,+ KIND_NODES,+ "Pass 1: nodes",+ SafetyPass::default,+ |state, block| safety_blob(state, block, &select, bbox),+ )?;++ let mut rows: Vec<SafetyRow> = Vec::new();+ let mut outside_bbox = 0usize;+ for chunk in chunks {+ rows.extend(chunk.rows);+ outside_bbox += chunk.outside_bbox;+ }++ // Deterministic order, so two runs of the same input are byte-identical and a+ // diff against the previous build shows only real changes. Position first+ // keeps features that are near each other near each other in the file, which+ // is what the tiler wants; the id only breaks ties.+ rows.sort_by_key(|r| (r.lat_e7, r.lon_e7, r.id));++ let mut writer = BufWriter::new(create(out)?);+ let mut line: Vec<u8> = Vec::new();+ for row in &rows {+ let tags = SafetyTags {+ name: row.name.as_deref(),+ direction: row.direction.as_deref(),+ operator: row.operator.as_deref(),+ reference: row.reference.as_deref(),+ surveillance_type: row.surveillance_type.as_deref(),+ ..Default::default()+ };+ let f: Feature = safety::feature(+ row.kind,+ &tags,+ row.lon_e7 as f64 * 1e-7,+ row.lat_e7 as f64 * 1e-7,+ row.id,+ );+ geojson::write_feature(&mut writer, &f, &mut line).map_err(io_err)?;+ }+ writer.flush().map_err(io_err)?;++ println!(+ "Wrote {} safety feature(s) to {}",+ rows.len(),+ out.display()+ );+ if outside_bbox > 0 {+ println!("{outside_bbox} feature(s) dropped by --bbox");+ }+ Ok(Stats {+ features: rows.len(),+ from_nodes: rows.len(),+ from_ways: 0,+ from_relations: 0,+ outside_bbox,+ })+}++fn safety_blob(+ state: &mut SafetyPass,+ block: &pbf::PrimitiveBlock,+ select: &Select,+ bbox: Option<&BBox>,+) -> Result<u8> {+ let mut kinds = 0u8;+ visit_block(block, KIND_NODES, &mut kinds, &mut |el: Element| {+ if let Element::Node(n) = el {+ if n.tags.is_empty() {+ return Ok(());+ }+ if !select.matches(|k| n.tags.get_str(k)) {+ return Ok(());+ }+ let t = SafetyTags {+ highway: n.tags.get_str("highway"),+ man_made: n.tags.get_str("man_made"),+ enforcement: n.tags.get_str("enforcement"),+ surveillance_type: n.tags.get_str("surveillance:type"),+ camera_type: n.tags.get_str("camera:type"),+ operator: n.tags.get_str("operator"),+ manufacturer: n.tags.get_str("manufacturer"),+ name: n.tags.get_str("name"),+ direction: n.tags.get_str("direction"),+ reference: n.tags.get_str("ref"),+ };+ let Some(kind) = safety::classify(&t) else {+ return Ok(());+ };+ // Counted after classification, so the number means "safety features+ // outside the box" rather than "nodes outside the box".+ if !bbox::keep_e7(bbox, n.lat_e7, n.lon_e7) {+ state.outside_bbox += 1;+ return Ok(());+ }+ state.rows.push(SafetyRow {+ lat_e7: n.lat_e7,+ lon_e7: n.lon_e7,+ id: n.id,+ kind,+ name: t.name.map(str::to_string),+ direction: t.direction.map(str::to_string),+ operator: t.operator.map(str::to_string),+ reference: t.reference.map(str::to_string),+ surveillance_type: t.surveillance_type.map(str::to_string),+ });+ }+ Ok(())+ })?;+ Ok(kinds)+}++fn create(path: &Path) -> Result<File> {+ File::create(path).map_err(|e| Error(format!("cannot write {}: {e}", path.display())))+}++fn io_err(e: std::io::Error) -> Error {+ Error(e.to_string())+}++// --- CLI ------------------------------------------------------------------++pub struct Args {+ pub input: PathBuf,+ pub out: PathBuf,+ pub layer: Layer,+ pub bbox: Option<BBox>,+}++/// `osm_extract IN.osm.pbf --layer NAME --out FILE [--bbox BOX]`+pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> {+ let mut input: Option<PathBuf> = None;+ let mut out: Option<PathBuf> = None;+ let mut layer: Option<Layer> = None;+ let mut bbox: Option<BBox> = None;+ let mut i = 0;+ while i < args.len() {+ match args[i].as_str() {+ flag @ ("--out" | "--layer" | "--bbox") => {+ i += 1;+ let value = args+ .get(i)+ .ok_or_else(|| format!("{flag} needs a value"))?+ .as_str();+ match flag {+ "--out" => out = Some(PathBuf::from(value)),+ "--layer" => layer = Some(Layer::parse(value)?),+ _ => bbox = Some(BBox::parse(value).map_err(|e| e.0)?),+ }+ }+ a if a.starts_with('-') => return Err(format!("unknown option: {a}")),+ a => {+ if input.is_some() {+ return Err(format!("unexpected extra argument: {a}"));+ }+ input = Some(PathBuf::from(a));+ }+ }+ i += 1;+ }+ Ok(Args {+ input: input.ok_or_else(|| "missing IN.osm.pbf".to_string())?,+ out: out.ok_or_else(|| "--out is required".to_string())?,+ layer: layer.ok_or_else(|| "--layer is required".to_string())?,+ bbox,+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::testpbf;++ fn features(path: &Path) -> Vec<String> {+ std::fs::read_to_string(path)+ .unwrap()+ .lines()+ .map(str::to_string)+ .collect()+ }++ #[test]+ fn extracts_the_safety_layer_from_a_pbf() {+ let (pbf_path, dir) = testpbf::write_layers_sample("extract_safety");+ let out = dir.join("safety.geojsonseq");+ let stats = build(+ &pbf_path,+ &out,+ &Options {+ layer: Layer::Safety,+ bbox: None,+ },+ )+ .unwrap();++ // The fixture's four safety nodes: a speed camera, an ALPR, a stop sign+ // and traffic signals. Everything else in it belongs to other layers.+ assert_eq!(stats.features, 4);+ assert_eq!(stats.from_nodes, 4);+ assert_eq!((stats.from_ways, stats.from_relations), (0, 0));++ let lines = features(&out);+ assert_eq!(lines.len(), 4);+ let kinds: Vec<&str> = ["speed_camera", "alpr", "stop_sign", "traffic_signals"]+ .into_iter()+ .filter(|k| lines.iter().any(|l| l.contains(&format!("\"kind\":\"{k}\""))))+ .collect();+ assert_eq!(kinds, ["speed_camera", "alpr", "stop_sign", "traffic_signals"]);++ // Every line is a Point Feature with an osm_id in the node/N form.+ for l in &lines {+ assert!(l.starts_with("{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\""), "{l}");+ assert!(l.contains("\"osm_id\":\"node/"), "{l}");+ }++ // The ALPR node keeps its operator and surveillance_type.+ let alpr = lines.iter().find(|l| l.contains("\"alpr\"")).unwrap();+ assert!(alpr.contains("\"operator\":\"Flock Safety\""), "{alpr}");+ assert!(alpr.contains("\"surveillance_type\":\"ALPR\""), "{alpr}");++ // The cafe node has a name and tags, but is not road furniture.+ assert!(!lines.iter().any(|l| l.contains("Corner Cafe")));+ }++ #[test]+ fn two_runs_are_byte_identical() {+ let (pbf_path, dir) = testpbf::write_layers_sample("extract_det");+ let run = |suffix: &str| {+ let out = dir.join(format!("safety{suffix}.geojsonseq"));+ build(+ &pbf_path,+ &out,+ &Options {+ layer: Layer::Safety,+ bbox: None,+ },+ )+ .unwrap();+ std::fs::read(out).unwrap()+ };+ assert_eq!(run("a"), run("b"));+ }++ #[test]+ fn a_bbox_that_excludes_everything_yields_an_empty_layer() {+ let (pbf_path, dir) = testpbf::write_layers_sample("extract_bbox");+ let out = dir.join("safety.geojsonseq");+ // The fixture sits near 37N 122W; this box is over the Atlantic.+ let stats = build(+ &pbf_path,+ &out,+ &Options {+ layer: Layer::Safety,+ bbox: Some(BBox::parse("-30,20,-20,30").unwrap()),+ },+ )+ .unwrap();+ assert_eq!(stats.features, 0);+ // The count says "4 safety features were outside the box", which is what+ // distinguishes a bad bbox from a PBF with no cameras in it.+ assert_eq!(stats.outside_bbox, 4);+ assert_eq!(features(&out).len(), 0);+ }++ #[test]+ fn a_bbox_that_includes_everything_changes_nothing() {+ let (pbf_path, dir) = testpbf::write_layers_sample("extract_bbox_all");+ let out = dir.join("safety.geojsonseq");+ let stats = build(+ &pbf_path,+ &out,+ &Options {+ layer: Layer::Safety,+ bbox: Some(BBox::parse("-123,36,-121,38").unwrap()),+ },+ )+ .unwrap();+ assert_eq!(stats.features, 4);+ assert_eq!(stats.outside_bbox, 0);+ }++ #[test]+ fn args_need_a_layer_and_an_out() {+ let ok = parse_args(&[+ "in.pbf".into(),+ "--layer".into(),+ "safety".into(),+ "--out".into(),+ "s.geojsonseq".into(),+ "--bbox".into(),+ "-122.6,37.2,-121.7,37.9".into(),+ ])+ .unwrap();+ assert_eq!(ok.input, PathBuf::from("in.pbf"));+ assert_eq!(ok.layer, Layer::Safety);+ assert!(ok.bbox.is_some());++ assert!(parse_args(&["in.pbf".into()]).is_err());+ assert!(parse_args(&["in.pbf".into(), "--layer".into(), "safety".into()]).is_err());+ assert!(parse_args(&["--layer".into(), "safety".into(), "--out".into(), "o".into()]).is_err());+ // A bad layer name names the ones that do exist.+ let err = parse_args(&[+ "in.pbf".into(),+ "--layer".into(),+ "nope".into(),+ "--out".into(),+ "o".into(),+ ])+ .map(|_| ())+ .unwrap_err();+ assert!(err.contains("safety"), "{err}");+ // A malformed bbox is rejected here, not silently ignored.+ assert!(parse_args(&[+ "in.pbf".into(),+ "--layer".into(),+ "safety".into(),+ "--out".into(),+ "o".into(),+ "--bbox".into(),+ "1,2,3".into(),+ ])+ .is_err());+ }+}
scripts/maps/osm_ingest/src/geojson.rs
diff --git a/scripts/maps/osm_ingest/src/geojson.rs b/scripts/maps/osm_ingest/src/geojson.rsnew file mode 100644index 0000000000..0e00d1abb9--- /dev/null+++ b/scripts/maps/osm_ingest/src/geojson.rs@@ -0,0 +1,318 @@+//! Shared GeoJSON writer for the extracted vector layers.+//!+//! The layer extractors emit newline-delimited GeoJSON (geojsonseq), which is+//! what the tilers read. This module is the single place that turns geometry and+//! properties into bytes, so every layer produces the same shape.+//!+//! ## Matching the Python normalisers+//!+//! The pipeline this replaces ended in+//! `json.dumps(feature, separators=(",", ":"), ensure_ascii=False)`, so:+//!+//! * Key order is `type`, `geometry`, `properties`, and properties are written in+//! the order the caller lists them. GeoJSON objects are unordered by spec, but+//! fixing the order is what makes two runs byte-identical and a diff readable.+//! * No whitespace anywhere: `,` and `:` separate, nothing else.+//! * Non-ASCII passes through as UTF-8 rather than becoming `\uXXXX`, which is+//! what `ensure_ascii=False` does. Only the JSON-mandatory escapes and C0+//! controls are rewritten.+//!+//! One deliberate difference: coordinates are written with a fixed 7 decimal+//! places, matching `poi_build`, where Python wrote the shortest round-tripping+//! representation. `-122.4194` therefore comes out as `-122.4194000`. The values+//! are identical once parsed -- OSM coordinates are 1e-7 integers, so 7 places is+//! exact -- and the differential harness compares parsed numbers, not bytes.++use std::io::{self, Write};++/// A coordinate pair in GeoJSON order: longitude, then latitude.+pub type Coord = (f64, f64);++/// The geometry shapes the extracted layers produce.+///+/// `Polygon` and `MultiPolygon` carry rings as the spec orders them: the exterior+/// ring first, then its holes.+pub enum Geometry {+ Point(Coord),+ LineString(Vec<Coord>),+ MultiLineString(Vec<Vec<Coord>>),+ Polygon(Vec<Vec<Coord>>),+ MultiPolygon(Vec<Vec<Vec<Coord>>>),+}++impl Geometry {+ pub fn type_name(&self) -> &'static str {+ match self {+ Geometry::Point(_) => "Point",+ Geometry::LineString(_) => "LineString",+ Geometry::MultiLineString(_) => "MultiLineString",+ Geometry::Polygon(_) => "Polygon",+ Geometry::MultiPolygon(_) => "MultiPolygon",+ }+ }++ /// True when there is nothing to draw. An empty geometry is never emitted:+ /// tippecanoe and our own tilers both treat it as a feature that vanishes at+ /// render time, which is worse than not being in the file.+ pub fn is_empty(&self) -> bool {+ match self {+ Geometry::Point(_) => false,+ Geometry::LineString(l) => l.len() < 2,+ Geometry::MultiLineString(ls) => ls.iter().all(|l| l.len() < 2),+ Geometry::Polygon(rings) => rings.first().is_none_or(|r| r.len() < 4),+ Geometry::MultiPolygon(polys) => polys+ .iter()+ .all(|rings| rings.first().is_none_or(|r| r.len() < 4)),+ }+ }+}++/// A property value.+pub enum Value {+ /// A JSON string. Escaped on write; UTF-8 bytes pass through.+ Str(Vec<u8>),+ /// A pre-rendered JSON literal (a number, `true`/`false`/`null`), written+ /// verbatim. Rendering numbers at the call site keeps this module out of the+ /// business of deciding a layer's numeric formatting.+ Raw(String),+}++impl Value {+ pub fn str(s: impl AsRef<[u8]>) -> Value {+ Value::Str(s.as_ref().to_vec())+ }++ pub fn num(n: impl std::fmt::Display) -> Value {+ Value::Raw(n.to_string())+ }+}++pub struct Feature<'a> {+ pub geometry: Geometry,+ pub props: Vec<(&'a str, Value)>,+}++/// Escape a string for a JSON string literal. UTF-8 bytes pass through verbatim;+/// only the JSON-mandatory escapes and C0 controls are rewritten.+pub fn json_escape(s: &[u8], out: &mut Vec<u8>) {+ for &c in s {+ match c {+ b'"' => out.extend_from_slice(b"\\\""),+ b'\\' => out.extend_from_slice(b"\\\\"),+ b'\n' => out.extend_from_slice(b"\\n"),+ b'\r' => out.extend_from_slice(b"\\r"),+ b'\t' => out.extend_from_slice(b"\\t"),+ c if c < 0x20 => out.extend_from_slice(format!("\\u{c:04x}").as_bytes()),+ c => out.push(c),+ }+ }+}++/// Render one feature into `line`, which is cleared first, and terminate it with+/// a newline. Reusing one buffer across a whole layer avoids a per-feature+/// allocation.+pub fn render_feature(f: &Feature, line: &mut Vec<u8>) {+ line.clear();+ line.extend_from_slice(b"{\"type\":\"Feature\",\"geometry\":{\"type\":\"");+ line.extend_from_slice(f.geometry.type_name().as_bytes());+ line.extend_from_slice(b"\",\"coordinates\":");+ write_coords(&f.geometry, line);+ line.extend_from_slice(b"},\"properties\":{");+ for (i, (key, value)) in f.props.iter().enumerate() {+ if i > 0 {+ line.push(b',');+ }+ line.push(b'"');+ json_escape(key.as_bytes(), line);+ line.extend_from_slice(b"\":");+ match value {+ Value::Str(s) => {+ line.push(b'"');+ json_escape(s, line);+ line.push(b'"');+ }+ Value::Raw(r) => line.extend_from_slice(r.as_bytes()),+ }+ }+ line.extend_from_slice(b"}}\n");+}++pub fn write_feature<W: Write>(out: &mut W, f: &Feature, line: &mut Vec<u8>) -> io::Result<()> {+ render_feature(f, line);+ out.write_all(line)+}++fn write_coord((lon, lat): Coord, out: &mut Vec<u8>) {+ // `write!` into a Vec<u8> is infallible.+ let _ = write!(out, "[{lon:.7},{lat:.7}]");+}++fn write_ring(ring: &[Coord], out: &mut Vec<u8>) {+ out.push(b'[');+ for (i, c) in ring.iter().enumerate() {+ if i > 0 {+ out.push(b',');+ }+ write_coord(*c, out);+ }+ out.push(b']');+}++fn write_rings(rings: &[Vec<Coord>], out: &mut Vec<u8>) {+ out.push(b'[');+ for (i, r) in rings.iter().enumerate() {+ if i > 0 {+ out.push(b',');+ }+ write_ring(r, out);+ }+ out.push(b']');+}++fn write_coords(g: &Geometry, out: &mut Vec<u8>) {+ match g {+ Geometry::Point(c) => write_coord(*c, out),+ Geometry::LineString(l) => write_ring(l, out),+ Geometry::MultiLineString(ls) => write_rings(ls, out),+ Geometry::Polygon(rings) => write_rings(rings, out),+ Geometry::MultiPolygon(polys) => {+ out.push(b'[');+ for (i, rings) in polys.iter().enumerate() {+ if i > 0 {+ out.push(b',');+ }+ write_rings(rings, out);+ }+ out.push(b']');+ }+ }+}++/// An OSM element reference in the `node/123` form the normalisers emitted, and+/// which the app and the differential harness pair features on.+pub fn osm_ref(kind: &str, id: i64) -> Value {+ Value::Str(format!("{kind}/{id}").into_bytes())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn render(f: &Feature) -> String {+ let mut line = Vec::new();+ render_feature(f, &mut line);+ String::from_utf8(line).unwrap()+ }++ #[test]+ fn a_point_feature_matches_the_python_shape() {+ // Exactly what json.dumps(..., separators=(",", ":"), ensure_ascii=False)+ // produced: no whitespace, key order type/geometry/properties.+ let f = Feature {+ geometry: Geometry::Point((-122.4194, 37.7749)),+ props: vec![+ ("kind", Value::str("speed_camera")),+ ("direction", Value::str("forward")),+ ("osm_id", osm_ref("node", 1001)),+ ],+ };+ assert_eq!(+ render(&f),+ "{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\+ \"coordinates\":[-122.4194000,37.7749000]},\"properties\":\+ {\"kind\":\"speed_camera\",\"direction\":\"forward\",\+ \"osm_id\":\"node/1001\"}}\n"+ );+ }++ #[test]+ fn numbers_are_written_verbatim() {+ let f = Feature {+ geometry: Geometry::Point((0.0, 0.0)),+ props: vec![("type", Value::num(12u16)), ("osm_id", Value::num(-200i64))],+ };+ assert!(render(&f).contains("\"type\":12,\"osm_id\":-200"));+ }++ #[test]+ fn lines_and_polygons_nest_correctly() {+ let line = Feature {+ geometry: Geometry::LineString(vec![(-122.42, 37.77), (-122.41, 37.78)]),+ props: vec![],+ };+ assert!(render(&line).contains(+ "\"coordinates\":[[-122.4200000,37.7700000],[-122.4100000,37.7800000]]"+ ));++ let multi = Feature {+ geometry: Geometry::MultiLineString(vec![vec![(0.0, 0.0), (1.0, 1.0)]]),+ props: vec![],+ };+ assert!(render(&multi)+ .contains("\"coordinates\":[[[0.0000000,0.0000000],[1.0000000,1.0000000]]]"));++ // A polygon's exterior ring comes first, then its holes.+ let poly = Feature {+ geometry: Geometry::Polygon(vec![+ vec![(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0), (0.0, 0.0)],+ vec![(0.5, 0.5), (1.5, 0.5), (1.5, 1.5), (0.5, 1.5), (0.5, 0.5)],+ ]),+ props: vec![],+ };+ let s = render(&poly);+ assert!(s.contains("\"type\":\"Polygon\""));+ assert!(+ s.find("0.5000000").unwrap() > s.find("2.0000000").unwrap(),+ "the hole must be written after the exterior ring: {s}"+ );+ }++ #[test]+ fn empty_properties_still_produce_a_valid_object() {+ let f = Feature {+ geometry: Geometry::Point((1.0, 2.0)),+ props: vec![],+ };+ assert!(render(&f).ends_with("\"properties\":{}}\n"));+ }++ #[test]+ fn json_escapes_only_what_it_must() {+ let mut out = Vec::new();+ json_escape("Ben \"B\" \\ Jerry\n\tCafé".as_bytes(), &mut out);+ assert_eq!(+ String::from_utf8(out).unwrap(),+ "Ben \\\"B\\\" \\\\ Jerry\\n\\tCafé"+ );+ let mut out = Vec::new();+ json_escape(&[0x01, 0x1f], &mut out);+ assert_eq!(String::from_utf8(out).unwrap(), "\\u0001\\u001f");+ }++ #[test]+ fn a_name_with_a_quote_survives_a_round_trip_through_the_writer() {+ let f = Feature {+ geometry: Geometry::Point((0.0, 0.0)),+ props: vec![("name", Value::str("Joe's \"Diner\""))],+ };+ assert!(render(&f).contains("\"name\":\"Joe's \\\"Diner\\\"\""));+ }++ #[test]+ fn emptiness_is_judged_per_geometry_kind() {+ assert!(!Geometry::Point((0.0, 0.0)).is_empty());+ assert!(Geometry::LineString(vec![(0.0, 0.0)]).is_empty());+ assert!(!Geometry::LineString(vec![(0.0, 0.0), (1.0, 1.0)]).is_empty());+ assert!(Geometry::MultiLineString(vec![vec![(0.0, 0.0)]]).is_empty());+ // A ring needs 4 points: three distinct corners plus the repeated close.+ assert!(Geometry::Polygon(vec![vec![(0.0, 0.0), (1.0, 0.0), (0.0, 0.0)]]).is_empty());+ assert!(!Geometry::Polygon(vec![vec![+ (0.0, 0.0),+ (1.0, 0.0),+ (1.0, 1.0),+ (0.0, 0.0)+ ]])+ .is_empty());+ assert!(Geometry::MultiPolygon(vec![]).is_empty());+ }+}
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 5dbee617e7..14aa5512d3 100644--- a/scripts/maps/osm_ingest/src/lib.rs+++ b/scripts/maps/osm_ingest/src/lib.rs@@ -1,17 +1,24 @@ //! Host-side OSM ingest for the Maps offline packs. //!-//! Two tools share this library:+//! Three tools share this library: //! //! * `road_graph` — the routing graph (`metadata.bin`, `nodes.bin`, `edges.bin`, //! `lanes.bin`, `road_names.bin`), consumed by //! `maps/src/main/rust/src/graph.rs`. //! * `poi_extract` — the `ma_pois` layer's geojsonseq plus `poi_names.bin` and //! `poi_index.bin`, consumed by `PoiIndex.kt`.+//! * `osm_extract` — one geojsonseq per baked vector layer, replacing the+//! `osmium tags-filter | osmium export | normalize_*.py` chain. See+//! [`extract`]. //!-//! Both used to be C++ built against libosmium, which meant they only ran under-//! WSL. Reading `.osm.pbf` directly — a hand-rolled protobuf decoder plus a-//! pure-Rust inflate — makes them native on every platform the app is built on.+//! The first two used to be C++ built against libosmium, which meant they only+//! ran under WSL. Reading `.osm.pbf` directly — a hand-rolled protobuf decoder+//! 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 bbox;+pub mod extract;+pub mod geojson; pub mod graph_build; pub mod names; pub mod osm;@@ -19,6 +26,8 @@ pub mod par; pub mod pbf; pub mod poi_build; pub mod proto;+pub mod safety;+pub mod select; pub mod spatial; pub mod tags;
scripts/maps/osm_ingest/src/poi_build.rs
diff --git a/scripts/maps/osm_ingest/src/poi_build.rs b/scripts/maps/osm_ingest/src/poi_build.rsindex 93ec3f5bc9..289bf62fd7 100644--- a/scripts/maps/osm_ingest/src/poi_build.rs+++ b/scripts/maps/osm_ingest/src/poi_build.rs@@ -36,6 +36,7 @@ use std::fs::File; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; +use crate::geojson::json_escape; use crate::names::NamePool; use crate::osm::{self, visit_block, Element, MEMBER_WAY}; use crate::pbf::{self, KIND_NODES, KIND_RELATIONS, KIND_WAYS};@@ -455,22 +456,6 @@ fn write_outputs( Ok((pois.len(), unique, bytes)) } -/// Escape a name for a JSON string. UTF-8 bytes pass through verbatim; only the-/// JSON-mandatory escapes and C0 controls are rewritten.-fn json_escape(s: &[u8], out: &mut Vec<u8>) {- for &c in s {- match c {- b'"' => out.extend_from_slice(b"\\\""),- b'\\' => out.extend_from_slice(b"\\\\"),- b'\n' => out.extend_from_slice(b"\\n"),- b'\r' => out.extend_from_slice(b"\\r"),- b'\t' => out.extend_from_slice(b"\\t"),- c if c < 0x20 => out.extend_from_slice(format!("\\u{c:04x}").as_bytes()),- c => out.push(c),- }- }-}- fn create(path: &Path) -> Result<File> { File::create(path).map_err(|e| Error(format!("cannot write {}: {e}", path.display()))) }@@ -692,19 +677,6 @@ mod tests { } } - #[test]- fn json_escapes_only_what_it_must() {- let mut out = Vec::new();- json_escape("Ben \"B\" \\ Jerry\n\tCafé".as_bytes(), &mut out);- assert_eq!(- String::from_utf8(out).unwrap(),- "Ben \\\"B\\\" \\\\ Jerry\\n\\tCafé"- );- let mut out = Vec::new();- json_escape(&[0x01, 0x1f], &mut out);- assert_eq!(String::from_utf8(out).unwrap(), "\\u0001\\u001f");- }- #[test] fn args_require_all_three_outputs() { let ok = parse_args(&[
scripts/maps/osm_ingest/src/safety.rs
diff --git a/scripts/maps/osm_ingest/src/safety.rs b/scripts/maps/osm_ingest/src/safety.rsnew file mode 100644index 0000000000..244ee56823--- /dev/null+++ b/scripts/maps/osm_ingest/src/safety.rs@@ -0,0 +1,484 @@+//! The `safety` layer: baked road furniture -- speed cameras, ALPR, generic+//! surveillance, stop signs and traffic signals.+//!+//! A port of `normalize_safety.py`, which is the contract of record. Everything+//! here is node-based; `osmium export` produced the odd tagged way with these+//! tags, and the Python dropped anything that was not a `Point`, so we only ever+//! look at nodes.+//!+//! ## The classification order is load-bearing+//!+//! It is a chain of early returns, not a set of independent rules:+//!+//! 1. `highway=speed_camera`+//! 2. `enforcement=maxspeed` -- **before** the surveillance branch. A camera+//! tagged both `man_made=surveillance` and `enforcement=maxspeed` is a speed+//! camera, not a surveillance camera, and reordering these two silently+//! reclassifies a whole category.+//! 3. `man_made=surveillance`, split into `alpr` or `surveillance`+//! 4. `highway=stop`+//! 5. `highway=traffic_signals`+//!+//! ## The ALPR heuristic is deliberately asymmetric+//!+//! DeFlock (deflock.me) tags automated licence-plate readers as+//! `man_made=surveillance` plus `surveillance:type=ALPR`, and Flock Safety is the+//! dominant operator and manufacturer. So:+//!+//! * `surveillance:type` is matched by **substring**, because real values include+//! things like `ALPR;camera` and `traffic ANPR`.+//! * `camera:type` is matched by **exact equality** against `alpr`/`anpr`,+//! because it is an enumerated field whose other values (`fixed`, `dome`,+//! `panning`) would be corrupted by a substring rule.+//! * `operator` and `manufacturer` are matched by substring on `flock`, catching+//! "Flock Safety", "Flock Safety LLC" and so on.+//!+//! That asymmetry is not an oversight in the Python and must survive the port.++use crate::geojson::{osm_ref, Feature, Geometry, Value};++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Kind {+ SpeedCamera,+ Alpr,+ Surveillance,+ StopSign,+ TrafficSignals,+}++impl Kind {+ pub fn as_str(self) -> &'static str {+ match self {+ Kind::SpeedCamera => "speed_camera",+ Kind::Alpr => "alpr",+ Kind::Surveillance => "surveillance",+ Kind::StopSign => "stop_sign",+ Kind::TrafficSignals => "traffic_signals",+ }+ }+}++/// The keys `osmium tags-filter` narrowed on, and which therefore have to be in+/// the PBF pre-filter for this layer.+pub const FILTERS: [&str; 3] = [+ "highway=speed_camera,stop,traffic_signals",+ "man_made=surveillance",+ "enforcement=maxspeed",+];++/// Just the tags this layer reads, in the plain `Option<&str>` shape+/// [`crate::tags`] uses, so classification is testable with no PBF.+#[derive(Debug, Default, Clone, Copy)]+pub struct SafetyTags<'a> {+ pub highway: Option<&'a str>,+ pub man_made: Option<&'a str>,+ pub enforcement: Option<&'a str>,+ pub surveillance_type: Option<&'a str>,+ pub camera_type: Option<&'a str>,+ pub operator: Option<&'a str>,+ pub manufacturer: Option<&'a str>,+ pub name: Option<&'a str>,+ pub direction: Option<&'a str>,+ pub reference: Option<&'a str>,+}++/// `normalize_safety.py`'s `_truthy`: absent, empty, and the three "no" spellings+/// all count as missing, so a `direction=no` never reaches the layer.+pub fn truthy(v: Option<&str>) -> bool {+ !matches!(v, None | Some("") | Some("no") | Some("false") | Some("0"))+}++pub fn classify(t: &SafetyTags) -> Option<Kind> {+ if t.highway == Some("speed_camera") {+ return Some(Kind::SpeedCamera);+ }+ // A node on an enforcement=maxspeed relation is often tagged directly, and+ // this must be checked before the surveillance branch below.+ if t.enforcement == Some("maxspeed") {+ return Some(Kind::SpeedCamera);+ }++ if t.man_made == Some("surveillance") {+ let surv = t.surveillance_type.unwrap_or("").to_lowercase();+ let cam = t.camera_type.unwrap_or("").to_lowercase();+ let operator = t.operator.unwrap_or("").to_lowercase();+ let manufacturer = t.manufacturer.unwrap_or("").to_lowercase();+ let is_alpr = surv.contains("alpr")+ || surv.contains("anpr")+ || cam == "alpr"+ || cam == "anpr"+ || operator.contains("flock")+ || manufacturer.contains("flock");+ return Some(if is_alpr { Kind::Alpr } else { Kind::Surveillance });+ }++ if t.highway == Some("stop") {+ return Some(Kind::StopSign);+ }+ if t.highway == Some("traffic_signals") {+ return Some(Kind::TrafficSignals);+ }+ None+}++/// Build the emitted feature. Property order matches the Python's insertion+/// order: `kind`, then the carried attributes, then `osm_id`.+pub fn feature<'a>(kind: Kind, t: &SafetyTags<'a>, lon: f64, lat: f64, node_id: i64) -> Feature<'a> {+ let mut props: Vec<(&'a str, Value)> = vec![("kind", Value::str(kind.as_str()))];+ for (key, value) in [+ ("name", t.name),+ ("direction", t.direction),+ ("operator", t.operator),+ ("ref", t.reference),+ ("surveillance_type", t.surveillance_type),+ ] {+ if truthy(value) {+ props.push((key, Value::str(value.unwrap())));+ }+ }+ // Always a string, as the Python's `str(osm_id)` made it, and always the+ // `node/N` form the harness pairs features on.+ props.push(("osm_id", osm_ref("node", node_id)));+ Feature {+ geometry: Geometry::Point((lon, lat)),+ props,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// The nine features of `scripts/maps/test/fixtures/safety_sample.geojsonseq`,+ /// transcribed as tag sets.+ ///+ /// The fixture is GeoJSON, which this crate has no reader for and does not+ /// want one -- it reads PBF. What the fixture actually pins is the tag-to-kind+ /// mapping, so the tags are what gets mirrored, and the assertions below are+ /// the twelve `test_normalize.py::test_safety` checks one for one.+ fn fixture() -> Vec<(&'static str, SafetyTags<'static>, bool)> {+ vec![+ // node/1001 -- highway=speed_camera with a direction.+ (+ "node/1001",+ SafetyTags {+ highway: Some("speed_camera"),+ direction: Some("forward"),+ ..Default::default()+ },+ true,+ ),+ // node/1002 -- enforcement=maxspeed, the second route to speed_camera.+ (+ "node/1002",+ SafetyTags {+ enforcement: Some("maxspeed"),+ ..Default::default()+ },+ true,+ ),+ // node/1003 -- surveillance:type=ALPR, operator Flock Safety.+ (+ "node/1003",+ SafetyTags {+ man_made: Some("surveillance"),+ surveillance_type: Some("ALPR"),+ operator: Some("Flock Safety"),+ ..Default::default()+ },+ true,+ ),+ // node/1004 -- ALPR via camera:type instead.+ (+ "node/1004",+ SafetyTags {+ man_made: Some("surveillance"),+ camera_type: Some("alpr"),+ ..Default::default()+ },+ true,+ ),+ // node/1005 -- a plain surveillance camera.+ (+ "node/1005",+ SafetyTags {+ man_made: Some("surveillance"),+ camera_type: Some("fixed"),+ ..Default::default()+ },+ true,+ ),+ // node/1006 -- a stop sign.+ (+ "node/1006",+ SafetyTags {+ highway: Some("stop"),+ ..Default::default()+ },+ true,+ ),+ // node/1007 -- traffic signals.+ (+ "node/1007",+ SafetyTags {+ highway: Some("traffic_signals"),+ ..Default::default()+ },+ true,+ ),+ // node/1008 -- a cafe. Not safety furniture.+ (+ "node/1008",+ SafetyTags {+ name: Some("Corner Cafe"),+ ..Default::default()+ },+ false,+ ),+ // way/1009 -- highway=stop on a LineString. Classifies, but the+ // geometry filter drops it, which is why `emitted` is false.+ (+ "way/1009",+ SafetyTags {+ highway: Some("stop"),+ ..Default::default()+ },+ false,+ ),+ ]+ }++ /// The kinds the layer emits for the fixture, i.e. after both the+ /// classification and the Point-only geometry filter.+ fn fixture_kinds() -> Vec<Kind> {+ fixture()+ .iter()+ .filter(|(_, _, emitted)| *emitted)+ .filter_map(|(_, t, _)| classify(t))+ .collect()+ }++ fn count(kinds: &[Kind], want: Kind) -> usize {+ kinds.iter().filter(|k| **k == want).count()+ }++ #[test]+ fn emits_seven_features() {+ assert_eq!(fixture_kinds().len(), 7);+ }++ #[test]+ fn speed_camera_from_highway_and_from_enforcement() {+ let kinds = fixture_kinds();+ assert!(kinds.contains(&Kind::SpeedCamera));+ // Two routes to the same kind: the tag and the enforcement relation role.+ assert_eq!(count(&kinds, Kind::SpeedCamera), 2);+ }++ #[test]+ fn alpr_from_surveillance_type_and_from_camera_type() {+ let kinds = fixture_kinds();+ assert!(kinds.contains(&Kind::Alpr));+ assert_eq!(count(&kinds, Kind::Alpr), 2);+ }++ #[test]+ fn generic_surveillance_stop_sign_and_traffic_signals() {+ let kinds = fixture_kinds();+ assert!(kinds.contains(&Kind::Surveillance));+ assert!(kinds.contains(&Kind::StopSign));+ assert!(kinds.contains(&Kind::TrafficSignals));+ }++ #[test]+ fn nothing_non_safety_leaks_through() {+ let cafe = fixture()+ .into_iter()+ .find(|(id, _, _)| *id == "node/1008")+ .unwrap();+ assert_eq!(classify(&cafe.1), None, "a cafe is not road furniture");+ }++ #[test]+ fn alpr_keeps_its_operator() {+ let (_, tags, _) = fixture()+ .into_iter()+ .find(|(id, _, _)| *id == "node/1003")+ .unwrap();+ let f = feature(classify(&tags).unwrap(), &tags, -122.417, 37.777, 1003);+ let operator = f+ .props+ .iter()+ .find(|(k, _)| *k == "operator")+ .expect("operator carried through");+ match &operator.1 {+ Value::Str(s) => assert_eq!(s, b"Flock Safety"),+ _ => panic!("operator must be a string"),+ }+ }++ #[test]+ fn every_feature_carries_an_osm_id_and_point_geometry() {+ for (_, tags, emitted) in fixture() {+ if !emitted {+ continue;+ }+ let kind = classify(&tags).unwrap();+ let f = feature(kind, &tags, 0.0, 0.0, 1);+ assert!(matches!(f.geometry, Geometry::Point(_)));+ // osm_id is last and always present.+ assert_eq!(f.props.last().unwrap().0, "osm_id");+ assert_eq!(f.props.first().unwrap().0, "kind");+ }+ }++ // --- the rules the fixture cannot express on its own ---++ #[test]+ fn enforcement_wins_over_surveillance() {+ // The ordering trap: a camera tagged both ways is a speed camera. Getting+ // this backwards reclassifies every enforcement camera as surveillance.+ let t = SafetyTags {+ man_made: Some("surveillance"),+ enforcement: Some("maxspeed"),+ surveillance_type: Some("ALPR"),+ ..Default::default()+ };+ assert_eq!(classify(&t), Some(Kind::SpeedCamera));+ }++ #[test]+ fn surveillance_type_matches_by_substring_but_camera_type_by_equality() {+ fn surv<'a>(v: &'a str) -> SafetyTags<'a> {+ SafetyTags {+ man_made: Some("surveillance"),+ surveillance_type: Some(v),+ ..Default::default()+ }+ }+ // Substring, and case-insensitive.+ assert_eq!(classify(&surv("ALPR")), Some(Kind::Alpr));+ assert_eq!(classify(&surv("alpr;camera")), Some(Kind::Alpr));+ assert_eq!(classify(&surv("traffic ANPR")), Some(Kind::Alpr));+ assert_eq!(classify(&surv("public")), Some(Kind::Surveillance));++ fn cam<'a>(v: &'a str) -> SafetyTags<'a> {+ SafetyTags {+ man_made: Some("surveillance"),+ camera_type: Some(v),+ ..Default::default()+ }+ }+ assert_eq!(classify(&cam("alpr")), Some(Kind::Alpr));+ assert_eq!(classify(&cam("ANPR")), Some(Kind::Alpr));+ // Exact match only: an enumerated field must not be substring-matched, or+ // every `alpr_capable`-style value would silently become an ALPR.+ assert_eq!(classify(&cam("alpr;dome")), Some(Kind::Surveillance));+ assert_eq!(classify(&cam("fixed")), Some(Kind::Surveillance));+ }++ #[test]+ fn the_flock_heuristic_hits_operator_and_manufacturer() {+ let base = SafetyTags {+ man_made: Some("surveillance"),+ ..Default::default()+ };+ assert_eq!(+ classify(&SafetyTags {+ operator: Some("Flock Safety"),+ ..base+ }),+ Some(Kind::Alpr)+ );+ assert_eq!(+ classify(&SafetyTags {+ manufacturer: Some("Flock Safety LLC"),+ ..base+ }),+ Some(Kind::Alpr)+ );+ assert_eq!(+ classify(&SafetyTags {+ operator: Some("City of Oakland"),+ ..base+ }),+ Some(Kind::Surveillance)+ );+ }++ #[test]+ fn surveillance_type_is_kept_as_a_property() {+ // Undocumented in the schema table but emitted by the Python, and the app+ // may already be reading it. Dropping it would be a silent schema break.+ let t = SafetyTags {+ man_made: Some("surveillance"),+ surveillance_type: Some("ALPR"),+ ..Default::default()+ };+ let f = feature(Kind::Alpr, &t, 0.0, 0.0, 1);+ assert!(f.props.iter().any(|(k, _)| *k == "surveillance_type"));+ }++ #[test]+ fn falsey_attribute_values_are_dropped() {+ for v in ["", "no", "false", "0"] {+ let t = SafetyTags {+ highway: Some("stop"),+ direction: Some(v),+ name: Some(v),+ ..Default::default()+ };+ let f = feature(Kind::StopSign, &t, 0.0, 0.0, 1);+ assert_eq!(+ f.props.len(),+ 2,+ "kind + osm_id only, but {v:?} was carried through"+ );+ }+ // Anything else is kept, including values that merely look falsey.+ let t = SafetyTags {+ highway: Some("stop"),+ direction: Some("both"),+ ..Default::default()+ };+ assert_eq!(feature(Kind::StopSign, &t, 0.0, 0.0, 1).props.len(), 3);+ }++ #[test]+ fn untagged_and_unrelated_nodes_classify_to_nothing() {+ assert_eq!(classify(&SafetyTags::default()), None);+ assert_eq!(+ classify(&SafetyTags {+ highway: Some("residential"),+ ..Default::default()+ }),+ None+ );+ // `man_made` that is not surveillance falls through to the highway rules.+ assert_eq!(+ classify(&SafetyTags {+ man_made: Some("mast"),+ ..Default::default()+ }),+ None+ );+ }++ #[test]+ fn the_pbf_filters_cover_every_classifying_tag() {+ let select = crate::select::Select::parse(&FILTERS).unwrap();+ for (id, tags, _) in fixture() {+ let get = |k: &str| match k {+ "highway" => tags.highway,+ "man_made" => tags.man_made,+ "enforcement" => tags.enforcement,+ _ => None,+ };+ // The pre-filter must never reject something the classifier accepts,+ // or the layer loses features for a reason nothing reports.+ if classify(&tags).is_some() {+ assert!(select.matches(get), "{id} classifies but is pre-filtered out");+ }+ }+ }+}
scripts/maps/osm_ingest/src/select.rs
diff --git a/scripts/maps/osm_ingest/src/select.rs b/scripts/maps/osm_ingest/src/select.rsnew file mode 100644index 0000000000..2d93554d0c--- /dev/null+++ b/scripts/maps/osm_ingest/src/select.rs@@ -0,0 +1,192 @@+//! Generic tag matching: the `osmium tags-filter` equivalent.+//!+//! Each layer script narrows a PBF with an expression like+//!+//! ```text+//! osmium tags-filter n/highway=speed_camera,stop,traffic_signals \+//! n/man_made=surveillance \+//! n/enforcement=maxspeed+//! ```+//!+//! [`Select`] is that expression: a set of `key=v1,v2` clauses, matching when+//! **any** of them does, which is what osmium's OR semantics mean. A clause with+//! no `=` matches on key presence alone (`w/maxspeed`).+//!+//! ## Why a lookup closure rather than a tag map+//!+//! [`Select::matches`] takes `impl Fn(&str) -> Option<&str>`, the shape+//! [`crate::osm::Tags::get_str`] already has. That means no map is built per+//! element on the hot path, and -- more usefully -- a selector can be unit-tested+//! against a plain array of pairs with no PBF anywhere in sight, exactly like the+//! classifiers in [`crate::tags`].+//!+//! This is a pre-filter, not the layer's schema decision. It exists to skip the+//! overwhelming majority of elements cheaply; the per-layer classifier still has+//! the final say on what is emitted and as what.++use crate::proto::{Error, Result};++/// One `key` or `key=v1,v2` clause.+#[derive(Debug, Clone, PartialEq)]+pub struct Clause {+ pub key: String,+ /// Empty means "any value", i.e. match on the key being present at all.+ pub values: Vec<String>,+}++impl Clause {+ fn matches(&self, value: Option<&str>) -> bool {+ match value {+ None => false,+ Some(v) => {+ if self.values.is_empty() {+ // osmium's bare `w/maxspeed` matches a present key whatever+ // its value, including the empty string.+ true+ } else {+ self.values.iter().any(|w| w == v)+ }+ }+ }+ }+}++#[derive(Debug, Clone, Default, PartialEq)]+pub struct Select {+ pub clauses: Vec<Clause>,+}++impl Select {+ /// Parse one clause per element of `specs`, in the `key` or `key=v1,v2` form.+ pub fn parse(specs: &[&str]) -> Result<Select> {+ let mut clauses = Vec::with_capacity(specs.len());+ for spec in specs {+ let spec = spec.trim();+ if spec.is_empty() {+ return Err(Error("empty tag filter".into()));+ }+ let (key, values) = match spec.split_once('=') {+ None => (spec.to_string(), Vec::new()),+ Some((k, v)) => {+ let k = k.trim();+ if k.is_empty() {+ return Err(Error(format!("tag filter has no key: {spec}")));+ }+ let values: Vec<String> = v+ .split(',')+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ .collect();+ if values.is_empty() {+ return Err(Error(format!("tag filter has no values: {spec}")));+ }+ (k.to_string(), values)+ }+ };+ clauses.push(Clause { key, values });+ }+ if clauses.is_empty() {+ return Err(Error("a selector needs at least one tag filter".into()));+ }+ Ok(Select { clauses })+ }++ /// True when any clause matches. `get` is a tag lookup, e.g.+ /// `|k| tags.get_str(k)`.+ pub fn matches<'a, F>(&self, get: F) -> bool+ where+ F: Fn(&str) -> Option<&'a str>,+ {+ self.clauses.iter().any(|c| c.matches(get(&c.key)))+ }++ /// Every key any clause mentions, deduplicated. Useful for a cheap+ /// "does this element carry any interesting key at all" screen.+ pub fn keys(&self) -> Vec<&str> {+ let mut out: Vec<&str> = self.clauses.iter().map(|c| c.key.as_str()).collect();+ out.sort_unstable();+ out.dedup();+ out+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A tag lookup over a plain slice -- the point of the closure-based API is+ /// that a test needs nothing more than this.+ fn tags<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<&'a str> + 'a {+ move |k| pairs.iter().find(|(pk, _)| *pk == k).map(|(_, v)| *v)+ }++ #[test]+ fn parses_the_osmium_clause_forms() {+ let s = Select::parse(&[+ "highway=speed_camera,stop,traffic_signals",+ "man_made=surveillance",+ "maxspeed",+ ])+ .unwrap();+ assert_eq!(s.clauses.len(), 3);+ assert_eq!(s.clauses[0].key, "highway");+ assert_eq!(s.clauses[0].values, ["speed_camera", "stop", "traffic_signals"]);+ // A bare key means "present, any value".+ assert_eq!(s.clauses[2].key, "maxspeed");+ assert!(s.clauses[2].values.is_empty());+ }++ #[test]+ fn tolerates_whitespace_and_trailing_commas() {+ let s = Select::parse(&[" highway = rail, subway , "]).unwrap();+ assert_eq!(s.clauses[0].key, "highway");+ assert_eq!(s.clauses[0].values, ["rail", "subway"]);+ }++ #[test]+ fn rejects_nonsense() {+ assert!(Select::parse(&[]).is_err());+ assert!(Select::parse(&[""]).is_err());+ assert!(Select::parse(&["=value"]).is_err());+ assert!(Select::parse(&["key="]).is_err());+ assert!(Select::parse(&["key=,,"]).is_err());+ }++ #[test]+ fn clauses_are_ored_not_anded() {+ let s = Select::parse(&["highway=speed_camera", "man_made=surveillance"]).unwrap();+ assert!(s.matches(tags(&[("highway", "speed_camera")])));+ assert!(s.matches(tags(&[("man_made", "surveillance")])));+ // Either alone is enough; neither is not.+ assert!(!s.matches(tags(&[("highway", "residential")])));+ assert!(!s.matches(tags(&[])));+ }++ #[test]+ fn a_bare_key_matches_any_value_including_empty() {+ let s = Select::parse(&["maxspeed"]).unwrap();+ assert!(s.matches(tags(&[("maxspeed", "50")])));+ assert!(s.matches(tags(&[("maxspeed", "none")])));+ // Present but empty still counts as present, as in osmium.+ assert!(s.matches(tags(&[("maxspeed", "")])));+ assert!(!s.matches(tags(&[("highway", "residential")])));+ }++ #[test]+ fn value_matching_is_exact_not_substring() {+ let s = Select::parse(&["railway=rail"]).unwrap();+ assert!(s.matches(tags(&[("railway", "rail")])));+ // `narrow_gauge` contains no "rail" substring issue, but `light_rail`+ // does -- and must not match a `railway=rail` clause.+ assert!(!s.matches(tags(&[("railway", "light_rail")])));+ assert!(!s.matches(tags(&[("railway", "railway")])));+ }++ #[test]+ fn keys_are_deduplicated_and_sorted() {+ let s = Select::parse(&["highway=stop", "man_made=surveillance", "highway=speed_camera"])+ .unwrap();+ assert_eq!(s.keys(), ["highway", "man_made"]);+ }+}
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 23eba4c164..f8a1abfc61 100644--- a/scripts/maps/osm_ingest/src/testpbf.rs+++ b/scripts/maps/osm_ingest/src/testpbf.rs@@ -289,10 +289,13 @@ pub fn primitive_block() -> Vec<u8> { /// The `Blob` message wrapping the fixture's `PrimitiveBlock`. pub fn sample_data_blob() -> Vec<u8> {- let payload = primitive_block();+ data_blob(&primitive_block())+}++fn data_blob(payload: &[u8]) -> Vec<u8> { let mut blob = Vec::new(); varint_field(2, payload.len() as u64, &mut blob); // raw_size- bytes_field(3, &zlib_store(&payload), &mut blob); // zlib_data+ bytes_field(3, &zlib_store(payload), &mut blob); // zlib_data blob } @@ -308,6 +311,10 @@ fn framed(kind: &str, blob: &[u8], out: &mut Vec<u8>) { /// A complete `.osm.pbf`: one `OSMHeader` blob (which every reader must skip) /// followed by one `OSMData` blob. pub fn sample_pbf() -> Vec<u8> {+ pbf_from_block(&primitive_block())+}++fn pbf_from_block(block: &[u8]) -> Vec<u8> { let mut header_block = Vec::new(); bytes_field(4, b"OsmSchema-V0.6", &mut header_block); bytes_field(4, b"DenseNodes", &mut header_block);@@ -318,21 +325,142 @@ pub fn sample_pbf() -> Vec<u8> { let mut out = Vec::new(); framed("OSMHeader", &header_blob, &mut out);- framed("OSMData", &sample_data_blob(), &mut out);+ framed("OSMData", &data_blob(block), &mut out); out } /// Write the fixture to a unique temp directory and return the path plus the /// directory (which the caller may use for outputs). pub fn write_sample(tag: &str) -> (std::path::PathBuf, std::path::PathBuf) {+ write_pbf(tag, &sample_pbf())+}++fn write_pbf(tag: &str, bytes: &[u8]) -> (std::path::PathBuf, std::path::PathBuf) { let dir = std::env::temp_dir().join(format!("osm_ingest_{tag}")); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("sample.osm.pbf");- std::fs::write(&path, sample_pbf()).unwrap();+ std::fs::write(&path, bytes).unwrap(); (path, dir) } +// ---- the vector-layer fixture --------------------------------------------+//+// A SECOND fixture rather than more features in the one above. The road-graph and+// POI tests assert exact counts against it (`ways.len() == 3`, `records == 3`,+// `NODE_COUNT`), so every addition there ripples into four modules' tests and+// makes each of them slightly less about what it is testing. The vector layers+// need different elements anyway.++/// `highway=speed_camera` with a direction.+pub const CAMERA_NODE_ID: i64 = 1001;+/// `man_made=surveillance` + `surveillance:type=ALPR` + a Flock operator, so it+/// hits the ALPR branch by two independent signals.+pub const ALPR_NODE_ID: i64 = 1003;+pub const STOP_SIGN_NODE_ID: i64 = 1006;+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;++/// One node in the vector-layer fixture: `(id, lat_e7, lon_e7, tags)`.+type FixtureNode = (i64, i32, i32, Vec<(u32, u32)>);++/// Dense-node group for an arbitrary node list. Ids must ascend, as they do in a+/// real PBF.+fn dense_group(nodes: &[FixtureNode]) -> Vec<u8> {+ let mut keys_vals: Vec<u32> = Vec::new();+ for (_, _, _, tags) in nodes {+ for (k, v) in tags {+ keys_vals.push(*k);+ keys_vals.push(*v);+ }+ keys_vals.push(ST_EMPTY);+ }+ let mut out = Vec::new();+ packed_delta(1, &nodes.iter().map(|n| n.0).collect::<Vec<_>>(), &mut out);+ packed_delta(8, &nodes.iter().map(|n| n.1 as i64).collect::<Vec<_>>(), &mut out);+ packed_delta(9, &nodes.iter().map(|n| n.2 as i64).collect::<Vec<_>>(), &mut out);+ packed_u32(10, &keys_vals, &mut out);+ out+}++/// The `PrimitiveBlock` for the vector-layer fixture. All nodes sit in San+/// Francisco, around 37.77N 122.41W, so a plausible `--bbox` includes them and an+/// Atlantic one does not.+pub fn layers_block() -> Vec<u8> {+ let mut st = StringTable::new();++ let k_highway = st.id("highway");+ let k_man_made = st.id("man_made");+ let k_surveillance_type = st.id("surveillance:type");+ let k_operator = st.id("operator");+ let k_direction = st.id("direction");+ let k_amenity = st.id("amenity");+ let k_name = st.id("name");++ let v_speed_camera = st.id("speed_camera");+ let v_surveillance = st.id("surveillance");+ let v_alpr = st.id("ALPR");+ let v_flock = st.id("Flock Safety");+ let v_forward = st.id("forward");+ let v_stop = st.id("stop");+ let v_traffic_signals = st.id("traffic_signals");+ let v_cafe = st.id("cafe");+ let v_corner_cafe = st.id("Corner Cafe");++ let nodes: Vec<FixtureNode> = vec![+ (+ CAMERA_NODE_ID,+ 377_749_000,+ -1_224_194_000,+ vec![(k_highway, v_speed_camera), (k_direction, v_forward)],+ ),+ (+ ALPR_NODE_ID,+ 377_770_000,+ -1_224_170_000,+ vec![+ (k_man_made, v_surveillance),+ (k_surveillance_type, v_alpr),+ (k_operator, v_flock),+ ],+ ),+ (+ STOP_SIGN_NODE_ID,+ 377_800_000,+ -1_224_150_000,+ vec![(k_highway, v_stop)],+ ),+ (+ SIGNALS_NODE_ID,+ 377_810_000,+ -1_224_140_000,+ vec![(k_highway, v_traffic_signals)],+ ),+ (+ LAYERS_CAFE_NODE_ID,+ 377_820_000,+ -1_224_130_000,+ vec![(k_amenity, v_cafe), (k_name, v_corner_cafe)],+ ),+ ];+ let dense = dense_group(&nodes);++ let mut node_group = Vec::new();+ bytes_field(2, &dense, &mut node_group);++ let mut block = Vec::new();+ bytes_field(1, &st.encode(), &mut block);+ bytes_field(2, &node_group, &mut block);+ varint_field(17, 100, &mut block); // granularity+ block+}++/// Write the vector-layer fixture to a unique temp directory.+pub fn write_layers_sample(tag: &str) -> (std::path::PathBuf, std::path::PathBuf) {+ write_pbf(tag, &pbf_from_block(&layers_block()))+}+ #[cfg(test)] mod tests { use super::*;