Modern Apps git

← Modern-Apps.git

maps: port the OSM ingesters from libosmium to Rust

Commit
4e5901ad89f5d230bb8bec423c39b47c62a93c0a
Author
vayun-mathur <[email protected]>
When
2026-08-21 00:59 UTC (3 months ago)
Parents
c2e4478

Diff

maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.ktindex 758685d80b..1901173c4d 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt@@ -3,7 +3,8 @@ package com.vayunmathur.maps.util /**  * Shared metadata for the OSM POI `type` enum baked into the v5 `ma_pois`  * source-layer and the `poi_index.bin` side file (P27). The numbering is the- * stable type map defined in `scripts/maps/README.md` / `poi_extract.cpp`+ * stable type map defined in `scripts/maps/README.md` /+ * `scripts/maps/osm_ingest/src/tags.rs`  * (0..49 categories, 255 = "other"); never renumber, only append.  *  * Kept in one place so the map render ([com.vayunmathur.maps.ui.MaPoisLayer],
scripts/maps/P11_OFFLINE_TRANSIT_SPIKE.md
diff --git a/scripts/maps/P11_OFFLINE_TRANSIT_SPIKE.md b/scripts/maps/P11_OFFLINE_TRANSIT_SPIKE.mdindex 53e5736b66..18a5289cb9 100644--- a/scripts/maps/P11_OFFLINE_TRANSIT_SPIKE.md+++ b/scripts/maps/P11_OFFLINE_TRANSIT_SPIKE.md@@ -16,6 +16,39 @@ artifacts committed. This document is the deliverable. > Net: the spike verdict (VIABLE) held, and the build tracked the plan. Consequently > the §1d gaps and several "blockers" in §4 are now addressed in code. +> **SECOND UPDATE (legacy transit path deleted).** The pre-build machinery this+> report describes in §2 no longer exists, so treat every file/line reference+> below as **historical**. Specifically, all of the following were removed once the+> RAPTOR planner was correct enough to be the only transit path:+>+> - `generator.cpp`'s **synthesized 15-minute headways**, its `transit.csv` input,+>   the `TRANSIT_FLAG` edge set, `transit_voyages.bin`, `transit_attributes.bin`,+>   the road↔transit transfer edges, and the **duplicated node per OSM node** the+>   `transit_nodes_mask` created.+> - `routing.rs`'s time-dependent transit A\* (the boarded-vs-not node "state" bit+>   and the 2-state heap key), `geometry.rs::get_transit_edge_time_10ms`, and+>   `graph.rs`'s voyage/attribute regions.+> - **`present_feeds` end-to-end.** Its only consumer was the deleted+>   "feed not present offline" degradation in `get_transit_edge_time_10ms`, so the+>   whole switch went with it — including the JNI `init(basePath, presentFeeds[])`+>   parameter. §2's framing of `present_feeds` as "exactly the switch P11 needs"+>   did not survive contact with a real timetable engine: the RAPTOR index is+>   discovered by bounding box per pack, which subsumes it.+>+> `TravelMode.PUBLIC_TRANSIT` in the road graph now means **walking** — it is only+> reached for a journey's access/egress/transfer legs. Because the duplicated+> nodes are gone, `node_count`/`edge_count` changed and every road pack must be+> regenerated; `metadata.bin` gained a magic + version so a mixed-vintage pack+> directory is rejected instead of misread.++> **THIRD UPDATE (the C++ generator is gone).** `generator.cpp` and+> `poi_extract.cpp`, described throughout §1a and §2, were replaced by+> **`scripts/maps/osm_ingest`** (Rust; `road_graph` + `poi_extract` binaries). It+> reads `.osm.pbf` natively, so the libosmium/`g++`/WSL toolchain those sections+> describe no longer applies and every `generator.cpp:NNN` line reference below is+> dead. The on-disk graph layout is unchanged. This completes §3c's "NO+> hand-written C++" direction for the ingest side as well.+ **Scope of the spike (from task #144 / `VELA_PORT_PLAN.md` P11):** investigate offline transit routing from the SAME Transitous/GTFS data as the P10 boards — ingest per-region GTFS into the downloadable offline packs + an on-device
scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex 479f8aebba..5be9bf63fe 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -39,12 +39,12 @@ all from the same file.   * `extract_pmtiles.sh` slices the world pmtiles into 64 Morton-grid     `zone_$i.pmtiles` offline packs. Tiles stay **zoned** (a single global     basemap is a ~137 GB download — see the size table below).-  * `generator.cpp` + `run_generator.sh` build the **routing graph** as a-    **single global graph** (`nodes.bin`, `edges.bin`, `transit_voyages.bin`,-    `transit_attributes.bin`, `lanes.bin`, `metadata.bin`, `road_names.bin`)-    with libosmium — see [Single global routing graph](#single-global-routing-graph-p16)-    below. **This is the routing-graph generator that P11 edits for GTFS** — it-    already has transit/GTFS scaffolding.+  * `osm_ingest` + `run_generator.sh` build the **routing graph** as a+    **single global graph** (`nodes.bin`, `edges.bin`, `lanes.bin`,+    `metadata.bin`, `road_names.bin`) — see+    [Single global routing graph](#single-global-routing-graph-p16)+    below. It carries **roads only**; public-transit timetables live in the+    separate `.transit` index built by `gtfs_ingest`.  --- @@ -96,7 +96,8 @@ lets POI **placement / name / type** come from OpenStreetMap instead of a runtime Google viewport scrape (Google is then hit only for rich details on tap). It deliberately does **not** reuse the base Protomaps `pois` layer (which the app suppresses). It is built by [`build_pois_layer.sh`](build_pois_layer.sh)-(→ [`poi_extract.cpp`](poi_extract.cpp)) at zooms **z12–z16**. The same pass also+(→ [`osm_ingest`](osm_ingest/)'s `poi_extract`) at zooms **z12–z16**. The same+pass also emits two compact side files (`poi_names.bin` + `poi_index.bin`, formats below) so the app can mmap + binary-scan POIs; the layer and the side files are mutually consistent (same POI set, same coordinates). See@@ -138,14 +139,15 @@ mutually consistent (same POI set, same coordinates). See   (`amenity`/`shop`/`tourism`/`leisure`/`office`/`healthcare`) becomes a POI. The   tag value maps to a stable **type number** (see the [POI type map](#poi-type-map));   a recognised key with an unmapped value falls into the `255` = "other" bucket.-  Way/relation geometry is reduced to a representative centroid (average of-  outer-ring node locations) so every POI renders as a point. Requiring a `name`-  naturally filters out unnamed street furniture (`amenity=bench`, etc.).-  Extraction is a single **libosmium** pass (`poi_extract.cpp`, matching the-  `generator.cpp` toolchain) — nodes are read directly and closed ways +-  multipolygon relations are assembled into areas via osmium's-  `MultipolygonManager`. The same pass emits the tile layer's geojsonseq AND the-  two side files, so all three are mutually consistent.+  Way/relation geometry is reduced to a representative centroid so every POI+  renders as a point. Requiring a `name` naturally filters out unnamed street+  furniture (`amenity=bench`, etc.).+  Extraction is a single pass of [`osm_ingest`](osm_ingest/)'s `poi_extract`+  (Rust, reads `.osm.pbf` natively) — nodes are read directly, closed ways use+  their own node ring, and `type=multipolygon`/`boundary` relations use the node+  locations of their `outer`-role member ways. The same pass emits the tile+  layer's geojsonseq AND the two side files, so all three are mutually+  consistent. * **Admin borders**:   * country + region → **Natural Earth 10m** (`ne_10m_admin_0_countries`,     `ne_10m_admin_1_states_provinces`). Chosen because the current `.fgb` are@@ -166,8 +168,9 @@ mutually consistent (same POI set, same coordinates). See | `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` | g++ `poi_extract.cpp` → geojsonseq + `poi_names.bin` + `poi_index.bin` → tippecanoe → `ma_pois.pmtiles` |-| `poi_extract.cpp` | libosmium POI extractor: nodes + way/relation centroids → `ma_pois` geojsonseq + the two side files (full TYPE MAP + on-disk layouts in the file header) |+| `build_pois_layer.sh` | `osm_ingest` `poi_extract` → geojsonseq + `poi_names.bin` + `poi_index.bin` → tippecanoe → `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` | | `publish_r2.sh` | Upload built `.pmtiles` to Cloudflare R2 (creds from env vars only) | | `normalize_safety.py` | OSM tags → `safety` layer schema (pure stdlib, unit-tested) |@@ -181,13 +184,17 @@ mutually consistent (same POI set, same coordinates). See  ## Prerequisites (tools) -Full build needs (all are existing off-the-shelf tools — no C++ authored here):+Full build needs (all are existing off-the-shelf tools — the only code authored+here is Rust and Python):  * **tippecanoe** ≥ 2.x (provides `tippecanoe` + `tile-join`, both write `.pmtiles`) * **osmium-tool** (`osmium`) * **GDAL** (`ogr2ogr`)-* **g++** (C++17) + **libosmium** headers — for the `ma_pois` extractor-  (`poi_extract.cpp`) and the routing-graph `generator.cpp`+* **cargo** (https://rustup.rs) — for the `ma_pois` extractor and the routing+  graph, both in [`osm_ingest`](osm_ingest/). No C/C++ toolchain and no+  libosmium: `osm_ingest` reads `.osm.pbf` natively, so the routing graph and the+  two POI side files build on **Windows** as well (`build_graph.ps1`). Only the+  `.pmtiles` steps still need tippecanoe/osmium. * **python3** (stdlib only) * Base build mode only: **Java 21** + the Protomaps basemap jar   (build once from `github.com/protomaps/basemaps`, `tiles/` → `mvn package`)@@ -337,7 +344,7 @@ to the `admin_country` / `admin_region` PMTiles layers (matching on `ISO_A2` / from OpenStreetMap (baked here), so the app never scrapes a Google map viewport to discover POIs — Google is queried only for rich details when the user taps a POI. It is built by [`build_pois_layer.sh`](build_pois_layer.sh) →-[`poi_extract.cpp`](poi_extract.cpp) and merged into `v5.pmtiles` by+[`osm_ingest`](osm_ingest/)'s `poi_extract` and merged into `v5.pmtiles` by `build_v5_pmtiles.sh` (skip with `--skip-pois`). The **same** `poi_extract` pass emits two compact side files **next to `--out`** so the app can `mmap` + binary-scan POIs without opening the tileset:@@ -363,8 +370,8 @@ AND a recognised POI key (`amenity`/`shop`/`tourism`/`leisure`/`office`/ ### POI type map  Stable POI type-number enum — **never renumber an existing value, only append**;-`255` is the catch-all "other". Kept in sync with `poi_extract.cpp` (source of-truth) and the app. Precedence when several keys are present:+`255` is the catch-all "other". Kept in sync with `osm_ingest/src/tags.rs`+(source of truth) and the app. Precedence when several keys are present: `amenity` → `shop` → `tourism` → `leisure` → `office` → `healthcare`.  | # | type | example OSM tags |@@ -451,7 +458,7 @@ POI, in the SAME order as the `ma_pois` features:  `record_count = filesize(poi_index.bin) / 14`. Records are **sorted ascending by the 64-bit Z-order (Morton) key of (lat, lon)** — computed exactly as-`generator.cpp`'s `latlng_to_spatial` (interleave the 32-bit normalized+`osm_ingest`'s `latlng_to_spatial` (interleave the 32-bit normalized `x=(lon+180)/360`, `y=(lat+90)/180`) — giving spatial locality for range scans. The Morton key itself is **not** stored; the app recomputes it from `lat_e7`/ `lon_e7` when needed. Both files are byte-for-byte reproducible for a given input.@@ -474,24 +481,23 @@ struct PoiRecord {   // 14 bytes, little-endian ## Single global routing graph (P16)  The offline **routing graph** is a **single global graph** — there is no-per-zone splitting and no separate merge/compaction stage. `generator.cpp`-emits, in one pass, exactly the on-disk layout the Rust router+per-zone splitting and no separate merge/compaction stage. `osm_ingest`'s+`road_graph` emits, in one pass, exactly the on-disk layout the Rust router (`maps/src/main/rust/src/graph.rs`) mmaps:  | File | Contents | Consumed by (graph.rs) | |---|---|---|-| `metadata.bin` | one `u64` node count | `load` |+| `metadata.bin` | `u32 magic` (`"MARG"` = `0x4752414D`), `u32 version` (1), `u64 node count` — 16 B | `load` | | `nodes.bin` | `NodeMaster[node_count + 1]` (16 B: `i32 lat_e7`, `i32 lon_e7`, `u64 edge_ptr`), trailing sentinel | `node` / `get_node` | | `edges.bin` | `Edge[edge_count]` (14 B: `u32 target`, `u32 dist_mm`, `u32 name_offset`, `u8 type`, `u8 speed_limit`) | `edge` |-| `transit_attributes.bin` | `TransitAttribute[node_count]` (8 B: `u32 stop_code_off`, `u32 feed_name_off`) | `get_node_transit_attr` |-| `transit_voyages.bin` | compact per-edge schedules (see below) | `transit_voyage_at` / `transit_dep_u32` | | `lanes.bin` | `u64 offsets[edge_count + 1]` then a `u16` turn-mask blob | `edge_lane_masks` | | `road_names.bin` | NUL-terminated string pool | `road_name` |  `intermediate.bin` (delta-encoded edge geometry) is **optional** and is not produced by this generator; `graph.rs` treats its absence gracefully and the router falls back to straight node-to-node segments. It can be added later-without changing any of the files above.+without changing any of the files above. When present it **is** length-validated+against `edge_count`, since its offset array is sized from it.  **Why single global (drop graph zoning):** the previous pipeline wrote per-zone `*_zone_N.bin` artifacts in a layout `graph.rs` could not load and relied on a@@ -500,18 +506,32 @@ merge/compaction stage that never existed in the repo (the old un-checked-in final layout directly into the generator closes that gap: freshly generated road data is now loadable by the shipping router with no extra step. -**Transit voyage compaction** (per transit edge, 4-byte slots starting at the-`voyage_offset` stored in the edge's `dist_mm`, count in `speed_limit`):--```-slot 0      u32  absolute departure of voyage 0 (10 ms units)-slot 1      {u16 dep_delta = voyage 0 travel time (10 ms), u16 duration = 0}-slot 1 + i  {u16 dep_delta = (dep_i − dep_{i-1}) seconds,-             u16 duration  = voyage i travel time (10 ms)}   for i = 1..count-1-```--This mirrors the decoder in `maps/src/main/rust/src/geometry.rs`-(`get_transit_edge_time_10ms`); keep the two in sync.+**Why `metadata.bin` has a magic + version.** The road graph is a directory of+independent files with no cross-file checksum, so a partial or mixed-vintage+update would previously have been read as a valid graph — `node_count` and+`edge_count` would disagree with the actual files and the router would read out of+bounds. The header makes that a clean rejection (`Graph::load` returns `None`).+It was added when the road graph stopped carrying transit at all (see below),+which changed both counts and so required every pack to be regenerated.++> **Update the app and the pack together.** The header protects a *new* reader+> from an old pack, but it cannot protect an *old* reader from a new pack: a build+> predating the header reads `metadata.bin` as a bare `u64 node_count`, so it takes+> the magic and version as the count — `0x00000001_4752414D` = 5,491,540,301+> instead of 35,857,253 — and then indexes `nodes.bin` far out of bounds. That is a+> native `SIGSEGV` in `findRouteNative`, not a clean failure. Pushing a regenerated+> pack to a device therefore also requires installing an app built from the same+> vintage or newer.++**No transit in the road graph.** The generator used to synthesize fake 15-minute+GTFS headways onto rail/bus ways and emit a `TRANSIT_FLAG` edge set, a+`transit_voyages.bin` schedule blob, a `transit_attributes.bin` per-node table,+and a **duplicated node per OSM node** so a road node and a transit node could+coexist. All of that is gone: public transit is planned exclusively by the RAPTOR+planner over the separate `.transit` index (`gtfs_ingest`, real GTFS timetables),+so `TravelMode.PUBLIC_TRANSIT` in the road graph now means *walking* — it is only+reached for a journey's access/egress/transfer legs. Dropping the duplicated+nodes is also the single biggest size win in this pipeline.  ### How the app obtains it — download-size implications @@ -580,9 +600,43 @@ $ ./build_pois_layer.sh --pbf california-latest.osm.pbf \ [ma_pois] tiling -> ma_pois.pmtiles (z12-16) ``` -Verified: `poi_extract.cpp` compiles clean; `ma_pois` appears in the tileset at+Verified: `ma_pois` appears in the tileset at **z12–16** (and coexists with other layers after `tile-join` — a merge with `safety.pmtiles` lists both `ma_pois` and `safety`); each tiled feature carries `name`/`type`/`osm_id`; `poi_index.bin` records decode back to the exact `ma_pois` features (Morton-sorted); and POIs sharing a name resolve to the same `poi_names.bin` offset (212 shared offsets in the sample), confirming dedup.++### Rust ingest port (replacing the libosmium C++)++`generator.cpp` and `poi_extract.cpp` were replaced by+[`osm_ingest`](osm_ingest/), which reads `.osm.pbf` natively (hand-rolled+protobuf decoder + pure-Rust inflate) and therefore needs no g++, no libosmium+and no WSL. Validated on the full 1.24 GB `california-latest.osm.pbf`, natively+on Windows:++```+road_graph:   23007 blobs, 4,264,993 routable ways, 35,857,253 nodes,+              74,340,356 edges, 323,441 unique names, LCC 35,358,417,+              60,711 isolated stops reconnected                      ~19 s+poi_extract:  284,216 POIs (172,448 node, 107,612 closed-way, 4,156 relation),+              188,990 unique names                                    ~5 s+```++Verified: `metadata.bin` is the 16-byte `MARG`/v1/`node_count` header;+`nodes.bin` is `node_count + 1` records with a sentinel whose `edge_ptr` equals+`edge_count`; `edges.bin` is an exact multiple of 14; `lanes.bin` is+`(edge_count + 1) × 8` offset bytes plus the `u16` blob; nodes and POI records+are Morton-ordered. **Both tools are deterministic** — two runs on California+produce byte-identical output for all eight files, which the C++ never did (it+filled its node array from concurrent workers and interned names in+thread-scheduling order).++Also cross-checked against the C++ itself, built in WSL against libosmium 2.20,+over a San Luis Obispo extract: identical `node_count` (88,666), `edge_count`+(181,481), `lanes.bin` length, `road_names.bin` string set and out-degree+sequence; identical edge `(type, speed, name)` groups with every `dist_mm` within+12 mm; and every POI the C++ found present with the same `name`/`type`. The two+intentional differences — coordinates 1.1 cm more accurate (the C++ truncated+`lat_e7`) and relation centroids within ~3 m instead of assembled rings — are+detailed in [`osm_ingest/README.md`](osm_ingest/README.md).
scripts/maps/build_graph.ps1
diff --git a/scripts/maps/build_graph.ps1 b/scripts/maps/build_graph.ps1new file mode 100644index 0000000000..f98422d057--- /dev/null+++ b/scripts/maps/build_graph.ps1@@ -0,0 +1,72 @@+# build_graph.ps1 -- build the single global routing graph on Windows.+#+# The whole point of porting generator.cpp to Rust (scripts/maps/osm_ingest) was+# that regenerating a pack no longer needs WSL, g++ or libosmium. This is the+# native entry point: one command, no bash.+#+# run_generator.sh is still the full Linux pipeline (it also configures the AWS+# CLI and syncs to R2). This script only builds the graph; upload separately with+# publish_r2.sh or `aws s3 sync`.+#+# Usage:+#   .\build_graph.ps1                                   # california-latest.osm.pbf -> map_data+#   .\build_graph.ps1 -Pbf C:\maps\california-latest.osm.pbf -Out C:\maps\map_data+#   .\build_graph.ps1 -Pois                             # also build the POI side files+#+# Only the default California extract is downloaded automatically; any other -Pbf+# must already exist (grab it from https://download.geofabrik.de).+#+# Requires: cargo (https://rustup.rs). The build needs roughly 10 GB of RAM on a+# state-sized extract.++[CmdletBinding()]+param(+    # Input OSM extract. Downloaded from Geofabrik if missing.+    [string]$Pbf = "california-latest.osm.pbf",+    # Output directory; this is the layout maps/src/main/rust/src/graph.rs mmaps.+    [string]$Out = "map_data",+    # Also emit poi_names.bin / poi_index.bin into $Out. The .pmtiles tile build+    # still needs tippecanoe, so it is not done here.+    [switch]$Pois+)++$ErrorActionPreference = "Stop"+$manifest = Join-Path $PSScriptRoot "osm_ingest\Cargo.toml"+$DefaultPbf = "california-latest.osm.pbf"+$DefaultUrl = "https://download.geofabrik.de/north-america/us/$DefaultPbf"++if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {+    throw "cargo not found. Install Rust from https://rustup.rs"+}++if (Test-Path $Pbf) {+    Write-Host "[1/3] Using $Pbf ($([math]::Round((Get-Item $Pbf).Length / 1GB, 2)) GB)"+} elseif ((Split-Path $Pbf -Leaf) -eq $DefaultPbf) {+    # Only the default extract has a known URL. Auto-downloading California into+    # some other requested filename would silently build a wrong-region graph.+    Write-Host "[1/3] $Pbf not found. Downloading $DefaultUrl ..."+    $partial = "$Pbf.partial"+    Invoke-WebRequest -Uri $DefaultUrl -OutFile $partial+    Move-Item -Force $partial $Pbf+} else {+    throw "$Pbf not found. Download it from https://download.geofabrik.de and retry."+}++Write-Host "[2/3] Building the routing graph -> $Out"+cargo run --release --manifest-path $manifest --bin road_graph -- $Pbf --out $Out+if ($LASTEXITCODE -ne 0) { throw "road_graph failed with exit code $LASTEXITCODE" }++if ($Pois) {+    Write-Host "[3/3] Building the POI side files -> $Out"+    cargo run --release --manifest-path $manifest --bin poi_extract -- $Pbf `+        --geojson (Join-Path $Out "ma_pois.geojsonseq") `+        --names   (Join-Path $Out "poi_names.bin") `+        --index   (Join-Path $Out "poi_index.bin")+    if ($LASTEXITCODE -ne 0) { throw "poi_extract failed with exit code $LASTEXITCODE" }+} else {+    Write-Host "[3/3] Skipping POIs (pass -Pois to build them)"+}++Write-Host ""+Write-Host "Graph written to $((Resolve-Path $Out).Path):"+Get-ChildItem $Out | Select-Object Name, Length | Format-Table -AutoSize
scripts/maps/build_pois_layer.sh
diff --git a/scripts/maps/build_pois_layer.sh b/scripts/maps/build_pois_layer.shindex 77848cc1aa..b44b97c37e 100644--- a/scripts/maps/build_pois_layer.sh+++ b/scripts/maps/build_pois_layer.sh@@ -18,8 +18,9 @@ set -euo pipefail #                       int32 lat_e7, int32 lon_e7, uint32 name_off, uint16 type #                     sorted by Morton (Z-order) key of (lat,lon) #-# See poi_extract.cpp for the full TYPE MAP + the exact on-disk layouts, and the-# README (`ma_pois` schema + file formats) for the app-side contract.+# See scripts/maps/osm_ingest (src/poi_build.rs) for the full TYPE MAP + the exact+# on-disk layouts, and the README (`ma_pois` schema + file formats) for the+# app-side contract. # # Usage: #   ./build_pois_layer.sh --pbf planet.osm.pbf --out ma_pois.pmtiles@@ -36,7 +37,10 @@ set -euo pipefail #   --maxzoom N       tippecanoe maxzoom (default 16) #   --keep-tmp        Don't delete intermediate files #-# Tools required: g++ (C++17) + libosmium headers, osmium (osmium-tool), tippecanoe+# Tools required: cargo, osmium (osmium-tool), tippecanoe. 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=""@@ -58,14 +62,14 @@ while [[ $# -gt 0 ]]; do         --minzoom) MINZOOM="$2"; shift 2 ;;         --maxzoom) MAXZOOM="$2"; shift 2 ;;         --keep-tmp) KEEP_TMP=1; shift ;;-        -h|--help) sed -n '4,40p' "$0" | sed 's/^# \?//'; exit 0 ;;+        -h|--help) sed -n '4,45p' "$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 g++        >/dev/null || { echo "ERROR: g++ not installed" >&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; } @@ -73,10 +77,6 @@ TMP="$(mktemp -d)" cleanup() { [[ "$KEEP_TMP" == "1" ]] || rm -rf "$TMP"; } trap cleanup EXIT -echo "[ma_pois] compiling poi_extract"-g++ -O3 -std=c++17 "$HERE/poi_extract.cpp" -o "$TMP/poi_extract" \-    -lz -lexpat -lbz2 -pthread- SRC="$PBF" if [[ -n "$BBOX" ]]; then     echo "[ma_pois] extracting metro bbox $BBOX"@@ -85,7 +85,8 @@ if [[ -n "$BBOX" ]]; then fi  echo "[ma_pois] extracting POIs -> geojsonseq + $NAMES_OUT + $INDEX_OUT"-"$TMP/poi_extract" "$SRC" \+cargo run --release --manifest-path "$HERE/osm_ingest/Cargo.toml" --bin poi_extract -- \+    "$SRC" \     --geojson "$TMP/ma_pois.geojsonseq" \     --names "$NAMES_OUT" \     --index "$INDEX_OUT"
scripts/maps/build_v5_pmtiles.sh
diff --git a/scripts/maps/build_v5_pmtiles.sh b/scripts/maps/build_v5_pmtiles.shindex 62f6227312..597ef703b9 100644--- a/scripts/maps/build_v5_pmtiles.sh+++ b/scripts/maps/build_v5_pmtiles.sh@@ -12,7 +12,7 @@ set -euo pipefail # # The ma_pois step ALSO emits two compact side files next to --out # (poi_names.bin + poi_index.bin) that the app mmaps for POI lookup — see-# build_pois_layer.sh / poi_extract.cpp / README for the exact formats.+# build_pois_layer.sh / osm_ingest / README for the exact formats. # # This single file REPLACES both: #   * https://data.vayunmathur.com/v4.pmtiles      (base tiles)
scripts/maps/generator.cpp
diff --git a/scripts/maps/generator.cpp b/scripts/maps/generator.cppdeleted file mode 100644index d0af966a85..0000000000--- a/scripts/maps/generator.cpp+++ /dev/null@@ -1,1134 +0,0 @@-#include <iostream>-#include <fstream>-#include <vector>-#include <string>-#include <algorithm>-#include <cstdint>-#include <unordered_map>-#include <iomanip>-#include <cmath>-#include <sys/mman.h>-#include <fcntl.h>-#include <unistd.h>-#include <cstring>-#include <chrono>-#include <sys/stat.h>-#include <bitset>-#include <thread>-#include <atomic>-#include <mutex>-#include <future>-#include <queue>-#include <condition_variable>-#include <functional>-#include <sstream>--using namespace std;--// Libosmium Headers-#include <osmium/io/any_input.hpp>-#include <osmium/handler.hpp>-#include <osmium/visitor.hpp>--// --- CONFIGURATION ----const uint64_t BITSET_SIZE = 20000000000ULL;-const string DATA_DIR = "map_data/";-const double DEG_TO_RAD = M_PI / 180.0;-const int ID_TILE_BITS = 16;-const size_t NUM_ID_TILES = 1 << ID_TILE_BITS;-const uint64_t ID_TILE_SHIFT = 64 - ID_TILE_BITS;--// --- OSM turn:lanes indication bits (one uint16_t mask per lane) ----// Emitted per directed edge into the single global lanes.bin below and decoded-// by the Rust router (maps/src/main/rust/src/graph.rs LANE_* constants). Keep-// the two in sync: this is an on-disk contract.-const uint16_t LANE_NONE = 1 << 0;-const uint16_t LANE_THROUGH = 1 << 1;-const uint16_t LANE_LEFT = 1 << 2;-const uint16_t LANE_SLIGHT_LEFT = 1 << 3;-const uint16_t LANE_SHARP_LEFT = 1 << 4;-const uint16_t LANE_RIGHT = 1 << 5;-const uint16_t LANE_SLIGHT_RIGHT = 1 << 6;-const uint16_t LANE_SHARP_RIGHT = 1 << 7;-const uint16_t LANE_REVERSE = 1 << 8;-const uint16_t LANE_MERGE_TO_LEFT = 1 << 9;-const uint16_t LANE_MERGE_TO_RIGHT = 1 << 10;--#pragma pack(push, 1)-struct NodeMaster {-    int32_t lat_e7;-    int32_t lon_e7;-    uint64_t spatial_id;-    uint32_t edge_ptr;-    uint32_t stop_code_off;-    uint32_t feed_name_off;-};--struct FinalEdge {-    uint32_t target;-    uint32_t dist_mm;-    uint32_t name_offset;-    uint8_t type;-    uint8_t speed_limit;-};--struct TransitVoyage {-    uint32_t dep_10ms;-    uint32_t arr_10ms;-};--// --- Final on-disk structs consumed by maps/src/main/rust/src/graph.rs ----// These describe the SINGLE GLOBAL graph layout (no zones). Keep them-// byte-for-byte in sync with the #[repr(C, packed)] structs in graph.rs.-struct FinalNode {            // graph.rs NodeMaster (16 bytes)-    int32_t lat_e7;-    int32_t lon_e7;-    uint64_t edge_ptr;        // global edge index (u64)-};--struct FinalTransitAttr {     // graph.rs TransitAttribute (8 bytes)-    uint32_t stop_code_off;-    uint32_t feed_name_off;-};--struct TransitVoyageCompact { // graph.rs TransitVoyageCompact (4 bytes)-    uint16_t dep_delta;-    uint16_t duration;-};--#define TRANSIT_FLAG 0x80-#define TRANSIT_NODE_FLAG (1ULL << 63)--struct NodeTemp {-    uint64_t osm_id;-    uint64_t spatial_value;-    int32_t lat_e7;-    int32_t lon_e7;-    uint32_t stop_code_off;-    uint32_t feed_name_off;-    uint64_t sort_key() const { return spatial_value; }-};--struct IDMapping {-    uint64_t osm_id;-    uint32_t local_id;-    uint64_t sort_key() const { return osm_id; }-};--struct TmpEdge {-    uint32_t source_lid;-    uint32_t target_lid;-    uint32_t dist_mm;-    uint32_t name_offset;-    uint8_t type;-    uint8_t speed_limit;-    uint32_t lane_off;    // index into g_lane_pool, 0xFFFFFFFF if none-    uint16_t lane_count;  // per-lane masks for this directed edge (0 if none)-    uint32_t sort_key() const { return source_lid; }-};--struct CachedWay {-    uint32_t name_offset;-    uint32_t first_node_idx;-    uint16_t node_count;-    uint8_t type;-    uint8_t speed_limit;-    bool oneway;-    uint32_t fwd_lane_off;   // index into lane pool for forward-direction lanes-    uint16_t fwd_lane_count; // 0 when the way has no forward turn:lanes-    uint32_t bwd_lane_off;   // index into lane pool for backward-direction lanes-    uint16_t bwd_lane_count; // 0 when the way has no backward turn:lanes-};-#pragma pack(pop)--// ==========================================-// THREAD-SAFE CONCURRENT ATOMIC BITSET-// Prevents OOM crashes from allocating 20GB.-// ==========================================-class AtomicBitset {-    std::atomic<uint8_t>* bits;-    uint64_t num_bytes;-public:-    AtomicBitset(uint64_t size) {-        num_bytes = size / 8 + 1;-        bits = new std::atomic<uint8_t>[num_bytes];-        for (uint64_t i = 0; i < num_bytes; ++i) {-            bits[i].store(0, std::memory_order_relaxed);-        }-    }-    ~AtomicBitset() {-        delete[] bits;-    }-    bool set(uint64_t idx) {-        uint64_t byte_idx = idx / 8;-        uint8_t bit_mask = 1 << (idx % 8);-        uint8_t current = bits[byte_idx].load(std::memory_order_relaxed);-        while (!(current & bit_mask)) {-            uint8_t new_val = current | bit_mask;-            if (bits[byte_idx].compare_exchange_weak(current, new_val, std::memory_order_relaxed)) {-                return true;-            }-        }-        return false;-    }-    bool get(uint64_t idx) const {-        uint64_t byte_idx = idx / 8;-        uint8_t bit_mask = 1 << (idx % 8);-        return (bits[byte_idx].load(std::memory_order_relaxed) & bit_mask) != 0;-    }-};--// ==========================================-// THREAD POOL & WORKER UTILITIES-// ==========================================--class MoveTask {-    struct Base {-        virtual ~Base() {}-        virtual void run() = 0;-    };-    template<typename F>-    struct Impl : Base {-        F f;-        Impl(F&& f) : f(std::move(f)) {}-        void run() override { f(); }-    };-    unique_ptr<Base> ptr;-public:-    MoveTask() = default;-    template<typename F>-    MoveTask(F&& f) : ptr(new Impl<F>(std::move(f))) {}-    void operator()() { if (ptr) ptr->run(); }-    explicit operator bool() const { return !!ptr; }-};--class ThreadPool {-public:-    ThreadPool(size_t threads) : stop(false) {-        for(size_t i = 0; i < threads; ++i)-            workers.emplace_back([this] {-                for(;;) {-                    MoveTask task;-                    {-                        unique_lock<mutex> lock(this->queue_mutex);-                        this->condition.wait(lock, [this]{ return this->stop || !this->tasks.empty(); });-                        if(this->stop && this->tasks.empty()) return;-                        task = move(this->tasks.front());-                        this->tasks.pop();-                        // Count this task as in-flight while still holding the-                        // lock, so wait_finished() can never observe an empty-                        // queue with a task mid-execution.-                        this->active_tasks.fetch_add(1, std::memory_order_relaxed);-                    }-                    task();-                    // Release-decrement so a subsequent acquire-load in-                    // wait_finished() establishes happens-before for all of this-                    // task's writes (masks, cached_ways, nodes_raw, ...).-                    this->active_tasks.fetch_sub(1, std::memory_order_release);-                }-            });-    }-    template<typename F>-    void enqueue(F&& f) {-        {-            unique_lock<mutex> lock(queue_mutex);-            condition_throttle.wait(lock, [this] { return tasks.size() < 100; });-            tasks.emplace(forward<F>(f));-        }-        condition.notify_one();-    }-    void wait_finished() {-        // Wait until the queue is drained AND every dequeued task has finished.-        // Checking only tasks.empty() (the old behaviour) returned while worker-        // threads were still executing the last tasks, letting stragglers mutate-        // shared state (nodes_raw/masks/cached_ways) after the caller moved on —-        // a data race that produced nondeterministic counts and heap corruption.-        for(;;) {-            {-                unique_lock<mutex> lock(queue_mutex);-                if (tasks.empty() && active_tasks.load(std::memory_order_acquire) == 0) break;-            }-            this_thread::sleep_for(chrono::milliseconds(1));-        }-    }-    ~ThreadPool() {-        { unique_lock<mutex> lock(queue_mutex); stop = true; }-        condition.notify_all();-        for(thread &worker: workers) worker.join();-    }-    void notify_worker_done() {-        unique_lock<mutex> lock(queue_mutex);-        condition_throttle.notify_one();-    }-private:-    vector<thread> workers;-    queue<MoveTask> tasks;-    mutex queue_mutex;-    condition_variable condition;-    condition_variable condition_throttle;-    bool stop;-    std::atomic<int> active_tasks{0}; // tasks dequeued but not yet finished-};--// ==========================================-// PARALLEL RADIX SORT-// ==========================================--template<typename T>-void parallel_radix_sort(vector<T>& data, int total_bits) {-    if (data.empty()) return;-    size_t n = data.size();-    vector<T> buffer(n);-    T* src = data.data();-    T* dst = buffer.data();-    int num_threads = thread::hardware_concurrency();--    for (int shift = 0; shift < total_bits; shift += 8) {-        size_t global_counts[256] = {0};-        vector<vector<size_t>> local_counts(num_threads, vector<size_t>(256, 0));--        auto count_func = [&](int tid, size_t start, size_t end) {-            for (size_t i = start; i < end; ++i) {-                local_counts[tid][(src[i].sort_key() >> shift) & 0xFF]++;-            }-        };--        vector<thread> threads;-        size_t chunk = n / num_threads;-        for(int t=0; t<num_threads; ++t)-            threads.emplace_back(count_func, t, t*chunk, (t==num_threads-1) ? n : (t+1)*chunk);-        for(auto& t : threads) t.join();--        size_t offsets[256];-        offsets[0] = 0;-        for (int i = 0; i < 256; ++i) {-            for(int t=0; t<num_threads; ++t) global_counts[i] += local_counts[t][i];-            if (i > 0) offsets[i] = offsets[i-1] + global_counts[i-1];-        }--        for (size_t i = 0; i < n; ++i) {-            dst[offsets[(src[i].sort_key() >> shift) & 0xFF]++] = src[i];-        }-        swap(src, dst);-    }-}--// ==========================================-// UTILITIES-// ==========================================--uint32_t g_lon_to_mm_scale[4096];-uint32_t g_id_tile_offsets[NUM_ID_TILES + 1];--void init_lookup_table() {-    for (int i = 0; i < 4096; ++i) {-        double lat_deg = (double)((i - 2048) << 19) * 1e-7;-        lat_deg = std::max(-90.0, std::min(90.0, lat_deg));-        double scale = 11.131949 * cos(lat_deg * DEG_TO_RAD) * 1024.0;-        g_lon_to_mm_scale[i] = (uint32_t)scale;-    }-}--inline uint32_t accurate_dist_mm(int32_t lat1_e7, int32_t lon1_e7, int32_t lat2_e7, int32_t lon2_e7) {-    const double R = 6371000800.0;-    double phi1 = (lat1_e7 * 1e-7) * DEG_TO_RAD;-    double phi2 = (lat2_e7 * 1e-7) * DEG_TO_RAD;-    double delta_phi = (lat2_e7 - lat1_e7) * 1e-7 * DEG_TO_RAD;-    double delta_lambda = (lon2_e7 - lon1_e7) * 1e-7 * DEG_TO_RAD;-    double s_dphi = sin(delta_phi / 2.0);-    double s_dlamb = sin(delta_lambda / 2.0);-    double a = s_dphi * s_dphi + cos(phi1) * cos(phi2) * s_dlamb * s_dlamb;-    double c = 2.0 * atan2(sqrt(a), sqrt(1.0 - a));-    return (uint32_t)(R * c);-}--uint64_t latlng_to_spatial(double lat, double lon) {-    double x = (lon + 180.0) / 360.0;-    double y = (lat + 90.0) / 180.0;-    uint32_t ix = (uint32_t)(x * 4294967295.0);-    uint32_t iy = (uint32_t)(y * 4294967295.0);-    uint64_t res = 0;-    for (int i = 0; i < 32; i++) {-        res |= ((uint64_t)((ix >> i) & 1) << (2 * i));-        res |= ((uint64_t)((iy >> i) & 1) << (2 * i + 1));-    }-    return res;-}--void build_id_tile_index(const vector<IDMapping>& mapping) {-    memset(g_id_tile_offsets, 0, sizeof(g_id_tile_offsets));-    for (const auto& entry : mapping) {-        uint32_t tile_idx = entry.osm_id >> ID_TILE_SHIFT;-        g_id_tile_offsets[tile_idx + 1]++;-    }-    for (size_t i = 1; i <= NUM_ID_TILES; ++i) {-        g_id_tile_offsets[i] += g_id_tile_offsets[i - 1];-    }-}--inline uint32_t get_local_id_by_osm(uint64_t osm_id, const vector<IDMapping>& mapping) {-    uint32_t tile_idx = osm_id >> ID_TILE_SHIFT;-    uint32_t start = g_id_tile_offsets[tile_idx];-    uint32_t end = g_id_tile_offsets[tile_idx + 1];-    auto it = lower_bound(mapping.begin() + start, mapping.begin() + end, IDMapping{osm_id, 0},-                          [](const IDMapping& a, const IDMapping& b) { return a.osm_id < b.osm_id; });-    if (it != mapping.begin() + end && it->osm_id == osm_id) return it->local_id;-    return 0xFFFFFFFF;-}--uint8_t parse_maxspeed(const char* str) {-    if (!str) return 0;-    char* endptr;-    double val = strtod(str, &endptr);-    if (val <= 0) return 0;-    while (*endptr == ' ') endptr++;-    if (strcmp(endptr, "mph") == 0) return (uint8_t)round(val * 1.60934);-    if (strcmp(endptr, "knots") == 0) return (uint8_t)round(val * 1.852);-    return (uint8_t)val;-}--uint8_t get_hw_id(const char* type) {-    if (!type) return 0;-    static const unordered_map<string, uint8_t> m = {-            {"motorway", 1}, {"trunk", 2}, {"primary", 3}, {"secondary", 4},-            {"tertiary", 5}, {"unclassified", 6}, {"residential", 7}, {"service", 8},-            {"living_street", 9}, {"pedestrian", 10}, {"track", 11}, {"footway", 12},-            {"cycleway", 13}, {"path", 14}, {"steps", 15}-    };-    auto it = m.find(type);-    return it != m.end() ? it->second : 0;-}--// --- OSM turn:lanes parsing ----// A single lane token may hold several ';'-separated indications (e.g.-// "through;right"); map each to its bit. An empty token or "none" => LANE_NONE.-static uint16_t parse_lane_token(const string& tok) {-    uint16_t mask = 0;-    size_t start = 0;-    while (start <= tok.size()) {-        size_t semi = tok.find(';', start);-        string ind = tok.substr(start, semi == string::npos ? string::npos : semi - start);-        // Trim surrounding whitespace.-        size_t b = ind.find_first_not_of(" \t");-        size_t e = ind.find_last_not_of(" \t");-        if (b != string::npos) ind = ind.substr(b, e - b + 1);-        else ind.clear();--        if (ind == "left") mask |= LANE_LEFT;-        else if (ind == "slight_left") mask |= LANE_SLIGHT_LEFT;-        else if (ind == "sharp_left") mask |= LANE_SHARP_LEFT;-        else if (ind == "through") mask |= LANE_THROUGH;-        else if (ind == "right") mask |= LANE_RIGHT;-        else if (ind == "slight_right") mask |= LANE_SLIGHT_RIGHT;-        else if (ind == "sharp_right") mask |= LANE_SHARP_RIGHT;-        else if (ind == "reverse") mask |= LANE_REVERSE;-        else if (ind == "merge_to_left") mask |= LANE_MERGE_TO_LEFT;-        else if (ind == "merge_to_right") mask |= LANE_MERGE_TO_RIGHT;-        // "none", "" and unknown values contribute no bit.--        if (semi == string::npos) break;-        start = semi + 1;-    }-    if (mask == 0) mask = LANE_NONE;-    return mask;-}--// Parse a pipe-separated turn:lanes value into one mask per lane (left->right).-// Returns empty when val is null/empty.-static vector<uint16_t> parse_turn_lanes(const char* val) {-    vector<uint16_t> lanes;-    if (!val || !*val) return lanes;-    string s(val);-    size_t start = 0;-    while (true) {-        size_t bar = s.find('|', start);-        lanes.push_back(parse_lane_token(-            s.substr(start, bar == string::npos ? string::npos : bar - start)));-        if (bar == string::npos) break;-        start = bar + 1;-    }-    return lanes;-}--// Build the per-lane mask list for one direction. Real turn:lanes take priority;-// when a plain lane count is known it pads/truncates so the count stays accurate.-// Returns empty (=> the router uses topology inference) when no turn:lanes exist.-static vector<uint16_t> build_dir_lanes(const char* turn_spec, int count_hint) {-    vector<uint16_t> lanes = parse_turn_lanes(turn_spec);-    if (lanes.empty()) return lanes;-    if (count_hint > 0) {-        if ((int)lanes.size() < count_hint)-            lanes.resize(count_hint, LANE_NONE);-        else if ((int)lanes.size() > count_hint)-            lanes.resize(count_hint);-    }-    return lanes;-}--static int parse_int_tag(const char* v) {-    if (!v) return 0;-    int n = atoi(v);-    return n > 0 ? n : 0;-}--bool is_transit_way(const osmium::TagList& tags) {-    const char* railway = tags.get_value_by_key("railway");-    if (railway && (strcmp(railway, "rail") == 0 || strcmp(railway, "subway") == 0 ||-                    strcmp(railway, "tram") == 0 || strcmp(railway, "light_rail") == 0)) return true;-    const char* route = tags.get_value_by_key("route");-    if (route && (strcmp(route, "bus") == 0 || strcmp(route, "train") == 0)) return true;-    return false;-}--void print_progress(const string& label, uint64_t current, uint64_t total) {-    static auto last_update = chrono::steady_clock::now();-    auto now = chrono::steady_clock::now();-    if (current < total && chrono::duration_cast<chrono::milliseconds>(now - last_update).count() < 500) return;-    last_update = now;-    float progress = (total == 0) ? 1.0f : (float)current / total;-    cout << "\r" << left << setw(20) << label << " [" << int(progress * 100.0) << "%] " << flush;-    if (current >= total) cout << endl;-}--uint32_t parse_time_10ms(const string& s) {-    int h, m, sec;-    if (sscanf(s.c_str(), "%d:%d:%d", &h, &m, &sec) == 3) {-        return (h * 3600 + m * 60 + sec) * 100;-    }-    return 0;-}--struct TransitInput {-    uint64_t u_osm, v_osm;-    string line_name;-    uint32_t dep, arr;-};--int main(int argc, char* argv[]) {-    if (argc < 2) { cerr << "Usage: " << argv[0] << " map.osm.pbf [transit.csv]" << endl; return 1; }--    mkdir(DATA_DIR.c_str(), 0777);-    init_lookup_table();-    ThreadPool pool(thread::hardware_concurrency());--    vector<TransitInput> transit_inputs;-    if (argc >= 3) {-        ifstream transit_in(argv[2]);-        string line;-        while (getline(transit_in, line)) {-            stringstream ss(line);-            string u_s, v_s, name, dep_s, arr_s;-            if (getline(ss, u_s, ',') && getline(ss, v_s, ',') && getline(ss, name, ',') &&-                getline(ss, dep_s, ',') && getline(ss, arr_s, ',')) {-                try {-                    transit_inputs.push_back({stoull(u_s), stoull(v_s), name, parse_time_10ms(dep_s), parse_time_10ms(arr_s)});-                } catch (...) {-                    continue;-                }-            }-        }-    }--    AtomicBitset useful_nodes_mask(BITSET_SIZE);-    AtomicBitset road_nodes_mask(BITSET_SIZE);-    AtomicBitset transit_nodes_mask(BITSET_SIZE);-    atomic<uint64_t> total_local_nodes{0};-    atomic<uint64_t> total_edges{0};--    vector<CachedWay> cached_ways;-    vector<uint64_t> way_nodes_topology;-    vector<uint16_t> lane_pool; // per-lane OSM turn masks referenced by ways/edges-    mutex way_cache_mtx;--    // STEP 1: Discovery & Caching (Pass 1 - Ways)-    unordered_map<string, uint32_t> name_pool;-    mutex name_pool_mtx;-    uint32_t name_offset = 0;-    ofstream name_out(DATA_DIR + "road_names.bin", ios::binary);--    {-        osmium::io::Reader reader{argv[1], osmium::osm_entity_bits::node | osmium::osm_entity_bits::way};-        uint64_t total_size = reader.file_size();--        while (auto buf = reader.read()) {-            pool.enqueue([&, buf = move(buf)]() mutable {-                vector<CachedWay> local_ways;-                vector<uint64_t> local_topology;-                vector<uint16_t> local_lane_pool;--                for (const auto& node : buf.select<osmium::Node>()) {-                    const char* hw = node.tags().get_value_by_key("highway");-                    const char* rw = node.tags().get_value_by_key("railway");-                    const char* pt = node.tags().get_value_by_key("public_transport");-                    if ((hw && (strcmp(hw, "bus_stop") == 0 || strcmp(hw, "bus_station") == 0 || strcmp(hw, "tram_stop") == 0)) ||-                        (rw && (strcmp(rw, "station") == 0 || strcmp(rw, "halt") == 0 || strcmp(rw, "tram_stop") == 0 || strcmp(rw, "stop") == 0)) ||-                        (pt && (strcmp(pt, "stop_position") == 0 || strcmp(pt, "platform") == 0 || strcmp(pt, "station") == 0))) {-                        if (node.id() < BITSET_SIZE) {-                            useful_nodes_mask.set(node.id());-                            if (road_nodes_mask.set(node.id())) total_local_nodes++;-                            // Stations/stops are transit points by definition-                            if (transit_nodes_mask.set(node.id())) total_local_nodes++;-                        }-                    }-                }--                for (const auto& way : buf.select<osmium::Way>()) {-                    uint8_t hw = get_hw_id(way.tags().get_value_by_key("highway"));-                    bool is_transit = is_transit_way(way.tags());-                    if (hw == 0 && !is_transit) continue;--                    uint32_t n_off = 0xFFFFFFFF;-                    const char* name_str = way.tags().get_value_by_key("name");-                    if (!name_str && is_transit) name_str = way.tags().get_value_by_key("ref");-                    if (name_str) {-                        lock_guard<mutex> lock(name_pool_mtx);-                        auto it = name_pool.find(name_str);-                        if (it != name_pool.end()) n_off = it->second;-                        else {-                            n_off = name_offset;-                            name_pool[string(name_str)] = n_off;-                            name_out.write(name_str, strlen(name_str) + 1);-                            name_offset += (strlen(name_str) + 1);-                        }-                    }--                    uint8_t speed = parse_maxspeed(way.tags().get_value_by_key("maxspeed"));-                    bool oneway = (strcmp(way.tags().get_value_by_key("oneway", ""), "yes") == 0);-                    const auto& nodes = way.nodes();--                    // Real OSM turn:lanes -> per-direction lane masks. Forward-                    // uses turn:lanes:forward (or plain turn:lanes on a oneway);-                    // backward uses turn:lanes:backward. Plain lanes[:forward|-                    // :backward] only refine the count. Absent => no lane data,-                    // so the router falls back to junction topology inference.-                    const char* tl = way.tags().get_value_by_key("turn:lanes");-                    const char* tlf = way.tags().get_value_by_key("turn:lanes:forward");-                    const char* tlb = way.tags().get_value_by_key("turn:lanes:backward");-                    int cnt_all = parse_int_tag(way.tags().get_value_by_key("lanes"));-                    int cnt_fwd = parse_int_tag(way.tags().get_value_by_key("lanes:forward"));-                    int cnt_bwd = parse_int_tag(way.tags().get_value_by_key("lanes:backward"));--                    const char* fwd_spec = tlf ? tlf : (oneway ? tl : nullptr);-                    int fwd_hint = cnt_fwd > 0 ? cnt_fwd : (oneway ? cnt_all : 0);-                    const char* bwd_spec = oneway ? nullptr : tlb;-                    int bwd_hint = cnt_bwd;-                    vector<uint16_t> fwd_lanes = build_dir_lanes(fwd_spec, fwd_hint);-                    vector<uint16_t> bwd_lanes = build_dir_lanes(bwd_spec, bwd_hint);--                    uint32_t fwd_lane_off = 0xFFFFFFFF;-                    uint16_t fwd_lane_count = 0;-                    if (!fwd_lanes.empty()) {-                        fwd_lane_off = local_lane_pool.size();-                        fwd_lane_count = (uint16_t)fwd_lanes.size();-                        local_lane_pool.insert(local_lane_pool.end(), fwd_lanes.begin(), fwd_lanes.end());-                    }-                    uint32_t bwd_lane_off = 0xFFFFFFFF;-                    uint16_t bwd_lane_count = 0;-                    if (!bwd_lanes.empty()) {-                        bwd_lane_off = local_lane_pool.size();-                        bwd_lane_count = (uint16_t)bwd_lanes.size();-                        local_lane_pool.insert(local_lane_pool.end(), bwd_lanes.begin(), bwd_lanes.end());-                    }--                    uint32_t topology_start = local_topology.size();-                    for (const auto& n : nodes) {-                        if (n.ref() < BITSET_SIZE) {-                            useful_nodes_mask.set(n.ref());-                            if (hw > 0) {-                                if (road_nodes_mask.set(n.ref())) total_local_nodes++;-                            }-                            if (is_transit) {-                                if (transit_nodes_mask.set(n.ref())) total_local_nodes++;-                            }-                        }-                        local_topology.push_back(n.ref());-                    }--                    local_ways.push_back({ n_off, topology_start, (uint16_t)nodes.size(), (uint8_t)(is_transit ? (hw | TRANSIT_FLAG) : hw), speed, oneway, fwd_lane_off, fwd_lane_count, bwd_lane_off, bwd_lane_count });-                    if (hw > 0) {-                        total_edges += (nodes.size() - 1) * (oneway ? 1 : 2);-                    }-                }--                if (!local_ways.empty()) {-                    lock_guard<mutex> lock(way_cache_mtx);-                    uint32_t global_topo_base = way_nodes_topology.size();-                    uint32_t global_lane_base = lane_pool.size();-                    for (auto& cw : local_ways) {-                        cw.first_node_idx += global_topo_base;-                        if (cw.fwd_lane_count > 0) cw.fwd_lane_off += global_lane_base;-                        if (cw.bwd_lane_count > 0) cw.bwd_lane_off += global_lane_base;-                    }-                    way_nodes_topology.insert(way_nodes_topology.end(), local_topology.begin(), local_topology.end());-                    lane_pool.insert(lane_pool.end(), local_lane_pool.begin(), local_lane_pool.end());-                    cached_ways.insert(cached_ways.end(), local_ways.begin(), local_ways.end());-                }-                pool.notify_worker_done();-            });-            print_progress("Step 1: Way Caching", reader.offset(), total_size);-        }-        pool.wait_finished();-    }--    // STEP 2: Node Collection (Pass 2 - Nodes)-    for (auto& ti : transit_inputs) {-        if (ti.u_osm < BITSET_SIZE) {-            useful_nodes_mask.set(ti.u_osm);-            if (transit_nodes_mask.set(ti.u_osm)) total_local_nodes++;-        }-        if (ti.v_osm < BITSET_SIZE) {-            useful_nodes_mask.set(ti.v_osm);-            if (transit_nodes_mask.set(ti.v_osm)) total_local_nodes++;-        }-    }--    vector<NodeTemp> nodes_raw(total_local_nodes);-    {-        osmium::io::Reader reader{argv[1], osmium::osm_entity_bits::node};-        uint64_t total_size = reader.file_size();-        atomic<uint64_t> idx{0};-        while (auto buf = reader.read()) {-            pool.enqueue([&nodes_raw, &idx, &useful_nodes_mask, &road_nodes_mask, &transit_nodes_mask, buf = move(buf), &pool, &name_pool, &name_pool_mtx, &name_offset, &name_out]() mutable {-                for (const auto& n : buf.select<osmium::Node>()) {-                    if (n.id() < BITSET_SIZE && useful_nodes_mask.get(n.id())) {-                        double lat = n.location().lat();-                        double lon = n.location().lon();-                        uint64_t spatial = latlng_to_spatial(lat, lon);-                        int32_t lat_e7 = (int32_t)(lat * 1e7);-                        int32_t lon_e7 = (int32_t)(lon * 1e7);--                        uint32_t stop_code_off = 0xFFFFFFFF;-                        uint32_t feed_name_off = 0xFFFFFFFF;--                        for (const auto& tag : n.tags()) {-                            if (strncmp(tag.key(), "gtfs:stop_code:", 15) == 0) {-                                string feed = tag.key() + 15;-                                const char* stop_name = n.tags().get_value_by_key("name");-                                string code = stop_name ? stop_name : tag.value();--                                lock_guard<mutex> lock(name_pool_mtx);-                                auto it_f = name_pool.find(feed);-                                if (it_f != name_pool.end()) feed_name_off = it_f->second;-                                else {-                                    feed_name_off = name_offset;-                                    name_pool[feed] = feed_name_off;-                                    name_out.write(feed.c_str(), feed.size() + 1);-                                    name_offset += (feed.size() + 1);-                                }--                                auto it_c = name_pool.find(code);-                                if (it_c != name_pool.end()) stop_code_off = it_c->second;-                                else {-                                    stop_code_off = name_offset;-                                    name_pool[code] = stop_code_off;-                                    name_out.write(code.c_str(), code.size() + 1);-                                    name_offset += (code.size() + 1);-                                }-                                break;-                            }-                        }--                        if (stop_code_off == 0xFFFFFFFF) {-                            const char* hw_tag = n.tags().get_value_by_key("highway");-                            const char* rw_tag = n.tags().get_value_by_key("railway");-                            const char* pt_tag = n.tags().get_value_by_key("public_transport");-                            if ((hw_tag && (strcmp(hw_tag, "bus_stop") == 0 || strcmp(hw_tag, "bus_station") == 0 || strcmp(hw_tag, "tram_stop") == 0)) ||-                                (rw_tag && (strcmp(rw_tag, "station") == 0 || strcmp(rw_tag, "halt") == 0 || strcmp(rw_tag, "tram_stop") == 0 || strcmp(rw_tag, "stop") == 0)) ||-                                (pt_tag && (strcmp(pt_tag, "stop_position") == 0 || strcmp(pt_tag, "platform") == 0 || strcmp(pt_tag, "station") == 0))) {-                                lock_guard<mutex> lock(name_pool_mtx);-                                const char* name_tag = n.tags().get_value_by_key("name");-                                string code = name_tag ? name_tag : "OSM_STOP";-                                auto it_c = name_pool.find(code);-                                if (it_c != name_pool.end()) stop_code_off = it_c->second;-                                else {-                                    stop_code_off = name_offset;-                                    name_pool[code] = stop_code_off;-                                    name_out.write(code.c_str(), code.size() + 1);-                                    name_offset += (code.size() + 1);-                                }-                            }-                        }--                        if (road_nodes_mask.get(n.id())) {-                            uint64_t c_idx = idx.fetch_add(1);-                            nodes_raw[c_idx] = { (uint64_t)n.id(), spatial, lat_e7, lon_e7, stop_code_off, feed_name_off };-                        }-                        if (transit_nodes_mask.get(n.id())) {-                            uint64_t c_idx = idx.fetch_add(1);-                            nodes_raw[c_idx] = { (uint64_t)n.id() | TRANSIT_NODE_FLAG, spatial, lat_e7, lon_e7, stop_code_off, feed_name_off };-                        }-                    }-                }-                pool.notify_worker_done();-            });-            print_progress("Step 2: Node Scan", reader.offset(), total_size);-        }-        pool.wait_finished();--        // COMPACTION FIX: Safely resize nodes_raw to discard unvisited/missing elements-        // to avoid shifting valid nodes with spatial coordinate 0 (Null Island) values.-        uint64_t final_nodes_count = idx.load();-        nodes_raw.resize(final_nodes_count);-        total_local_nodes = final_nodes_count;-    }--    cout << "Parallel Radix Sorting Nodes..." << endl;-    parallel_radix_sort(nodes_raw, 64);-    vector<NodeMaster> node_masters(total_local_nodes);-    vector<IDMapping> id_to_local(total_local_nodes);--    for (uint32_t i = 0; i < total_local_nodes; ++i) {-        node_masters[i] = { nodes_raw[i].lat_e7, nodes_raw[i].lon_e7, nodes_raw[i].spatial_value, 0, nodes_raw[i].stop_code_off, nodes_raw[i].feed_name_off };-        id_to_local[i] = { nodes_raw[i].osm_id, i };-    }-    vector<NodeTemp>().swap(nodes_raw);--    // CRITICAL SORT ORDER FIX: Sort and index id_to_local mappings IMMEDIATELY-    // before we run get_local_id_by_osm for the transit groups! Calling binary searches-    // on unsorted lists was generating garbage indices and wild overlapping sawtooth route maps.-    cout << "Parallel Radix Sorting Mapping..." << endl;-    parallel_radix_sort(id_to_local, 64);-    build_id_tile_index(id_to_local);--    vector<bool> is_road_node(total_local_nodes, false);-    for (uint32_t i = 0; i < total_local_nodes; ++i) {-        if (!(id_to_local[i].osm_id & TRANSIT_NODE_FLAG)) {-            is_road_node[id_to_local[i].local_id] = true;-        }-    }--    // Group transit inputs by (u, v)-    struct TransitEdgeGroup {-        vector<TransitVoyage> voyages;-        uint32_t name_off;-    };-    map<pair<uint32_t, uint32_t>, TransitEdgeGroup> transit_groups;--    if (transit_inputs.empty()) {-        cout << "Synthesizing transit voyages (15-min frequency)..." << endl;-        lock_guard<mutex> lock(name_pool_mtx);-        for (const auto& cw : cached_ways) {-            if (cw.type & TRANSIT_FLAG) {-                for (size_t i = 0; i < (size_t)cw.node_count - 1; ++i) {-                    uint64_t u_osm = way_nodes_topology[cw.first_node_idx + i];-                    uint64_t v_osm = way_nodes_topology[cw.first_node_idx + i + 1];-                    uint32_t u_lid = get_local_id_by_osm(u_osm | TRANSIT_NODE_FLAG, id_to_local);-                    uint32_t v_lid = get_local_id_by_osm(v_osm | TRANSIT_NODE_FLAG, id_to_local);-                    if (u_lid == 0xFFFFFFFF || v_lid == 0xFFFFFFFF) continue;--                    uint32_t dist = accurate_dist_mm(node_masters[u_lid].lat_e7, node_masters[u_lid].lon_e7,-                                                     node_masters[v_lid].lat_e7, node_masters[v_lid].lon_e7);-                    double speed_m_s = (cw.type & 0x7F) == 0 ? 11.1 : 5.5;-                    uint32_t travel_time_10ms = (uint32_t)((dist / 1000.0) / speed_m_s * 100.0);--                    auto& group = transit_groups[{u_lid, v_lid}];-                    group.name_off = cw.name_offset;-                    for (int h = 0; h < 24; ++h) {-                        for (int m = 0; m < 60; m += 15) {-                            uint32_t dep = (h * 3600 + m * 60) * 100;-                            group.voyages.push_back({dep, dep + travel_time_10ms});-                        }-                    }-                }-            }-        }-    } else {-        lock_guard<mutex> lock(name_pool_mtx);-        for (auto& ti : transit_inputs) {-            uint32_t u_lid = get_local_id_by_osm(ti.u_osm | TRANSIT_NODE_FLAG, id_to_local);-            uint32_t v_lid = get_local_id_by_osm(ti.v_osm | TRANSIT_NODE_FLAG, id_to_local);-            if (u_lid != 0xFFFFFFFF && v_lid != 0xFFFFFFFF) {-                uint32_t n_off = 0xFFFFFFFF;-                auto it = name_pool.find(ti.line_name);-                if (it != name_pool.end()) n_off = it->second;-                else {-                    n_off = name_offset;-                    name_pool[ti.line_name] = n_off;-                    name_out.write(ti.line_name.c_str(), ti.line_name.size() + 1);-                    name_offset += (ti.line_name.size() + 1);-                }-                transit_groups[{u_lid, v_lid}].voyages.push_back({ti.dep, ti.arr});-                transit_groups[{u_lid, v_lid}].name_off = n_off;-            }-        }-    }--    for (auto& entry : transit_groups) {-        sort(entry.second.voyages.begin(), entry.second.voyages.end(), [](const TransitVoyage& a, const TransitVoyage& b) {-            return a.dep_10ms < b.dep_10ms;-        });-    }--    total_edges += transit_groups.size();-    total_edges += total_local_nodes * 2; // Upper bound for transfer edges--    vector<TmpEdge> tmp_edges(total_edges);-    atomic<uint64_t> global_edge_idx{0};-    {-        size_t n_ways = cached_ways.size();-        size_t chunk = n_ways / thread::hardware_concurrency();-        vector<future<void>> construction_tasks;-        for (int t = 0; t < (int)thread::hardware_concurrency(); ++t) {-            construction_tasks.push_back(async(launch::async, [&, t, chunk, n_ways]() {-                size_t start_way = t * chunk;-                size_t end_way = (t == (int)thread::hardware_concurrency() - 1) ? n_ways : (t + 1) * chunk;-                vector<TmpEdge> local_buffer;-                local_buffer.reserve(10000);-                for (size_t w = start_way; w < end_way; ++w) {-                    const auto& cw = cached_ways[w];-                    // Skip ways that are dedicated transit infrastructure (no highway type)-                    if ((cw.type & TRANSIT_FLAG) && (cw.type & 0x7F) == 0) continue;--                    for (size_t i = 0; i < (size_t)cw.node_count - 1; ++i) {-                        uint64_t u_osm = way_nodes_topology[cw.first_node_idx + i];-                        uint64_t v_osm = way_nodes_topology[cw.first_node_idx + i + 1];-                        uint32_t u_lid = get_local_id_by_osm(u_osm, id_to_local);-                        uint32_t v_lid = get_local_id_by_osm(v_osm, id_to_local);-                        if (u_lid == 0xFFFFFFFF || v_lid == 0xFFFFFFFF) continue;-                        uint32_t dist = accurate_dist_mm(node_masters[u_lid].lat_e7, node_masters[u_lid].lon_e7,-                                                         node_masters[v_lid].lat_e7, node_masters[v_lid].lon_e7);-                        local_buffer.push_back({ u_lid, v_lid, dist, cw.name_offset, cw.type, cw.speed_limit, cw.fwd_lane_off, cw.fwd_lane_count });-                        if (!cw.oneway) local_buffer.push_back({ v_lid, u_lid, dist, cw.name_offset, cw.type, cw.speed_limit, cw.bwd_lane_off, cw.bwd_lane_count });-                        if (local_buffer.size() >= 9000) {-                            uint64_t start = global_edge_idx.fetch_add(local_buffer.size());-                            memcpy(&tmp_edges[start], local_buffer.data(), local_buffer.size() * sizeof(TmpEdge));-                            local_buffer.clear();-                        }-                    }-                }-                if (!local_buffer.empty()) {-                    uint64_t start = global_edge_idx.fetch_add(local_buffer.size());-                    memcpy(&tmp_edges[start], local_buffer.data(), local_buffer.size() * sizeof(TmpEdge));-                }-            }));-        }-        for (auto& task : construction_tasks) task.wait();--        for (auto& entry : transit_groups) {-            uint32_t u_lid = entry.first.first;-            uint32_t v_lid = entry.first.second;-            tmp_edges[global_edge_idx.fetch_add(1)] = { u_lid, v_lid, 0, entry.second.name_off, TRANSIT_FLAG, (uint8_t)min((size_t)255, entry.second.voyages.size()), 0xFFFFFFFF, 0 };-        }--        // NEW: Add transfer edges for shared stop nodes-        for (uint32_t i = 0; i < total_local_nodes; ++i) {-            uint64_t osm_u = id_to_local[i].osm_id;-            if (!(osm_u & TRANSIT_NODE_FLAG)) { // it's a road node-                uint32_t transit_lid = get_local_id_by_osm(osm_u | TRANSIT_NODE_FLAG, id_to_local);-                if (transit_lid != 0xFFFFFFFF) {-                    if (node_masters[i].stop_code_off != 0xFFFFFFFF) {-                        uint32_t road_lid = i;-                        // 15 meter transfer distance (15000mm)-                        tmp_edges[global_edge_idx.fetch_add(1)] = { road_lid, transit_lid, 15000, 0xFFFFFFFF, 12, 5, 0xFFFFFFFF, 0 };-                        tmp_edges[global_edge_idx.fetch_add(1)] = { transit_lid, road_lid, 15000, 0xFFFFFFFF, 12, 5, 0xFFFFFFFF, 0 };-                    }-                }-            }-        }--        tmp_edges.resize(global_edge_idx.load());-        cout << "Step 3: Graph Construction Complete. Real Edges Count: " << tmp_edges.size() << endl;-    }--    vector<IDMapping>().swap(id_to_local);-    vector<uint64_t>().swap(way_nodes_topology);-    vector<CachedWay>().swap(cached_ways);--    cout << "Parallel Radix Sorting Edges..." << endl;-    parallel_radix_sort(tmp_edges, 32);--    // --- Connect Isolated Bus Stops ----    {-        cout << "Identifying Connected Components..." << endl;-        vector<int32_t> component_id(total_local_nodes, -1);-        uint32_t lcc_id = 0;-        uint32_t max_size = 0;--        vector<uint32_t> node_to_edge(total_local_nodes + 1);-        uint32_t cur_edge = 0;-        for (uint32_t i = 0; i < total_local_nodes; ++i) {-            node_to_edge[i] = cur_edge;-            while (cur_edge < tmp_edges.size() && tmp_edges[cur_edge].source_lid == i) cur_edge++;-        }-        node_to_edge[total_local_nodes] = cur_edge;--        vector<uint32_t> q;-        q.reserve(total_local_nodes);--        int32_t current_comp = 0;-        for (uint32_t i = 0; i < total_local_nodes; ++i) {-            if (component_id[i] == -1) {-                uint32_t start_idx = q.size();-                q.push_back(i);-                component_id[i] = current_comp;-                uint32_t head = start_idx;-                while (head < q.size()) {-                    uint32_t u = q[head++];-                    for (uint32_t e = node_to_edge[u]; e < node_to_edge[u + 1]; ++e) {-                        uint32_t v = tmp_edges[e].target_lid;-                        if (component_id[v] == -1) {-                            component_id[v] = current_comp;-                            q.push_back(v);-                        }-                    }-                }-                uint32_t comp_size = q.size() - start_idx;-                if (comp_size > max_size) {-                    max_size = comp_size;-                    lcc_id = current_comp;-                }-                current_comp++;-            }-        }-        cout << "LCC ID: " << lcc_id << ", Size: " << max_size << " / " << total_local_nodes << endl;--        vector<TmpEdge> new_edges;-        for (uint32_t i = 0; i < total_local_nodes; ++i) {-            if (node_masters[i].stop_code_off != 0xFFFFFFFF && component_id[i] != (int32_t)lcc_id && is_road_node[i]) {-                uint32_t best_node = 0xFFFFFFFF;-                uint32_t best_dist = 0xFFFFFFFF;--                for (int radius = 1000; radius <= 1000000; radius *= 10) {-                    int start = max(0, (int)i - radius);-                    int end = min((int)total_local_nodes, (int)i + radius);-                    for (int j = start; j < end; ++j) {-                        if (component_id[j] == (int32_t)lcc_id && is_road_node[j]) {-                            uint32_t d = accurate_dist_mm(node_masters[i].lat_e7, node_masters[i].lon_e7,-                                                          node_masters[j].lat_e7, node_masters[j].lon_e7);-                            if (d < best_dist) {-                                best_dist = d;-                                best_node = j;-                            }-                        }-                    }-                    if (best_node != 0xFFFFFFFF) break;-                }--                if (best_node != 0xFFFFFFFF) {-                    new_edges.push_back({ i, (uint32_t)best_node, best_dist, 0xFFFFFFFF, 12, 5, 0xFFFFFFFF, 0 });-                    new_edges.push_back({ (uint32_t)best_node, i, best_dist, 0xFFFFFFFF, 12, 5, 0xFFFFFFFF, 0 });-                }-            }-        }--        if (!new_edges.empty()) {-            cout << "Adding " << new_edges.size() << " synthetic connections for isolated bus stops." << endl;-            tmp_edges.insert(tmp_edges.end(), new_edges.begin(), new_edges.end());-            parallel_radix_sort(tmp_edges, 32);-        }-    }--    // STEP 4: Finalize & write the SINGLE GLOBAL graph (no zones, no separate-    // merge stage). Emit exactly the on-disk layout that-    // maps/src/main/rust/src/graph.rs loads:-    //   metadata.bin            single u64 node_count-    //   nodes.bin               FinalNode[node_count + 1] (trailing sentinel)-    //   edges.bin               FinalEdge[edge_count]-    //   transit_attributes.bin  FinalTransitAttr[node_count]-    //   transit_voyages.bin     compact per-edge voyage records (see below)-    //   lanes.bin               u64 offsets[edge_count + 1] + u16 mask blob-    //   road_names.bin          string pool (already streamed above)-    // tmp_edges is globally sorted by source_lid, so a single linear cursor-    // assigns each node its global edge range in one pass.-    cout << "Finalizing single global graph..." << endl;--    ofstream nodes_out(DATA_DIR + "nodes.bin", ios::binary);-    ofstream edges_out(DATA_DIR + "edges.bin", ios::binary);-    ofstream attrs_out(DATA_DIR + "transit_attributes.bin", ios::binary);-    ofstream voyages_out(DATA_DIR + "transit_voyages.bin", ios::binary);-    ofstream lanes_out(DATA_DIR + "lanes.bin", ios::binary);--    // lanes.bin: one byte offset into the u16 mask blob per edge + a trailing-    // sentinel, so edge e's masks are blob[offsets[e]..offsets[e+1]].-    vector<uint64_t> lane_offsets;-    lane_offsets.reserve(tmp_edges.size() + 1);-    vector<uint16_t> lane_blob;--    uint64_t global_edge_ptr = 0;-    uint64_t transit_voyage_slots = 0; // in TransitVoyageCompact (4-byte) units-    size_t e_cursor = 0;--    for (uint32_t lid = 0; lid < total_local_nodes; ++lid) {-        FinalNode fn = { node_masters[lid].lat_e7, node_masters[lid].lon_e7, global_edge_ptr };-        nodes_out.write((char*)&fn, sizeof(FinalNode));--        FinalTransitAttr fa = { node_masters[lid].stop_code_off, node_masters[lid].feed_name_off };-        attrs_out.write((char*)&fa, sizeof(FinalTransitAttr));--        while (e_cursor < tmp_edges.size() && tmp_edges[e_cursor].source_lid == lid) {-            const TmpEdge& te = tmp_edges[e_cursor];-            uint32_t out_dist = te.dist_mm;-            uint8_t out_speed = te.speed_limit;--            if (te.type & TRANSIT_FLAG) {-                // Compact this transit edge's schedule into transit_voyages.bin.-                // Per edge, starting at slot `voyage_offset` (4-byte slots):-                //   [slot 0]     u32 absolute departure of voyage 0 (10ms units)-                //   [slot 1]     {dep_delta = voyage 0 travel time (10ms), 0}-                //   [slot 1 + i] {dep_delta = (dep_i - dep_{i-1}) seconds,-                //                 duration = voyage i travel time (10ms)}-                // graph.rs stores voyage_offset in the edge's dist_mm and the-                // voyage count in speed_limit; geometry.rs decodes it this way.-                auto it = transit_groups.find({te.source_lid, te.target_lid});-                if (it != transit_groups.end() && !it->second.voyages.empty()) {-                    const auto& vs = it->second.voyages; // sorted by dep_10ms-                    uint32_t vc = (uint32_t)min((size_t)255, vs.size());-                    out_dist = (uint32_t)transit_voyage_slots;-                    out_speed = (uint8_t)vc;--                    uint32_t dep0 = vs[0].dep_10ms;-                    voyages_out.write((char*)&dep0, sizeof(uint32_t));-                    TransitVoyageCompact c0 = {-                        (uint16_t)min<uint32_t>(0xFFFF, vs[0].arr_10ms - vs[0].dep_10ms), 0 };-                    voyages_out.write((char*)&c0, sizeof(TransitVoyageCompact));-                    transit_voyage_slots += 2;--                    uint32_t dep_prev = dep0;-                    for (uint32_t i = 1; i < vc; ++i) {-                        uint32_t dep = vs[i].dep_10ms;-                        TransitVoyageCompact ci = {-                            (uint16_t)min<uint32_t>(0xFFFF, (dep - dep_prev) / 100),-                            (uint16_t)min<uint32_t>(0xFFFF, vs[i].arr_10ms - vs[i].dep_10ms) };-                        voyages_out.write((char*)&ci, sizeof(TransitVoyageCompact));-                        transit_voyage_slots += 1;-                        dep_prev = dep;-                    }-                } else {-                    out_speed = 0; // transit edge with no usable schedule-                }-            }--            FinalEdge fe = { te.target_lid, out_dist, te.name_offset, te.type, out_speed };-            edges_out.write((char*)&fe, sizeof(FinalEdge));--            lane_offsets.push_back((uint64_t)lane_blob.size() * sizeof(uint16_t));-            if (te.lane_count > 0 && te.lane_off != 0xFFFFFFFF) {-                for (uint16_t l = 0; l < te.lane_count; ++l)-                    lane_blob.push_back(lane_pool[te.lane_off + l]);-            }--            global_edge_ptr++;-            e_cursor++;-        }-    }--    // Trailing sentinel node: edge_ptr == edge_count so graph.rs can read-    // node(v + 1).edge_ptr as the end of node v's edge range.-    FinalNode sentinel = { 0, 0, global_edge_ptr };-    nodes_out.write((char*)&sentinel, sizeof(FinalNode));--    // Finalize lanes.bin: offsets (with trailing sentinel) then the mask blob.-    lane_offsets.push_back((uint64_t)lane_blob.size() * sizeof(uint16_t));-    lanes_out.write((char*)lane_offsets.data(), sizeof(uint64_t) * lane_offsets.size());-    if (!lane_blob.empty())-        lanes_out.write((char*)lane_blob.data(), sizeof(uint16_t) * lane_blob.size());--    // metadata.bin: a single u64 node_count (graph.rs reads read_at::<u64>(_, 0)).-    ofstream meta_out(DATA_DIR + "metadata.bin", ios::binary);-    uint64_t node_count_out = total_local_nodes;-    meta_out.write((char*)&node_count_out, sizeof(uint64_t));--    cout << "Processing Complete. Nodes: " << total_local_nodes-         << " Edges: " << global_edge_ptr << endl;-    return 0;-}\ No newline at end of file
scripts/maps/osm_ingest/Cargo.lock
diff --git a/scripts/maps/osm_ingest/Cargo.lock b/scripts/maps/osm_ingest/Cargo.locknew file mode 100644index 0000000000..f596afcd72--- /dev/null+++ b/scripts/maps/osm_ingest/Cargo.lock@@ -0,0 +1,25 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+]++[[package]]+name = "osm_ingest"+version = "0.1.0"+dependencies = [+ "miniz_oxide",+]
scripts/maps/osm_ingest/Cargo.toml
diff --git a/scripts/maps/osm_ingest/Cargo.toml b/scripts/maps/osm_ingest/Cargo.tomlnew file mode 100644index 0000000000..2b7886b344--- /dev/null+++ b/scripts/maps/osm_ingest/Cargo.toml@@ -0,0 +1,43 @@+# Host-side OSM ingest tools for the Maps offline packs.+#+# 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.+#+# Deliberately DETACHED from the Android Rust workspace (the empty [workspace]+# table below), exactly like `scripts/maps/gtfs_ingest`: it is a host binary, so+# `cargo build` here never pulls the aarch64-android toolchain or the app+# crates' lints. Its single dependency, `miniz_oxide`, is a pure-Rust+# DECODE-ONLY inflate implementation already in the local registry cache (the+# app's maps crate pulls it via flate2), so builds still resolve offline.+[package]+name = "osm_ingest"+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)"++[lib]+name = "osm_ingest"+path = "src/lib.rs"++[[bin]]+name = "road_graph"+path = "src/bin/road_graph.rs"++[[bin]]+name = "poi_extract"+path = "src/bin/poi_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.+miniz_oxide = "0.8"++[profile.release]+opt-level = 3++# Detach from the repo-root workspace so this host tool builds standalone/offline.+[workspace]
scripts/maps/osm_ingest/README.md
diff --git a/scripts/maps/osm_ingest/README.md b/scripts/maps/osm_ingest/README.mdnew file mode 100644index 0000000000..6e15d8ae83--- /dev/null+++ b/scripts/maps/osm_ingest/README.md@@ -0,0 +1,189 @@+# 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:++| 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` |++## Why Rust (LANGUAGE RULE)++- **Rust-first:** the same rule that made `gtfs_ingest` Rust rather than Python,+  and the router Rust rather than C++ (`maps/src/main/cpp/` is gone). These two+  files were the last hand-written C++ in the Maps pipeline.+- **No libosmium, so no WSL.** The C++ needed `g++` + `libosmium2-dev` ++  `-lz -lexpat -lbz2`, which do not exist on Windows, so regenerating a pack+  meant dropping into WSL. `.osm.pbf` is read natively here: a hand-rolled+  protobuf decoder (`src/proto.rs`, mirroring the encoder in+  `maps/src/main/rust/src/mvt.rs`) over a pure-Rust inflate.+- **Offline builds:** the crate is detached from the repo-root Cargo workspace+  (the empty `[workspace]` in `Cargo.toml`), like `gtfs_ingest`, so `cargo build`+  never pulls the aarch64-android toolchain or the app crates' lints. The single+  dependency, `miniz_oxide`, is a **decode-only** inflate crate — we never+  compress — following the `ruzstd` precedent in+  `networklocation/src/main/rust/Cargo.toml`. It is already in the local registry+  cache because the app's maps crate pulls it via `flate2`.+- **Deterministic**, which the C++ was not. See below.++## Usage++```sh+# Routing graph -> map_data/ (the directory run_generator.sh uploads to R2)+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+```++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.++## Output contracts++Every layout below is read by code elsewhere in the repo. Changing one without+changing its reader produces a graph that loads as garbage, which is why+`metadata.bin` carries a magic and version.++| File | Layout | Reader |+|---|---|---|+| `metadata.bin` | `u32 magic "MARG"`, `u32 version 1`, `u64 node_count` (16 B) | `graph.rs` `GRAPH_MAGIC`/`GRAPH_VERSION` |+| `nodes.bin` | `NodeMaster[node_count + 1]`: `i32 lat_e7, i32 lon_e7, u64 edge_ptr`; Morton-sorted, trailing sentinel whose `edge_ptr == edge_count` | `graph.rs` |+| `edges.bin` | `Edge[edge_count]`, **14 bytes**: `u32 target, u32 dist_mm, u32 name_offset, u8 type, u8 speed_limit` | `graph.rs` — `edge_count` comes from the *file size*, so this must be an exact multiple of 14 |+| `lanes.bin` | `u64 byte_offsets[edge_count + 1]` then the packed `u16` per-lane turn masks | `graph.rs` `LANE_*` |+| `road_names.bin` | deduped NUL-terminated UTF-8 pool; a name offset is a byte offset | `graph.rs` |+| `poi_index.bin` | 14-byte records: `i32 lat_e7, i32 lon_e7, u32 name_off, u16 type`, Morton-sorted | `PoiIndex.kt` |+| `poi_names.bin` | same pool convention as `road_names.bin` | `PoiIndex.kt` |++The POI Morton sort key is computed from the *stored* `lat_e7`/`lon_e7`, not from+the pre-rounding `f64` centroid the C++ used, so the order matches the key a+reader recomputes from the file. On California that removed 9 ordering+inversions the old tool produced.++The POI type numbers live in `src/tags.rs` and are also tabulated in+`scripts/maps/README.md`. **Never renumber an existing type — only append.**++## Determinism++Every output is a pure function of the input file. This is a real change: the C+++generator filled its node array with `idx.fetch_add(1)` from concurrent workers+and interned way names in thread-scheduling order, so two runs of the C++ on the+same extract produced different node ordering, different `name_offset` values and+therefore different `road_names.bin`, `edges.bin` and `nodes.bin`.++The mechanism is in `src/par.rs` and `pbf::run_pass`: work is split into fixed+contiguous chunks (of blobs, ways or nodes), chunks are claimed dynamically so a+heavy chunk cannot stall a core, but each chunk's results are stored at its own+index and merged **in index order**. Name interning then happens single-threaded+during that merge. The chunk size is a constant, not a function of the core+count, so the output does not vary between machines either.++Verified on the full California extract: two runs produce byte-identical+`metadata.bin`, `nodes.bin`, `edges.bin`, `lanes.bin`, `road_names.bin`,+`poi_index.bin`, `poi_names.bin` and geojsonseq.++## How the reader works++A `.osm.pbf` is a flat sequence of `[u32 BE header_len][BlobHeader][Blob]`.+`pbf::scan_blobs` walks that framing once reading only headers, recording each+`OSMData` blob's `(offset, len)`. Threads then each open their own `File`, seek,+read and inflate their own blobs — no channels, no shared queue, no throttling+condvar, which is how the C++ `ThreadPool`/`MoveTask`/`wait_finished` machinery+(and the data race its comments describe) disappears.++Every blob is self-checked: `miniz_oxide` validates the zlib header and the+Adler-32 trailer, and the inflated length is compared against the blob's declared+`raw_size`. Across California's 23,007 blobs that is strong evidence the reader+is correct. Compressions that would need a C library (lzma, bzip2, lz4, zstd)+are reported as a clear error rather than silently skipped, because a skipped+blob would yield a quietly incomplete graph.++Because a PBF stores all nodes, then all ways, then all relations, the first pass+records which entity kinds each blob held; later passes skip blobs outright.+`road_graph` needs two passes (ways must be known before we know which nodes+matter) and `poi_extract` needs three (relations -> ways -> nodes).++## Testing++`cargo test` runs 46 in-crate tests, following the `gtfs_ingest` pattern. The+fixture in `src/testpbf.rs` hand-encodes a complete `.osm.pbf` — including real+zlib framing built from stored DEFLATE blocks and a real Adler-32 — so the+decoder is tested against bytes produced independently of it.++- **protobuf**: uvarint at every 7-bit boundary, 10-byte negative `int64`,+  zigzag against the spec's vectors, packed deltas, skipping unknown fields of+  every wire type, and truncated input rejected.+- **`latlng_to_spatial`** compared against a transcription of+  `graph.rs::latlng_to_spatial` for a table of coordinates. If these drift the+  device's spatial binary search silently returns the wrong nodes.+- **`accurate_dist_mm`** against known city-pair great-circle distances, and+  across the antimeridian and pole to pole (where a naive `i32` coordinate+  subtraction overflows).+- **tags**: `get_hw_id`, `parse_maxspeed` (`mph` ×1.60934, `knots` ×1.852,+  non-numeric -> 0), `turn:lanes` (`|` lanes, `;` indications, unknown ->+  `LANE_NONE`, count pad/truncate), and POI `classify` precedence including the+  rule that bare `railway`/`public_transport` values are *not* POIs.+- **whole pipeline**: the fixture through `road_graph`, asserting the exact+  `metadata.bin` bytes, the `nodes.bin` sentinel, `edges.bin % 14 == 0`, Morton+  ordering, the full decoded edge set, the exact `road_names.bin`, and the+  `lanes.bin` offset/blob split — plus the same for `poi_extract`, and a+  two-runs-are-identical check for both.+- **ring centroid**: that the repeated ring vertex is the one with the smallest+  `(lon, lat)`, so the centroid does not move when the ring's start rotates.+  Getting this wrong put small buildings metres off the old tool's output.++## Cross-checked against the C++ it replaces++The C++ cannot be a byte-for-byte oracle (it was nondeterministic), so the port+was validated *structurally*. Both toolchains were run over the same San Luis+Obispo extract — the C++ built in WSL against libosmium 2.20 — and compared on+invariants that do not depend on its thread-scheduling-dependent ordering:++| Invariant | Result |+|---|---|+| `metadata.bin` magic / version / `node_count` | identical (88,666 nodes) |+| `edge_count` | identical (181,481) |+| `lanes.bin` length | identical (1,453,984 B) |+| `road_names.bin` string set | identical (1,125 names) |+| Node coordinates | every one matches; 7,164 differ by exactly one 1e-7 unit (1.1 cm) — see below |+| Edge `(type, speed_limit, name)` groups + `dist_mm` | identical groups, every distance within 12 mm |+| Out-degree sequence | identical |+| POIs the C++ found | all 1,413 present, identical `name` + `type` |+| Node/closed-way POI coordinates | all within one 1e-7 unit |+| Relation POI centroids | 4 of 15 over 1 m, worst 3.1 m |++Two deliberate differences:++- **Coordinates are 1.1 cm more accurate.** The C++ recovered `lat_e7` as+  `(int32_t)(location.lat() * 1e7)` — truncating a double that libosmium had+  already divided by 1e7 — so ~8% of coordinates came out one unit low. This+  keeps the PBF's exact integer, which also shifts `dist_mm` by a few mm.+- **Three extra POIs.** libosmium's assembler cannot close a ring whose member+  ways were cut off by the bbox, so it silently dropped three boundary relations+  (Los Padres National Forest, Santa Lucia Wilderness, Cuesta Ridge). The centroid+  approximation here still places them. Gaining a named POI is the better failure+  mode, and on an unclipped extract the question does not arise.++## Known limitations++- **Relation POI centroids are approximated.** libosmium assembled true polygon+  rings (`MultipolygonManager` + `Assembler`); porting a ring assembler is a+  large piece of work on its own. Here a relation's outer ring is approximated by+  the deduplicated node ids of its `outer`-role member ways. That is exact when+  the ring is a single closed way; when it is split across several, the measured+  error was under 3.1 m across the sample above. POIs render as points at z12–z16,+  so this is not visible, but `poi_index.bin` is not byte-identical to the C++ for+  relation-derived POIs. Node- and closed-way-derived POIs match exactly.+- **Closed-way areas** use `first ref == last ref` where libosmium compared end+  *locations*. Equivalent for real OSM data and it avoids needing a location+  index during the way pass.+- **Memory.** `road_graph` holds a 2.5 GB node-id bitset (sized from the C++'s+  `BITSET_SIZE = 20e9`, so node ids at or above it are skipped exactly as+  before) plus the node and edge arrays: roughly 10 GB peak on California. Same+  ballpark as the C++, and it will not run on a small machine.+- `build_pois_layer.sh` still needs `tippecanoe` and `osmium-tool` for the+  `.pmtiles` output, so the POI *tile* build stays non-Windows. Only the two side+  files became native.
scripts/maps/osm_ingest/src/bin/poi_extract.rs
diff --git a/scripts/maps/osm_ingest/src/bin/poi_extract.rs b/scripts/maps/osm_ingest/src/bin/poi_extract.rsnew file mode 100644index 0000000000..b6e609a832--- /dev/null+++ b/scripts/maps/osm_ingest/src/bin/poi_extract.rs@@ -0,0 +1,48 @@+//! `poi_extract IN.osm.pbf --geojson FILE --names FILE --index FILE`+//!+//! Replaces `scripts/maps/poi_extract.cpp`. See `osm_ingest::poi_build` for the+//! POI type map and the on-disk record layout.++use std::process::ExitCode;++const USAGE: &str =+    "Usage: poi_extract IN.osm.pbf --geojson FILE --names FILE --index FILE";++fn main() -> ExitCode {+    let argv: Vec<String> = std::env::args().skip(1).collect();+    let args = match osm_ingest::poi_build::parse_args(&argv) {+        Ok(v) => v,+        Err(e) => {+            eprintln!("error: {e}\n{USAGE}");+            return ExitCode::FAILURE;+        }+    };++    let started = std::time::Instant::now();+    match osm_ingest::poi_build::build(&args.input, &args.geojson, &args.names, &args.index) {+        Ok(stats) => {+            println!(+                "{} POI(s) ({} node, {} closed-way, {} relation), {} unique name(s) \+                 ({} bytes) in {:.1}s",+                stats.records,+                stats.from_nodes,+                stats.from_ways,+                stats.from_relations,+                stats.unique_names,+                stats.name_bytes,+                started.elapsed().as_secs_f64()+            );+            println!(+                "Wrote {}, {}, {}",+                args.geojson.display(),+                args.names.display(),+                args.index.display()+            );+            ExitCode::SUCCESS+        }+        Err(e) => {+            eprintln!("error: {e}");+            ExitCode::FAILURE+        }+    }+}
scripts/maps/osm_ingest/src/bin/road_graph.rs
diff --git a/scripts/maps/osm_ingest/src/bin/road_graph.rs b/scripts/maps/osm_ingest/src/bin/road_graph.rsnew file mode 100644index 0000000000..58597c6534--- /dev/null+++ b/scripts/maps/osm_ingest/src/bin/road_graph.rs@@ -0,0 +1,42 @@+//! `road_graph IN.osm.pbf [--out DIR]` — build the single global routing graph.+//!+//! Replaces `scripts/maps/generator.cpp`. See `osm_ingest::graph_build` for the+//! on-disk contract.++use std::process::ExitCode;++const USAGE: &str = "Usage: road_graph IN.osm.pbf [--out DIR]   (default --out map_data)";++fn main() -> ExitCode {+    let args: Vec<String> = std::env::args().skip(1).collect();+    let (input, out_dir) = match osm_ingest::graph_build::parse_args(&args) {+        Ok(v) => v,+        Err(e) => {+            eprintln!("error: {e}\n{USAGE}");+            return ExitCode::FAILURE;+        }+    };++    let started = std::time::Instant::now();+    match osm_ingest::graph_build::build(&input, &out_dir) {+        Ok(stats) => {+            println!(+                "{} node(s), {} edge(s), {} unique name(s) ({} bytes), LCC {} node(s), \+                 {} isolated stop(s) reconnected in {:.1}s",+                stats.node_count,+                stats.edge_count,+                stats.unique_names,+                stats.name_bytes,+                stats.lcc_size,+                stats.reconnected_stops,+                started.elapsed().as_secs_f64()+            );+            println!("Wrote {}", out_dir.display());+            ExitCode::SUCCESS+        }+        Err(e) => {+            eprintln!("error: {e}");+            ExitCode::FAILURE+        }+    }+}
scripts/maps/osm_ingest/src/graph_build.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build.rs b/scripts/maps/osm_ingest/src/graph_build.rsnew file mode 100644index 0000000000..7d70a1da47--- /dev/null+++ b/scripts/maps/osm_ingest/src/graph_build.rs@@ -0,0 +1,891 @@+//! Road-graph build: `.osm.pbf` -> `metadata.bin` / `nodes.bin` / `edges.bin` /+//! `lanes.bin` / `road_names.bin`.+//!+//! A faithful port of the former `scripts/maps/generator.cpp`, preserving the+//! on-disk contract byte for byte. The reader is+//! `maps/src/main/rust/src/graph.rs`, which is the authority for every layout+//! decision here:+//!+//! | File | Layout |+//! |---|---|+//! | `metadata.bin` | `u32 magic "MARG"`, `u32 version`, `u64 node_count` (16 B) |+//! | `nodes.bin` | `NodeMaster[node_count + 1]`: `i32 lat_e7, i32 lon_e7, u64 edge_ptr`; the trailing sentinel's `edge_ptr` is `edge_count` |+//! | `edges.bin` | `Edge[edge_count]`, **14 bytes each**: `u32 target, u32 dist_mm, u32 name_offset, u8 type, u8 speed_limit` |+//! | `lanes.bin` | `u64 byte_offsets[edge_count + 1]` then the packed `u16` mask blob |+//! | `road_names.bin` | deduped NUL-terminated string pool |+//!+//! `edge_count` is derived on device from `edges.bin`'s *file size*, so that file+//! must stay an exact multiple of 14 bytes.+//!+//! Two behavioural notes where this differs from the C++:+//!+//! * It is **deterministic**. The C++ filled its node array via+//!   `idx.fetch_add(1)` from concurrent workers and interned names in+//!   thread-scheduling order, so its node order, `name_offset` values and+//!   therefore all of `road_names.bin`/`edges.bin`/`nodes.bin` differed between+//!   two runs of itself. Here every parallel stage merges per-chunk results in+//!   chunk order, so the output is a pure function of the input.+//! * The C++ kept two bitsets, `useful_nodes_mask` and `road_nodes_mask`, but+//!   set and cleared them in exactly the same places, so they always held+//!   identical contents. One bitset does the same job for half the memory.++use std::fs::File;+use std::io::{BufWriter, Write};+use std::path::{Path, PathBuf};++use crate::names::{LocalNames, NamePool, NO_NAME};+use crate::osm::{visit_block, Element};+use crate::par;+use crate::pbf::{self, KIND_NODES, KIND_WAYS};+use crate::proto::{Error, Result};+use crate::spatial::{accurate_dist_mm, spatial_from_e7};+use crate::tags;++/// Node ids at or above this are skipped, exactly as in the C++. The bitset that+/// tracks "is this node part of the graph" is sized from it (2.5 GB).+pub const BITSET_SIZE: u64 = 20_000_000_000;++/// `"MARG"` little-endian — `GRAPH_MAGIC` in `graph.rs`.+const GRAPH_MAGIC: u32 = 0x4752_414D;+const GRAPH_VERSION: u32 = 1;++/// Synthetic edges that reattach an isolated transit stop to the routable graph.+const RECONNECT_TYPE: u8 = 12;+const RECONNECT_SPEED: u8 = 5;++/// Sentinel in a `CachedWay`/`TmpEdge` lane offset meaning "no lane data".+const NO_LANES: u32 = 0xFFFF_FFFF;++/// Fallback stop code for a transit stop node with no `name`.+const UNNAMED_STOP: &[u8] = b"OSM_STOP";++pub struct Stats {+    pub node_count: u64,+    pub edge_count: u64,+    pub unique_names: usize,+    pub name_bytes: u32,+    pub lcc_size: u64,+    pub reconnected_stops: usize,+}++/// A plain (non-atomic) bitset. Bits are set from a single thread during the+/// merge and only read afterwards, so no atomics are needed.+struct Bitset {+    bits: Vec<u8>,+}++impl Bitset {+    fn new(size_bits: u64) -> Bitset {+        Bitset {+            bits: vec![0u8; (size_bits / 8 + 1) as usize],+        }+    }++    /// Returns true when this call is what set the bit.+    fn set(&mut self, idx: u64) -> bool {+        let byte = &mut self.bits[(idx / 8) as usize];+        let mask = 1u8 << (idx % 8);+        let was = *byte & mask != 0;+        *byte |= mask;+        !was+    }++    fn get(&self, idx: u64) -> bool {+        self.bits[(idx / 8) as usize] & (1u8 << (idx % 8)) != 0+    }+}++/// A routable way, cached from pass 1 so pass 3 can emit its edges without+/// re-reading the file.+#[derive(Clone)]+struct CachedWay {+    /// Pass 1 stores a chunk-local name id; the merge rewrites it to the pool+    /// offset (or `NO_NAME`).+    name: u32,+    first_ref: u64,+    ref_count: u32,+    type_: u8,+    speed_limit: u8,+    oneway: bool,+    fwd_lane_off: u32,+    fwd_lane_count: u16,+    bwd_lane_off: u32,+    bwd_lane_count: u16,+}++#[derive(Default)]+struct Pass1 {+    ways: Vec<CachedWay>,+    refs: Vec<i64>,+    lanes: Vec<u16>,+    names: LocalNames,+    stop_nodes: Vec<i64>,+}++#[derive(Clone, Copy)]+struct NodeTmp {+    spatial: u64,+    osm_id: i64,+    lat_e7: i32,+    lon_e7: i32,+    /// Chunk-local name id in pass 2, pool offset after the merge.+    stop_code: u32,+}++#[derive(Default)]+struct Pass2 {+    nodes: Vec<NodeTmp>,+    names: LocalNames,+}++#[derive(Clone, Copy)]+struct TmpEdge {+    source: u32,+    target: u32,+    dist_mm: u32,+    name_offset: u32,+    type_: u8,+    speed_limit: u8,+    lane_off: u32,+    lane_count: u16,+}++pub fn build(input: &Path, out_dir: &Path) -> Result<Stats> {+    std::fs::create_dir_all(out_dir)+        .map_err(|e| Error(format!("cannot create {}: {e}", out_dir.display())))?;++    let blobs = pbf::scan_blobs(input)?;+    println!("Scanned {} data blob(s) in {}", blobs.len(), input.display());++    let mut pool = NamePool::new(BufWriter::new(create(&out_dir.join("road_names.bin"))?));++    // --- Pass 1: routable ways (cached) + transit stop nodes -----------------+    let (chunks, blob_kinds) = pbf::run_pass(+        input,+        &blobs,+        None,+        KIND_NODES | KIND_WAYS,+        "Pass 1: ways + stops",+        Pass1::default,+        pass1_blob,+    )?;++    let mut ways: Vec<CachedWay> = Vec::new();+    let mut way_refs: Vec<i64> = Vec::new();+    let mut lane_pool: Vec<u16> = Vec::new();+    let mut mask = Bitset::new(BITSET_SIZE);+    let mut node_count: u64 = 0;++    for chunk in chunks {+        let name_map = chunk.names.flush(&mut pool).map_err(io_err)?;+        let ref_base = way_refs.len() as u64;+        let lane_base = lane_pool.len() as u32;+        for mut w in chunk.ways {+            w.name = if w.name == u32::MAX {+                NO_NAME+            } else {+                name_map[w.name as usize]+            };+            w.first_ref += ref_base;+            if w.fwd_lane_count > 0 {+                w.fwd_lane_off += lane_base;+            }+            if w.bwd_lane_count > 0 {+                w.bwd_lane_off += lane_base;+            }+            ways.push(w);+        }+        for id in chunk.refs.iter().chain(chunk.stop_nodes.iter()) {+            if *id >= 0 && (*id as u64) < BITSET_SIZE && mask.set(*id as u64) {+                node_count += 1;+            }+        }+        way_refs.extend_from_slice(&chunk.refs);+        lane_pool.extend_from_slice(&chunk.lanes);+    }+    println!(+        "Cached {} routable way(s), {} node ref(s), {} graph node(s) expected",+        ways.len(),+        way_refs.len(),+        node_count+    );++    // --- Pass 2: coordinates and stop codes for the marked nodes -------------+    let (chunks, _) = pbf::run_pass(+        input,+        &blobs,+        Some(&blob_kinds),+        KIND_NODES,+        "Pass 2: node scan",+        Pass2::default,+        |state, block| pass2_blob(state, block, &mask),+    )?;++    let mut nodes: Vec<NodeTmp> = Vec::with_capacity(node_count as usize);+    for chunk in chunks {+        let name_map = chunk.names.flush(&mut pool).map_err(io_err)?;+        for mut n in chunk.nodes {+            if n.stop_code != u32::MAX {+                n.stop_code = name_map[n.stop_code as usize];+            } else {+                n.stop_code = NO_NAME;+            }+            nodes.push(n);+        }+    }+    drop(mask);+    let node_count = nodes.len() as u64;++    // Sort spatially so the device's Morton binary search works, then build the+    // osm_id -> local_id map the edge pass needs. The C++ used a hand-rolled+    // parallel LSD radix sort; `sort_by_key` is also stable, so ordering+    // semantics are unchanged.+    println!("Sorting {node_count} node(s) by spatial key...");+    nodes.sort_by_key(|n| n.spatial);+    let mut id_to_local: Vec<(i64, u32)> = nodes+        .iter()+        .enumerate()+        .map(|(i, n)| (n.osm_id, i as u32))+        .collect();+    id_to_local.sort_by_key(|e| e.0);++    // --- Pass 3: edges ------------------------------------------------------+    println!("Building edges from {} way(s)...", ways.len());+    let per_chunk = par::map_chunks(&ways, 4096, |_, chunk| {+        let mut out: Vec<TmpEdge> = Vec::new();+        for w in chunk {+            for i in 0..w.ref_count.saturating_sub(1) as usize {+                let u_osm = way_refs[w.first_ref as usize + i];+                let v_osm = way_refs[w.first_ref as usize + i + 1];+                let (u, v) = match (local_id(&id_to_local, u_osm), local_id(&id_to_local, v_osm)) {+                    (Some(u), Some(v)) => (u, v),+                    _ => continue,+                };+                let (a, b) = (&nodes[u as usize], &nodes[v as usize]);+                let dist = accurate_dist_mm(a.lat_e7, a.lon_e7, b.lat_e7, b.lon_e7);+                out.push(TmpEdge {+                    source: u,+                    target: v,+                    dist_mm: dist,+                    name_offset: w.name,+                    type_: w.type_,+                    speed_limit: w.speed_limit,+                    lane_off: w.fwd_lane_off,+                    lane_count: w.fwd_lane_count,+                });+                if !w.oneway {+                    out.push(TmpEdge {+                        source: v,+                        target: u,+                        dist_mm: dist,+                        name_offset: w.name,+                        type_: w.type_,+                        speed_limit: w.speed_limit,+                        lane_off: w.bwd_lane_off,+                        lane_count: w.bwd_lane_count,+                    });+                }+            }+        }+        out+    });+    let mut edges: Vec<TmpEdge> = per_chunk.into_iter().flatten().collect();+    drop(id_to_local);+    drop(ways);+    drop(way_refs);+    println!("Built {} edge(s), sorting by source...", edges.len());+    edges.sort_by_key(|e| e.source);++    // --- Reconnect isolated transit stops -----------------------------------+    let (lcc_size, reconnected) = reconnect_isolated_stops(&nodes, &mut edges);++    // --- Write --------------------------------------------------------------+    let edge_count = write_graph(out_dir, &nodes, &edges, &lane_pool)?;+    let unique_names = pool.unique_count();+    let name_bytes = pool.byte_len();+    pool.finish().map_err(io_err)?;++    println!("Done. Nodes: {node_count}  Edges: {edge_count}");+    Ok(Stats {+        node_count,+        edge_count,+        unique_names,+        name_bytes,+        lcc_size,+        reconnected_stops: reconnected,+    })+}++fn pass1_blob(state: &mut Pass1, block: &pbf::PrimitiveBlock) -> Result<u8> {+    let mut kinds = 0u8;+    visit_block(+        block,+        KIND_NODES | KIND_WAYS,+        &mut kinds,+        &mut |el: Element| {+            match el {+                Element::Node(n) => {+                    if tags::is_stop_node(+                        n.tags.get_str("highway"),+                        n.tags.get_str("railway"),+                        n.tags.get_str("public_transport"),+                    ) {+                        state.stop_nodes.push(n.id);+                    }+                }+                Element::Way(w) => {+                    let type_ = tags::get_hw_id(w.tags.get_str("highway"));+                    if type_ == 0 {+                        return Ok(());+                    }+                    let name = match w.tags.get("name") {+                        Some(n) => state.names.id(n),+                        None => u32::MAX,+                    };+                    let speed_limit = tags::parse_maxspeed(w.tags.get_str("maxspeed"));+                    let oneway = w.tags.get_str("oneway") == Some("yes");++                    // Forward lanes come from turn:lanes:forward, or from plain+                    // turn:lanes on a oneway; backward from turn:lanes:backward.+                    // Plain `lanes*` only refine the count. No turn:lanes at all+                    // means no lane data, and the router infers lanes from+                    // junction topology instead.+                    let tl = w.tags.get_str("turn:lanes");+                    let tlf = w.tags.get_str("turn:lanes:forward");+                    let tlb = w.tags.get_str("turn:lanes:backward");+                    let count_all = tags::parse_int_tag(w.tags.get_str("lanes"));+                    let count_fwd = tags::parse_int_tag(w.tags.get_str("lanes:forward"));+                    let count_bwd = tags::parse_int_tag(w.tags.get_str("lanes:backward"));++                    let fwd_spec = tlf.or(if oneway { tl } else { None });+                    let fwd_hint = if count_fwd > 0 {+                        count_fwd+                    } else if oneway {+                        count_all+                    } else {+                        0+                    };+                    let bwd_spec = if oneway { None } else { tlb };+                    let fwd = tags::build_dir_lanes(fwd_spec, fwd_hint);+                    let bwd = tags::build_dir_lanes(bwd_spec, count_bwd);++                    let mut push_lanes = |lanes: &[u16]| -> (u32, u16) {+                        if lanes.is_empty() {+                            return (NO_LANES, 0);+                        }+                        let off = state.lanes.len() as u32;+                        state.lanes.extend_from_slice(lanes);+                        (off, lanes.len() as u16)+                    };+                    let (fwd_lane_off, fwd_lane_count) = push_lanes(&fwd);+                    let (bwd_lane_off, bwd_lane_count) = push_lanes(&bwd);++                    let first_ref = state.refs.len() as u64;+                    state.refs.extend_from_slice(w.refs);+                    state.ways.push(CachedWay {+                        name,+                        first_ref,+                        ref_count: w.refs.len() as u32,+                        type_,+                        speed_limit,+                        oneway,+                        fwd_lane_off,+                        fwd_lane_count,+                        bwd_lane_off,+                        bwd_lane_count,+                    });+                }+                Element::Relation(_) => {}+            }+            Ok(())+        },+    )?;+    Ok(kinds)+}++fn pass2_blob(state: &mut Pass2, block: &pbf::PrimitiveBlock, mask: &Bitset) -> Result<u8> {+    let mut kinds = 0u8;+    visit_block(block, KIND_NODES, &mut kinds, &mut |el: Element| {+        if let Element::Node(n) = el {+            if n.id < 0 || n.id as u64 >= BITSET_SIZE || !mask.get(n.id as u64) {+                return Ok(());+            }+            // A `gtfs:stop_code:<feed>` tag means this node is a matched GTFS+            // stop; its `name` (or the code itself) becomes the stop label the+            // transit planner shows. Otherwise fall back to the plain OSM stop+            // tags.+            let gtfs_code = n+                .tags+                .iter()+                .find(|(k, _)| k.starts_with(b"gtfs:stop_code:"))+                .map(|(_, v)| n.tags.get("name").unwrap_or(v));+            let stop_code = match gtfs_code {+                Some(code) => state.names.id(code),+                None => {+                    if tags::is_stop_node(+                        n.tags.get_str("highway"),+                        n.tags.get_str("railway"),+                        n.tags.get_str("public_transport"),+                    ) {+                        state.names.id(n.tags.get("name").unwrap_or(UNNAMED_STOP))+                    } else {+                        u32::MAX+                    }+                }+            };+            state.nodes.push(NodeTmp {+                spatial: spatial_from_e7(n.lat_e7, n.lon_e7),+                osm_id: n.id,+                lat_e7: n.lat_e7,+                lon_e7: n.lon_e7,+                stop_code,+            });+        }+        Ok(())+    })?;+    Ok(kinds)+}++fn local_id(mapping: &[(i64, u32)], osm_id: i64) -> Option<u32> {+    mapping+        .binary_search_by_key(&osm_id, |e| e.0)+        .ok()+        .map(|i| mapping[i].1)+}++/// Find the largest connected component, then hook every transit stop outside it+/// to its nearest node inside it with a synthetic bidirectional edge. Without+/// this a matched GTFS stop that OSM never attached to a road is unreachable and+/// the transit planner cannot get the user to it.+///+/// Returns `(lcc_size, edges_added / 2)`.+fn reconnect_isolated_stops(nodes: &[NodeTmp], edges: &mut Vec<TmpEdge>) -> (u64, usize) {+    let n = nodes.len();+    if n == 0 {+        return (0, 0);+    }+    println!("Identifying connected components...");++    // `edges` is sorted by source, so one linear cursor yields the CSR ranges.+    // u64 (not u32) so a graph past 4.29 G directed edges fails loudly rather than+    // silently truncating the ranges the component scan walks.+    let mut node_to_edge = vec![0u64; n + 1];+    let mut cursor = 0usize;+    for (i, slot) in node_to_edge.iter_mut().enumerate().take(n) {+        *slot = cursor as u64;+        while cursor < edges.len() && edges[cursor].source as usize == i {+            cursor += 1;+        }+    }+    node_to_edge[n] = cursor as u64;++    let mut component = vec![u32::MAX; n];+    let mut queue: Vec<u32> = Vec::with_capacity(n);+    let mut lcc = 0u32;+    let mut lcc_size = 0usize;+    let mut next_comp = 0u32;+    for start in 0..n {+        if component[start] != u32::MAX {+            continue;+        }+        let base = queue.len();+        queue.push(start as u32);+        component[start] = next_comp;+        let mut head = base;+        while head < queue.len() {+            let u = queue[head] as usize;+            head += 1;+            for e in node_to_edge[u]..node_to_edge[u + 1] {+                let v = edges[e as usize].target as usize;+                if component[v] == u32::MAX {+                    component[v] = next_comp;+                    queue.push(v as u32);+                }+            }+        }+        let size = queue.len() - base;+        if size > lcc_size {+            lcc_size = size;+            lcc = next_comp;+        }+        next_comp += 1;+    }+    println!("LCC {lcc}: {lcc_size} / {n} node(s)");++    let isolated: Vec<u32> = (0..n as u32)+        .filter(|i| nodes[*i as usize].stop_code != NO_NAME && component[*i as usize] != lcc)+        .collect();+    if isolated.is_empty() {+        return (lcc_size as u64, 0);+    }++    // The nodes are Morton-sorted, so index distance approximates spatial+    // distance: widen an index window around the stop until it contains an LCC+    // node, then take the closest one in that window.+    let found = par::map_chunks(&isolated, 256, |_, chunk| {+        let mut out: Vec<TmpEdge> = Vec::new();+        let mut failed = 0usize;+        for &i in chunk {+            let stop = &nodes[i as usize];+            let mut best: Option<(u32, u32)> = None;+            let mut radius = 1000usize;+            while radius <= 1_000_000 {+                let lo = (i as usize).saturating_sub(radius);+                let hi = (i as usize + radius).min(n);+                for j in lo..hi {+                    if component[j] != lcc {+                        continue;+                    }+                    let d = accurate_dist_mm(+                        stop.lat_e7,+                        stop.lon_e7,+                        nodes[j].lat_e7,+                        nodes[j].lon_e7,+                    );+                    if best.is_none_or(|(bd, _)| d < bd) {+                        best = Some((d, j as u32));+                    }+                }+                if best.is_some() {+                    break;+                }+                radius *= 10;+            }+            if let Some((dist, target)) = best {+                out.push(TmpEdge {+                    source: i,+                    target,+                    dist_mm: dist,+                    name_offset: NO_NAME,+                    type_: RECONNECT_TYPE,+                    speed_limit: RECONNECT_SPEED,+                    lane_off: NO_LANES,+                    lane_count: 0,+                });+                out.push(TmpEdge {+                    source: target,+                    target: i,+                    dist_mm: dist,+                    name_offset: NO_NAME,+                    type_: RECONNECT_TYPE,+                    speed_limit: RECONNECT_SPEED,+                    lane_off: NO_LANES,+                    lane_count: 0,+                });+            } else {+                failed += 1;+            }+        }+        (out, failed)+    });++    let unreachable: usize = found.iter().map(|(_, f)| f).sum();+    let new_edges: Vec<TmpEdge> = found.into_iter().flat_map(|(e, _)| e).collect();+    let added = new_edges.len() / 2;+    if unreachable > 0 {+        // The index window caps at 1e6 nodes, so a stop in a region with no+        // routable road within that window stays unreachable. Say so rather than+        // dropping it silently: an unreachable stop is exactly what this pass+        // exists to prevent.+        println!("WARNING: {unreachable} isolated stop(s) had no reachable road nearby");+    }+    if added > 0 {+        println!("Adding {} synthetic connection(s) for isolated stops", new_edges.len());+        edges.extend_from_slice(&new_edges);+        edges.sort_by_key(|e| e.source);+    }+    (lcc_size as u64, added)+}++fn write_graph(+    out_dir: &Path,+    nodes: &[NodeTmp],+    edges: &[TmpEdge],+    lane_pool: &[u16],+) -> Result<u64> {+    println!("Writing the single global graph...");+    let mut nodes_out = BufWriter::new(create(&out_dir.join("nodes.bin"))?);+    let mut edges_out = BufWriter::new(create(&out_dir.join("edges.bin"))?);+    let mut lanes_out = BufWriter::new(create(&out_dir.join("lanes.bin"))?);++    let mut lane_offsets: Vec<u64> = Vec::with_capacity(edges.len() + 1);+    let mut lane_blob: Vec<u16> = Vec::new();+    let mut edge_ptr: u64 = 0;+    let mut cursor = 0usize;++    for (lid, node) in nodes.iter().enumerate() {+        write_node(&mut nodes_out, node.lat_e7, node.lon_e7, edge_ptr).map_err(io_err)?;+        while cursor < edges.len() && edges[cursor].source as usize == lid {+            let e = &edges[cursor];+            write_edge(&mut edges_out, e).map_err(io_err)?;+            lane_offsets.push(lane_blob.len() as u64 * 2);+            if e.lane_count > 0 && e.lane_off != NO_LANES {+                let start = e.lane_off as usize;+                lane_blob.extend_from_slice(&lane_pool[start..start + e.lane_count as usize]);+            }+            edge_ptr += 1;+            cursor += 1;+        }+    }+    // Trailing sentinel so `graph.rs` can read node(v + 1).edge_ptr as the end of+    // node v's edge range.+    write_node(&mut nodes_out, 0, 0, edge_ptr).map_err(io_err)?;++    lane_offsets.push(lane_blob.len() as u64 * 2);+    for off in &lane_offsets {+        lanes_out.write_all(&off.to_le_bytes()).map_err(io_err)?;+    }+    for mask in &lane_blob {+        lanes_out.write_all(&mask.to_le_bytes()).map_err(io_err)?;+    }++    nodes_out.flush().map_err(io_err)?;+    edges_out.flush().map_err(io_err)?;+    lanes_out.flush().map_err(io_err)?;++    // metadata.bin's magic + version let the device refuse a pack directory+    // holding files from two different vintages instead of misreading it.+    let mut meta = create(&out_dir.join("metadata.bin"))?;+    meta.write_all(&GRAPH_MAGIC.to_le_bytes()).map_err(io_err)?;+    meta.write_all(&GRAPH_VERSION.to_le_bytes()).map_err(io_err)?;+    meta.write_all(&(nodes.len() as u64).to_le_bytes())+        .map_err(io_err)?;+    meta.flush().map_err(io_err)?;++    Ok(edge_ptr)+}++fn write_node<W: Write>(out: &mut W, lat_e7: i32, lon_e7: i32, edge_ptr: u64) -> std::io::Result<()> {+    out.write_all(&lat_e7.to_le_bytes())?;+    out.write_all(&lon_e7.to_le_bytes())?;+    out.write_all(&edge_ptr.to_le_bytes())+}++fn write_edge<W: Write>(out: &mut W, e: &TmpEdge) -> std::io::Result<()> {+    out.write_all(&e.target.to_le_bytes())?;+    out.write_all(&e.dist_mm.to_le_bytes())?;+    out.write_all(&e.name_offset.to_le_bytes())?;+    out.write_all(&[e.type_, e.speed_limit])+}++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())+}++/// Parse the tool's command line: `road_graph IN.osm.pbf [--out DIR]`.+pub fn parse_args(args: &[String]) -> std::result::Result<(PathBuf, PathBuf), String> {+    let mut input: Option<PathBuf> = None;+    let mut out = PathBuf::from("map_data");+    let mut i = 0;+    while i < args.len() {+        match args[i].as_str() {+            "--out" | "-o" => {+                i += 1;+                let dir = args.get(i).ok_or_else(|| "--out needs a directory".to_string())?;+                out = PathBuf::from(dir);+            }+            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((input.ok_or_else(|| "missing IN.osm.pbf".to_string())?, out))+}++#[cfg(test)]+mod tests {+    use super::*;+    use crate::tags::{LANE_LEFT, LANE_THROUGH};+    use crate::testpbf;++    struct Outputs {+        meta: Vec<u8>,+        nodes: Vec<u8>,+        edges: Vec<u8>,+        lanes: Vec<u8>,+        names: Vec<u8>,+    }++    fn read_outputs(dir: &Path) -> Outputs {+        let f = |n: &str| std::fs::read(dir.join(n)).unwrap();+        Outputs {+            meta: f("metadata.bin"),+            nodes: f("nodes.bin"),+            edges: f("edges.bin"),+            lanes: f("lanes.bin"),+            names: f("road_names.bin"),+        }+    }++    fn node_at(o: &Outputs, i: usize) -> (i32, i32, u64) {+        let b = &o.nodes[i * 16..i * 16 + 16];+        (+            i32::from_le_bytes(b[0..4].try_into().unwrap()),+            i32::from_le_bytes(b[4..8].try_into().unwrap()),+            u64::from_le_bytes(b[8..16].try_into().unwrap()),+        )+    }++    fn edge_at(o: &Outputs, i: usize) -> (u32, u32, u32, u8, u8) {+        let b = &o.edges[i * 14..i * 14 + 14];+        (+            u32::from_le_bytes(b[0..4].try_into().unwrap()),+            u32::from_le_bytes(b[4..8].try_into().unwrap()),+            u32::from_le_bytes(b[8..12].try_into().unwrap()),+            b[12],+            b[13],+        )+    }++    fn name_at(o: &Outputs, off: u32) -> String {+        let start = off as usize;+        let end = start + o.names[start..].iter().position(|b| *b == 0).unwrap();+        String::from_utf8(o.names[start..end].to_vec()).unwrap()+    }++    #[test]+    fn synthetic_extract_produces_the_documented_layout() {+        let (pbf_path, dir) = testpbf::write_sample("graph_build");+        let stats = build(&pbf_path, &dir).unwrap();+        let o = read_outputs(&dir);++        // Nodes 1-4 come from the residential way, node 5 is the bus stop; the+        // cafe node (6) is on no routable way and carries no stop tag, so it is+        // not part of the graph at all.+        assert_eq!(stats.node_count, 5);+        assert_eq!(o.meta, {+            let mut want = Vec::new();+            want.extend(0x4752_414Du32.to_le_bytes());+            want.extend(1u32.to_le_bytes());+            want.extend(5u64.to_le_bytes());+            want+        });++        // nodes.bin holds node_count + 1 records; edges.bin is a multiple of 14.+        assert_eq!(o.nodes.len(), 16 * 6);+        assert_eq!(o.edges.len() % 14, 0);+        let edge_count = (o.edges.len() / 14) as u64;+        assert_eq!(edge_count, stats.edge_count);+        // 3 bidirectional segments + 1 oneway segment + 2 synthetic stop edges.+        assert_eq!(edge_count, 6 + 1 + 2);++        // The sentinel's edge_ptr is the edge count, and edge_ptr is monotonic.+        assert_eq!(node_at(&o, 5).2, edge_count);+        assert_eq!(node_at(&o, 0).2, 0);+        for i in 0..5 {+            assert!(node_at(&o, i).2 <= node_at(&o, i + 1).2);+        }++        // Nodes are Morton-ordered.+        let keys: Vec<u64> = (0..5)+            .map(|i| {+                let (lat, lon, _) = node_at(&o, i);+                spatial_from_e7(lat, lon)+            })+            .collect();+        assert!(keys.windows(2).all(|w| w[0] <= w[1]), "{keys:?}");++        // Every edge's source range agrees with the nodes.bin pointers, and the+        // whole edge set matches the fixture's geometry.+        // (source lat/lon, target lat/lon, dist_mm, type, speed_limit, name)+        type SeenEdge = (i32, i32, i32, i32, u32, u8, u8, String);+        let mut seen: Vec<SeenEdge> = Vec::new();+        for lid in 0..5usize {+            let (slat, slon, start) = node_at(&o, lid);+            let end = node_at(&o, lid + 1).2;+            for e in start..end {+                let (target, dist, name_off, type_, speed) = edge_at(&o, e as usize);+                let (tlat, tlon, _) = node_at(&o, target as usize);+                let name = if name_off == NO_NAME {+                    String::new()+                } else {+                    name_at(&o, name_off)+                };+                seen.push((slat, slon, tlat, tlon, dist, type_, speed, name));+            }+        }+        assert_eq!(seen.len(), edge_count as usize);++        // Main St: 3 segments each way, type 7 (residential), no maxspeed.+        let main: Vec<_> = seen.iter().filter(|e| e.7 == "Main St").collect();+        assert_eq!(main.len(), 6);+        assert!(main.iter().all(|e| e.5 == 7 && e.6 == 0));+        // The service way is a oneway from node 4 to node 2, 30 mph -> 48 km/h.+        let service: Vec<_> = seen.iter().filter(|e| e.5 == 8).collect();+        assert_eq!(service.len(), 1);+        assert_eq!(service[0].6, 48);+        assert_eq!((service[0].0, service[0].1), (370_030_000, -1_220_000_000));+        assert_eq!((service[0].2, service[0].3), (370_010_000, -1_220_000_000));+        // The bus stop was reconnected both ways with the synthetic type/speed.+        let synth: Vec<_> = seen.iter().filter(|e| e.5 == 12).collect();+        assert_eq!(synth.len(), 2);+        assert!(synth.iter().all(|e| e.6 == 5 && e.7.is_empty()));+        assert_eq!(stats.reconnected_stops, 1);+        assert_eq!(stats.lcc_size, 4);++        // road_names.bin holds each unique string once. "Main St" is the only way+        // name; "Test Stop" is the bus stop's code. "Plaza" belongs to an+        // unrouted area and must not appear.+        assert_eq!(o.names, b"Main St\0Test Stop\0".to_vec());+        assert_eq!(stats.unique_names, 2);+        assert_eq!(stats.name_bytes, 18);++        // lanes.bin: u64 offsets[edge_count + 1] then the u16 blob. Only Main+        // St's forward direction carries turn:lanes.+        let offsets_bytes = (edge_count as usize + 1) * 8;+        assert!(o.lanes.len() >= offsets_bytes);+        let offsets: Vec<u64> = (0..=edge_count as usize)+            .map(|i| u64::from_le_bytes(o.lanes[i * 8..i * 8 + 8].try_into().unwrap()))+            .collect();+        assert!(offsets.windows(2).all(|w| w[0] <= w[1]));+        assert_eq!(*offsets.last().unwrap() as usize, o.lanes.len() - offsets_bytes);+        let blob: Vec<u16> = o.lanes[offsets_bytes..]+            .chunks_exact(2)+            .map(|c| u16::from_le_bytes(c.try_into().unwrap()))+            .collect();+        // Three forward Main St edges, two lane masks each.+        assert_eq!(blob, [[LANE_LEFT, LANE_THROUGH]; 3].concat());+    }++    #[test]+    fn two_runs_are_byte_identical() {+        let (pbf_path, dir_a) = testpbf::write_sample("graph_det_a");+        let (_, dir_b) = testpbf::write_sample("graph_det_b");+        build(&pbf_path, &dir_a).unwrap();+        build(&pbf_path, &dir_b).unwrap();+        for f in [+            "metadata.bin",+            "nodes.bin",+            "edges.bin",+            "lanes.bin",+            "road_names.bin",+        ] {+            assert_eq!(+                std::fs::read(dir_a.join(f)).unwrap(),+                std::fs::read(dir_b.join(f)).unwrap(),+                "{f} differs between runs"+            );+        }+    }++    #[test]+    fn args_default_the_output_directory() {+        let (input, out) = parse_args(&["cal.osm.pbf".into()]).unwrap();+        assert_eq!(input, PathBuf::from("cal.osm.pbf"));+        assert_eq!(out, PathBuf::from("map_data"));+        let (_, out) = parse_args(&["cal.osm.pbf".into(), "--out".into(), "d".into()]).unwrap();+        assert_eq!(out, PathBuf::from("d"));+        assert!(parse_args(&[]).is_err());+        assert!(parse_args(&["a".into(), "b".into()]).is_err());+        assert!(parse_args(&["--wat".into()]).is_err());+    }+}
scripts/maps/osm_ingest/src/lib.rs
diff --git a/scripts/maps/osm_ingest/src/lib.rs b/scripts/maps/osm_ingest/src/lib.rsnew file mode 100644index 0000000000..5dbee617e7--- /dev/null+++ b/scripts/maps/osm_ingest/src/lib.rs@@ -0,0 +1,26 @@+//! Host-side OSM ingest for the Maps offline packs.+//!+//! Two 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`.+//!+//! 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.++pub mod graph_build;+pub mod names;+pub mod osm;+pub mod par;+pub mod pbf;+pub mod poi_build;+pub mod proto;+pub mod spatial;+pub mod tags;++#[cfg(test)]+mod testpbf;
scripts/maps/osm_ingest/src/names.rs
diff --git a/scripts/maps/osm_ingest/src/names.rs b/scripts/maps/osm_ingest/src/names.rsnew file mode 100644index 0000000000..60ef04d8f5--- /dev/null+++ b/scripts/maps/osm_ingest/src/names.rs@@ -0,0 +1,120 @@+//! Deduplicating NUL-terminated string pool.+//!+//! Both `road_names.bin` and `poi_nam

Diff truncated.