//! `overlay.bin`: the motorway/trunk/primary subgraph of a finished v7 graph, //! renumbered densely so a long on-device search reads contiguous blocks. //! //! Read side and layout: `maps/src/main/rust/src/graph_overlay.rs`; the two must //! agree byte for byte. //! //! ```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: rank u64[N.div_ceil(512) + 1] then present u8[N.div_ceil(8)] over //! the full node ids; overlay id = rank(full id) //! ``` //! //! Overlay ids are assigned in increasing full-id order, so they inherit the //! graph's spatial ordering and the rank is the whole id map. use std::io::{self, Write as _}; use std::path::Path; use std::sync::atomic::{AtomicU8, Ordering}; use tilecodec::blocked::{write_blocked_with, BlockCache, Blocked, BLOCKED_MAGIC, BLOCK_RECORDS}; use crate::par; pub const OVERLAY_MAGIC: u32 = 0x4C56_4F4D; pub const OVERLAY_VERSION: u32 = 1; const NODE_LEN: usize = 16; const EDGE_LEN: usize = 20; const GRAPH_MAGIC: u32 = 0x4752_414D; const ESCAPE_BLOCK: u64 = 1024; const TARGET_DELTA_ESCAPE: i16 = i16::MIN; const DIST_MM_ESCAPE: u32 = 0xFF_FFFF; /// Road-class bits of an edge's type byte (bit 6 is the reverse-geometry flag). const CLASS_MASK: u8 = 0x3F; /// Highest road class on the overlay: motorway 1, trunk 2, primary 3 (their /// `*_link` ramps share the parent's number, see [`crate::tags::get_hw_id`]). const MAX_CLASS: u8 = 3; const RANK_BLOCK_BYTES: u64 = 64; #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct OverlayStats { pub full_nodes: u64, pub full_edges: u64, pub nodes: u64, pub edges: u64, pub bytes: u64, } fn bad(msg: impl Into) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, msg.into()) } fn map(path: &Path) -> io::Result { let f = std::fs::File::open(path)?; // SAFETY: read-only map of a finished build output nothing else writes. unsafe { memmap2::Mmap::map(&f) } } fn u32_at(b: &[u8], at: usize) -> u32 { u32::from_le_bytes(b[at..at + 4].try_into().expect("4 bytes")) } fn u64_at(b: &[u8], at: usize) -> u64 { u64::from_le_bytes(b[at..at + 8].try_into().expect("8 bytes")) } fn align8(n: u64) -> u64 { (n + 7) & !7 } /// One full-graph edge as the overlay needs it. #[derive(Clone, Copy)] struct FullEdge { target: u32, dist_mm: u32, type_: u8, speed_limit: u8, } /// Sequential reader over a v7 graph: visits every node in id order with its /// out-edges, inflating each block once. struct GraphWalk<'a> { node_count: u32, nodes: Blocked<'a>, edges: Blocked<'a>, edges_file: &'a [u8], escape_rows_off: usize, escape_count: u64, } impl<'a> GraphWalk<'a> { fn open(meta: &[u8], nodes: &'a [u8], edges: &'a [u8]) -> io::Result> { if meta.len() < 40 || u32_at(meta, 0) != GRAPH_MAGIC { return Err(bad("metadata.bin is not a MARG header")); } if u32_at(meta, 4) != 7 { return Err(bad(format!( "graph version {} — the overlay reads v7 only", u32_at(meta, 4) ))); } let node_count = u64_at(meta, 8); let edge_count = u64_at(meta, 16); let escape_count = u64_at(meta, 24); let node_count = u32::try_from(node_count).map_err(|_| bad("node count past u32"))?; let nodes_b = Blocked::parse(nodes).map_err(|e| bad(format!("nodes.bin: {e}")))?; let edges_b = Blocked::parse(edges).map_err(|e| bad(format!("edges.bin: {e}")))?; if nodes_b.record_len() != 12 || nodes_b.unpacked_len() != (u64::from(node_count) + 1) * 12 { return Err(bad("nodes.bin does not match the header's node count")); } if edges_b.record_len() != 7 || edges_b.unpacked_len() != edge_count * 7 { return Err(bad("edges.bin does not match the header's edge count")); } let rec_end = edges_b .block_offset(edges_b.block_count()) .ok_or_else(|| bad("edges.bin has no end offset"))?; let escape_first_off = align8(rec_end); let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1; let escape_rows_off = (escape_first_off + escape_blocks * 4) as usize; if escape_rows_off as u64 + escape_count * 12 > edges.len() as u64 { return Err(bad("edges.bin escape table runs past the file")); } Ok(GraphWalk { node_count, nodes: nodes_b, edges: edges_b, edges_file: edges, escape_rows_off, escape_count, }) } /// Node `id`'s record: `(lat_e7, lon_e7, edge_ptr)`, through `cache`. fn node_at(&self, id: u64, cache: &mut BlockCache) -> io::Result<(i32, i32, u64)> { let per = u64::from(BLOCK_RECORDS); let b = cache .get(&self.nodes, (id / per) as usize) .map_err(|e| bad(format!("nodes.bin: {e}")))?; let at = (id % per) as usize * 12; let r = &b[at..at + 12]; Ok(( i32::from_le_bytes(r[0..4].try_into().expect("4")), i32::from_le_bytes(r[4..8].try_into().expect("4")), u64::from(u32::from_le_bytes(r[8..12].try_into().expect("4"))), )) } /// The first escape row whose edge index is `>= edge`. Rows are written ascending by /// edge index (the `edges.bin` contract), so this is a binary search; it is what lets a /// walk start mid-graph with the same cursor a walk from node 0 would have reached. fn escape_row_from(&self, edge: u64) -> u64 { let idx = |row: u64| u64::from(u32_at(self.edges_file, self.escape_rows_off + row as usize * 12)); let (mut lo, mut hi) = (0u64, self.escape_count); while lo < hi { let mid = lo + (hi - lo) / 2; if idx(mid) < edge { lo = mid + 1; } else { hi = mid; } } lo } /// Call `f(u, lat_e7, lon_e7, &[(edge_idx, FullEdge)])` for every node. #[cfg(test)] fn for_each( &self, f: impl FnMut(u32, i32, i32, &[(u64, FullEdge)]) -> io::Result<()>, ) -> io::Result<()> { self.for_range(0, self.node_count, f) } /// [`for_each`](Self::for_each) over nodes `a..b` only, inflating each block it touches /// once. Independent ranges share nothing, which is what lets the build walk them on /// every core at once. fn for_range( &self, a: u32, b: u32, mut f: impl FnMut(u32, i32, i32, &[(u64, FullEdge)]) -> io::Result<()>, ) -> io::Result<()> { let (mut ncache, mut ecache) = (BlockCache::new(1), BlockCache::new(1)); let per = u64::from(BLOCK_RECORDS); let mut out: Vec<(u64, FullEdge)> = Vec::new(); let (mut lat, mut lon, mut lo) = self.node_at(u64::from(a), &mut ncache)?; // A walk from node 0 starts its cursor at row 0, exactly as the sequential walk did. let mut escape_row = if a == 0 { 0 } else { self.escape_row_from(lo) }; for u in a..b { let (nlat, nlon, hi) = self.node_at(u64::from(u) + 1, &mut ncache)?; out.clear(); for i in lo..hi { let blk = ecache .get(&self.edges, (i / per) as usize) .map_err(|e| bad(format!("edges.bin: {e}")))?; let at = (i % per) as usize * 7; let r = &blk[at..at + 7]; let delta = i16::from_le_bytes([r[0], r[1]]); let dist = u32::from_le_bytes([r[2], r[3], r[4], 0]); let (target, dist_mm) = if delta == TARGET_DELTA_ESCAPE || dist == DIST_MM_ESCAPE { // Escape rows are sorted by edge index, and edges are visited // in index order, so one cursor finds every row. loop { if escape_row >= self.escape_count { return Err(bad(format!("edge {i} is escaped but has no escape row"))); } let at = self.escape_rows_off + escape_row as usize * 12; let row = &self.edges_file[at..at + 12]; escape_row += 1; if u64::from(u32_at(row, 0)) == i { break (u32_at(row, 4), u32_at(row, 8)); } } } else { (u.wrapping_add_signed(i32::from(delta)), dist) }; out.push((i, FullEdge { target, dist_mm, type_: r[5], speed_limit: r[6] })); } f(u, lat, lon, &out)?; (lat, lon, lo) = (nlat, nlon, hi); } Ok(()) } } fn on_overlay(type_: u8) -> bool { (1..=MAX_CLASS).contains(&(type_ & CLASS_MASK)) } /// Nodes per parallel work unit: four 4096-record node blocks. /// /// The output never depends on it — every unit's result is merged in unit order — but it /// is a constant rather than a function of the core count so the work split is the same /// on every machine. Small enough that California (7.2 M nodes) still yields ~440 units /// for 192 threads; large enough that the one edge block a unit shares with its neighbour /// (inflated by both) is a few percent of its work. const CHUNK_NODES: u32 = 4 * BLOCK_RECORDS; /// Pass 1's per-unit result: the arterial out-edges in node order, and the coordinates of /// every node that owns one, so pass 2 needs to re-inflate no edge block at all and only /// the node blocks holding an overlay node that is a target and never a source. #[derive(Default)] struct Arterials { sources: Vec<(u32, i32, i32)>, edges: Vec<(u32, u64, FullEdge)>, } /// One unit's emitted records. `nodes`' `edge_ptr` fields are relative to the unit and /// rebased in the ordered merge, once every earlier unit's edge count is known. struct Emitted { nodes: Vec, edges: Vec, edge_count: u64, } /// Build `overlay.bin` beside the graph in `graph_dir` (or at `out`). pub fn build(graph_dir: &Path, out: &Path) -> io::Result { let meta = std::fs::read(graph_dir.join("metadata.bin"))?; let nodes = map(&graph_dir.join("nodes.bin"))?; let edges = map(&graph_dir.join("edges.bin"))?; build_from(&meta, &nodes, &edges, out) } /// [`build`] over section bytes, so an archive's graph sections can be used /// without unpacking them to a directory. /// /// Parallel and deterministic: the graph is cut into fixed [`CHUNK_NODES`] ranges, each /// walked on its own thread by [`par::map_chunks`], and every per-range result is merged in /// range order, so the file is byte-identical at any thread count — and to the sequential /// two-walk builder this replaced, which spent its whole run inflating every `nodes.bin` /// and `edges.bin` block twice on one core. pub fn build_from(meta: &[u8], nodes: &[u8], edges: &[u8], out: &Path) -> io::Result { build_from_chunked(meta, nodes, edges, out, CHUNK_NODES) } include!("overlay_s1.rs");