maps: add the build_all superscript and a differential harness
- Commit
635c9b277c91b9646a2266cc17ced00d97590ecf- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 05:43 UTC (3 months ago)
- Parents
dd3c356
Diff
scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex f20e312431..82137a4005 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -163,29 +163,106 @@ mutually consistent (same POI set, same coordinates). See | File | Purpose | |---|---|-| `build_v5_pmtiles.sh` | **Top-level orchestrator**: base + safety + maxspeed + transit_lines + ma_pois + admin + transit_stops → merge → `v5.pmtiles` |+| `build_all.sh` | **The superscript**: one command from `.osm.pbf` + GTFS to all 9 runtime artifacts, with per-stage stamps and a `manifest.txt` of sizes and SHA-256s. Chains graph → pois → transit → tiles |+| `build_all.ps1` | **Windows twin** of the above. Stages graph/pois/transit are complete; the tiles stage composites only the cargo-only layers onto a `-BaseArchive` (see [Caveats](#caveats--known-limitations)) |+| `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_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` → tippecanoe → `ma_pois.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) | | `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** | | `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` |-| `tile_build/` | Rust MVT + PMTiles v3 crate (detached), **replacing tippecanoe and tile-join**: `tile_points` (tile a point geojsonseq) and `tile_join` (merge archives). Container layout documented in `src/pmtiles.rs` |-| `publish_r2.sh` | Upload built `.pmtiles` to Cloudflare R2 (creds from env vars only) |+| `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_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) | | `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 | | `test/fixtures/*` | Tiny sample inputs for the test | --- +## Caveats & known limitations++These are structural, not bugs waiting to be fixed. Read them before assuming a+build is reproducible or cargo-only.++### 1. Planetiler cannot be ported++`build_base_layers.sh --mode build` runs Java 21 plus the Protomaps basemap jar.+Nothing here replaces it, so **`--base-mode build` is the one documented Java+exception** and it fails loudly when `java` is absent rather than silently+falling back. The default is `--base-mode reuse`, which fetches a published+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.++### 3. Output is not byte-identical to tippecanoe, by design++`--drop-densest-as-needed` is a lossy per-tile heuristic, and+`--extend-zooms-if-still-dropping` can push an archive *past* its own+`--maximum-zoom`. Our tilers implement a deterministic, documented drop policy+and a fixed max zoom instead. Consequences:++* Per-tile feature counts differ. `test/diff_pmtiles.py --max-feature-delta`+ is the explicit budget for that; the flag exists so the divergence has a number+ rather than being unbounded.+* Tests assert **our own invariants** (ring closure, winding order,+ Douglas-Peucker monotonicity, PMTiles round-trip), never equality with+ tippecanoe.+* An MVT re-encode rebuilds each layer's key/value dictionaries in first-use+ order, so even an untouched tile can come back a few bytes different. Compare+ the decoded model, which is what the spec defines.+* `--detect-shared-borders` is not reproduced. Adjacent admin polygons are+ simplified independently, so at low zoom a shared border can show a hairline+ gap or overlap. Noted rather than papered over.++### 4. World transit is a large step up in cost++Today's `world.transit` is built from `.url` fields alone, which silently drops+most US feeds — 38 of California's 49 sources — because they are referenced by+`transitland-atlas-id` with no URL. Resolving those references the way+`build_ca_transit.ps1` does turns 27 feeds and 18 MB into hundreds of feeds and+many GB of downloads. **A `--region` filter is mandatory** for staging: validate+on California, then a few regions, then the world.++The two producers also differ in what they can emit. Only the DMFR-resolving+path knows each feed's original source name, so only it can write the three-field+manifest that gives stops their MOTIS ids — and without those, live delays cannot+be matched to a stop.++### 5. Credential env vars are not uniform++`publish_r2.sh` reads `R2_ENDPOINT` / `R2_ACCESS_KEY_ID` /+`R2_SECRET_ACCESS_KEY`. `vendor_pmtiles.sh` also accepts the `AWS_*` pair. The+deprecated `run_generator.sh` used `R2_ACCESS_KEY` / `R2_SECRET_KEY` and now+bridges them onto the first set.++### 6. Intermediates are never deleted++`build_v5_pmtiles.sh` keeps everything under `--workdir`, and+`build_admin_layers.sh` leaves its `admin_*.geojsonseq` in `--outdir`. That is+what makes a re-run cheap. `--keep-work` only silences the reminder; it does not+change the behaviour.++---+ ## Prerequisites (tools) Full build needs (all are existing off-the-shelf tools — the only code authored@@ -212,11 +289,13 @@ here is Rust and Python): ### What builds on Windows -Everything that is cargo-only: the routing graph (`build_graph.ps1`), the offline-transit pack (`build_ca_transit.ps1`), the `transit_stops` layer-(`build_transit_stops_layer.ps1`) and the final merge (`tile_join`). The-OSM-derived vector layers still need tippecanoe + osmium and therefore a Linux-box or WSL.+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`. 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@@ -242,6 +321,32 @@ The **dry-run test** needs only `python3`. ## Run commands +### 0. Everything, in one command++`build_all.sh` is the entry point. It builds all 9 artifacts in dependency order,+stamps each stage so a re-run is cheap, and writes a `manifest.txt` of sizes and+SHA-256s that should be identical across two runs of the same inputs.++```bash+# see the plan without touching anything+./build_all.sh --pbf norcal-latest.osm.pbf --bbox -122.6,37.2,-121.7,37.9 --dry-run++# a metro build, fetching the PBF and resolving one GTFS region+./build_all.sh --geofabrik north-america/us/california \+ --gtfs-region 'us-ca' --out-dir ./ca_build --out ./ca_build/v5-ca.pmtiles++# then publish all 9+./build_all.sh <same args> --publish+```++The `--bbox` clip happens **once**, up front, and is shared by every stage — so+unlike the per-layer scripts, the routing graph honours it too. That needs+`osmium`.++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.+ ### 1. Dry run (single metro — validates safety + border layers) Prove a valid `.pmtiles` with the new layers without a planet build. Example@@ -562,6 +667,12 @@ so `TravelMode.PUBLIC_TRANSIT` in the road graph now means *walking* — it is o reached for a journey's access/egress/transfer legs. Dropping the duplicated nodes is also the single biggest size win in this pipeline. +The two download entries outlived their producer, though: `MainActivity`'s+`InitialDownloadChecker` kept fetching `transit_voyages.bin` (290 MB) and+`transit_attributes.bin` (122 MB) long after the generator that wrote them was+deleted, and nothing in the app parsed either. They have now been removed, taking+412 MB off a cold start and the download list from 10 entries to 8.+ ### How the app obtains it — download-size implications The routing graph and the map **tiles** have very different size profiles, so
scripts/maps/build_all.ps1
diff --git a/scripts/maps/build_all.ps1 b/scripts/maps/build_all.ps1new file mode 100644index 0000000000..d8483ce882--- /dev/null+++ b/scripts/maps/build_all.ps1@@ -0,0 +1,381 @@+# build_all.ps1 — the Windows twin of build_all.sh.+#+# Same job: one command, from an .osm.pbf plus a GTFS source to the runtime+# artifacts, with every bytes-to-bytes transformation done by our own Rust crates+# and only network I/O and process orchestration here.+#+# WHAT THIS TWIN CAN AND CANNOT DO. The layers that still go through osmium,+# tippecanoe, GDAL and python3 (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+# 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+# pois poi_names.bin poi_index.bin+# transit world.transit+# tiles v5.pmtiles (name from -Out)+# plus manifest.txt with each one's size and SHA-256, byte-comparable with the+# manifest.txt build_all.sh writes.+#+# Each stage stamps <Work>\stamps on success, so a re-run skips finished work;+# -Force ignores the stamps.+#+# Examples:+# .\build_all.ps1 -Pbf california-latest.osm.pbf -GtfsRegion us-ca+# .\build_all.ps1 -Geofabrik north-america/us/california -Only graph+# .\build_all.ps1 -Pbf norcal.osm.pbf -DryRun+#+# Requirements: PowerShell 7, cargo, and `tar` (in-box on Windows 10+) for the+# transit registries. Nothing else.++[CmdletBinding()]+param(+ # Inputs+ [string] $Pbf = "",+ # Geofabrik region path, e.g. north-america/us/california ('-latest.osm.pbf'+ # is appended). Cached in -Work.+ [string] $Geofabrik = "",+ # feeds.manifest ('name=dir[=motis_prefix]' per line) for world.transit and+ # the transit_stops tile layer.+ [string] $GtfsManifest = "",+ # Transitous registry file to resolve instead, e.g. 'us-ca'.+ [string] $GtfsRegion = "",++ # Outputs+ [string] $OutDir = "build_all_out",+ [string] $Out = "",+ [string] $Work = "",+ # Base tile archive to composite onto: a local .pmtiles, or a URL to fetch.+ # Required by the tiles stage on Windows.+ [string] $BaseArchive = "",++ # Stage control+ [switch] $SkipGraph,+ [switch] $SkipPois,+ [switch] $SkipTransit,+ [switch] $SkipTiles,+ [ValidateSet("", "graph", "pois", "transit", "tiles")]+ [string] $Only = "",+ [switch] $Force,+ [switch] $DryRun,++ # 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",++ # Publishing. Delegates to publish_r2.sh, which needs bash (WSL or Git Bash).+ [switch] $Publish,+ [switch] $PublishDryRun,++ [int] $Jobs = 6+)++$ErrorActionPreference = "Stop"+$Here = $PSScriptRoot++function Invoke-Step {+ param([string] $Exe, [string[]] $StepArgs)+ if ($DryRun) {+ Write-Host "[dry-run] $Exe $($StepArgs -join ' ')"+ return+ }+ & $Exe @StepArgs+ if ($LASTEXITCODE -ne 0) { throw "$Exe failed with exit code $LASTEXITCODE" }+}++function Test-Stage {+ param([string] $Name)+ if ($Only) { return $Only -eq $Name }+ switch ($Name) {+ "graph" { return -not $SkipGraph }+ "pois" { return -not $SkipPois }+ "transit" { return -not $SkipTransit }+ "tiles" { return -not $SkipTiles }+ }+ return $false+}++function Test-Stamp {+ param([string] $Name)+ return (-not $Force) -and (Test-Path (Join-Path $Stamps "$Name.done"))+}++function Set-Stamp {+ param([string] $Name)+ if (-not $DryRun) { New-Item -ItemType File -Force -Path (Join-Path $Stamps "$Name.done") | Out-Null }+}++function Assert-Pbf {+ param([string] $Stage)+ if (-not $script:Pbf) { throw "-Pbf or -Geofabrik is required for the $Stage stage (or -Skip$Stage)" }+ if (-not $DryRun -and -not (Test-Path $script:Pbf)) { throw "pbf not found: $script:Pbf" }+}++if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {+ throw "cargo not installed (https://rustup.rs)"+}+if ($EnginePois -ne "rust" -and $EnginePois -ne "legacy") {+ throw "-EnginePois must be rust or legacy"+}+if ($EnginePois -eq "legacy") {+ throw "-EnginePois legacy needs tippecanoe, which has no Windows build; use rust (the default)"+}++New-Item -ItemType Directory -Force -Path $OutDir | Out-Null+$OutDir = (Resolve-Path $OutDir).Path+if (-not $Work) { $Work = Join-Path $OutDir "work" }+New-Item -ItemType Directory -Force -Path $Work | Out-Null+$Work = (Resolve-Path $Work).Path+if (-not $Out) { $Out = Join-Path $OutDir "v5.pmtiles" }+$Stamps = Join-Path $Work "stamps"+New-Item -ItemType Directory -Force -Path $Stamps | Out-Null++$OsmManifest = Join-Path $Here "osm_ingest\Cargo.toml"+$TileManifest = Join-Path $Here "tile_build\Cargo.toml"+$GtfsCargo = Join-Path $Here "gtfs_ingest\Cargo.toml"++# --- input: fetch the PBF if asked ---+# Network I/O lives here rather than in osm_ingest, which is why that crate has+# no HTTP dependency.+if ($Geofabrik) {+ if ($Pbf) { throw "pass -Pbf or -Geofabrik, not both" }+ $leaf = ($Geofabrik -split '/')[-1]+ $Pbf = Join-Path $Work "$leaf-latest.osm.pbf"+ if (Test-Path $Pbf) {+ Write-Host "[all] reusing cached $Pbf"+ } else {+ $url = "https://download.geofabrik.de/$Geofabrik-latest.osm.pbf"+ Write-Host "[all] fetching $url"+ if (-not $DryRun) {+ # Download to .partial so an interrupted fetch is never mistaken for a+ # complete cached extract on the next run.+ $partial = "$Pbf.partial"+ Invoke-WebRequest -Uri $url -OutFile $partial -MaximumRedirection 5+ Move-Item -Force $partial $Pbf+ }+ }+}++$PoisTile = Join-Path $Work "ma_pois.pmtiles"+$StopsTile = Join-Path $Work "transit_stops.pmtiles"+$TransitWork = Join-Path $Work "transit"++# --- stage: graph (5 files) ---+if (Test-Stage "graph") {+ if (Test-Stamp "graph") {+ Write-Host "=== graph: stamp present, skipping (-Force to redo) ==="+ } else {+ Assert-Pbf "Graph"+ Write-Host "=== graph -> $OutDir (metadata/road_names/nodes/edges/lanes.bin) ==="+ # Gated deliberately: road_graph truncates its outputs as it writes, so a+ # failure here must not fall through to the manifest or the publish.+ Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $OsmManifest,+ "--bin", "road_graph", "--", $Pbf, "--out", $OutDir)+ Set-Stamp "graph"+ }+}++# --- stage: pois (2 side files + the ma_pois tile layer) ---+# One poi_extract pass produces the geojson the tiler reads AND the two side+# files, so they cannot disagree. The side files go straight to -OutDir.+if (Test-Stage "pois") {+ if (Test-Stamp "pois") {+ Write-Host "=== pois: stamp present, skipping (-Force to redo) ==="+ } else {+ Assert-Pbf "Pois"+ $poiGeo = Join-Path $Work "ma_pois.geojsonseq"+ Write-Host "=== pois -> $OutDir\poi_names.bin + poi_index.bin ==="+ Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $OsmManifest,+ "--bin", "poi_extract", "--", $Pbf,+ "--geojson", $poiGeo,+ "--names", (Join-Path $OutDir "poi_names.bin"),+ "--index", (Join-Path $OutDir "poi_index.bin"))+ Write-Host "=== pois -> $PoisTile (z12-16, tile_points) ==="+ Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $TileManifest,+ "--bin", "tile_points", "--",+ "--geojson", $poiGeo, "--out", $PoisTile, "--layer", "ma_pois",+ "--minzoom", "12", "--maxzoom", "16")+ Set-Stamp "pois"+ }+}++# --- stage: transit (world.transit) ---+# build_ca_transit.ps1 is the only producer that resolves transitland-atlas DMFR+# references, so it is the one that can emit MOTIS stop ids. Its manifest is the+# three-field form, and it lands beside the downloads.+if (Test-Stage "transit") {+ if (Test-Stamp "transit") {+ Write-Host "=== transit: stamp present, skipping (-Force to redo) ==="+ } else {+ if (-not $GtfsManifest -and -not $GtfsRegion) {+ throw "the transit stage needs -GtfsManifest or -GtfsRegion (or -SkipTransit)"+ }+ if ($GtfsManifest -and $GtfsRegion) {+ throw "pass -GtfsManifest or -GtfsRegion, not both"+ }+ if ($GtfsRegion) {+ Write-Host "=== transit: resolving region $GtfsRegion -> $OutDir\world.transit ==="+ Invoke-Step "pwsh" @("-NoProfile", "-File", (Join-Path $Here "build_ca_transit.ps1"),+ "-Region", $GtfsRegion, "-Work", $TransitWork, "-Out", $OutDir,+ "-PackName", "world", "-Jobs", "$Jobs")+ $script:EffectiveGtfsManifest = Join-Path $TransitWork "feeds.manifest"+ } else {+ Write-Host "=== transit: merging $GtfsManifest -> $OutDir\world.transit ==="+ Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $GtfsCargo,+ "--bin", "gtfs_ingest", "--", $OutDir, "world", "--manifest", $GtfsManifest)+ $script:EffectiveGtfsManifest = $GtfsManifest+ }+ Set-Stamp "transit"+ }+}+if (-not $script:EffectiveGtfsManifest) {+ $candidate = Join-Path $TransitWork "feeds.manifest"+ if (Test-Path $candidate) { $script:EffectiveGtfsManifest = $candidate }+ elseif ($GtfsManifest) { $script:EffectiveGtfsManifest = $GtfsManifest }+}++# --- stage: tiles (cargo-only layers onto a base archive) ---+if (Test-Stage "tiles") {+ if (Test-Stamp "tiles") {+ Write-Host "=== tiles: stamp present, skipping (-Force to redo) ==="+ } else {+ if (-not $BaseArchive) {+ throw @"+the tiles stage needs -BaseArchive on Windows.++Only ma_pois and transit_stops are cargo-only today; safety, 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:++ .\build_all.ps1 ... -BaseArchive https://data.vayunmathur.com/v5.pmtiles++For a complete v5 with every layer, run build_all.sh under WSL.+"@+ }++ $base = $BaseArchive+ if ($BaseArchive -match '^https?://') {+ $base = Join-Path $Work "base.pmtiles"+ if (Test-Path $base) {+ Write-Host "[all] reusing cached base $base"+ } else {+ Write-Host "[all] fetching $BaseArchive (this can be very large)"+ if (-not $DryRun) {+ $partial = "$base.partial"+ Invoke-WebRequest -Uri $BaseArchive -OutFile $partial -MaximumRedirection 5+ Move-Item -Force $partial $base+ }+ }+ } elseif (-not $DryRun -and -not (Test-Path $base)) {+ throw "-BaseArchive not found: $base"+ }++ # 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)) {+ $stopsGeo = Join-Path $Work "transit_stops.geojsonseq"+ Write-Host "=== tiles: transit_stops -> $StopsTile ==="+ Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $GtfsCargo,+ "--bin", "transit_stops", "--",+ "--geojson", $stopsGeo, "--manifest", $script:EffectiveGtfsManifest)+ Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $TileManifest,+ "--bin", "tile_points", "--",+ "--geojson", $stopsGeo, "--out", $StopsTile, "--layer", "transit_stops",+ "--minzoom", "11", "--maxzoom", "14")+ } else {+ Write-Warning "no GTFS manifest available; skipping the transit_stops layer"+ }++ # Later inputs win a layer-name collision, so the overlays go after base.+ $inputs = @($base)+ foreach ($t in @($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)"+ Set-Stamp "tiles"+ }+}++# --- manifest.txt: name, size, SHA-256 for all 9 ---+# Same column layout as build_all.sh so the two are diffable, and lowercase hex+# so the digests compare directly.+$artifacts = @("metadata.bin", "road_names.bin", "nodes.bin", "edges.bin", "lanes.bin",+ "poi_names.bin", "poi_index.bin", "world.transit", (Split-Path $Out -Leaf))++function Get-ArtifactPath {+ param([string] $Name)+ if ($Name -eq (Split-Path $Out -Leaf)) { return $Out }+ return (Join-Path $OutDir $Name)+}++if ($DryRun) {+ Write-Host ""+ Write-Host "[dry-run] would write $OutDir\manifest.txt over these 9 artifacts:"+ $artifacts | ForEach-Object { Write-Host " $_" }+} else {+ $manifestFile = Join-Path $OutDir "manifest.txt"+ $lines = @()+ $present = @()+ $missing = @()+ foreach ($a in $artifacts) {+ $p = Get-ArtifactPath $a+ if (Test-Path $p) {+ $len = (Get-Item $p).Length+ $sha = (Get-FileHash -Algorithm SHA256 -Path $p).Hash.ToLowerInvariant()+ $lines += ("{0,-16} {1,14} {2}" -f $a, $len, $sha)+ $present += $p+ } else {+ $lines += ("{0,-16} {1,14} {2}" -f $a, "-", "MISSING")+ $missing += $a+ }+ }+ # LF, no BOM: manifest.txt is compared against the one build_all.sh writes.+ [System.IO.File]::WriteAllText($manifestFile, (($lines -join "`n") + "`n"), (New-Object System.Text.UTF8Encoding($false)))+ Write-Host ""+ Write-Host "=== $manifestFile ($($present.Count)/9 present) ==="+ $lines | ForEach-Object { Write-Host $_ }+ if ($missing.Count -gt 0) {+ # Not fatal: -Skip*/-Only runs are expected to leave holes. Naming them is+ # what stops a partial run from looking like a complete one.+ Write-Warning "NOT built this run: $($missing -join ', ')"+ }+}++# --- publish (optional) ---+# publish_r2.sh stays the single uploader; reimplementing it here would give the+# two platforms different keys, content types and cache headers.+if ($Publish) {+ $bash = Get-Command bash -ErrorAction SilentlyContinue+ if ($DryRun) {+ Write-Host "[dry-run] would publish every present artifact via publish_r2.sh"+ } elseif (-not $bash) {+ throw @"+-Publish needs bash to run publish_r2.sh (WSL or Git Bash). Either install one,+or upload from a Linux box with:++ ./scripts/maps/publish_r2.sh <files...>+"@+ } elseif ($present.Count -eq 0) {+ throw "-Publish but nothing was built"+ } else {+ Write-Host ""+ Write-Host "=== publishing $($present.Count) artifact(s) to R2 ==="+ $pubArgs = @((Join-Path $Here "publish_r2.sh")) + $present+ if ($PublishDryRun) { $pubArgs += "--dry-run" }+ Invoke-Step $bash.Source $pubArgs+ }+} else {+ Write-Host ""+ Write-Host "Publish (creds from env -- see README 'Publishing to R2'):"+ Write-Host " `$env:R2_ENDPOINT='https://<ACCOUNT_ID>.r2.cloudflarestorage.com'"+ Write-Host " `$env:R2_ACCESS_KEY_ID='...'; `$env:R2_SECRET_ACCESS_KEY='...'"+ Write-Host " .\build_all.ps1 <same args> -Publish"+}
scripts/maps/build_all.sh
diff --git a/scripts/maps/build_all.sh b/scripts/maps/build_all.shnew file mode 100644index 0000000000..025dcc28fc--- /dev/null+++ b/scripts/maps/build_all.sh@@ -0,0 +1,410 @@+#!/bin/bash+set -euo pipefail++# build_all.sh — ONE command that builds every runtime artifact the maps app+# downloads, from an .osm.pbf plus a GTFS source.+#+# Replaces driving three disjoint pipelines by hand (run_generator.sh for the+# graph, build_v5_pmtiles.sh for the tiles, build_world_transit.sh for transit),+# and closes the gap where poi_names.bin/poi_index.bin had to be hand-copied+# into the graph directory before the upload would pick them up.+#+# THE 9 ARTIFACTS, all landing in --out-dir:+# graph metadata.bin road_names.bin nodes.bin edges.bin lanes.bin+# pois poi_names.bin poi_index.bin+# transit world.transit+# tiles v5.pmtiles (name from --out)+# plus manifest.txt listing every one with its size and SHA-256. The first eight+# are what MainActivity's InitialDownloadChecker fetches; the ninth is streamed.+#+# Stages run in order graph -> pois -> transit -> tiles. Each writes a stamp file+# under <work>/stamps on success, so a re-run skips what already finished;+# --force ignores the stamps.+#+# THE DIVISION OF LABOUR: this script and its build_all.ps1 twin own network I/O+# and process orchestration, nothing else. Every bytes-to-bytes transformation+# belongs in the Rust crates (osm_ingest, gtfs_ingest, tile_build) — that is why+# they carry no HTTP stack and why the downloads live out here.+#+# Usage:+# ./build_all.sh --pbf california-latest.osm.pbf --gtfs-manifest feeds.manifest+# ./build_all.sh --geofabrik north-america/us/california --gtfs-region 'us-ca'+# ./build_all.sh --pbf norcal.osm.pbf --bbox -122.6,37.2,-121.7,37.9 --dry-run+#+# Options:+# Inputs+# --pbf FILE OSM extract for the graph, POI and tile layers+# --geofabrik REGION fetch the PBF instead, e.g. 'north-america/us/california'+# ('-latest.osm.pbf' is appended). Cached in <work>.+# --gtfs-manifest F feeds.manifest ('name=dir[=motis_prefix]' per line) for+# world.transit and the transit_stops tile layer+# --gtfs-region GLOB build that manifest from the Transitous registry+# instead, e.g. 'us-ca' (see build_world_transit.sh)+# --bbox BOX "minlon,minlat,maxlon,maxlat". Clipped ONCE up front and+# reused by every stage, so the graph honours it too.+# Needs osmium.+# Outputs+# --out-dir DIR where the 9 artifacts land (default ./build_all_out)+# --out FILE the tile archive (default <out-dir>/v5.pmtiles). Its+# basename becomes the published key, so match whatever+# style.json points at.+# --work DIR scratch + stamps (default <out-dir>/work)+# --base-archive URL published archive to reuse for the base layers+# (default: build_base_layers.sh's own)+# --base-mode M build|reuse (default reuse; build needs java 21 + --base-jar)+# --base-jar FILE protomaps basemap jar (--base-mode build only)+# --base-area A planetiler area (--base-mode build only; default planet)+# Stage control+# --skip-graph --skip-pois --skip-transit --skip-tiles+# --only STAGE run exactly one of graph|pois|transit|tiles+# --force ignore stamps and redo every requested stage+# --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-maxspeed E rust|legacy (default legacy)+# --engine-transit-lines E (default legacy)+# --engine-admin E rust|legacy (default legacy)+# --engine-pois E rust|legacy (default rust: tile_points, no tippecanoe)+# Publishing+# --publish upload every built artifact via publish_r2.sh+# --publish-dry-run with --publish, pass --dry-run through to publish_r2.sh+# -h|--help this help+#+# Tools: cargo always. The legacy engines additionally need osmium, tippecanoe,+# python3 and (for admin) ogr2ogr; --base-mode build needs java 21; --bbox needs+# osmium. See the "Caveats" section of README.md for exactly which layers are+# cargo-only today.++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"++PBF=""+GEOFABRIK=""+GTFS_MANIFEST=""+GTFS_REGION=""+BBOX=""+OUT_DIR="./build_all_out"+OUT=""+WORK=""+BASE_ARCHIVE=""+BASE_MODE="reuse"+BASE_JAR=""+BASE_AREA="planet"+SKIP_GRAPH=0+SKIP_POIS=0+SKIP_TRANSIT=0+SKIP_TILES=0+ONLY=""+FORCE=0+DRY_RUN=0+PUBLISH=0+PUBLISH_DRY_RUN=0+ENGINE_BASE="legacy"+ENGINE_SAFETY="legacy"+ENGINE_MAXSPEED="legacy"+ENGINE_TRANSIT_LINES="legacy"+ENGINE_ADMIN="legacy"+ENGINE_POIS="rust"++while [[ $# -gt 0 ]]; do+ case "$1" in+ --pbf) PBF="$2"; shift 2 ;;+ --geofabrik) GEOFABRIK="$2"; shift 2 ;;+ --gtfs-manifest) GTFS_MANIFEST="$2"; shift 2 ;;+ --gtfs-region) GTFS_REGION="$2"; shift 2 ;;+ --bbox) BBOX="$2"; shift 2 ;;+ --out-dir) OUT_DIR="$2"; shift 2 ;;+ --out) OUT="$2"; shift 2 ;;+ --work) WORK="$2"; shift 2 ;;+ --base-archive) BASE_ARCHIVE="$2"; shift 2 ;;+ --base-mode) BASE_MODE="$2"; shift 2 ;;+ --base-jar) BASE_JAR="$2"; shift 2 ;;+ --base-area) BASE_AREA="$2"; shift 2 ;;+ --skip-graph) SKIP_GRAPH=1; shift ;;+ --skip-pois) SKIP_POIS=1; shift ;;+ --skip-transit) SKIP_TRANSIT=1; shift ;;+ --skip-tiles) SKIP_TILES=1; shift ;;+ --only) ONLY="$2"; shift 2 ;;+ --force) FORCE=1; shift ;;+ --dry-run) DRY_RUN=1; shift ;;+ --publish) PUBLISH=1; shift ;;+ --publish-dry-run) PUBLISH_DRY_RUN=1; shift ;;+ --engine-base) ENGINE_BASE="$2"; shift 2 ;;+ --engine-safety) ENGINE_SAFETY="$2"; shift 2 ;;+ --engine-maxspeed) ENGINE_MAXSPEED="$2"; shift 2 ;;+ --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 ;;+ *) echo "Unknown arg: $1" >&2; exit 1 ;;+ esac+done++case "$ONLY" in+ ""|graph|pois|transit|tiles) : ;;+ *) echo "ERROR: --only must be graph|pois|transit|tiles (got '$ONLY')" >&2; exit 1 ;;+esac++# A `rust` engine is only offered once that layer has actually been ported.+# Refusing it loudly beats silently running the legacy path and reporting success.+engine_check() {+ local layer="$1" engine="$2" ported="$3"+ case "$engine" in+ legacy|rust) : ;;+ *) echo "ERROR: --engine-$layer must be rust|legacy (got '$engine')" >&2; exit 1 ;;+ esac+ if [[ "$engine" == "rust" && "$ported" != "1" ]]; then+ echo "ERROR: --engine-$layer rust is not implemented yet; use legacy" >&2+ exit 1+ fi+}+engine_check base "$ENGINE_BASE" 0+engine_check safety "$ENGINE_SAFETY" 0+engine_check maxspeed "$ENGINE_MAXSPEED" 0+engine_check transit-lines "$ENGINE_TRANSIT_LINES" 0+engine_check admin "$ENGINE_ADMIN" 0+engine_check pois "$ENGINE_POIS" 1++command -v cargo >/dev/null || { echo "ERROR: cargo not installed (https://rustup.rs)" >&2; exit 1; }++mkdir -p "$OUT_DIR"+OUT_DIR="$(cd "$OUT_DIR" && pwd)"+WORK="${WORK:-$OUT_DIR/work}"+mkdir -p "$WORK"+WORK="$(cd "$WORK" && pwd)"+OUT="${OUT:-$OUT_DIR/v5.pmtiles}"+STAMPS="$WORK/stamps"+mkdir -p "$STAMPS"++run() {+ if [[ "$DRY_RUN" == "1" ]]; then+ printf '[dry-run]'+ printf ' %q' "$@"+ printf '\n'+ return 0+ fi+ "$@"+}++stage_done() { [[ "$FORCE" == "0" && -f "$STAMPS/$1.done" ]]; }+mark_done() { [[ "$DRY_RUN" == "1" ]] || : > "$STAMPS/$1.done"; }++want_stage() {+ if [[ -n "$ONLY" ]]; then+ [[ "$ONLY" == "$1" ]]+ return+ fi+ local var="SKIP_${1^^}"+ [[ "${!var}" == "0" ]]+}++require_pbf() {+ [[ -n "$PBF" ]] || { echo "ERROR: --pbf or --geofabrik required for the $1 stage (or --skip-$1)" >&2; exit 1; }+ [[ -f "$PBF" || "$DRY_RUN" == "1" ]] || { echo "ERROR: pbf not found: $PBF" >&2; exit 1; }+}++# --- input: fetch the PBF if asked ---+# Network I/O lives here rather than in osm_ingest, which is why that crate has+# no HTTP dependency.+if [[ -n "$GEOFABRIK" ]]; then+ [[ -z "$PBF" ]] || { echo "ERROR: pass --pbf or --geofabrik, not both" >&2; exit 1; }+ PBF="$WORK/$(basename "$GEOFABRIK")-latest.osm.pbf"+ if [[ -f "$PBF" ]]; then+ echo "[all] reusing cached $PBF"+ else+ command -v curl >/dev/null || { echo "ERROR: --geofabrik needs curl" >&2; exit 1; }+ echo "[all] fetching https://download.geofabrik.de/$GEOFABRIK-latest.osm.pbf"+ # Download to .partial so an interrupted fetch is never mistaken for a+ # complete cached extract on the next run.+ run curl -fL --retry 3 -o "$PBF.partial" \+ "https://download.geofabrik.de/$GEOFABRIK-latest.osm.pbf"+ run mv "$PBF.partial" "$PBF"+ fi+fi++# --- input: clip once, share everywhere ---+# The per-layer scripts each do their own `osmium extract -b` when handed --bbox.+# Clipping once here instead means one extract rather than six, and it is the+# only way the graph stage can honour a bbox at all (road_graph has no --bbox).+if [[ -n "$BBOX" ]]; then+ require_pbf graph+ command -v osmium >/dev/null || { echo "ERROR: --bbox needs osmium-tool" >&2; exit 1; }+ CLIPPED="$WORK/metro.osm.pbf"+ if [[ -f "$CLIPPED" && "$FORCE" == "0" ]]; then+ echo "[all] reusing bbox extract $CLIPPED"+ else+ echo "[all] clipping to $BBOX (once, shared by every stage)"+ run osmium extract --overwrite -b "$BBOX" "$PBF" -o "$CLIPPED"+ fi+ PBF="$CLIPPED"+fi++POIS_TILE="$WORK/ma_pois.pmtiles"+# build_world_transit.sh always lands its resolved manifest here, including when+# it was handed one via --manifest, so the tiles stage has a single place to look.+TRANSIT_WORK="$WORK/transit"+EFFECTIVE_GTFS_MANIFEST="$TRANSIT_WORK/feeds.manifest"++# --- stage: graph (5 files) ---+if want_stage graph; then+ if stage_done graph; then+ echo "=== graph: stamp present, skipping (--force to redo) ==="+ else+ require_pbf graph+ echo "=== graph -> $OUT_DIR (metadata/road_names/nodes/edges/lanes.bin) ==="+ # Gated deliberately: road_graph truncates its outputs as it writes, so a+ # failure here must not fall through to the manifest or the publish.+ run cargo run --release --quiet --manifest-path "$HERE/osm_ingest/Cargo.toml" \+ --bin road_graph -- "$PBF" --out "$OUT_DIR"+ mark_done graph+ fi+fi++# --- stage: pois (2 side files + the ma_pois tile layer) ---+# One poi_extract pass produces the geojson the tiler reads AND the two side+# files, so they cannot disagree. The side files go straight to --out-dir; that+# is the manual copy step run_generator.sh used to ask for.+if want_stage pois; then+ if stage_done pois; then+ echo "=== pois: stamp present, skipping (--force to redo) ==="+ else+ require_pbf pois+ echo "=== pois -> $OUT_DIR/poi_{names,index}.bin + $POIS_TILE ==="+ run "$HERE/build_pois_layer.sh" \+ --pbf "$PBF" \+ --out "$POIS_TILE" \+ --names-out "$OUT_DIR/poi_names.bin" \+ --index-out "$OUT_DIR/poi_index.bin" \+ --engine "$ENGINE_POIS"+ mark_done pois+ fi+fi++# --- stage: transit (world.transit) ---+if want_stage transit; then+ if stage_done transit; then+ echo "=== transit: stamp present, skipping (--force to redo) ==="+ else+ if [[ -z "$GTFS_MANIFEST" && -z "$GTFS_REGION" ]]; then+ echo "ERROR: transit stage needs --gtfs-manifest or --gtfs-region (or --skip-transit)" >&2+ exit 1+ fi+ [[ -z "$GTFS_MANIFEST" || -z "$GTFS_REGION" ]] || {+ echo "ERROR: pass --gtfs-manifest or --gtfs-region, not both" >&2; exit 1; }+ echo "=== transit -> $OUT_DIR/world.transit ==="+ WT_ARGS=(--work "$TRANSIT_WORK" --out "$OUT_DIR")+ if [[ -n "$GTFS_MANIFEST" ]]; then+ WT_ARGS+=(--manifest "$GTFS_MANIFEST")+ else+ WT_ARGS+=(--region "$GTFS_REGION")+ fi+ [[ "$DRY_RUN" == "1" ]] && WT_ARGS+=(--dry-run)+ "$HERE/build_world_transit.sh" "${WT_ARGS[@]}"+ mark_done transit+ fi+fi++# --- stage: tiles (v5.pmtiles) ---+if want_stage tiles; then+ if stage_done tiles; then+ echo "=== tiles: stamp present, skipping (--force to redo) ==="+ else+ require_pbf tiles+ echo "=== tiles -> $OUT ==="+ V5_ARGS=(--pbf "$PBF" --out "$OUT" --workdir "$WORK/v5" --base-mode "$BASE_MODE")+ # The pois stage already built the layer and the side files; --skip-pois+ # plus --extra-layer folds that archive into the merge without a second+ # poi_extract pass.+ if [[ -f "$POIS_TILE" || "$DRY_RUN" == "1" ]]; then+ V5_ARGS+=(--skip-pois --extra-layer "$POIS_TILE")+ fi+ [[ -n "$BASE_ARCHIVE" ]] && V5_ARGS+=(--base-source "$BASE_ARCHIVE")+ [[ "$BASE_MODE" == "build" ]] && V5_ARGS+=(--base-jar "$BASE_JAR" --base-area "$BASE_AREA")+ if [[ -f "$EFFECTIVE_GTFS_MANIFEST" ]]; then+ V5_ARGS+=(--gtfs-manifest "$EFFECTIVE_GTFS_MANIFEST")+ elif [[ -n "$GTFS_MANIFEST" ]]; then+ V5_ARGS+=(--gtfs-manifest "$GTFS_MANIFEST")+ fi+ V5_ARGS+=(--engine-base "$ENGINE_BASE"+ --engine-safety "$ENGINE_SAFETY"+ --engine-maxspeed "$ENGINE_MAXSPEED"+ --engine-transit-lines "$ENGINE_TRANSIT_LINES"+ --engine-admin "$ENGINE_ADMIN")+ [[ "$DRY_RUN" == "1" ]] && V5_ARGS+=(--dry-run)+ "$HERE/build_v5_pmtiles.sh" "${V5_ARGS[@]}"+ mark_done tiles+ fi+fi++# --- manifest.txt: name, size, SHA-256 for all 9 ---+ARTIFACTS=(metadata.bin road_names.bin nodes.bin edges.bin lanes.bin+ poi_names.bin poi_index.bin world.transit)++sha256_of() {+ if command -v sha256sum >/dev/null; then+ sha256sum "$1" | cut -d' ' -f1+ elif command -v shasum >/dev/null; then+ shasum -a 256 "$1" | cut -d' ' -f1+ else+ echo "no-sha256-tool"+ fi+}+size_of() { stat -c%s "$1" 2>/dev/null || stat -f%z "$1" 2>/dev/null || echo 0; }++artifact_path() {+ if [[ "$1" == "$(basename "$OUT")" ]]; then echo "$OUT"; else echo "$OUT_DIR/$1"; fi+}++if [[ "$DRY_RUN" == "1" ]]; then+ echo ""+ echo "[dry-run] would write $OUT_DIR/manifest.txt over these 9 artifacts:"+ printf ' %s\n' "${ARTIFACTS[@]}" "$(basename "$OUT")"+else+ MANIFEST_FILE="$OUT_DIR/manifest.txt"+ : > "$MANIFEST_FILE"+ PRESENT=()+ MISSING=()+ for a in "${ARTIFACTS[@]}" "$(basename "$OUT")"; do+ p="$(artifact_path "$a")"+ if [[ -f "$p" ]]; then+ printf '%-16s %14s %s\n' "$a" "$(size_of "$p")" "$(sha256_of "$p")" >> "$MANIFEST_FILE"+ PRESENT+=("$p")+ else+ printf '%-16s %14s %s\n' "$a" "-" "MISSING" >> "$MANIFEST_FILE"+ MISSING+=("$a")+ fi+ done+ echo ""+ echo "=== $OUT_DIR/manifest.txt (${#PRESENT[@]}/9 present) ==="+ cat "$MANIFEST_FILE"+ if [[ ${#MISSING[@]} -gt 0 ]]; then+ # Not fatal: --skip-*/--only runs are expected to leave holes. Naming them+ # is what stops a partial run from looking like a complete one.+ echo ""+ echo "[all] NOT built this run: ${MISSING[*]}" >&2+ fi+fi++# --- publish (optional) ---+if [[ "$PUBLISH" == "1" ]]; then+ if [[ "$DRY_RUN" == "1" ]]; then+ echo "[dry-run] would publish every present artifact via publish_r2.sh"+ elif [[ ${#PRESENT[@]} -eq 0 ]]; then+ echo "ERROR: --publish but nothing was built" >&2+ exit 1+ else+ echo ""+ echo "=== publishing ${#PRESENT[@]} artifact(s) to R2 ==="+ PUB_ARGS=("${PRESENT[@]}")+ [[ "$PUBLISH_DRY_RUN" == "1" ]] && PUB_ARGS+=(--dry-run)+ # publish_r2.sh keys each file by basename, which is what the app's URLs+ # expect; --out's basename is therefore the tile key.+ "$HERE/publish_r2.sh" "${PUB_ARGS[@]}"+ fi+else+ echo ""+ echo "Publish (creds from env — see README 'Publishing to R2'):"+ echo " export R2_ENDPOINT=https://<ACCOUNT_ID>.r2.cloudflarestorage.com"+ echo " export R2_ACCESS_KEY_ID=... R2_SECRET_ACCESS_KEY=..."+ echo " $0 <same args> --publish"+fi
scripts/maps/build_pois_layer.sh
diff --git a/scripts/maps/build_pois_layer.sh b/scripts/maps/build_pois_layer.shindex b44b97c37e..024d5c692e 100644--- a/scripts/maps/build_pois_layer.sh+++ b/scripts/maps/build_pois_layer.sh@@ -33,14 +33,18 @@ set -euo pipefail # --names-out FILE Output name table (default: poi_names.bin) # --index-out FILE Output record index (default: poi_index.bin) # --bbox BOX Optional "minlon,minlat,maxlon,maxlat" metro extract (dry runs)-# --minzoom N tippecanoe minzoom (default 12)-# --maxzoom N tippecanoe maxzoom (default 16)+# --minzoom N tiler minzoom (default 12)+# --maxzoom N tiler maxzoom (default 16)+# --engine E rust|legacy tiler (default rust). `rust` is tile_build's+# tile_points, so no tippecanoe install is needed; `legacy`+# is tippecanoe. The GeoJSON is Rust-produced either way, so+# this layer never needed tippecanoe in the first place. # --keep-tmp Don't delete intermediate files #-# Tools required: cargo, osmium (osmium-tool), tippecanoe. The two side files can-# also be built on their own, on any platform, with:+# Tools required: cargo. Additionally osmium (osmium-tool) only for --bbox, and+# tippecanoe only for --engine legacy. The two side files can also be built on+# their own, on any platform, with: # cargo run --release --manifest-path osm_ingest/Cargo.toml --bin poi_extract -- ...-# only the .pmtiles step needs tippecanoe/osmium. HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PBF=""@@ -50,6 +54,7 @@ INDEX_OUT="poi_index.bin" BBOX="" MINZOOM=12 MAXZOOM=16+ENGINE="rust" KEEP_TMP=0 while [[ $# -gt 0 ]]; do@@ -61,17 +66,28 @@ while [[ $# -gt 0 ]]; do --bbox) BBOX="$2"; shift 2 ;; --minzoom) MINZOOM="$2"; shift 2 ;; --maxzoom) MAXZOOM="$2"; shift 2 ;;+ --engine) ENGINE="$2"; shift 2 ;; --keep-tmp) KEEP_TMP=1; shift ;;- -h|--help) sed -n '4,45p' "$0" | sed 's/^# \?//'; exit 0 ;;+ -h|--help) sed -n '4,47p' "$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 cargo >/dev/null || { echo "ERROR: cargo not installed (https://rustup.rs)" >&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; }+# Only demanded where actually used, so the default rust path runs on a box with+# neither osmium nor tippecanoe installed.+if [[ -n "$BBOX" ]]; then+ command -v osmium >/dev/null || { echo "ERROR: --bbox needs osmium-tool" >&2; exit 1; }+fi+if [[ "$ENGINE" == "legacy" ]]; then+ command -v tippecanoe >/dev/null || { echo "ERROR: --engine legacy needs tippecanoe" >&2; exit 1; }+fi TMP="$(mktemp -d)" cleanup() { [[ "$KEEP_TMP" == "1" ]] || rm -rf "$TMP"; }@@ -95,14 +111,24 @@ FEATURES="$(wc -l < "$TMP/ma_pois.geojsonseq" | tr -d ' ')" echo "[ma_pois] $FEATURES POI feature(s)" [[ "$FEATURES" -gt 0 ]] || echo "[ma_pois] WARNING: 0 features — check bbox/extract" -echo "[ma_pois] tiling -> $OUT (z$MINZOOM-$MAXZOOM)"-tippecanoe --force \- -o "$OUT" \- -l ma_pois \- --minimum-zoom="$MINZOOM" \- --maximum-zoom="$MAXZOOM" \- --drop-densest-as-needed \- --extend-zooms-if-still-dropping \- "$TMP/ma_pois.geojsonseq"+echo "[ma_pois] 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 "$TMP/ma_pois.geojsonseq" \+ --out "$OUT" \+ --layer ma_pois \+ --minzoom "$MINZOOM" \+ --maxzoom "$MAXZOOM"+else+ tippecanoe --force \+ -o "$OUT" \+ -l ma_pois \+ --minimum-zoom="$MINZOOM" \+ --maximum-zoom="$MAXZOOM" \+ --drop-densest-as-needed \+ --extend-zooms-if-still-dropping \+ "$TMP/ma_pois.geojsonseq"+fi echo "[ma_pois] done: $OUT + $NAMES_OUT + $INDEX_OUT"
scripts/maps/build_v5_pmtiles.sh
diff --git a/scripts/maps/build_v5_pmtiles.sh b/scripts/maps/build_v5_pmtiles.shindex a3cb487e55..c072fcd1e5 100644--- a/scripts/maps/build_v5_pmtiles.sh+++ b/scripts/maps/build_v5_pmtiles.sh@@ -54,6 +54,17 @@ set -euo pipefail # --base-mode M build|reuse (passed to build_base_layers.sh; default reuse) # --base-jar FILE protomaps basemap jar (base-mode build) # --base-area A planetiler area name/path (base-mode build; default planet)+# --base-source URL published archive to reuse (base-mode reuse; default is+# build_base_layers.sh's own)+# --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-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 # --skip-safety omit safety layer # --skip-maxspeed omit maxspeed layer@@ -79,6 +90,14 @@ BBOX="" BASE_MODE="reuse" BASE_JAR="" BASE_AREA="planet"+BASE_SOURCE=""+EXTRA_LAYERS=()+ENGINE_BASE="legacy"+ENGINE_SAFETY="legacy"+ENGINE_MAXSPEED="legacy"+ENGINE_TRANSIT_LINES="legacy"+ENGINE_ADMIN="legacy"+DRY_RUN=0 SKIP_BASE=0 SKIP_SAFETY=0 SKIP_MAXSPEED=0@@ -100,6 +119,14 @@ while [[ $# -gt 0 ]]; do --base-mode) BASE_MODE="$2"; shift 2 ;; --base-jar) BASE_JAR="$2"; shift 2 ;; --base-area) BASE_AREA="$2"; shift 2 ;;+ --base-source) BASE_SOURCE="$2"; shift 2 ;;+ --extra-layer) EXTRA_LAYERS+=("$2"); shift 2 ;;+ --engine-base) ENGINE_BASE="$2"; shift 2 ;;+ --engine-safety) ENGINE_SAFETY="$2"; shift 2 ;;+ --engine-maxspeed) ENGINE_MAXSPEED="$2"; shift 2 ;;+ --engine-transit-lines) ENGINE_TRANSIT_LINES="$2"; shift 2 ;;+ --engine-admin) ENGINE_ADMIN="$2"; shift 2 ;;+ --dry-run) DRY_RUN=1; shift ;; --skip-base) SKIP_BASE=1; shift ;; --skip-safety) SKIP_SAFETY=1; shift ;; --skip-maxspeed) SKIP_MAXSPEED=1; shift ;;@@ -111,14 +138,49 @@ 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,72p' "$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 +# Every layer keeps a rust|legacy switch even before it has a rust path, so the+# superscript can pass one uniformly. Asking for an unported engine is an error+# rather than a silent fall-back to legacy.+engine_check() {+ local layer="$1" engine="$2" ported="$3"+ case "$engine" in+ legacy|rust) : ;;+ *) echo "ERROR: --engine-$layer must be rust|legacy (got '$engine')" >&2; exit 1 ;;+ esac+ if [[ "$engine" == "rust" && "$ported" != "1" ]]; then+ echo "ERROR: --engine-$layer rust is not implemented yet; use legacy" >&2+ exit 1+ fi+}+engine_check base "$ENGINE_BASE" 0+engine_check safety "$ENGINE_SAFETY" 0+engine_check maxspeed "$ENGINE_MAXSPEED" 0+engine_check transit-lines "$ENGINE_TRANSIT_LINES" 0+engine_check admin "$ENGINE_ADMIN" 0++run() {+ if [[ "$DRY_RUN" == "1" ]]; then+ printf '[dry-run]'+ printf ' %q' "$@"+ printf '\n'+ return 0+ fi+ "$@"+}+ command -v cargo >/dev/null || { echo "ERROR: cargo not installed (https://rustup.rs)" >&2; exit 1; } mkdir -p "$WORK" +# Hoisted out of the POIs branch: the summary block below reads it too, and+# leaving it branch-local meant `set -u` only spared us because both sites happen+# to share the same guard.+OUTDIR="$(cd "$(dirname "$OUT")" && pwd)"+ INPUTS=() # --- 1. base ---@@ -129,8 +191,9 @@ if [[ "$SKIP_BASE" == "1" ]]; then else BASE_ARGS=(--mode "$BASE_MODE" --out "$BASE") [[ -n "$BBOX" ]] && BASE_ARGS+=(--bbox "$BBOX")+ [[ -n "$BASE_SOURCE" ]] && BASE_ARGS+=(--source "$BASE_SOURCE") [[ "$BASE_MODE" == "build" ]] && BASE_ARGS+=(--jar "$BASE_JAR" --area "$BASE_AREA")- "$HERE/build_base_layers.sh" "${BASE_ARGS[@]}"+ run "$HERE/build_base_layers.sh" "${BASE_ARGS[@]}" fi INPUTS+=("$BASE") @@ -139,7 +202,7 @@ 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") [[ -n "$BBOX" ]] && SAFETY_ARGS+=(--bbox "$BBOX")- "$HERE/build_safety_layer.sh" "${SAFETY_ARGS[@]}"+ run "$HERE/build_safety_layer.sh" "${SAFETY_ARGS[@]}" INPUTS+=("$WORK/safety.pmtiles") fi @@ -148,7 +211,7 @@ if [[ "$SKIP_MAXSPEED" == "0" ]]; then [[ -n "$PBF" ]] || { echo "ERROR: --pbf required for maxspeed layer (or --skip-maxspeed)" >&2; exit 1; } MS_ARGS=(--pbf "$PBF" --out "$WORK/maxspeed.pmtiles") [[ -n "$BBOX" ]] && MS_ARGS+=(--bbox "$BBOX")- "$HERE/build_maxspeed_layer.sh" "${MS_ARGS[@]}"+ run "$HERE/build_maxspeed_layer.sh" "${MS_ARGS[@]}" INPUTS+=("$WORK/maxspeed.pmtiles") fi @@ -157,18 +220,17 @@ if [[ "$SKIP_TRANSIT_LINES" == "0" ]]; then [[ -n "$PBF" ]] || { echo "ERROR: --pbf required for transit_lines layer (or --skip-transit-lines)" >&2; exit 1; } TL_ARGS=(--pbf "$PBF" --out "$WORK/transit_lines.pmtiles") [[ -n "$BBOX" ]] && TL_ARGS+=(--bbox "$BBOX")- "$HERE/build_transit_lines_layer.sh" "${TL_ARGS[@]}"+ run "$HERE/build_transit_lines_layer.sh" "${TL_ARGS[@]}" INPUTS+=("$WORK/transit_lines.pmtiles") fi # --- 5. ma_pois (our baked OSM POI layer + poi_names.bin/poi_index.bin) --- if [[ "$SKIP_POIS" == "0" ]]; then [[ -n "$PBF" ]] || { echo "ERROR: --pbf required for ma_pois layer (or --skip-pois)" >&2; exit 1; }- OUTDIR="$(cd "$(dirname "$OUT")" && pwd)" POIS_ARGS=(--pbf "$PBF" --out "$WORK/ma_pois.pmtiles" \ --names-out "$OUTDIR/poi_names.bin" --index-out "$OUTDIR/poi_index.bin") [[ -n "$BBOX" ]] && POIS_ARGS+=(--bbox "$BBOX")- "$HERE/build_pois_layer.sh" "${POIS_ARGS[@]}"+ run "$HERE/build_pois_layer.sh" "${POIS_ARGS[@]}" INPUTS+=("$WORK/ma_pois.pmtiles") fi @@ -178,7 +240,7 @@ if [[ "$SKIP_ADMIN" == "0" ]]; then [[ -n "$PBF" ]] && ADMIN_ARGS+=(--pbf "$PBF") [[ -n "$BBOX" ]] && ADMIN_ARGS+=(--bbox "$BBOX") [[ -z "$PBF" ]] && ADMIN_ARGS+=(--no-city)- "$HERE/build_admin_layers.sh" "${ADMIN_ARGS[@]}"+ run "$HERE/build_admin_layers.sh" "${ADMIN_ARGS[@]}" for l in admin_country admin_region admin_city; do [[ -f "$WORK/admin/$l.pmtiles" ]] && INPUTS+=("$WORK/admin/$l.pmtiles") done@@ -192,22 +254,39 @@ if [[ "$SKIP_TRANSIT_STOPS" == "0" ]]; then # that never asked for stops. echo "[v5] no --gtfs-manifest given; skipping transit_stops layer" >&2 else- "$HERE/build_transit_stops_layer.sh" \+ run "$HERE/build_transit_stops_layer.sh" \ --manifest "$GTFS_MANIFEST" \ --out "$WORK/transit_stops.pmtiles" \ --workdir "$WORK/transit_stops" INPUTS+=("$WORK/transit_stops.pmtiles") fi fi++# --- 7b. layers the caller already built ---+# Last in, so an --extra-layer wins a name collision with anything above it.+for f in ${EXTRA_LAYERS[@]+"${EXTRA_LAYERS[@]}"}; do+ if [[ -f "$f" || "$DRY_RUN" == "1" ]]; then+ INPUTS+=("$f")+ else+ echo "ERROR: --extra-layer not found: $f" >&2+ exit 1+ fi+done+ # --- 8. merge --- echo "[v5] merging ${#INPUTS[@]} source(s) -> $OUT" printf ' + %s\n' "${INPUTS[@]}" # Our own tile_join, not tippecanoe's: it unions each tile's layers and carries # line/polygon geometry through untouched, and needs no tippecanoe install. Later # inputs win a layer-name collision, so a rebuilt overlay replaces a stale copy.-cargo run --release --quiet --manifest-path "$HERE/tile_build/Cargo.toml" \+run cargo run --release --quiet --manifest-path "$HERE/tile_build/Cargo.toml" \ --bin tile_join -- --out "$OUT" "${INPUTS[@]}" +if [[ "$DRY_RUN" == "1" ]]; then+ echo "[dry-run] stopping before the summary; nothing was built"+ exit 0+fi+ SIZE="$(stat -c%s "$OUT" 2>/dev/null || stat -f%z "$OUT" 2>/dev/null || echo '?')" echo "[v5] done: $OUT (${SIZE} bytes)" echo ""@@ -237,4 +316,6 @@ else echo "Then P13 updates style.json url -> pmtiles://https://data.vayunmathur.com/v5.pmtiles" fi +# Intermediates are never deleted, by design -- they are what makes a re-run cheap.+# --keep-work only silences this reminder. [[ "$KEEP_WORK" == "1" ]] || echo "(intermediates kept in $WORK; pass --keep-work to silence)"
scripts/maps/run_generator.sh
diff --git a/scripts/maps/run_generator.sh b/scripts/maps/run_generator.shindex 3346a151ac..1f34b436aa 100755--- a/scripts/maps/run_generator.sh+++ b/scripts/maps/run_generator.sh@@ -1,107 +1,75 @@ #!/bin/bash-set -o pipefail+set -euo pipefail++# run_generator.sh — DEPRECATED, kept as a thin wrapper over build_all.sh.+#+# What this used to do: build the routing graph (5 files), then `aws s3 sync` 7+# keys. The other two keys were poi_names.bin and poi_index.bin, which it never+# produced -- you had to copy them into map_data/ by hand first. Because the sync+# used `--exclude "*"` plus explicit `--include`s, forgetting that step uploaded+# 5 of 7 keys and still printed "Pipeline Finished Successfully".+#+# build_all.sh runs poi_extract itself, so those two files are always there. It+# also builds world.transit and the tile archive, which this script never did.+#+# The old CLI still works:+# ./run_generator.sh [california-latest.osm.pbf]+# and forwards to:+# ./build_all.sh --pbf <that> --out-dir map_data \+# --skip-transit --skip-tiles --publish+# i.e. the same 7 keys as before, minus the manual copy.+#+# TWO BEHAVIOUR CHANGES worth knowing:+# * Credentials. publish_r2.sh reads R2_ENDPOINT / R2_ACCESS_KEY_ID /+# R2_SECRET_ACCESS_KEY. This script read R2_ACCESS_KEY / R2_SECRET_KEY, so+# those two are bridged below for compatibility.+# * No AWS CLI bootstrap. publish_r2.sh uses rclone or aws, whichever is+# present, and tells you how to install one if neither is.+#+# For anything new, call build_all.sh directly -- it has --dry-run, per-stage+# skips, stamps, and a manifest.txt with sizes and SHA-256s.++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"++if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then+ sed -n '4,31p' "$0" | sed 's/^# \?//'+ exit 0+fi -# --- CONFIGURATION --- # Load environment variables from .env file if it exists-if [ -f .env ]; then+if [[ -f .env ]]; then echo "Loading configuration from .env..." set -a+ # shellcheck disable=SC1091 source .env set +a fi -R2_ENDPOINT="${R2_ENDPOINT:-https://<ACCOUNT_ID>.r2.cloudflarestorage.com}"-BUCKET_NAME="${BUCKET_NAME:-maps}"-ACCESS_KEY="${R2_ACCESS_KEY:-ACCESS_KEY_HERE}"-SECRET_KEY="${R2_SECRET_KEY:-SECRET_KEY_HERE}"-DEFAULT_PBF="california-latest.osm.pbf"-DATA_DIR="map_data"-HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-INGEST_DIR="$HERE/osm_ingest"--# Helper to run commands with sudo only if available-run_cmd() {- if command -v sudo >/dev/null 2>&1; then- sudo "$@"- else- "$@"- fi-}--# Use provided argument or default to california-latest.osm.pbf-INPUT_PBF="${1:-$DEFAULT_PBF}"+# Bridge the old credential names onto the ones publish_r2.sh reads.+export R2_ACCESS_KEY_ID="${R2_ACCESS_KEY_ID:-${R2_ACCESS_KEY:-}}"+export R2_SECRET_ACCESS_KEY="${R2_SECRET_ACCESS_KEY:-${R2_SECRET_KEY:-}}"+export R2_BUCKET="${R2_BUCKET:-${BUCKET_NAME:-maps}}" -# --- 1. SYSTEM DEPENDENCIES ----# The graph builder is Rust (scripts/maps/osm_ingest) and reads .osm.pbf-# natively, so there is no libosmium/g++/zlib toolchain to install any more ---# only cargo, and the AWS CLI for the upload. On Windows use build_graph.ps1-# instead; it runs the same builder without needing bash at all.-echo "[1/5] Checking build tools..."-command -v cargo >/dev/null || { echo "ERROR: cargo not installed (https://rustup.rs)" >&2; exit 1; }+INPUT_PBF="${1:-california-latest.osm.pbf}" -# --- 2. AWS CLI INSTALLATION ----if ! command -v aws &> /dev/null; then- echo "[2/5] Installing AWS CLI v2..."- curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"- unzip -q awscliv2.zip- run_cmd ./aws/install- rm -rf aws awscliv2.zip-else- echo "[2/5] AWS CLI is already installed."-fi+echo "=========================================================" >&2+echo "run_generator.sh is DEPRECATED. It now just calls:" >&2+echo " build_all.sh --pbf $INPUT_PBF --out-dir map_data \\" >&2+echo " --skip-transit --skip-tiles --publish" >&2+echo "Use build_all.sh directly for the full 9-artifact build." >&2+echo "=========================================================" >&2 -# --- 3. DATA DOWNLOAD ----if [ ! -f "$INPUT_PBF" ]; then- echo "[3/5] $INPUT_PBF not found. Downloading California extract..."- curl -OL "https://download.geofabrik.de/north-america/us/california-latest.osm.pbf"+ARGS=(--out-dir map_data --skip-transit --skip-tiles --publish)+if [[ -f "$INPUT_PBF" ]]; then+ ARGS=(--pbf "$INPUT_PBF" "${ARGS[@]}")+elif [[ "$INPUT_PBF" == "california-latest.osm.pbf" ]]; then+ # Only auto-download the one extract this script always defaulted to; any+ # other missing path is a typo, and fetching California for it would build a+ # graph for the wrong region.+ ARGS=(--geofabrik north-america/us/california "${ARGS[@]}") else- echo "[3/5] $INPUT_PBF already exists. Skipping download."-fi--# --- 4. CLOUDFLARE R2 CONFIGURATION ----echo "[4/5] Configuring credentials for R2..."-aws configure set aws_access_key_id "$ACCESS_KEY" --profile r2-aws configure set aws_secret_access_key "$SECRET_KEY" --profile r2-aws configure set region auto --profile r2--# --- 5. GRAPH BUILD ----# Must be gated: on failure the output files have already been truncated by the-# builder, and syncing those to R2 would publish a partial graph over the live one.-echo "[5/5] Building the routing graph..."-if ! cargo run --release --manifest-path "$INGEST_DIR/Cargo.toml" --bin road_graph -- \- "$INPUT_PBF" --out "$DATA_DIR"; then- echo "ERROR: road_graph failed; not uploading anything." >&2+ echo "ERROR: pbf not found: $INPUT_PBF" >&2 exit 1 fi -# --- 6. AUTOMATED UPLOAD ----echo "Uploading files to Cloudflare R2..."--# 6a. Upload the SINGLE GLOBAL routing graph (no per-zone artifacts).-# These are exactly the files maps/src/main/rust/src/graph.rs mmaps from one-# directory. The offline TILE packs (zone_*.pmtiles) and the P11 transit index-# (world.transit) are published separately (extract_pmtiles.sh / gtfs_ingest)-# and are intentionally NOT part of this graph upload.-#-# poi_names.bin / poi_index.bin are the P27 POI side files emitted by-# build_v5_pmtiles.sh (build_pois_layer.sh) beside v5.pmtiles. Copy them into-# "$DATA_DIR" before this sync (or point --workdir/--out there) so the app can-# fetch them from the same data.vayunmathur.com host as the graph.-echo "Syncing single global graph to R2..."--aws s3 sync "$DATA_DIR" "s3://$BUCKET_NAME/" \- --endpoint-url "$R2_ENDPOINT" \- --profile r2 \- --content-type "application/octet-stream" \- --exclude "*" \- --include "metadata.bin" \- --include "road_names.bin" \- --include "nodes.bin" \- --include "edges.bin" \- --include "lanes.bin" \- --include "poi_names.bin" \- --include "poi_index.bin"--echo "---------------------------------------------------------"-echo "Pipeline Finished Successfully."-echo "---------------------------------------------------------"\ No newline at end of file+exec "$HERE/build_all.sh" "${ARGS[@]}"
scripts/maps/test/diff_geojsonseq.py
diff --git a/scripts/maps/test/diff_geojsonseq.py b/scripts/maps/test/diff_geojsonseq.pynew file mode 100644index 0000000000..8858f0e77d--- /dev/null+++ b/scripts/maps/test/diff_geojsonseq.py@@ -0,0 +1,232 @@+#!/usr/bin/env python3+"""diff_geojsonseq.py — the extraction half of the differential harness.++Runs a legacy (osmium/ogr2ogr + normalize_*.py) GeoJSONSeq and a Rust+(osm_extract) one through the same canonicaliser and diffs them. This is the real+safety net for the port: every layer that moves to Rust gets checked here against+the pipeline it replaces, on the same PBF, before its `--engine` default flips.++WHAT MUST MATCH, AND WHY THE TOLERANCES DIFFER:++ * Properties: exactly, always. Every attribute is either a raw tag passthrough+ or a documented classification, so any difference is a bug, not a rounding+ artefact. `maxspeed` is the sharp case -- "35 mph" must survive as the string+ "35 mph", so a normalising parse shows up here as a property diff.++ * Point geometry: exactly, to the 7 decimal places both sides emit. A node's+ coordinate is copied, not computed.++ * Line and polygon geometry: within --epsilon (default 1e-7 degrees, i.e. the+ last emitted digit). The two sides reach the same vertices by different+ routes -- libosmium assembles ways through its own node cache, we look them+ up in a sorted table -- so the final decimal can differ. Vertex COUNTS and+ nesting structure must still match exactly; a different number of vertices is+ a different shape, not a rounding difference.++Features are paired on --key-prop (default `osm_id`), which both pipelines carry+and which is stable across them. Features with no key are paired on rounded+geometry instead, and unpairable ones are reported rather than ignored.++Usage:+ ./diff_geojsonseq.py legacy.geojsonseq rust.geojsonseq+ ./diff_geojsonseq.py legacy.geojsonseq rust.geojsonseq --epsilon 1e-6+ ./diff_geojsonseq.py a.geojsonseq b.geojsonseq --ignore-prop timestamp++Exit code 0 when the two agree within tolerance, 1 otherwise.+"""++from __future__ import annotations++import argparse+import sys+from pathlib import Path+from typing import Any++ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(ROOT))++# Reuse the normalisers' own reader so the harness accepts exactly the inputs+# they do: geojsonseq, a FeatureCollection, and the \x1e record separator.+from normalize_safety import iter_features # noqa: E402++POINT_TYPES = ("Point", "MultiPoint")+++def load(path: Path) -> list[dict[str, Any]]:+ return list(iter_features(path.read_text(encoding="utf-8")))+++def feature_key(feat: dict[str, Any], key_prop: str) -> str:+ props = feat.get("properties") or {}+ key = props.get(key_prop)+ if key not in (None, ""):+ return f"{key_prop}={key}"+ # No stable id: fall back to the geometry, rounded hard enough that the two+ # pipelines' last-digit disagreement cannot split a pair.+ return "geom=" + repr(round_coords(feat.get("geometry") or {}, 5))+++def round_coords(geom: Any, places: int) -> Any:+ if isinstance(geom, dict):+ return {k: round_coords(v, places) for k, v in sorted(geom.items())}+ if isinstance(geom, list):+ return [round_coords(v, places) for v in geom]+ if isinstance(geom, float):+ return round(geom, places)+ return geom+++def coord_shape(coords: Any) -> Any:+ """Nesting structure and vertex counts, with the numbers removed.++ A shape mismatch means a genuinely different geometry and is never excused by+ --epsilon.+ """+ if isinstance(coords, list):+ if coords and not isinstance(coords[0], list):+ return len(coords)+ return [coord_shape(c) for c in coords]+ return 0+++def max_coord_delta(a: Any, b: Any) -> float:+ if isinstance(a, list) and isinstance(b, list):+ if len(a) != len(b):+ return float("inf")+ return max((max_coord_delta(x, y) for x, y in zip(a, b)), default=0.0)+ if isinstance(a, (int, float)) and isinstance(b, (int, float)):+ return abs(float(a) - float(b))+ return 0.0 if a == b else float("inf")+++def compare_geometry(a: dict[str, Any], b: dict[str, Any], epsilon: float) -> str | None:+ at, bt = a.get("type"), b.get("type")+ if at != bt:+ return f"geometry type {at!r} vs {bt!r}"+ sa, sb = coord_shape(a.get("coordinates")), coord_shape(b.get("coordinates"))+ if sa != sb:+ return f"geometry shape {sa} vs {sb}"+ delta = max_coord_delta(a.get("coordinates"), b.get("coordinates"))+ # Points are copied coordinates, so they get no tolerance at all.+ tolerance = 0.0 if at in POINT_TYPES else epsilon+ if delta > tolerance:+ return f"geometry differs by {delta:.3e} (tolerance {tolerance:.3e})"+ return None+++def compare_props(+ a: dict[str, Any], b: dict[str, Any], ignore: set[str]+) -> list[str]:+ out = []+ keys = (set(a) | set(b)) - ignore+ for k in sorted(keys):+ if k not in a:+ out.append(f"property {k!r} only in rust ({b[k]!r})")+ elif k not in b:+ out.append(f"property {k!r} only in legacy ({a[k]!r})")+ elif a[k] != b[k]:+ out.append(f"property {k!r}: legacy {a[k]!r} vs rust {b[k]!r}")+ return out+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument("legacy", type=Path, help="GeoJSONSeq from the osmium/python path")+ ap.add_argument("rust", type=Path, help="GeoJSONSeq from osm_extract")+ ap.add_argument(+ "--epsilon",+ type=float,+ default=1e-7,+ help="per-coordinate tolerance in degrees for lines and polygons "+ "(default 1e-7, the last emitted digit). Points always require exactness.",+ )+ ap.add_argument(+ "--key-prop",+ default="osm_id",+ help="property both sides carry, used to pair features (default osm_id)",+ )+ ap.add_argument(+ "--ignore-prop",+ action="append",+ default=[],+ help="property to exclude from the comparison (repeatable)",+ )+ ap.add_argument(+ "--max-report",+ type=int,+ default=20,+ help="stop printing after this many differing features (default 20)",+ )+ args = ap.parse_args()++ legacy = load(args.legacy)+ rust = load(args.rust)+ ignore = set(args.ignore_prop)++ lmap: dict[str, dict[str, Any]] = {}+ rmap: dict[str, dict[str, Any]] = {}+ ldupes = rdupes = 0+ for feats, m in ((legacy, lmap), (rust, rmap)):+ for f in feats:+ k = feature_key(f, args.key_prop)+ if k in m:+ # Duplicate keys make a pairing ambiguous. Count them rather than+ # silently letting the last one win and calling the run clean.+ if m is lmap:+ ldupes += 1+ else:+ rdupes += 1+ continue+ m[k] = f++ print(f"legacy: {len(legacy)} feature(s), {len(lmap)} unique key(s)")+ print(f"rust : {len(rust)} feature(s), {len(rmap)} unique key(s)")+ if ldupes or rdupes:+ print(f"WARNING: duplicate keys skipped -- legacy {ldupes}, rust {rdupes}")++ only_legacy = sorted(set(lmap) - set(rmap))+ only_rust = sorted(set(rmap) - set(lmap))+ prop_diffs: list[tuple[str, list[str]]] = []+ geom_diffs: list[tuple[str, str]] = []++ for k in sorted(set(lmap) & set(rmap)):+ a, b = lmap[k], rmap[k]+ pd = compare_props(a.get("properties") or {}, b.get("properties") or {}, ignore)+ if pd:+ prop_diffs.append((k, pd))+ gd = compare_geometry(a.get("geometry") or {}, b.get("geometry") or {}, args.epsilon)+ if gd:+ geom_diffs.append((k, gd))++ def report(title: str, items: list, fmt) -> None:+ if not items:+ return+ print(f"\n{title} ({len(items)}):")+ for item in items[: args.max_report]:+ print(fmt(item))+ if len(items) > args.max_report:+ print(f" ... and {len(items) - args.max_report} more")++ report("only in legacy", only_legacy, lambda k: f" {k}")+ report("only in rust", only_rust, lambda k: f" {k}")+ report(+ "property differences",+ prop_diffs,+ lambda kv: " " + kv[0] + "\n" + "\n".join(f" {d}" for d in kv[1]),+ )+ report("geometry differences", geom_diffs, lambda kv: f" {kv[0]}: {kv[1]}")++ failures = len(only_legacy) + len(only_rust) + len(prop_diffs) + len(geom_diffs)+ print()+ if failures == 0:+ print(f"OK: {len(lmap)} feature(s) agree (epsilon {args.epsilon:.3e})")+ return 0+ print(+ f"FAIL: {len(only_legacy)} legacy-only, {len(only_rust)} rust-only, "+ f"{len(prop_diffs)} property diff(s), {len(geom_diffs)} geometry diff(s)"+ )+ return 1+++if __name__ == "__main__":+ sys.exit(main())
scripts/maps/test/diff_pmtiles.py
diff --git a/scripts/maps/test/diff_pmtiles.py b/scripts/maps/test/diff_pmtiles.pynew file mode 100644index 0000000000..e6b0385e2f--- /dev/null+++ b/scripts/maps/test/diff_pmtiles.py@@ -0,0 +1,199 @@+#!/usr/bin/env python3+"""diff_pmtiles.py — the tiling half of the differential harness.++Compares a tippecanoe-built archive against one of ours by decoding both with+`tile_build`'s `pmtiles_dump` and diffing the decoded model.++WHY NOT A BYTE COMPARISON. Three reasons, all documented in the plan and none of+them fixable:++ * `--drop-densest-as-needed` is a lossy per-tile heuristic. We deliberately+ implement a different, deterministic drop policy instead, so per-tile feature+ counts will not match. --max-feature-delta is the budget for that difference,+ and the point of the flag is to make the size of the divergence explicit+ rather than unbounded.+ * `--extend-zooms-if-still-dropping` can push tippecanoe's archive past its own+ --maximum-zoom. We do not reproduce it, so tippecanoe may carry zooms we+ have no opinion about; those are reported, not failed, unless --strict-zooms.+ * An MVT re-encode rebuilds each layer's key/value dictionaries in first-use+ order, so even an untouched tile comes back a few bytes different.++WHAT IS HELD TO EXACTNESS:+ * Which layers appear at which zooms (modulo the extended-zoom caveat above).+ * The property key set per (zoom, layer). A missing or extra attribute is a+ schema break, and the app reads these by name.+ * The tile extent.+ * Geometry type mix per (zoom, layer) -- a line layer must not start emitting+ polygons.++Usage:+ ./diff_pmtiles.py legacy.pmtiles ours.pmtiles+ ./diff_pmtiles.py legacy.pmtiles ours.pmtiles --layer maxspeed --max-feature-delta 10+ ./diff_pmtiles.py a.pmtiles b.pmtiles --strict-zooms++Exit code 0 when they agree within the stated budget, 1 otherwise.+"""++from __future__ import annotations++import argparse+import subprocess+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+CRATE = ROOT / "tile_build"+++def dump_command(explicit: Path | None) -> list[str]:+ if explicit:+ return [str(explicit)]+ for name in ("pmtiles_dump", "pmtiles_dump.exe"):+ built = CRATE / "target" / "release" / name+ if built.exists():+ return [str(built)]+ # Falling back to `cargo run` keeps this usable on a clean checkout, at the+ # cost of a build on first use.+ return [+ "cargo",+ "run",+ "--release",+ "--quiet",+ "--manifest-path",+ str(CRATE / "Cargo.toml"),+ "--bin",+ "pmtiles_dump",+ "--",+ ]+++def run_dump(cmd: list[str], archive: Path, layer: str | None) -> dict[tuple[str, str], dict[str, str]]:+ argv = cmd + [str(archive)]+ if layer:+ argv += ["--layer", layer]+ proc = subprocess.run(argv, capture_output=True, text=True)+ if proc.returncode != 0:+ sys.stderr.write(proc.stderr)+ raise SystemExit(f"pmtiles_dump failed on {archive}")+ if proc.stderr.strip():+ sys.stderr.write(proc.stderr)++ out: dict[tuple[str, str], dict[str, str]] = {}+ for line in proc.stdout.splitlines():+ parts = line.split("\t")+ if len(parts) < 3:+ continue+ zoom, layer_name = parts[0], parts[1]+ fields = {}+ for p in parts[2:]:+ k, _, v = p.partition("=")+ fields[k] = v+ out[(zoom, layer_name)] = fields+ return out+++def zoom_num(z: str) -> int:+ return int(z.lstrip("z"))+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument("legacy", type=Path, help="archive built by tippecanoe")+ ap.add_argument("ours", type=Path, help="archive built by tile_build")+ ap.add_argument("--layer", help="restrict the comparison to one layer")+ ap.add_argument(+ "--max-feature-delta",+ type=float,+ default=5.0,+ help="permitted per-(zoom,layer) feature-count difference, in percent of "+ "the legacy count (default 5). This is the documented drop delta.",+ )+ ap.add_argument(+ "--dump",+ type=Path,+ help="path to a pmtiles_dump binary (default: the crate's release build, "+ "else `cargo run`)",+ )+ ap.add_argument(+ "--strict-zooms",+ action="store_true",+ help="treat a zoom present in only one archive as a failure. Off by "+ "default because --extend-zooms-if-still-dropping is not reproduced.",+ )+ args = ap.parse_args()++ cmd = dump_command(args.dump)+ legacy = run_dump(cmd, args.legacy, args.layer)+ ours = run_dump(cmd, args.ours, args.layer)++ print(f"legacy: {len(legacy)} (zoom, layer) pair(s) {args.legacy}")+ print(f"ours : {len(ours)} (zoom, layer) pair(s) {args.ours}")++ only_legacy = sorted(set(legacy) - set(ours), key=lambda p: (zoom_num(p[0]), p[1]))+ only_ours = sorted(set(ours) - set(legacy), key=lambda p: (zoom_num(p[0]), p[1]))++ failures: list[str] = []+ warnings: list[str] = []++ # A layer missing from one side at a zoom BOTH sides cover is a real hole. The+ # same thing at a zoom only one side reaches is the extended-zoom caveat.+ legacy_zooms = {z for z, _ in legacy}+ our_zooms = {z for z, _ in ours}+ for pair in only_legacy:+ msg = f"{pair[0]} {pair[1]}: in legacy, absent from ours"+ (failures if (pair[0] in our_zooms or args.strict_zooms) else warnings).append(msg)+ for pair in only_ours:+ msg = f"{pair[0]} {pair[1]}: in ours, absent from legacy"+ (failures if (pair[0] in legacy_zooms or args.strict_zooms) else warnings).append(msg)++ for pair in sorted(set(legacy) & set(ours), key=lambda p: (zoom_num(p[0]), p[1])):+ a, b = legacy[pair], ours[pair]+ label = f"{pair[0]} {pair[1]}"++ akeys = set(filter(None, a.get("keys", "").split(",")))+ bkeys = set(filter(None, b.get("keys", "").split(",")))+ if akeys != bkeys:+ missing = sorted(akeys - bkeys)+ extra = sorted(bkeys - akeys)+ failures.append(f"{label}: property keys differ (missing {missing}, extra {extra})")++ if a.get("extent") != b.get("extent"):+ failures.append(f"{label}: extent {a.get('extent')} vs {b.get('extent')}")++ ageoms = {p.split(":")[0] for p in a.get("geom", "").split(",") if p}+ bgeoms = {p.split(":")[0] for p in b.get("geom", "").split(",") if p}+ if ageoms != bgeoms:+ failures.append(f"{label}: geometry types {sorted(ageoms)} vs {sorted(bgeoms)}")++ af = int(a.get("features", 0))+ bf = int(b.get("features", 0))+ if af == 0:+ if bf != 0:+ failures.append(f"{label}: legacy has 0 features, ours has {bf}")+ else:+ pct = abs(bf - af) / af * 100.0+ if pct > args.max_feature_delta:+ failures.append(+ f"{label}: features {af} vs {bf} ({pct:.1f}% > "+ f"{args.max_feature_delta:.1f}% budget)"+ )+ elif bf != af:+ warnings.append(f"{label}: features {af} vs {bf} ({pct:.1f}%, within budget)")++ if warnings:+ print(f"\nwithin budget / expected ({len(warnings)}):")+ for w in warnings:+ print(f" {w}")++ print()+ if not failures:+ print(f"OK: {len(set(legacy) & set(ours))} (zoom, layer) pair(s) agree")+ return 0+ print(f"FAIL ({len(failures)}):")+ for f in failures:+ print(f" {f}")+ return 1+++if __name__ == "__main__":+ sys.exit(main())
scripts/maps/tile_build/Cargo.toml
diff --git a/scripts/maps/tile_build/Cargo.toml b/scripts/maps/tile_build/Cargo.tomlindex 483ae36f81..b0ec17188d 100644--- a/scripts/maps/tile_build/Cargo.toml+++ b/scripts/maps/tile_build/Cargo.toml@@ -31,6 +31,9 @@ path = "src/bin/tile_points.rs" [[bin]] name = "tile_join" path = "src/bin/tile_join.rs"+[[bin]]+name = "pmtiles_dump"+path = "src/bin/pmtiles_dump.rs" [dependencies] miniz_oxide = "0.8" [profile.release]
scripts/maps/tile_build/src/bin/pmtiles_dump.rs
diff --git a/scripts/maps/tile_build/src/bin/pmtiles_dump.rs b/scripts/maps/tile_build/src/bin/pmtiles_dump.rsnew file mode 100644index 0000000000..a2d7c1e2b1--- /dev/null+++ b/scripts/maps/tile_build/src/bin/pmtiles_dump.rs@@ -0,0 +1,243 @@+//! `pmtiles_dump` — print a canonical, line-oriented summary of a PMTiles+//! archive. The decoder half of the differential harness.+//!+//! Usage:+//! pmtiles_dump IN.pmtiles [--mode summary|tiles|header] [--layer NAME]+//!+//! Output is deterministic and sorted, so two archives can be compared with a+//! plain textual diff. That is the point: comparing our tiler against tippecanoe+//! byte-for-byte is meaningless (`--drop-densest-as-needed` is a lossy per-tile+//! heuristic, and a re-encode reorders the key/value dictionaries anyway), so the+//! harness compares the decoded model instead — which layers exist at which+//! zooms, how many features they hold, and which property keys they carry.+//!+//! Modes:+//! summary one line per (zoom, layer): tile/feature counts, geometry-type+//! counts, and the sorted union of property keys. The default, and+//! what `diff_pmtiles.py` reads.+//! tiles one line per (z/x/y, layer). Verbose, for chasing a single tile.+//! header the archive header fields, one per line.++use std::collections::{BTreeMap, BTreeSet};+use std::process::ExitCode;+use tile_build::mvt::{GeomType, Tile};+use tile_build::{gz, pmtiles};++fn main() -> ExitCode {+ let args: Vec<String> = std::env::args().collect();+ let mut input = None;+ let mut mode = "summary".to_string();+ let mut only_layer: Option<String> = None;++ let mut i = 1;+ while i < args.len() {+ let take = |i: usize| args.get(i + 1).cloned();+ match args[i].as_str() {+ "--mode" => {+ match take(i) {+ Some(m) => mode = m,+ None => {+ eprintln!("pmtiles_dump: --mode needs a value");+ return ExitCode::from(2);+ }+ }+ i += 2;+ }+ "--layer" => {+ only_layer = take(i);+ i += 2;+ }+ "-h" | "--help" => {+ usage();+ return ExitCode::SUCCESS;+ }+ other if other.starts_with('-') => {+ eprintln!("pmtiles_dump: unexpected argument '{other}'");+ usage();+ return ExitCode::from(2);+ }+ other => {+ if input.is_some() {+ eprintln!("pmtiles_dump: more than one input archive given");+ return ExitCode::from(2);+ }+ input = Some(other.to_string());+ i += 1;+ }+ }+ }++ let Some(input) = input else {+ eprintln!("pmtiles_dump: an input archive is required");+ usage();+ return ExitCode::from(2);+ };+ if !matches!(mode.as_str(), "summary" | "tiles" | "header") {+ eprintln!("pmtiles_dump: --mode must be summary|tiles|header (got '{mode}')");+ return ExitCode::from(2);+ }++ let bytes = match std::fs::read(&input) {+ Ok(b) => b,+ Err(e) => {+ eprintln!("pmtiles_dump: cannot read {input}: {e}");+ return ExitCode::FAILURE;+ }+ };+ let archive = match pmtiles::Archive::parse(&bytes) {+ Ok(a) => a,+ Err(e) => {+ eprintln!("pmtiles_dump: {input} is not a readable PMTiles archive: {e}");+ return ExitCode::FAILURE;+ }+ };++ if mode == "header" {+ let h = &archive.header;+ println!("min_zoom\t{}", h.min_zoom);+ println!("max_zoom\t{}", h.max_zoom);+ println!("addressed_tiles\t{}", h.addressed_tiles);+ println!("tile_entries\t{}", h.tile_entries);+ println!("tile_contents\t{}", h.tile_contents);+ println!("clustered\t{}", h.clustered);+ println!("tile_type\t{}", h.tile_type);+ println!("tile_compression\t{}", h.tile_compression);+ println!("min_lon_e7\t{}", h.min_lon_e7);+ println!("min_lat_e7\t{}", h.min_lat_e7);+ println!("max_lon_e7\t{}", h.max_lon_e7);+ println!("max_lat_e7\t{}", h.max_lat_e7);+ return ExitCode::SUCCESS;+ }++ let tiles = match archive.iter_tiles() {+ Ok(t) => t,+ Err(e) => {+ eprintln!("pmtiles_dump: cannot walk the tile directory: {e}");+ return ExitCode::FAILURE;+ }+ };++ // (zoom, layer) -> accumulator, ordered by BTreeMap so the output is sorted+ // without a separate sort step.+ let mut agg: BTreeMap<(u8, String), Agg> = BTreeMap::new();+ let mut undecodable = 0usize;++ for (id, body) in tiles {+ let (z, x, y) = pmtiles::tile_zxy(id);+ let raw = if archive.header.tile_compression == pmtiles::COMPRESSION_GZIP {+ match gz::decompress(body) {+ Ok(v) => v,+ Err(e) => {+ eprintln!("pmtiles_dump: z{z}/{x}/{y}: {e}");+ undecodable += 1;+ continue;+ }+ }+ } else {+ body.to_vec()+ };+ let tile = match Tile::decode(&raw) {+ Ok(t) => t,+ Err(e) => {+ eprintln!("pmtiles_dump: z{z}/{x}/{y}: {e}");+ undecodable += 1;+ continue;+ }+ };+ for layer in &tile.layers {+ if let Some(want) = &only_layer {+ if &layer.name != want {+ continue;+ }+ }+ if mode == "tiles" {+ let mut keys: BTreeSet<&str> = BTreeSet::new();+ let mut geoms: BTreeMap<&str, usize> = BTreeMap::new();+ for f in &layer.features {+ *geoms.entry(geom_name(f.geom_type)).or_insert(0) += 1;+ for (k, _) in &f.props {+ keys.insert(k.as_str());+ }+ }+ println!(+ "{z}/{x}/{y}\t{}\tfeatures={}\textent={}\tgeom={}\tkeys={}",+ layer.name,+ layer.features.len(),+ layer.extent,+ join_counts(&geoms),+ keys.into_iter().collect::<Vec<_>>().join(","),+ );+ }+ let e = agg.entry((z, layer.name.clone())).or_default();+ e.tiles += 1;+ e.features += layer.features.len();+ e.extents.insert(layer.extent);+ for f in &layer.features {+ *e.geoms.entry(geom_name(f.geom_type).to_string()).or_insert(0) += 1;+ for (k, _) in &f.props {+ e.keys.insert(k.clone());+ }+ }+ }+ }++ if mode == "summary" {+ for ((z, layer), a) in &agg {+ println!(+ "z{z}\t{layer}\ttiles={}\tfeatures={}\textent={}\tgeom={}\tkeys={}",+ a.tiles,+ a.features,+ a.extents+ .iter()+ .map(|e| e.to_string())+ .collect::<Vec<_>>()+ .join("/"),+ join_counts_owned(&a.geoms),+ a.keys.iter().cloned().collect::<Vec<_>>().join(","),+ );+ }+ }++ if undecodable > 0 {+ // Loud on stderr but not fatal: a partial dump of a damaged archive is+ // still the most useful thing to hand the differ.+ eprintln!("pmtiles_dump: {undecodable} tile(s) could not be decoded");+ }+ ExitCode::SUCCESS+}++#[derive(Default)]+struct Agg {+ tiles: usize,+ features: usize,+ extents: BTreeSet<u32>,+ geoms: BTreeMap<String, usize>,+ keys: BTreeSet<String>,+}++fn geom_name(t: GeomType) -> &'static str {+ match t {+ GeomType::Unknown => "unknown",+ GeomType::Point => "point",+ GeomType::LineString => "line",+ GeomType::Polygon => "polygon",+ }+}++fn join_counts(m: &BTreeMap<&str, usize>) -> String {+ m.iter()+ .map(|(k, v)| format!("{k}:{v}"))+ .collect::<Vec<_>>()+ .join(",")+}++fn join_counts_owned(m: &BTreeMap<String, usize>) -> String {+ m.iter()+ .map(|(k, v)| format!("{k}:{v}"))+ .collect::<Vec<_>>()+ .join(",")+}++fn usage() {+ eprintln!("usage: pmtiles_dump IN.pmtiles [--mode summary|tiles|header] [--layer NAME]");+}