Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / overlay.rs

overlay.rs287 lines · 11.3 KiBRaw
1//! `overlay.bin`: the motorway/trunk/primary subgraph of a finished v7 graph,
2//! renumbered densely so a long on-device search reads contiguous blocks.
3//!
4//! Read side and layout: `maps/src/main/rust/src/graph_overlay.rs`; the two must
5//! agree byte for byte.
6//!
7//! ```text
8//! [magic "MOVL" u32][version u32]
9//! [full_node_count u64][full_edge_count u64]
10//! [overlay_node_count u64 M][overlay_edge_count u64 K]
11//! [nodes_len u64][edges_len u64]
12//! nodes: ZBLK, 16 B (lat_e7 i32, lon_e7 i32, edge_ptr u32, full_node u32), M + 1
13//! records, the sentinel's edge_ptr = K
14//! pad to 8
15//! edges: ZBLK, 20 B (target u32 overlay id, dist_mm u32, full_edge u64,
16//! type u8, speed_limit u8, pad u16), K records, grouped by source
17//! pad to 8
18//! portals: rank u64[N.div_ceil(512) + 1] then present u8[N.div_ceil(8)] over
19//! the full node ids; overlay id = rank(full id)
20//! ```
21//!
22//! Overlay ids are assigned in increasing full-id order, so they inherit the
23//! graph's spatial ordering and the rank is the whole id map.
24
25use std::io::{self, Write as _};
26use std::path::Path;
27
28use std::sync::atomic::{AtomicU8, Ordering};
29
30use tilecodec::blocked::{write_blocked_with, BlockCache, Blocked, BLOCKED_MAGIC, BLOCK_RECORDS};
31
32use crate::par;
33
34pub const OVERLAY_MAGIC: u32 = 0x4C56_4F4D;
35pub const OVERLAY_VERSION: u32 = 1;
36const NODE_LEN: usize = 16;
37const EDGE_LEN: usize = 20;
38const GRAPH_MAGIC: u32 = 0x4752_414D;
39const ESCAPE_BLOCK: u64 = 1024;
40const TARGET_DELTA_ESCAPE: i16 = i16::MIN;
41const DIST_MM_ESCAPE: u32 = 0xFF_FFFF;
42/// Road-class bits of an edge's type byte (bit 6 is the reverse-geometry flag).
43const CLASS_MASK: u8 = 0x3F;
44/// Highest road class on the overlay: motorway 1, trunk 2, primary 3 (their
45/// `*_link` ramps share the parent's number, see [`crate::tags::get_hw_id`]).
46const MAX_CLASS: u8 = 3;
47const RANK_BLOCK_BYTES: u64 = 64;
48
49#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
50pub struct OverlayStats {
51 pub full_nodes: u64,
52 pub full_edges: u64,
53 pub nodes: u64,
54 pub edges: u64,
55 pub bytes: u64,
56}
57
58fn bad(msg: impl Into<String>) -> io::Error {
59 io::Error::new(io::ErrorKind::InvalidData, msg.into())
60}
61
62fn map(path: &Path) -> io::Result<memmap2::Mmap> {
63 let f = std::fs::File::open(path)?;
64 // SAFETY: read-only map of a finished build output nothing else writes.
65 unsafe { memmap2::Mmap::map(&f) }
66}
67
68fn u32_at(b: &[u8], at: usize) -> u32 {
69 u32::from_le_bytes(b[at..at + 4].try_into().expect("4 bytes"))
70}
71
72fn u64_at(b: &[u8], at: usize) -> u64 {
73 u64::from_le_bytes(b[at..at + 8].try_into().expect("8 bytes"))
74}
75
76fn align8(n: u64) -> u64 {
77 (n + 7) & !7
78}
79
80/// One full-graph edge as the overlay needs it.
81#[derive(Clone, Copy)]
82struct FullEdge {
83 target: u32,
84 dist_mm: u32,
85 type_: u8,
86 speed_limit: u8,
87}
88
89/// Sequential reader over a v7 graph: visits every node in id order with its
90/// out-edges, inflating each block once.
91struct GraphWalk<'a> {
92 node_count: u32,
93 nodes: Blocked<'a>,
94 edges: Blocked<'a>,
95 edges_file: &'a [u8],
96 escape_rows_off: usize,
97 escape_count: u64,
98}
99
100impl<'a> GraphWalk<'a> {
101 fn open(meta: &[u8], nodes: &'a [u8], edges: &'a [u8]) -> io::Result<GraphWalk<'a>> {
102 if meta.len() < 40 || u32_at(meta, 0) != GRAPH_MAGIC {
103 return Err(bad("metadata.bin is not a MARG header"));
104 }
105 if u32_at(meta, 4) != 7 {
106 return Err(bad(format!(
107 "graph version {} — the overlay reads v7 only",
108 u32_at(meta, 4)
109 )));
110 }
111 let node_count = u64_at(meta, 8);
112 let edge_count = u64_at(meta, 16);
113 let escape_count = u64_at(meta, 24);
114 let node_count = u32::try_from(node_count).map_err(|_| bad("node count past u32"))?;
115 let nodes_b = Blocked::parse(nodes).map_err(|e| bad(format!("nodes.bin: {e}")))?;
116 let edges_b = Blocked::parse(edges).map_err(|e| bad(format!("edges.bin: {e}")))?;
117 if nodes_b.record_len() != 12 || nodes_b.unpacked_len() != (u64::from(node_count) + 1) * 12
118 {
119 return Err(bad("nodes.bin does not match the header's node count"));
120 }
121 if edges_b.record_len() != 7 || edges_b.unpacked_len() != edge_count * 7 {
122 return Err(bad("edges.bin does not match the header's edge count"));
123 }
124 let rec_end = edges_b
125 .block_offset(edges_b.block_count())
126 .ok_or_else(|| bad("edges.bin has no end offset"))?;
127 let escape_first_off = align8(rec_end);
128 let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;
129 let escape_rows_off = (escape_first_off + escape_blocks * 4) as usize;
130 if escape_rows_off as u64 + escape_count * 12 > edges.len() as u64 {
131 return Err(bad("edges.bin escape table runs past the file"));
132 }
133 Ok(GraphWalk {
134 node_count,
135 nodes: nodes_b,
136 edges: edges_b,
137 edges_file: edges,
138 escape_rows_off,
139 escape_count,
140 })
141 }
142
143 /// Node `id`'s record: `(lat_e7, lon_e7, edge_ptr)`, through `cache`.
144 fn node_at(&self, id: u64, cache: &mut BlockCache) -> io::Result<(i32, i32, u64)> {
145 let per = u64::from(BLOCK_RECORDS);
146 let b = cache
147 .get(&self.nodes, (id / per) as usize)
148 .map_err(|e| bad(format!("nodes.bin: {e}")))?;
149 let at = (id % per) as usize * 12;
150 let r = &b[at..at + 12];
151 Ok((
152 i32::from_le_bytes(r[0..4].try_into().expect("4")),
153 i32::from_le_bytes(r[4..8].try_into().expect("4")),
154 u64::from(u32::from_le_bytes(r[8..12].try_into().expect("4"))),
155 ))
156 }
157
158 /// The first escape row whose edge index is `>= edge`. Rows are written ascending by
159 /// edge index (the `edges.bin` contract), so this is a binary search; it is what lets a
160 /// walk start mid-graph with the same cursor a walk from node 0 would have reached.
161 fn escape_row_from(&self, edge: u64) -> u64 {
162 let idx =
163 |row: u64| u64::from(u32_at(self.edges_file, self.escape_rows_off + row as usize * 12));
164 let (mut lo, mut hi) = (0u64, self.escape_count);
165 while lo < hi {
166 let mid = lo + (hi - lo) / 2;
167 if idx(mid) < edge {
168 lo = mid + 1;
169 } else {
170 hi = mid;
171 }
172 }
173 lo
174 }
175
176 /// Call `f(u, lat_e7, lon_e7, &[(edge_idx, FullEdge)])` for every node.
177 #[cfg(test)]
178 fn for_each(
179 &self,
180 f: impl FnMut(u32, i32, i32, &[(u64, FullEdge)]) -> io::Result<()>,
181 ) -> io::Result<()> {
182 self.for_range(0, self.node_count, f)
183 }
184
185 /// [`for_each`](Self::for_each) over nodes `a..b` only, inflating each block it touches
186 /// once. Independent ranges share nothing, which is what lets the build walk them on
187 /// every core at once.
188 fn for_range(
189 &self,
190 a: u32,
191 b: u32,
192 mut f: impl FnMut(u32, i32, i32, &[(u64, FullEdge)]) -> io::Result<()>,
193 ) -> io::Result<()> {
194 let (mut ncache, mut ecache) = (BlockCache::new(1), BlockCache::new(1));
195 let per = u64::from(BLOCK_RECORDS);
196 let mut out: Vec<(u64, FullEdge)> = Vec::new();
197 let (mut lat, mut lon, mut lo) = self.node_at(u64::from(a), &mut ncache)?;
198 // A walk from node 0 starts its cursor at row 0, exactly as the sequential walk did.
199 let mut escape_row = if a == 0 { 0 } else { self.escape_row_from(lo) };
200 for u in a..b {
201 let (nlat, nlon, hi) = self.node_at(u64::from(u) + 1, &mut ncache)?;
202 out.clear();
203 for i in lo..hi {
204 let blk = ecache
205 .get(&self.edges, (i / per) as usize)
206 .map_err(|e| bad(format!("edges.bin: {e}")))?;
207 let at = (i % per) as usize * 7;
208 let r = &blk[at..at + 7];
209 let delta = i16::from_le_bytes([r[0], r[1]]);
210 let dist = u32::from_le_bytes([r[2], r[3], r[4], 0]);
211 let (target, dist_mm) = if delta == TARGET_DELTA_ESCAPE || dist == DIST_MM_ESCAPE {
212 // Escape rows are sorted by edge index, and edges are visited
213 // in index order, so one cursor finds every row.
214 loop {
215 if escape_row >= self.escape_count {
216 return Err(bad(format!("edge {i} is escaped but has no escape row")));
217 }
218 let at = self.escape_rows_off + escape_row as usize * 12;
219 let row = &self.edges_file[at..at + 12];
220 escape_row += 1;
221 if u64::from(u32_at(row, 0)) == i {
222 break (u32_at(row, 4), u32_at(row, 8));
223 }
224 }
225 } else {
226 (u.wrapping_add_signed(i32::from(delta)), dist)
227 };
228 out.push((i, FullEdge { target, dist_mm, type_: r[5], speed_limit: r[6] }));
229 }
230 f(u, lat, lon, &out)?;
231 (lat, lon, lo) = (nlat, nlon, hi);
232 }
233 Ok(())
234 }
235}
236
237fn on_overlay(type_: u8) -> bool {
238 (1..=MAX_CLASS).contains(&(type_ & CLASS_MASK))
239}
240
241/// Nodes per parallel work unit: four 4096-record node blocks.
242///
243/// The output never depends on it — every unit's result is merged in unit order — but it
244/// is a constant rather than a function of the core count so the work split is the same
245/// on every machine. Small enough that California (7.2 M nodes) still yields ~440 units
246/// for 192 threads; large enough that the one edge block a unit shares with its neighbour
247/// (inflated by both) is a few percent of its work.
248const CHUNK_NODES: u32 = 4 * BLOCK_RECORDS;
249
250/// Pass 1's per-unit result: the arterial out-edges in node order, and the coordinates of
251/// every node that owns one, so pass 2 needs to re-inflate no edge block at all and only
252/// the node blocks holding an overlay node that is a target and never a source.
253#[derive(Default)]
254struct Arterials {
255 sources: Vec<(u32, i32, i32)>,
256 edges: Vec<(u32, u64, FullEdge)>,
257}
258
259/// One unit's emitted records. `nodes`' `edge_ptr` fields are relative to the unit and
260/// rebased in the ordered merge, once every earlier unit's edge count is known.
261struct Emitted {
262 nodes: Vec<u8>,
263 edges: Vec<u8>,
264 edge_count: u64,
265}
266
267/// Build `overlay.bin` beside the graph in `graph_dir` (or at `out`).
268pub fn build(graph_dir: &Path, out: &Path) -> io::Result<OverlayStats> {
269 let meta = std::fs::read(graph_dir.join("metadata.bin"))?;
270 let nodes = map(&graph_dir.join("nodes.bin"))?;
271 let edges = map(&graph_dir.join("edges.bin"))?;
272 build_from(&meta, &nodes, &edges, out)
273}
274
275/// [`build`] over section bytes, so an archive's graph sections can be used
276/// without unpacking them to a directory.
277///
278/// Parallel and deterministic: the graph is cut into fixed [`CHUNK_NODES`] ranges, each
279/// walked on its own thread by [`par::map_chunks`], and every per-range result is merged in
280/// range order, so the file is byte-identical at any thread count — and to the sequential
281/// two-walk builder this replaced, which spent its whole run inflating every `nodes.bin`
282/// and `edges.bin` block twice on one core.
283pub fn build_from(meta: &[u8], nodes: &[u8], edges: &[u8], out: &Path) -> io::Result<OverlayStats> {
284 build_from_chunked(meta, nodes, edges, out, CHUNK_NODES)
285}
286
287include!("overlay_s1.rs");