Modern Apps git

← Modern-Apps.git

maps: router on shared ZBLK code; no fake 0 m elevation profile (#planet4)

Commit
bee3b2c6494e341988e51271e454c7393bce1405
Author
Vayun Mathur <[email protected]>
When
2026-11-11 21:09 UTC (24 days ago)
Parents
19fe5bc
Graph and transit readers audited field by field against road_graph,
road_overlay and gtfs_ingest and probed on the real planet4 build: MARG
v7, blocked nodes/edges (zstd frames), escapes, name bitmap, intermediate
trailer, lanes, MOVL v1 overlay and TRIX v7 all match (0 mismatches vs
the shared decoder). Changes:

- graph_part1.rs BlockedView::parse now validates through
  tilecodec::blocked::Blocked::parse and decodes frames with the shared
  inflate_frame instead of a hand-copied parser. The copy indexed the
  offset table before checking it fit in the section, so a truncated
  section panicked (abort in release) inside JNI init instead of
  reporting "no graph"; it also skipped the first-offset check.
- GRAPH_MAGIC/GRAPH_VERSION(_MIN) and the TRIX magic/version range are
  re-exported from tilecodec::mamaps::archive rather than duplicated, so
  the app, the archive validator and the writer share one range.
- planet4 (like planet3) ships no elevation section: planet_build.sh runs
  road_graph without --dem. The router filled every step with 0 m, so the
  route sheet drew a flat chart with 0 m ascent. New Graph::has_elevation;
  findRouteNative sends empty elevation arrays when it is false, which
  Kotlin already reads as "no profile". (Writer follow-up: pass --dem.)

Real-archive harness (tests/real_archive.rs, #[ignore], MAMAPS_REAL_ARCHIVE
gated, release): graph loads (440 M nodes, 1.10 G edges, overlay
attached) in 12 ms; drive/walk/bike routes in SF, NYC, London, Tokyo and
SF->LA over the highway overlay (614 km, 0.3 s) with road names and lane
guidance; transit loads, 4th & King departures, America/Los_Angeles,
MOTIS stop ids, 438 SF rail lines, and RAPTOR journeys in SF, NYC,
London and Tokyo.

Verified: cargo test -p offlinerouter (93 lib + real-archive 2/2),
clippy no errors, Android build in the toolchain container.

Diff

maps/src/main/rust/src/graph.rs
diff --git a/maps/src/main/rust/src/graph.rs b/maps/src/main/rust/src/graph.rsindex def76661f7..cc4480a220 100644--- a/maps/src/main/rust/src/graph.rs+++ b/maps/src/main/rust/src/graph.rs@@ -72,7 +72,7 @@ pub const DEG_TO_RAD: f64 = std::f64::consts::PI / 180.0; /// per-OSM-node transit nodes were removed: that changed `node_count` and /// `edge_count`, so a pack directory holding files from two vintages reads /// garbage. The magic + version make that a clean rejection instead.-pub const GRAPH_MAGIC: u32 = 0x4752_414D;+pub use tilecodec::mamaps::archive::GRAPH_MAGIC; /// Version 2 narrowed `nodes.bin` to 12-byte records, made `lanes.bin` a sparse /// index and gave `intermediate.bin` two-level offsets — 50.8 GB of planet became /// 34 GB. Version 3 gave `intermediate.bin` a presence bitmap and dropped both@@ -88,9 +88,10 @@ pub const GRAPH_MAGIC: u32 = 0x4752_414D; /// Version 7 blocked-compresses `nodes.bin`, `edges.bin` records and /// `elevation.bin` (ZBLK sections); readers accept 6 and 7, inflating v7 /// sections once on first use.-pub const GRAPH_VERSION: u32 = 7;-/// Oldest graph version decoded: v6 raw tables still read directly.-pub const GRAPH_VERSION_MIN: u32 = 6;+///+/// Re-exported from tilecodec (with [`GRAPH_VERSION_MIN`], v6: raw tables still read+/// directly) so the app, the archive validator and the writer share one range.+pub use tilecodec::mamaps::archive::{GRAPH_VERSION, GRAPH_VERSION_MIN};  /// Sentinel `name_offset` meaning "this edge has no name". ///
maps/src/main/rust/src/graph_part1.rs
diff --git a/maps/src/main/rust/src/graph_part1.rs b/maps/src/main/rust/src/graph_part1.rsindex db8d99d50d..437338c466 100644--- a/maps/src/main/rust/src/graph_part1.rs+++ b/maps/src/main/rust/src/graph_part1.rs@@ -116,51 +116,29 @@ unsafe impl Send for BlockedView {} unsafe impl Sync for BlockedView {}  impl BlockedView {-    /// Parse over `bytes` (the whole section file/slice). Refuses bad magic,-    /// unknown flags, zero stride, and offsets outside the section. Mirrors-    /// `tilecodec::blocked::Blocked::parse` without borrowing it, so no-    /// lifetime ties this view to the mapping.+    /// Parse over `bytes` (the whole section file/slice) with the shared+    /// `tilecodec::blocked::Blocked::parse` — the same header and offset-table+    /// checks the writer's own reader runs (bad magic, unknown flags, zero+    /// stride, a table running past the section, unordered or out-of-bounds+    /// offsets) — then copies the offset table so no lifetime ties this view to+    /// the mapping. A corrupt section is `None` (no graph), never a panic.     pub(crate) fn parse(bytes: &[u8]) -> Option<BlockedView> {-        if bytes.len() < 28 {-            return None;-        }-        let u32_at = |o: usize| {-            u32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]])-        };-        let u64_at = |o: usize| {-            u64::from_le_bytes([-                bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3], bytes[o + 4],-                bytes[o + 5], bytes[o + 6], bytes[o + 7],-            ])-        };-        if u32_at(0) != tilecodec::blocked::BLOCKED_MAGIC || u32_at(4) != 0 {-            return None;-        }-        let record_len = u32_at(8) as usize;-        let records_per_block = u32_at(12) as u64;-        let unpacked_len = u64_at(16);-        if record_len == 0 || records_per_block == 0 {-            return None;-        }-        let block_count = u32_at(24) as usize;-        let mut offsets = Vec::with_capacity(block_count + 1);-        for i in 0..=block_count {-            let o = u64_at(28 + i * 8);-            if o > bytes.len() as u64 || (i > 0 && o < offsets[i - 1]) {-                return None;-            }-            offsets.push(o);-        }+        let shared = tilecodec::blocked::Blocked::parse(bytes).ok()?;+        let block_count = shared.block_count();+        let offsets = (0..=block_count)+            .map(|b| shared.block_offset(b))+            .collect::<Option<Vec<u64>>>()?;+        let records_per_block = shared.records_per_block();         // No end-equality check: a blocked record array may share its file         // with trailing tables (`edges.bin`'s escapes/names). Truncation is-        // still refused above — an offset past the bytes fails.+        // still refused by the shared parse — an offset past the bytes fails.         Some(BlockedView {-            record_len,+            record_len: shared.record_len(),             records_per_block,             block_shift: records_per_block                 .is_power_of_two()                 .then(|| records_per_block.trailing_zeros()),-            unpacked_len,+            unpacked_len: shared.unpacked_len(),             offsets,             frames: bytes.as_ptr(),             blocks: (0..block_count).map(|_| std::sync::OnceLock::new()).collect(),@@ -188,14 +166,11 @@ impl BlockedView {         let want = block_bytes.min(self.unpacked_len.saturating_sub(b as u64 * block_bytes)) as usize;         let (start, end) = (self.offsets[b] as usize, self.offsets[b + 1] as usize);         let frame = unsafe { std::slice::from_raw_parts(self.frames.add(start), end - start) };-        let mut out = Vec::with_capacity(want);-        let decoded = ruzstd::decoding::StreamingDecoder::new(frame)-            .ok()-            .and_then(|mut d| std::io::Read::read_to_end(&mut d, &mut out).ok());-        if decoded.is_none() || out.len() != want {-            return Box::default();+        // The shared ZBLK frame decode (same code the writer's reader runs).+        match tilecodec::blocked::inflate_frame(frame, want) {+            Ok(out) if out.len() == want => out.into_boxed_slice(),+            _ => Box::default(),         }-        out.into_boxed_slice()     } } 
maps/src/main/rust/src/graph_part2b.rs
diff --git a/maps/src/main/rust/src/graph_part2b.rs b/maps/src/main/rust/src/graph_part2b.rsindex 51f49c96df..4042e05781 100644--- a/maps/src/main/rust/src/graph_part2b.rs+++ b/maps/src/main/rust/src/graph_part2b.rs@@ -61,6 +61,14 @@ impl Graph {         self.node(id)     } +    /// Whether the graph carries node elevations at all (`elevation.bin` / archive kind 7, raw+    /// v6 or blocked v7). The planet archives are built without it (`road_graph` ran without+    /// `--dem`), and then every [`node_elevation`](Self::node_elevation) is 0: callers use this+    /// to report "no profile" instead of a flat 0 m one.+    pub fn has_elevation(&self) -> bool {+        self.elevation_view.is_some() || !self.elevation.is_null()+    }+     /// Ground elevation of node `id` in metres, or 0 when the graph carries no `elevation.bin` or     /// `id` is out of range. Baked from the DEM at build time (WS-G); a build without a DEM, or a     /// node off the DEM's coverage, reads as 0 so the route profile is simply flat there.
maps/src/main/rust/src/jni/routes.rs
diff --git a/maps/src/main/rust/src/jni/routes.rs b/maps/src/main/rust/src/jni/routes.rsindex ceafa216a1..d3219af5cc 100644--- a/maps/src/main/rust/src/jni/routes.rs+++ b/maps/src/main/rust/src/jni/routes.rs@@ -196,7 +196,14 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findRouteNat             return Ok(null);         } -        let steps = reconstruct_path(&g, &speeds, mode, &ctx, scratch);+        let mut steps = reconstruct_path(&g, &speeds, mode, &ctx, scratch);+        // No elevation section (planet4 ships none): every sample is a fabricated 0 m, which+        // Kotlin would draw as a flat chart with 0 m ascent. Empty arrays read as "no profile".+        if !g.has_elevation() {+            for step in &mut steps {+                step.elevations.clear();+            }+        }         // Whole-route elevation totals (WS-G): cumulative ascent/descent in metres, computed once and         // carried on every RawStep so Kotlin can read them off any step.         let (ascent_m, descent_m) = route_ascent_descent(&steps);
maps/src/main/rust/src/transit.rs
diff --git a/maps/src/main/rust/src/transit.rs b/maps/src/main/rust/src/transit.rsindex 3d726dc20e..21472daf14 100644--- a/maps/src/main/rust/src/transit.rs+++ b/maps/src/main/rust/src/transit.rs@@ -1,7 +1,7 @@ //! On-device transit index loader + RAPTOR journey planner (P11b / world pack). //! //! Consumes the compact `.transit` index produced by the host tool-//! `scripts/maps/gtfs_ingest` (P11a). The on-disk layout (format v6 "TRX2") is+//! `scripts/maps/gtfs_ingest` (P11a). The on-disk layout (format v3..=v7 "TRIX") is //! documented at the top of that tool's `src/index.rs` and MUST stay in sync //! with the section constants and record accessors here. //!@@ -40,15 +40,18 @@ use crate::graph::{read_at, MmapRegion}; use std::collections::HashMap; -// --- Format constants (mirror scripts/maps/gtfs_ingest/src/index.rs) ----const MAGIC: u32 = 0x5452_4958; // "TRIX"-/// Newest format this reader understands. v7 only adds host-only RAIL_LINES after the-/// sections read here, which the directory loop below ignores.-const VERSION: u32 = 7;-/// Oldest format still accepted. Reading both means an app update and a pack-/// rebuild can land in either order without offline transit silently degrading-/// to the online planner in between.-const VERSION_MIN: u32 = 3;+// --- Format constants: the shared tilecodec values the writer (gtfs_ingest) and the+// archive validator also check, so the three ranges cannot drift apart. ---+// `"TRIX"`, little-endian.+use tilecodec::mamaps::archive::TRANSIT_MAGIC as MAGIC;+// Newest format this reader understands (7). v7 only adds host-only RAIL_LINES after+// the sections read here, which the directory loop below ignores (and `mamaps_pack`+// strips to length 0).+use tilecodec::mamaps::archive::TRANSIT_VERSION as VERSION;+// Oldest format still accepted (3). Reading both means an app update and a pack+// rebuild can land in either order without offline transit silently degrading+// to the online planner in between.+use tilecodec::mamaps::archive::TRANSIT_VERSION_MIN as VERSION_MIN; pub const NONE: u32 = 0xFFFF_FFFF; const HEADER_LEN: usize = 80; /// Section count of the newest format. The section directory is sized to this
maps/src/main/rust/tests/real_archive.rs
diff --git a/maps/src/main/rust/tests/real_archive.rs b/maps/src/main/rust/tests/real_archive.rsnew file mode 100644index 0000000000..3b8981d43a--- /dev/null+++ b/maps/src/main/rust/tests/real_archive.rs@@ -0,0 +1,167 @@+//! The offline router (graph + highway overlay + transit) against a REAL planet archive+//! (`planet4.mamaps`, or the byte-identical local build `scripts/maps/inputs/world.mamaps`).+//!+//! Ignored by default and gated on `MAMAPS_REAL_ARCHIVE`:+//!+//! ```text+//! MAMAPS_REAL_ARCHIVE=/path/to/world.mamaps \+//!   cargo test -p offlinerouter --release --test real_archive -- --ignored --nocapture --test-threads=1+//! ```+//!+//! Same calls the JNI layer makes (`Graph::load_archive`, `prepare_routing` ++//! `perform_search_loop` + `reconstruct_path`, `TransitIndex::load_archive`, `plan`,+//! `stop_departures`), minus the JNI marshalling and live traffic.++use offlinerouter::geometry::TrafficSpeeds;+use offlinerouter::graph::{Graph, BICYCLE, DRIVING, WALK};+use offlinerouter::routing::{perform_search_loop, prepare_routing, reconstruct_path, StepData};+use offlinerouter::state::{RadixHeap, RoutingScratchpad};+use offlinerouter::transit::{+    plan, rail_lines, stop_departures, LegKind, QueryDay, Schedule, TransitIndex,+};++const ENV: &str = "MAMAPS_REAL_ARCHIVE";++/// (label, from (lat, lon), to (lat, lon), travel mode).+type RouteCase = (&'static str, (f64, f64), (f64, f64), i32);++fn archive() -> Option<String> {+    match std::env::var(ENV) {+        Ok(p) if !p.trim().is_empty() && std::path::Path::new(&p).is_file() => Some(p),+        _ => {+            eprintln!("{ENV} not set (or not a file): real-archive test skipped");+            None+        }+    }+}++fn crow_km(a: (f64, f64), b: (f64, f64)) -> f64 {+    let (la1, lo1, la2, lo2) = (a.0.to_radians(), a.1.to_radians(), b.0.to_radians(), b.1.to_radians());+    let h = ((la2 - la1) / 2.0).sin().powi(2) + la1.cos() * la2.cos() * ((lo2 - lo1) / 2.0).sin().powi(2);+    2.0 * 6371.0 * h.sqrt().asin()+}++/// One route through the app's routing core, or `None` when it does not snap/route.+fn route(g: &Graph, from: (f64, f64), to: (f64, f64), mode: i32) -> Option<Vec<StepData>> {+    let speeds = TrafficSpeeds::default();+    let mut scratch = RoutingScratchpad::new();+    let mut heap = RadixHeap::new();+    let mut ensure = |_lat_e7: i32, _lon_e7: i32| {};+    let mut ctx =+        prepare_routing(g, &speeds, &mut ensure, from.0, from.1, to.0, to.1, mode, &mut scratch, &mut heap)?;+    perform_search_loop(g, &speeds, &mut ensure, mode, &mut ctx, &mut scratch, &mut heap);+    if ctx.target_node == 0xFFFF_FFFF && ctx.direct.is_none() {+        return None;+    }+    Some(reconstruct_path(g, &speeds, mode, &ctx, &mut scratch))+}++#[test]+#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"]+fn graph_sections_load_and_routes_resolve() {+    let Some(path) = archive() else { return };+    let t0 = std::time::Instant::now();+    let g = Graph::load_archive(&path).expect("Graph::load_archive refused the archive");+    println!(+        "graph: {} nodes, {} edges, overlay {}, elevation {}, loaded in {:?}",+        g.node_count,+        g.edge_count,+        g.overlay().is_some(),+        g.has_elevation(),+        t0.elapsed()+    );+    assert!(g.node_count > 100_000_000, "not a planet graph");+    assert!(g.overlay().is_some(), "highway overlay (kind 14) not attached");++    let cases: &[RouteCase] = &[+        ("SF drive Ferry Bldg -> Golden Gate Park", (37.7955, -122.3937), (37.7694, -122.4862), DRIVING),+        ("SF walk Union Sq -> Ferry Bldg", (37.7880, -122.4075), (37.7955, -122.3937), WALK),+        ("SF bike Mission -> Marina", (37.7599, -122.4148), (37.8037, -122.4368), BICYCLE),+        ("NYC drive Midtown -> JFK", (40.7580, -73.9855), (40.6413, -73.7781), DRIVING),+        ("London drive Westminster -> Camden", (51.4995, -0.1248), (51.5390, -0.1426), DRIVING),+        ("Tokyo walk Shibuya -> Harajuku", (35.6595, 139.7005), (35.6702, 139.7027), WALK),+        ("Long drive SF -> LA (overlay)", (37.7749, -122.4194), (34.0522, -118.2437), DRIVING),+    ];+    for &(name, from, to, mode) in cases {+        let t = std::time::Instant::now();+        let steps = route(&g, from, to, mode).unwrap_or_else(|| panic!("{name}: no route"));+        let km = steps.iter().map(|s| s.dist_mm).sum::<u64>() as f64 / 1e6;+        let mins = steps.iter().map(|s| s.time_10ms).sum::<u64>() as f64 / 6000.0;+        let named = steps.iter().filter(|s| g.road_name(s.name_off).is_some()).count();+        let lanes = steps.iter().filter(|s| !s.lanes.is_empty()).count();+        let crow = crow_km(from, to);+        println!(+            "{name}: {km:.1} km (crow {crow:.1}), {mins:.0} min, {} steps ({named} named, {lanes} with lanes) in {:?}",+            steps.len(),+            t.elapsed()+        );+        assert!(!steps.is_empty(), "{name}: empty route");+        assert!(km >= crow * 0.95 && km <= crow * 3.0 + 2.0, "{name}: implausible length {km} km for {crow} km crow");+        assert!(named > 0, "{name}: no step resolved a road name (road_names section)");+        for s in &steps {+            assert_eq!(s.coords.len() % 2, 0);+            assert!(s.elevations.is_empty() || s.elevations.len() == s.coords.len() / 2);+        }+    }+    // Lane guidance (lanes section) shows up on a long drive through big junctions.+    let la = route(&g, (37.7749, -122.4194), (34.0522, -118.2437), DRIVING).unwrap();+    assert!(la.iter().any(|s| !s.lanes.is_empty()), "no lane guidance on SF -> LA");+}++#[test]+#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"]+fn transit_section_loads_plans_and_lists_departures() {+    let Some(path) = archive() else { return };+    assert!(TransitIndex::has_archive_transit(&path), "no transit section (kind 13)");+    let t0 = std::time::Instant::now();+    let idx = TransitIndex::load_archive(&path).expect("TransitIndex::load_archive refused the archive");+    println!("transit: feed {:?}, loaded in {:?}", idx.feed_name(), t0.elapsed());+    assert!(idx.covers(37.7749, -122.4194), "transit pack does not cover SF");++    // A weekday mid-morning (Wednesday 2026-11-11), the day this test was written.+    let sched = Schedule { day: QueryDay::for_date(2, 20261111), overlay: None };+    let nine = 9 * 3600;++    let board = stop_departures(&idx, 37.7764, -122.3943, nine, sched, 10); // SF Caltrain 4th & King+    println!("departures at 4th & King: {:?}",+        board.iter().map(|d| format!("{} -> {} @{}", d.route_name, d.headsign, d.dep_secs)).collect::<Vec<_>>());+    assert!(!board.is_empty(), "no offline departures at SF 4th & King");+    assert!(board.windows(2).all(|w| w[0].dep_secs <= w[1].dep_secs));++    let tz = idx.timezone_at(37.7749, -122.4194);+    let motis = idx.nearest_stop_motis_id(37.7764, -122.3943);+    println!("timezone {tz}, MOTIS stop id {motis:?}");+    assert_eq!(tz, "America/Los_Angeles");++    let lines = rail_lines(&idx, 37.70, -122.50, 37.81, -122.38);+    println!("rail lines in SF bbox: {}", lines.len());+    assert!(!lines.is_empty());++    for (name, from, to) in [+        ("SF Mission -> Downtown", (37.7599, -122.4148), (37.7880, -122.4075)),+        ("NYC Brooklyn -> Midtown", (40.6782, -73.9442), (40.7580, -73.9855)),+        ("London Camden -> Westminster", (51.5390, -0.1426), (51.4995, -0.1248)),+        ("Tokyo Shinjuku -> Tokyo Stn", (35.6896, 139.7006), (35.6812, 139.7671)),+    ] {+        let legs = plan(&idx, from.0, from.1, to.0, to.1, nine, sched);+        match &legs {+            Some(legs) => println!(+                "plan {name}: {}",+                legs.iter()+                    .map(|l| {+                        let kind = match l.kind {+                            LegKind::Walk => "walk",+                            LegKind::Wait => "wait",+                            LegKind::Ride => "ride",+                        };+                        format!("{kind}:{}({}->{})", l.name, l.from_stop, l.to_stop)+                    })+                    .collect::<Vec<_>>()+                    .join(" | ")+            ),+            None => println!("plan {name}: no journey"),+        }+        let legs = legs.unwrap_or_else(|| panic!("{name}: no transit journey"));+        assert!(legs.iter().any(|l| l.kind == LegKind::Ride), "{name}: journey has no ride");+    }+}