maps: highway overlay search for long routes + archive kind 14
- Commit
ce28ce7c4f4bb8d456e80b40c5c03c224db7a8f6- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 01:34 UTC (1 month ago)
- Parents
fbc87f7
Diff
library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rsindex ec1d547193..d22ff31c83 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs@@ -35,6 +35,11 @@ pub const ARCHIVE_KIND_POI_SPATIAL: u8 = 11; pub const ARCHIVE_KIND_POI_WORDS: u8 = 12; /// Transit `<feed>.transit` payload: `TRIX` pack. pub const ARCHIVE_KIND_TRANSIT: u8 = 13;+/// Graph `overlay.bin` payload: the `MOVL` highway overlay (optional).+pub const ARCHIVE_KIND_GRAPH_OVERLAY: u8 = 14;+/// Highest kind this build writes. Readers accept any non-zero kind and skip+/// the ones they do not know, so a newer archive still opens in an older app.+pub const ARCHIVE_KIND_MAX_KNOWN: u8 = ARCHIVE_KIND_GRAPH_OVERLAY; /// `metadata.bin` (`MARG`) magic, little-endian `u32`. pub const GRAPH_MAGIC: u32 = 0x4752_414D;
library/tilecodec/src/main/rust/src/mamaps/archive/entry.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/entry.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/entry.rsindex 5b608d2ffe..65e7a2473a 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/entry.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/entry.rs@@ -18,6 +18,12 @@ pub struct ArchiveEntry { pub extra: u64, } +/// Whether this build defines section `kind`. Writers (the packer) stay strict+/// with this; readers skip what it rejects.+pub fn is_known_kind(kind: u8) -> bool {+ (1..=ARCHIVE_KIND_MAX_KNOWN).contains(&kind)+}+ impl ArchiveEntry { pub fn parse(buf: &[u8]) -> Result<ArchiveEntry> { if buf.len() < ARCHIVE_ENTRY_LEN {@@ -27,23 +33,11 @@ impl ArchiveEntry { return err("a single-archive entry has non-zero reserved bytes"); } let kind = buf[0];- if !matches!(- kind,- ARCHIVE_KIND_GRAPH_META- | ARCHIVE_KIND_GRAPH_NODES- | ARCHIVE_KIND_GRAPH_EDGES- | ARCHIVE_KIND_GRAPH_INTERMEDIATE- | ARCHIVE_KIND_GRAPH_NAMES- | ARCHIVE_KIND_GRAPH_LANES- | ARCHIVE_KIND_GRAPH_ELEVATION- | ARCHIVE_KIND_POI_INDEX- | ARCHIVE_KIND_POI_NAMES- | ARCHIVE_KIND_POI_ATTRS- | ARCHIVE_KIND_POI_SPATIAL- | ARCHIVE_KIND_POI_WORDS- | ARCHIVE_KIND_TRANSIT- ) {- return err(format!("a single-archive entry names unknown section kind {kind}"));+ // Any non-zero kind parses: an unknown one is a section from a newer+ // writer, which `ArchiveView::section` lookups simply never ask for.+ // Failing closed here made every older app refuse a newer archive.+ if kind == 0 {+ return err("a single-archive entry names section kind 0"); } let u32_at = |o: usize| u32::from_le_bytes([buf[o], buf[o + 1], buf[o + 2], buf[o + 3]]); let u64_at = |o: usize| {
library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rsindex bb101f4506..8a30dd746d 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs@@ -101,12 +101,13 @@ pub use consts::{ ARCHIVE_ALIGN, ARCHIVE_DIR_HEADER_LEN, ARCHIVE_ENTRY_LEN, ARCHIVE_FOOTER_LEN, ARCHIVE_MAGIC, ARCHIVE_KIND_GRAPH_EDGES, ARCHIVE_KIND_GRAPH_ELEVATION, ARCHIVE_KIND_GRAPH_INTERMEDIATE, ARCHIVE_KIND_GRAPH_LANES, ARCHIVE_KIND_GRAPH_META, ARCHIVE_KIND_GRAPH_NAMES,- ARCHIVE_KIND_GRAPH_NODES, ARCHIVE_KIND_POI_ATTRS, ARCHIVE_KIND_POI_INDEX, ARCHIVE_KIND_POI_NAMES,+ ARCHIVE_KIND_GRAPH_NODES, ARCHIVE_KIND_GRAPH_OVERLAY, ARCHIVE_KIND_MAX_KNOWN, ARCHIVE_KIND_POI_ATTRS,+ ARCHIVE_KIND_POI_INDEX, ARCHIVE_KIND_POI_NAMES, ARCHIVE_KIND_POI_SPATIAL, ARCHIVE_KIND_POI_WORDS, ARCHIVE_KIND_TRANSIT, GRAPH_MAGIC, GRAPH_META_LEN, GRAPH_VERSION, GRAPH_VERSION_MIN, POI_RECORD_BYTES, TRANSIT_MAGIC, TRANSIT_VERSION, TRANSIT_VERSION_MIN, };-pub use entry::ArchiveEntry;+pub use entry::{is_known_kind, ArchiveEntry}; pub use footer::ArchiveFooter; pub use layout::{align_up, serialize_dir, sidecar_start}; pub use view::ArchiveView;
library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rsindex 9dfbfd3606..d2c648956c 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/tests.rs@@ -88,19 +88,42 @@ fn the_footer_is_32_bytes_behind_mama8() { assert!(ArchiveFooter::parse(&bad).is_err(), "bad magic is refused"); } -/// Fail-watched: entries are 32 bytes, kinds are the thirteen defined, and-/// the directory is `count` + entries padded to 8. A revert of the stride-/// quotes `left: 24, right: 32`.+/// Fail-watched: entries are 32 bytes, the overlay is kind 14, and any non-zero+/// kind parses (so a newer writer's section does not lock out older readers)+/// while only the defined ones count as known. #[test]-fn entries_are_32_bytes_with_thirteen_known_kinds() {+fn entries_are_32_bytes_and_unknown_kinds_parse() { let e = ArchiveEntry { kind: ARCHIVE_KIND_TRANSIT, flags: 0, offset: 8192, len: 128, extra: 0 }; assert_eq!(e.serialize().len(), 32, "entries must stay 32 B"); assert_eq!(ArchiveEntry::parse(&e.serialize()).expect("parse"), e); assert_eq!(ARCHIVE_KIND_GRAPH_META, 1, "graph meta is kind 1"); assert_eq!(ARCHIVE_KIND_TRANSIT, 13, "transit is kind 13");- let mut bad = e.serialize();- bad[0] = 99;- assert!(ArchiveEntry::parse(&bad).is_err(), "unknown kind");+ assert_eq!(ARCHIVE_KIND_GRAPH_OVERLAY, 14, "the highway overlay is kind 14");+ let mut future = e.serialize();+ future[0] = 99;+ assert_eq!(ArchiveEntry::parse(&future).expect("a future kind parses").kind, 99);+ assert!(!is_known_kind(99) && is_known_kind(ARCHIVE_KIND_GRAPH_OVERLAY) && !is_known_kind(0));+ let mut zero = e.serialize();+ zero[0] = 0;+ assert!(ArchiveEntry::parse(&zero).is_err(), "kind 0 is never a section");+}++/// An archive carrying a section this build has never heard of still opens,+/// and the known sections around it still slice.+#[test]+fn an_archive_with_an_unknown_section_still_opens() {+ let mut transit = vec![0u8; 80 + 20 * 16];+ transit[0..4].copy_from_slice(&TRANSIT_MAGIC.to_le_bytes());+ transit[4..8].copy_from_slice(&TRANSIT_VERSION.to_le_bytes());+ transit[8..12].copy_from_slice(&20u32.to_le_bytes());+ let mut header = v7_header(0);+ let payloads = vec![(ARCHIVE_KIND_TRANSIT, transit.clone(), 0), (99u8, vec![7u8; 24], 0)];+ let bytes = assemble(&header, &payloads);+ header.file_len = bytes.len() as u64;+ let bytes = assemble(&header, &payloads);+ let view = ArchiveView::parse(&bytes, &header).expect("an unknown kind is skipped, not refused");+ assert_eq!(view.section(&bytes, ARCHIVE_KIND_TRANSIT), Some(&transit[..]));+ assert_eq!(view.section(&bytes, 99), Some(&[7u8; 24][..])); } /// Fail-watched: the sidecar starts past the tile data — never inside the header tail
library/tilecodec/src/main/rust/src/mamaps/archive/view.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/view.rsindex ca5e7b193c..5c702a3db9 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/view.rs@@ -69,7 +69,7 @@ impl ArchiveView { let count = u32::from_le_bytes([dir[0], dir[1], dir[2], dir[3]]) as usize; if count > 32 { return err(format!(- "a single-archive directory names {count} sections, past the 13 this format defines"+ "a single-archive directory names {count} sections, past the 32 a directory may hold" )); } let want = ARCHIVE_DIR_HEADER_LEN + count * ARCHIVE_ENTRY_LEN;
maps/src/main/rust/examples/route_diff.rs
diff --git a/maps/src/main/rust/examples/route_diff.rs b/maps/src/main/rust/examples/route_diff.rsindex 9d94453559..0f4562613c 100644--- a/maps/src/main/rust/examples/route_diff.rs+++ b/maps/src/main/rust/examples/route_diff.rs@@ -57,6 +57,7 @@ fn main() -> std::process::ExitCode { Some("bench") => bench(&args[1..]), Some("dump") => dump(&args[1..]), Some("dump-compare") => dump_compare(&args[1..]),+ Some("sections") => sections(&args[1..]), _ => Err(USAGE.to_string()), }; match r {@@ -72,12 +73,14 @@ fn main() -> std::process::ExitCode { const USAGE: &str = "\ usage: route_diff gen-pairs --graph DIR --out FILE [--count N]- route_diff report --graph DIR --pairs FILE --out FILE+ route_diff report --graph DIR --pairs FILE --out FILE [--overlay FILE] route_diff compare --baseline FILE --candidate FILE [--tol-mm N] [--tol-10ms N] route_diff geometry --baseline DIR --candidate DIR- route_diff bench --graph DIR --pairs FILE [--passes N] [--cold]+ route_diff bench --graph DIR --pairs FILE [--passes N] [--cold] [--verbose] [--overlay FILE]+ route_diff dump route_diff dump --graph DIR --out FILE- route_diff dump-compare --baseline FILE --candidate FILE [--limit N]";+ route_diff dump-compare --baseline FILE --candidate FILE [--limit N]+ route_diff sections --archive FILE [--dump KIND]"; fn flag(args: &[String], name: &str) -> Option<String> { args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned()@@ -87,12 +90,55 @@ fn need(args: &[String], name: &str) -> Result<String, String> { flag(args, name).ok_or_else(|| format!("missing {name}\n{USAGE}")) } +/// Print `kind offset len` for every sidecar section of a `.mamaps`, reading+/// only the footer and directory, so sections can be cut out with `dd`.+fn sections(args: &[String]) -> Result<bool, String> {+ use std::io::{Read as _, Seek as _, SeekFrom};+ use tilecodec::mamaps::archive::{ArchiveEntry, ArchiveFooter};+ let path = need(args, "--archive")?;+ let mut f = std::fs::File::open(&path).map_err(|e| format!("{path}: {e}"))?;+ let mut read_at = |at: SeekFrom, len: usize| -> Result<Vec<u8>, String> {+ let mut buf = vec![0u8; len];+ f.seek(at).and_then(|_| f.read_exact(&mut buf)).map_err(|e| format!("{path}: {e}"))?;+ Ok(buf)+ };+ let footer = ArchiveFooter::parse(&read_at(SeekFrom::End(-32), 32)?).map_err(|e| e.0)?;+ let dir = read_at(SeekFrom::Start(footer.dir_offset), footer.dir_len as usize)?;+ let count = u32::from_le_bytes(dir[0..4].try_into().expect("4 bytes")) as usize;+ let dump: Option<u8> = flag(args, "--dump").map(|k| k.parse().map_err(|e| format!("--dump: {e}"))).transpose()?;+ for i in 0..count {+ let e = ArchiveEntry::parse(&dir[4 + i * 32..]).map_err(|e| e.0)?;+ match dump {+ None => println!("{} {} {}", e.kind, e.offset, e.len),+ Some(k) if k == e.kind => {+ f.seek(SeekFrom::Start(e.offset)).map_err(|e| e.to_string())?;+ let mut out = std::io::stdout().lock();+ std::io::copy(&mut (&mut f).take(e.len), &mut out).map_err(|e| e.to_string())?;+ return Ok(true);+ }+ Some(_) => {}+ }+ }+ Ok(dump.is_none())+}+ fn load(dir: &str) -> Result<Graph, String> { Graph::load(dir).or_else(|| Graph::load_archive(&archive_path(dir))).ok_or_else(|| { format!("cannot load a graph from {dir} (missing/short files, or a bad metadata.bin header)") }) } +/// [`load`], then attach `--overlay FILE` when given.+fn load_with_overlay(dir: &str, args: &[String]) -> Result<Graph, String> {+ let mut g = load(dir)?;+ if let Some(path) = flag(args, "--overlay") {+ if !g.attach_overlay_file(&path) {+ return Err(format!("{path}: not an overlay for this graph"));+ }+ }+ Ok(g)+}+ // --------------------------------------------------------------------------- // gen-pairs // ---------------------------------------------------------------------------@@ -204,7 +250,7 @@ fn report(args: &[String]) -> Result<bool, String> { let pairs_path = need(args, "--pairs")?; let out = need(args, "--out")?; - let g = load(&dir)?;+ let g = load_with_overlay(&dir, args)?; let pairs = read_pairs(&pairs_path)?; let speeds = TrafficSpeeds::default(); let mut scratch = RoutingScratchpad::new();@@ -575,13 +621,14 @@ fn bench(args: &[String]) -> Result<bool, String> { return Err("--passes wants at least one".to_string()); } let cold = args.iter().any(|a| a == "--cold");+ let verbose = args.iter().any(|a| a == "--verbose"); if cold { let evicted = evict(&dir)?; println!("evicted {evicted} pack file(s) from the page cache"); } let load_started = std::time::Instant::now();- let g = load(&dir)?;+ let g = load_with_overlay(&dir, args)?; let load_ms = load_started.elapsed().as_secs_f64() * 1e3; let pairs = read_pairs(&pairs_path)?;@@ -605,9 +652,22 @@ fn bench(args: &[String]) -> Result<bool, String> { pair.mode, &mut scratch, &mut heap, ); if let Some(mut ctx) = ctx {+ let hierarchical = ctx.hierarchy; perform_search_loop( &g, &speeds, &mut ensure, pair.mode, &mut ctx, &mut scratch, &mut heap, );+ if verbose {+ println!(+ " {} mode={} {:.0} ms iterations={} hierarchy={} fell_back={} routed={}",+ pair.kind,+ pair.mode,+ one.elapsed().as_secs_f64() * 1e3,+ ctx.iterations,+ hierarchical,+ hierarchical && !ctx.hierarchy,+ ctx.target_node != 0xFFFF_FFFF || ctx.direct.is_some(),+ );+ } if ctx.target_node != 0xFFFF_FFFF || ctx.direct.is_some() { let steps = reconstruct_path(&g, &speeds, pair.mode, &ctx, &mut scratch); p.routed += 1;
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 6af262225f..1425748a6f 100644--- a/maps/src/main/rust/src/graph.rs+++ b/maps/src/main/rust/src/graph.rs@@ -442,4 +442,5 @@ include!("graph_part2b.rs"); include!("graph_part3.rs"); include!("graph_part4.rs"); include!("graph_part4b.rs");-include!("graph_part5.rs");\ No newline at end of file+include!("graph_part5.rs");+include!("graph_overlay.rs");\ No newline at end of file
maps/src/main/rust/src/graph_overlay.rs
diff --git a/maps/src/main/rust/src/graph_overlay.rs b/maps/src/main/rust/src/graph_overlay.rsnew file mode 100644index 0000000000..1e704d0f8f--- /dev/null+++ b/maps/src/main/rust/src/graph_overlay.rs@@ -0,0 +1,458 @@+// --- Highway overlay ---+//+// The motorway/trunk/primary subgraph of the full graph, renumbered densely in+// full-id order, so a long search reads a few contiguous blocks instead of one+// block per scattered arterial node. Written by `road_overlay` in+// `scripts/maps/osm_ingest`; the two layouts must agree.+//+// ```text+// [magic "MOVL" u32][version u32]+// [full_node_count u64][full_edge_count u64]+// [overlay_node_count u64 M][overlay_edge_count u64 K]+// [nodes_len u64][edges_len u64]+// nodes: ZBLK, 16 B (lat_e7 i32, lon_e7 i32, edge_ptr u32, full_node u32), M + 1+// records, the sentinel's edge_ptr = K+// pad to 8+// edges: ZBLK, 20 B (target u32 overlay id, dist_mm u32, full_edge u64,+// type u8, speed_limit u8, pad u16), K records, grouped by source+// pad to 8+// portals: EdgeBitmap over the full node ids; overlay id = rank(full id)+// ```++/// `"MOVL"`, little-endian.+pub const OVERLAY_MAGIC: u32 = 0x4C56_4F4D;+pub const OVERLAY_VERSION: u32 = 1;+const OVERLAY_HEADER_LEN: usize = 56;+const OVERLAY_NODE_LEN: usize = 16;+const OVERLAY_EDGE_LEN: usize = 20;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct OverlayNode {+ pub lat_e7: i32,+ pub lon_e7: i32,+ pub edge_ptr: u64,+ pub full_node: u32,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct OverlayEdge {+ pub target: u32,+ pub dist_mm: u32,+ pub full_edge: u64,+ pub type_: u8,+ pub speed_limit: u8,+}++pub struct Overlay {+ _region: Option<MmapRegion>,+ _owned: Option<Vec<u8>>,+ pub node_count: u32,+ pub edge_count: u64,+ nodes: BlockedView,+ edges: BlockedView,+ portals: EdgeBitmap,+}++unsafe impl Send for Overlay {}+unsafe impl Sync for Overlay {}++impl Overlay {+ /// Parse an overlay over `bytes`, refusing one built for a different graph or+ /// whose tables do not match its counts. `bytes` must outlive the overlay; the+ /// owning region or buffer is attached by the caller.+ fn parse(bytes: &[u8], full_nodes: u32, full_edges: u64) -> Option<Overlay> {+ if bytes.len() < OVERLAY_HEADER_LEN {+ return None;+ }+ let u32_at = |o: usize| u32::from_le_bytes(bytes[o..o + 4].try_into().expect("4 bytes"));+ let u64_at = |o: usize| u64::from_le_bytes(bytes[o..o + 8].try_into().expect("8 bytes"));+ if u32_at(0) != OVERLAY_MAGIC || u32_at(4) != OVERLAY_VERSION {+ return None;+ }+ if u64_at(8) != u64::from(full_nodes) || u64_at(16) != full_edges {+ return None;+ }+ let (m, k) = (u64_at(24), u64_at(32));+ // Overlay ids live above the full ids in one u32 space, below the+ // 0xFFFF_FFFF "no node" sentinel.+ if u64::from(full_nodes) + m >= u64::from(u32::MAX) {+ return None;+ }+ let (nodes_len, edges_len) = (u64_at(40) as usize, u64_at(48) as usize);+ let nodes_at = OVERLAY_HEADER_LEN;+ let edges_at = align_up(nodes_at.checked_add(nodes_len)? as u64, SECTION_ALIGN) as usize;+ let portals_at = align_up(edges_at.checked_add(edges_len)? as u64, SECTION_ALIGN) as usize;+ let portals_len = EdgeBitmap::bytes(u64::from(full_nodes)) as usize;+ if portals_at.checked_add(portals_len)? != bytes.len() {+ return None;+ }+ let nodes = BlockedView::parse(&bytes[nodes_at..nodes_at + nodes_len])?;+ let edges = BlockedView::parse(&bytes[edges_at..edges_at + edges_len])?;+ if nodes.record_len != OVERLAY_NODE_LEN+ || nodes.unpacked_len != (m + 1) * OVERLAY_NODE_LEN as u64+ || edges.record_len != OVERLAY_EDGE_LEN+ || edges.unpacked_len != k * OVERLAY_EDGE_LEN as u64+ {+ return None;+ }+ let base = bytes[portals_at..].as_ptr();+ let portals = EdgeBitmap {+ rank: base,+ present: unsafe { base.add(EdgeBitmap::present_offset(u64::from(full_nodes)) as usize) },+ };+ if portals.total(u64::from(full_nodes)) != m {+ return None;+ }+ Some(Overlay {+ _region: None,+ _owned: None,+ node_count: m as u32,+ edge_count: k,+ nodes,+ edges,+ portals,+ })+ }++ /// Overlay node `o`; `o == node_count` is the sentinel.+ #[inline]+ pub fn node(&self, o: u32) -> OverlayNode {+ match self.nodes.record(u64::from(o)) {+ Some(&[a0, a1, a2, a3, b0, b1, b2, b3, c0, c1, c2, c3, d0, d1, d2, d3, ..]) => OverlayNode {+ lat_e7: i32::from_le_bytes([a0, a1, a2, a3]),+ lon_e7: i32::from_le_bytes([b0, b1, b2, b3]),+ edge_ptr: u64::from(u32::from_le_bytes([c0, c1, c2, c3])),+ full_node: u32::from_le_bytes([d0, d1, d2, d3]),+ },+ _ => OverlayNode { lat_e7: 0, lon_e7: 0, edge_ptr: 0, full_node: u32::MAX },+ }+ }++ #[inline]+ pub fn edge_range(&self, o: u32) -> (u64, u64) {+ (self.node(o).edge_ptr, self.node(o + 1).edge_ptr)+ }++ #[inline]+ pub fn edge(&self, i: u64) -> OverlayEdge {+ match self.edges.record(i) {+ Some(r) if r.len() >= OVERLAY_EDGE_LEN => OverlayEdge {+ target: u32::from_le_bytes(r[0..4].try_into().expect("4 bytes")),+ dist_mm: u32::from_le_bytes(r[4..8].try_into().expect("4 bytes")),+ full_edge: u64::from_le_bytes(r[8..16].try_into().expect("8 bytes")),+ type_: r[16],+ speed_limit: r[17],+ },+ _ => OverlayEdge { target: u32::MAX, dist_mm: 0, full_edge: INVALID_EDGE, type_: 0, speed_limit: 0 },+ }+ }++ /// The overlay id of full node `full`, when it is on the overlay.+ #[inline]+ pub fn of_full(&self, full: u32) -> Option<u32> {+ let idx = u64::from(full);+ self.portals.contains(idx).then(|| self.portals.rank_of(idx) as u32)+ }+}++impl Graph {+ pub fn overlay(&self) -> Option<&Overlay> {+ self.overlay.as_ref()+ }++ /// Attach an overlay from a standalone `overlay.bin` (the graph-dir layout).+ /// Returns false, leaving any current overlay in place, when it does not+ /// parse or was built for a different graph.+ pub fn attach_overlay_file(&mut self, path: &str) -> bool {+ let Some(region) = MmapRegion::map(path) else {+ return false;+ };+ let bytes = unsafe { std::slice::from_raw_parts(region.base(), region.len) };+ match Overlay::parse(bytes, self.node_count, self.edge_count) {+ Some(mut ov) => {+ ov._region = Some(region);+ self.overlay = Some(ov);+ true+ }+ None => false,+ }+ }++ /// [`Graph::attach_overlay_file`] over an owned buffer (tests and hosts+ /// without mmap).+ pub fn attach_overlay_bytes(&mut self, bytes: Vec<u8>) -> bool {+ let view = unsafe { std::slice::from_raw_parts(bytes.as_ptr(), bytes.len()) };+ match Overlay::parse(view, self.node_count, self.edge_count) {+ Some(mut ov) => {+ ov._owned = Some(bytes);+ self.overlay = Some(ov);+ true+ }+ None => false,+ }+ }++ /// The full-graph node behind a search id: itself below `node_count`, the+ /// overlay node's full node above it.+ #[inline]+ pub fn full_node_of(&self, id: u32) -> u32 {+ match (&self.overlay, id.checked_sub(self.node_count)) {+ (Some(ov), Some(o)) => ov.node(o).full_node,+ _ => id,+ }+ }+}++#[cfg(test)]+mod overlay_tests {+ use super::*;+ use crate::geometry::{accurate_dist_mm, TrafficSpeeds, ROAD_TYPE_MASK};+ use crate::routing::{perform_search_loop, prepare_routing, reconstruct_path};+ use crate::state::{RadixHeap, RoutingScratchpad};+ use tilecodec::blocked::write_blocked;++ const MOTORWAY_T: u8 = 1;+ const RESIDENTIAL_T: u8 = 7;+ const SPAN: u32 = 41;+ const STEP_E7: i32 = 500_000; // 0.05 deg of longitude at the equator, ~5.6 km++ /// `(source, target, type)`; distances come from the node coordinates.+ type Edge = (u32, u32, u8);++ fn pad8(v: &mut Vec<u8>) {+ while v.len() % 8 != 0 {+ v.push(0);+ }+ }++ /// A v7 graph with no escapes, names or stored geometry, in the exact tail+ /// layouts `assemble` checks.+ fn build_graph(nodes: &[(i32, i32)], edges: &[Edge]) -> Graph {+ let n = nodes.len() as u32;+ let e = edges.len() as u64;+ let mut sorted = edges.to_vec();+ sorted.sort_by_key(|&(s, t, _)| (s, t));+ let mut node_recs = Vec::new();+ let mut ptr = 0u32;+ for (id, &(lat, lon)) in nodes.iter().enumerate() {+ node_recs.extend_from_slice(&lat.to_le_bytes());+ node_recs.extend_from_slice(&lon.to_le_bytes());+ node_recs.extend_from_slice(&ptr.to_le_bytes());+ ptr += sorted.iter().filter(|&&(s, _, _)| s == id as u32).count() as u32;+ }+ node_recs.extend_from_slice(&[0u8; 8]);+ node_recs.extend_from_slice(&(e as u32).to_le_bytes());+ let mut edge_recs = Vec::new();+ for &(s, t, ty) in &sorted {+ let (a, b) = (nodes[s as usize], nodes[t as usize]);+ let dist = accurate_dist_mm(a.0, a.1, b.0, b.1);+ edge_recs.extend_from_slice(&((t as i64 - s as i64) as i16).to_le_bytes());+ edge_recs.extend_from_slice(&dist.to_le_bytes()[..3]);+ edge_recs.push(ty);+ edge_recs.push(0);+ }+ let mut edges_bytes = write_blocked(&edge_recs, 7);+ pad8(&mut edges_bytes);+ edges_bytes.extend(std::iter::repeat(0u8).take(((e.div_ceil(ESCAPE_BLOCK) + 1) * 4) as usize));+ pad8(&mut edges_bytes);+ edges_bytes.extend(std::iter::repeat(0u8).take(EdgeBitmap::bytes(e) as usize));+ let intermediate = vec![0u8; (EdgeBitmap::bytes(e) + 18) as usize];+ let mut meta = Vec::new();+ meta.extend_from_slice(&GRAPH_MAGIC.to_le_bytes());+ meta.extend_from_slice(&GRAPH_VERSION.to_le_bytes());+ meta.extend_from_slice(&u64::from(n).to_le_bytes());+ meta.extend_from_slice(&e.to_le_bytes());+ meta.extend_from_slice(&0u64.to_le_bytes());+ meta.extend_from_slice(&0u64.to_le_bytes());+ let owned = vec![meta, write_blocked(&node_recs, 12), edges_bytes, intermediate];+ let at = |i: usize| unsafe { std::slice::from_raw_parts(owned[i].as_ptr(), owned[i].len()) };+ let sections = GraphSections {+ meta: at(0),+ nodes: at(1),+ edges: at(2),+ intermediate: at(3),+ road_names: None,+ lanes: None,+ elevation: None,+ };+ Graph::assemble(+ sections,+ GraphOwnership {+ nodes: None,+ edges: None,+ intermediate: None,+ road_names: None,+ lanes: None,+ elevation: None,+ archive: None,+ buffers: owned,+ },+ )+ .expect("synthetic graph assembles")+ }++ /// The overlay of `g`: every node touching a class <= 3 edge, in full-id+ /// order, and those edges. An independent writer from the ingest one, so the+ /// two cross-check the format.+ fn build_overlay(g: &Graph, full_nodes_header: u64) -> Vec<u8> {+ let n = g.node_count;+ let is_arterial = |ty: u8| (ty & ROAD_TYPE_MASK) <= 3 && (ty & ROAD_TYPE_MASK) >= 1;+ let mut on = vec![false; n as usize];+ for u in 0..n {+ let (s, e) = g.edge_range(u);+ for i in s..e {+ let edge = g.edge(u, i);+ if is_arterial(edge.type_) {+ on[u as usize] = true;+ on[edge.target as usize] = true;+ }+ }+ }+ let ids: Vec<u32> = (0..n).filter(|&u| on[u as usize]).collect();+ let of = |full: u32| ids.binary_search(&full).unwrap() as u32;+ let (mut node_recs, mut edge_recs, mut k) = (Vec::new(), Vec::new(), 0u32);+ for &u in &ids {+ let nd = g.node(u);+ node_recs.extend_from_slice(&nd.lat_e7.to_le_bytes());+ node_recs.extend_from_slice(&nd.lon_e7.to_le_bytes());+ node_recs.extend_from_slice(&k.to_le_bytes());+ node_recs.extend_from_slice(&u.to_le_bytes());+ let (s, e) = g.edge_range(u);+ for i in s..e {+ let edge = g.edge(u, i);+ if is_arterial(edge.type_) {+ edge_recs.extend_from_slice(&of(edge.target).to_le_bytes());+ edge_recs.extend_from_slice(&edge.dist_mm.to_le_bytes());+ edge_recs.extend_from_slice(&i.to_le_bytes());+ edge_recs.extend_from_slice(&[edge.type_, edge.speed_limit, 0, 0]);+ k += 1;+ }+ }+ }+ node_recs.extend_from_slice(&[0u8; 8]);+ node_recs.extend_from_slice(&k.to_le_bytes());+ node_recs.extend_from_slice(&u32::MAX.to_le_bytes());+ let nodes = write_blocked(&node_recs, OVERLAY_NODE_LEN);+ let edges = write_blocked(&edge_recs, OVERLAY_EDGE_LEN);+ let mut out = Vec::new();+ for v in [u64::from(OVERLAY_MAGIC) | (u64::from(OVERLAY_VERSION) << 32), full_nodes_header, g.edge_count,+ ids.len() as u64, u64::from(k), nodes.len() as u64, edges.len() as u64]+ {+ out.extend_from_slice(&v.to_le_bytes());+ }+ out.extend_from_slice(&nodes);+ pad8(&mut out);+ out.extend_from_slice(&edges);+ pad8(&mut out);+ let blocks = u64::from(n).div_ceil(RANK_BLOCK_BYTES * 8);+ let mut present = vec![0u8; u64::from(n).div_ceil(8) as usize];+ for &u in &ids {+ present[(u / 8) as usize] |= 1 << (u % 8);+ }+ let mut running = 0u64;+ for b in 0..=blocks {+ out.extend_from_slice(&running.to_le_bytes());+ let lo = (b * RANK_BLOCK_BYTES) as usize;+ let hi = (lo + RANK_BLOCK_BYTES as usize).min(present.len());+ if lo < hi {+ running += present[lo..hi].iter().map(|x| u64::from(x.count_ones())).sum::<u64>();+ }+ }+ out.extend_from_slice(&present);+ out+ }++ /// A ~220 km motorway along the equator with a residential road 1.1 km north+ /// of it, joined by a residential connector at every node. Motorway ids+ /// `0..SPAN`, residential ids `SPAN..2*SPAN`.+ fn corridor() -> Graph {+ let mut nodes = Vec::new();+ for lat in [0, 100_000] {+ for i in 0..SPAN as i32 {+ nodes.push((lat, i * STEP_E7));+ }+ }+ let mut edges = Vec::new();+ for i in 0..SPAN - 1 {+ for (s, t) in [(i, i + 1), (i + 1, i)] {+ edges.push((s, t, MOTORWAY_T));+ edges.push((SPAN + s, SPAN + t, RESIDENTIAL_T));+ }+ }+ for i in 0..SPAN {+ edges.push((i, SPAN + i, RESIDENTIAL_T));+ edges.push((SPAN + i, i, RESIDENTIAL_T));+ }+ build_graph(&nodes, &edges)+ }++ /// `(total time, total distance, iterations, used overlay)` for the corridor's+ /// end-to-end drive on the residential side.+ fn drive(g: &Graph) -> (u64, u64, i32, bool) {+ let speeds = TrafficSpeeds::default();+ let (mut scratch, mut heap) = (RoutingScratchpad::new(), RadixHeap::new());+ let mut ensure = |_: i32, _: i32| {};+ let end_lon = f64::from((SPAN as i32 - 1) * STEP_E7) * 1e-7;+ let mut ctx = prepare_routing(+ g, &speeds, &mut ensure, 0.0101, 0.0001, 0.0101, end_lon - 0.0001, DRIVING, &mut scratch,+ &mut heap,+ )+ .expect("both ends snap");+ let hierarchical = ctx.hierarchy;+ perform_search_loop(g, &speeds, &mut ensure, DRIVING, &mut ctx, &mut scratch, &mut heap);+ assert_ne!(ctx.target_node, 0xFFFF_FFFF, "a route is found");+ assert!(ctx.hierarchy == hierarchical, "the overlay search did not fall back");+ let steps = reconstruct_path(g, &speeds, DRIVING, &ctx, &mut scratch);+ (+ steps.iter().map(|s| s.time_10ms).sum(),+ steps.iter().map(|s| s.dist_mm).sum(),+ ctx.iterations,+ hierarchical,+ )+ }++ #[test]+ fn the_overlay_maps_full_ids_both_ways() {+ let mut g = corridor();+ let bytes = build_overlay(&g, u64::from(g.node_count));+ assert!(g.attach_overlay_bytes(bytes));+ let ov = g.overlay().expect("attached");+ assert_eq!(ov.node_count, SPAN, "exactly the motorway nodes");+ assert_eq!(ov.edge_count, u64::from(2 * (SPAN - 1)));+ for full in 0..SPAN {+ let o = ov.of_full(full).expect("motorway node is a portal");+ assert_eq!(ov.node(o).full_node, full);+ assert_eq!(g.full_node_of(g.node_count + o), full);+ }+ assert_eq!(ov.of_full(SPAN), None, "residential nodes are not on the overlay");+ for o in 0..ov.node_count {+ let (s, e) = ov.edge_range(o);+ for i in s..e {+ let edge = ov.edge(i);+ let full = g.edge(ov.node(o).full_node, edge.full_edge);+ assert_eq!(full.target, ov.node(edge.target).full_node, "overlay edge {i} is its full edge");+ assert_eq!(full.dist_mm, edge.dist_mm);+ }+ }+ }++ #[test]+ fn an_overlay_route_matches_the_full_search() {+ let full = drive(&corridor());+ assert!(!full.3, "no overlay, no hierarchy");+ let mut g = corridor();+ let bytes = build_overlay(&g, u64::from(g.node_count));+ assert!(g.attach_overlay_bytes(bytes));+ let hier = drive(&g);+ assert!(hier.3, "a 220 km drive uses the overlay");+ assert_eq!((hier.0, hier.1), (full.0, full.1), "same time and distance as plain A*");+ }++ #[test]+ fn an_overlay_built_for_another_graph_is_refused() {+ let mut g = corridor();+ let bytes = build_overlay(&g, u64::from(g.node_count) + 1);+ assert!(!g.attach_overlay_bytes(bytes));+ assert!(g.overlay().is_none());+ }+}
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 9044652edd..db8d99d50d 100644--- a/maps/src/main/rust/src/graph_part1.rs+++ b/maps/src/main/rust/src/graph_part1.rs@@ -81,6 +81,9 @@ pub struct Graph { edges_view: Option<BlockedView>, elevation_view: Option<BlockedView>, + /// The optional highway overlay. See `graph_overlay.rs`.+ overlay: Option<Overlay>,+ // Derived cost tables (computed in `load`, matching the C++ `init`). pub lon_to_mm_scale: [u32; 4096], pub time_scale_fixed: [u64; 4],
maps/src/main/rust/src/graph_part2.rs
diff --git a/maps/src/main/rust/src/graph_part2.rs b/maps/src/main/rust/src/graph_part2.rsindex 0ab5bb85ec..c907f8ded3 100644--- a/maps/src/main/rust/src/graph_part2.rs+++ b/maps/src/main/rust/src/graph_part2.rs@@ -391,6 +391,7 @@ impl Graph { nodes_view, edges_view, elevation_view,+ overlay: None, lon_to_mm_scale, time_scale_fixed, edge_time_multipliers,
maps/src/main/rust/src/graph_part4.rs
diff --git a/maps/src/main/rust/src/graph_part4.rs b/maps/src/main/rust/src/graph_part4.rsindex 17ff32eb8e..e67c26d767 100644--- a/maps/src/main/rust/src/graph_part4.rs+++ b/maps/src/main/rust/src/graph_part4.rs@@ -18,7 +18,7 @@ use tilecodec::mamaps::archive::{ ARCHIVE_KIND_GRAPH_ELEVATION, ARCHIVE_KIND_GRAPH_INTERMEDIATE, ARCHIVE_KIND_GRAPH_LANES, ARCHIVE_KIND_GRAPH_META, ARCHIVE_KIND_GRAPH_NAMES, ARCHIVE_KIND_GRAPH_NODES,- ARCHIVE_KIND_GRAPH_EDGES, ArchiveView,+ ARCHIVE_KIND_GRAPH_EDGES, ARCHIVE_KIND_GRAPH_OVERLAY, ArchiveView, }; use tilecodec::mamaps::header::Header; @@ -462,6 +462,7 @@ impl Graph { nodes_view, edges_view, elevation_view,+ overlay: None, lon_to_mm_scale, time_scale_fixed, edge_time_multipliers,
maps/src/main/rust/src/graph_part4b.rs
diff --git a/maps/src/main/rust/src/graph_part4b.rs b/maps/src/main/rust/src/graph_part4b.rsindex b830e548f1..faa46ba852 100644--- a/maps/src/main/rust/src/graph_part4b.rs+++ b/maps/src/main/rust/src/graph_part4b.rs@@ -26,7 +26,10 @@ impl Graph { lanes: section(ARCHIVE_KIND_GRAPH_LANES), elevation: section(ARCHIVE_KIND_GRAPH_ELEVATION), };- Graph::assemble(+ // Borrowed from the mapping the graph is about to own, so it outlives+ // the overlay that views it.+ let overlay = section(ARCHIVE_KIND_GRAPH_OVERLAY).map(|b| (b.as_ptr(), b.len()));+ let mut g = Graph::assemble( sections, GraphOwnership { nodes: None,@@ -38,6 +41,12 @@ impl Graph { archive: Some(region), buffers: Vec::new(), },- )+ )?;+ if let Some((ptr, len)) = overlay {+ let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };+ // Absent, stale or malformed all mean the same thing: no overlay.+ g.overlay = Overlay::parse(bytes, g.node_count, g.edge_count);+ }+ Some(g) } }
maps/src/main/rust/src/routing/search.rs
diff --git a/maps/src/main/rust/src/routing/search.rs b/maps/src/main/rust/src/routing/search.rsindex 0a8a6bcf75..860f871102 100644--- a/maps/src/main/rust/src/routing/search.rs+++ b/maps/src/main/rust/src/routing/search.rs@@ -44,6 +44,38 @@ pub struct RoutingContext { /// A route that stays on the edge it started on, when both ends snapped to /// the same road. See [`direct_path`]. pub direct: Option<Direct>,+ /// Whether the search hops onto the highway overlay away from both ends.+ /// See [`is_local`].+ pub hierarchy: bool,+}++/// Driving routes at least this long (straight line) use the highway overlay+/// when the graph has one.+const HIERARCHY_MIN_MM: u32 = 150_000_000;+/// Within this distance of either end the search expands every road; beyond it+/// a full-graph node only hops onto the overlay.+pub const OVERLAY_LOCAL_MM: u32 = 30_000_000;++/// Whether a point is close enough to either end to expand the full graph.+///+/// Plain A* on a cross-country route expands every residential street inside an+/// ellipse a thousand kilometres wide, and because nodes are stored in spatial+/// order the arterials it follows are scattered across the whole node table, so+/// every step inflates another block. Away from both ends the search runs on the+/// overlay instead: the same arterial edges at the same costs, stored densely.+/// Transitions between a full node and its overlay twin cost nothing and change+/// nothing about the heuristic, so A* stays consistent. Routes are near-optimal+/// rather than provably optimal: a minor-road shortcut far from both ends is not+/// seen.+#[inline]+fn is_local(g: &Graph, lat_e7: i32, lon_e7: i32, ctx: &RoutingContext) -> bool {+ fast_dist_mm(g, lat_e7, lon_e7, ctx.start.proj_lat, ctx.start.proj_lon) < OVERLAY_LOCAL_MM+ || near_end(g, lat_e7, lon_e7, ctx)+}++#[inline]+fn near_end(g: &Graph, lat_e7: i32, lon_e7: i32, ctx: &RoutingContext) -> bool {+ fast_dist_mm(g, lat_e7, lon_e7, ctx.end.proj_lat, ctx.end.proj_lon) < OVERLAY_LOCAL_MM } /// A route from the start projection to the end projection that never leaves the@@ -211,22 +243,12 @@ pub fn prepare_routing( ensure_traffic(start.proj_lat, start.proj_lon); } - let push = |node: u32, travel_dist_mm: u32, scratch: &mut RoutingScratchpad, heap: &mut RadixHeap| {- let t_actual = get_edge_time_10ms(- g, traffic, INVALID_EDGE, travel_dist_mm, start.type_, start.speed_limit, mode,- );- {- let entry = scratch.get_entry(node);- entry.g_fwd = t_actual;- }- let n_data = g.get_node(node);- let h = heuristic_time_10ms(g, n_data.lat_e7, n_data.lon_e7, end.proj_lat, end.proj_lon, mode);- heap.push(t_actual.wrapping_add(h), node);- };- push(start.node_a, start.dist_a_mm, scratch, heap);- push(start.node_b, start.dist_b_mm, scratch, heap);-+ seed(g, traffic, &start, &end, mode, scratch, heap); let direct = direct_path(g, traffic, &start, &end, mode);+ let hierarchy = mode == DRIVING+ && g.overlay().is_some()+ && accurate_dist_mm(start.proj_lat, start.proj_lon, end.proj_lat, end.proj_lon)+ >= HIERARCHY_MIN_MM; Some(RoutingContext { start,@@ -234,9 +256,33 @@ pub fn prepare_routing( target_node: 0xFFFF_FFFF, iterations: 0, direct,+ hierarchy, }) } +/// Push the start edge's two endpoints onto the open set.+fn seed(+ g: &Graph,+ traffic: &TrafficSpeeds,+ start: &SnappedEdge,+ end: &SnappedEdge,+ mode: i32,+ scratch: &mut RoutingScratchpad,+ heap: &mut RadixHeap,+) {+ let mut push = |node: u32, travel_dist_mm: u32| {+ let t_actual = get_edge_time_10ms(+ g, traffic, INVALID_EDGE, travel_dist_mm, start.type_, start.speed_limit, mode,+ );+ scratch.get_entry(node).g_fwd = t_actual;+ let n_data = g.get_node(node);+ let h = heuristic_time_10ms(g, n_data.lat_e7, n_data.lon_e7, end.proj_lat, end.proj_lon, mode);+ heap.push(t_actual.wrapping_add(h), node);+ };+ push(start.node_a, start.dist_a_mm);+ push(start.node_b, start.dist_b_mm);+}+ /// Polyline of `edge_idx` in source-to-target order, falling back to the straight /// chord when the edge stores no geometry. fn edge_polyline(g: &Graph, edge_idx: u64, source: u32, target: u32) -> Vec<LatLon> {@@ -395,6 +441,10 @@ fn direct_path( } /// A* main loop. Fills `ctx.target_node` on success.+///+/// A hierarchical search that finds nothing (an end whose only way out is a long+/// minor road) is retried over every road, so pruning can cost time but never a+/// route. pub fn perform_search_loop( g: &Graph, traffic: &TrafficSpeeds,@@ -403,6 +453,26 @@ pub fn perform_search_loop( ctx: &mut RoutingContext, scratch: &mut RoutingScratchpad, heap: &mut RadixHeap,+) {+ search(g, traffic, ensure_traffic, mode, ctx, scratch, heap);+ if ctx.hierarchy && ctx.target_node == 0xFFFF_FFFF {+ ctx.hierarchy = false;+ ctx.iterations = 0;+ scratch.reset();+ heap.clear();+ seed(g, traffic, &ctx.start, &ctx.end, mode, scratch, heap);+ search(g, traffic, ensure_traffic, mode, ctx, scratch, heap);+ }+}++fn search(+ g: &Graph,+ traffic: &TrafficSpeeds,+ ensure_traffic: &mut dyn FnMut(i32, i32),+ mode: i32,+ ctx: &mut RoutingContext,+ scratch: &mut RoutingScratchpad,+ heap: &mut RadixHeap, ) { // Cap is a safety net only. The 36M-node CA graph needs ~6.4M expansions for // the longest routes (SF->LA), so the old 1M cap aborted them ("no route").@@ -414,18 +484,27 @@ pub fn perform_search_loop( // apart rather than a few metres, so the wrong choice costs the length of // the street. Score both completions and keep the better one. let mut best_total = u32::MAX;+ let n_full = g.node_count;+ let overlay = if ctx.hierarchy { g.overlay() } else { None };+ let (end_lat, end_lon) = (ctx.end.proj_lat, ctx.end.proj_lon); while !heap.empty() && ctx.iterations < 25_000_000 { ctx.iterations += 1; let (score, u) = heap.pop(); let u_cost = scratch.get_entry(u).g_fwd;- if u >= g.node_count {- continue;- }- let n_u = g.node(u);- let h_u = heuristic_time_10ms(- g, n_u.lat_e7, n_u.lon_e7, ctx.end.proj_lat, ctx.end.proj_lon, mode,- );+ let (lat_u, lon_u) = if u < n_full {+ let n = g.node(u);+ (n.lat_e7, n.lon_e7)+ } else {+ match overlay {+ Some(ov) if u - n_full < ov.node_count => {+ let n = ov.node(u - n_full);+ (n.lat_e7, n.lon_e7)+ }+ _ => continue,+ }+ };+ let h_u = heuristic_time_10ms(g, lat_u, lon_u, end_lat, end_lon, mode); // A node is re-pushed every time its cost improves, so older entries for it // linger in the heap. The fresh entry pops first and already expanded the // node at this same cost, so expanding a stale one again finds nothing new.@@ -458,37 +537,69 @@ pub fn perform_search_loop( } if mode == DRIVING {- ensure_traffic(n_u.lat_e7, n_u.lon_e7);+ ensure_traffic(lat_u, lon_u); }- let (s, e_ptr) = g.edge_range(u); - for i in s..e_ptr {- let edge = g.edge(u, i);- if !is_mode_allowed(edge.type_, mode) {- continue;+ let mut improve = |v: u32, new_g: u32| -> bool {+ let entry_v = scratch.get_entry(v);+ let better = new_g < entry_v.g_fwd;+ if better {+ entry_v.g_fwd = new_g;+ entry_v.p_fwd = u; }-- let travel_time =- get_edge_time_10ms(g, traffic, i, edge.dist_mm, edge.type_, edge.speed_limit, mode);-- let v = edge.target;- let new_g = u_cost.wrapping_add(travel_time);- let update = {- let entry_v = scratch.get_entry(v);- if new_g < entry_v.g_fwd {- entry_v.g_fwd = new_g;- entry_v.p_fwd = u;- true- } else {- false+ better+ };+ let mut push = |v: u32, new_g: u32, lat_v: i32, lon_v: i32| {+ heap.push(new_g.wrapping_add(heuristic_time_10ms(g, lat_v, lon_v, end_lat, end_lon, mode)), v);+ };++ if u >= n_full {+ let Some(ov) = overlay else { continue };+ let o = u - n_full;+ let (s, e_ptr) = ov.edge_range(o);+ for i in s..e_ptr {+ let edge = ov.edge(i);+ if edge.target >= ov.node_count || !is_mode_allowed(edge.type_, mode) {+ continue; }- };- if update {- let n_v = g.get_node(v);- let h = heuristic_time_10ms(- g, n_v.lat_e7, n_v.lon_e7, ctx.end.proj_lat, ctx.end.proj_lon, mode,+ let travel_time = get_edge_time_10ms(+ g, traffic, edge.full_edge, edge.dist_mm, edge.type_, edge.speed_limit, mode, );- heap.push(new_g.wrapping_add(h), v);+ let (v, new_g) = (n_full + edge.target, u_cost.wrapping_add(travel_time));+ if improve(v, new_g) {+ let t = ov.node(edge.target);+ push(v, new_g, t.lat_e7, t.lon_e7);+ }+ }+ // Back onto the full graph only where the destination's local roads are.+ if near_end(g, lat_u, lon_u, ctx) {+ let full = ov.node(o).full_node;+ if improve(full, u_cost) {+ push(full, u_cost, lat_u, lon_u);+ }+ }+ continue;+ }++ if overlay.is_none() || is_local(g, lat_u, lon_u, ctx) {+ let (s, e_ptr) = g.edge_range(u);+ for i in s..e_ptr {+ let edge = g.edge(u, i);+ if !is_mode_allowed(edge.type_, mode) {+ continue;+ }+ let travel_time =+ get_edge_time_10ms(g, traffic, i, edge.dist_mm, edge.type_, edge.speed_limit, mode);+ let new_g = u_cost.wrapping_add(travel_time);+ if improve(edge.target, new_g) {+ let n_v = g.get_node(edge.target);+ push(edge.target, new_g, n_v.lat_e7, n_v.lon_e7);+ }+ }+ }+ if let Some(o) = overlay.and_then(|ov| ov.of_full(u)) {+ if improve(n_full + o, u_cost) {+ push(n_full + o, u_cost, lat_u, lon_u); } } }
maps/src/main/rust/src/routing/steps/reconstruct.rs
diff --git a/maps/src/main/rust/src/routing/steps/reconstruct.rs b/maps/src/main/rust/src/routing/steps/reconstruct.rsindex f506bb486b..55338bf4ec 100644--- a/maps/src/main/rust/src/routing/steps/reconstruct.rs+++ b/maps/src/main/rust/src/routing/steps/reconstruct.rs@@ -88,7 +88,13 @@ pub fn reconstruct_path( let mut curr = ctx.target_node; let mut safety = 0u32; while curr != 0xFFFF_FFFF && safety < 1_000_000 {- path_nodes.push(curr);+ // Overlay hops name the same junction twice (full id, then overlay id),+ // and overlay edges are full-graph edges, so mapping back and dropping the+ // repeat leaves an ordinary full-graph path.+ let full = g.full_node_of(curr);+ if path_nodes.last() != Some(&full) {+ path_nodes.push(full);+ } curr = scratch.get_entry(curr).p_fwd; safety += 1; }