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

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

overlay.rs397 lines · 16.9 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 tilecodec::blocked::{BlockCache, Blocked, BlockedStreamWriter};
29
30pub const OVERLAY_MAGIC: u32 = 0x4C56_4F4D;
31pub const OVERLAY_VERSION: u32 = 1;
32const NODE_LEN: usize = 16;
33const EDGE_LEN: usize = 20;
34const GRAPH_MAGIC: u32 = 0x4752_414D;
35const ESCAPE_BLOCK: u64 = 1024;
36const TARGET_DELTA_ESCAPE: i16 = i16::MIN;
37const DIST_MM_ESCAPE: u32 = 0xFF_FFFF;
38/// Road-class bits of an edge's type byte (bit 6 is the reverse-geometry flag).
39const CLASS_MASK: u8 = 0x3F;
40/// Highest road class on the overlay: motorway 1, trunk 2, primary 3 (their
41/// `*_link` ramps share the parent's number, see [`crate::tags::get_hw_id`]).
42const MAX_CLASS: u8 = 3;
43const RANK_BLOCK_BYTES: u64 = 64;
44
45#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
46pub struct OverlayStats {
47 pub full_nodes: u64,
48 pub full_edges: u64,
49 pub nodes: u64,
50 pub edges: u64,
51 pub bytes: u64,
52}
53
54fn bad(msg: impl Into<String>) -> io::Error {
55 io::Error::new(io::ErrorKind::InvalidData, msg.into())
56}
57
58fn map(path: &Path) -> io::Result<memmap2::Mmap> {
59 let f = std::fs::File::open(path)?;
60 // SAFETY: read-only map of a finished build output nothing else writes.
61 unsafe { memmap2::Mmap::map(&f) }
62}
63
64fn u32_at(b: &[u8], at: usize) -> u32 {
65 u32::from_le_bytes(b[at..at + 4].try_into().expect("4 bytes"))
66}
67
68fn u64_at(b: &[u8], at: usize) -> u64 {
69 u64::from_le_bytes(b[at..at + 8].try_into().expect("8 bytes"))
70}
71
72fn align8(n: u64) -> u64 {
73 (n + 7) & !7
74}
75
76/// One full-graph edge as the overlay needs it.
77#[derive(Clone, Copy)]
78struct FullEdge {
79 target: u32,
80 dist_mm: u32,
81 type_: u8,
82 speed_limit: u8,
83}
84
85/// Sequential reader over a v7 graph: visits every node in id order with its
86/// out-edges, inflating each block once.
87struct GraphWalk<'a> {
88 node_count: u32,
89 nodes: Blocked<'a>,
90 edges: Blocked<'a>,
91 edges_file: &'a [u8],
92 escape_rows_off: usize,
93 escape_count: u64,
94}
95
96impl<'a> GraphWalk<'a> {
97 fn open(meta: &[u8], nodes: &'a [u8], edges: &'a [u8]) -> io::Result<GraphWalk<'a>> {
98 if meta.len() < 40 || u32_at(meta, 0) != GRAPH_MAGIC {
99 return Err(bad("metadata.bin is not a MARG header"));
100 }
101 if u32_at(meta, 4) != 7 {
102 return Err(bad(format!("graph version {} — the overlay reads v7 only", u32_at(meta, 4))));
103 }
104 let node_count = u64_at(meta, 8);
105 let edge_count = u64_at(meta, 16);
106 let escape_count = u64_at(meta, 24);
107 let node_count = u32::try_from(node_count).map_err(|_| bad("node count past u32"))?;
108 let nodes_b = Blocked::parse(nodes).map_err(|e| bad(format!("nodes.bin: {e}")))?;
109 let edges_b = Blocked::parse(edges).map_err(|e| bad(format!("edges.bin: {e}")))?;
110 if nodes_b.record_len() != 12 || nodes_b.unpacked_len() != (u64::from(node_count) + 1) * 12 {
111 return Err(bad("nodes.bin does not match the header's node count"));
112 }
113 if edges_b.record_len() != 7 || edges_b.unpacked_len() != edge_count * 7 {
114 return Err(bad("edges.bin does not match the header's edge count"));
115 }
116 let rec_end = edges_b.block_offset(edges_b.block_count()).ok_or_else(|| bad("edges.bin has no end offset"))?;
117 let escape_first_off = align8(rec_end);
118 let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;
119 let escape_rows_off = (escape_first_off + escape_blocks * 4) as usize;
120 if escape_rows_off as u64 + escape_count * 12 > edges.len() as u64 {
121 return Err(bad("edges.bin escape table runs past the file"));
122 }
123 Ok(GraphWalk {
124 node_count,
125 nodes: nodes_b,
126 edges: edges_b,
127 edges_file: edges,
128 escape_rows_off,
129 escape_count,
130 })
131 }
132
133 /// Call `f(u, lat_e7, lon_e7, &[(edge_idx, FullEdge)])` for every node.
134 fn for_each(&self, mut f: impl FnMut(u32, i32, i32, &[(u64, FullEdge)]) -> io::Result<()>) -> io::Result<()> {
135 let (mut ncache, mut ecache) = (BlockCache::new(1), BlockCache::new(1));
136 let per = 4096u64;
137 let mut node_rec = |id: u64, cache: &mut BlockCache| -> io::Result<(i32, i32, u64)> {
138 let b = cache.get(&self.nodes, (id / per) as usize).map_err(|e| bad(format!("nodes.bin: {e}")))?;
139 let at = (id % per) as usize * 12;
140 let r = &b[at..at + 12];
141 Ok((
142 i32::from_le_bytes(r[0..4].try_into().expect("4")),
143 i32::from_le_bytes(r[4..8].try_into().expect("4")),
144 u64::from(u32::from_le_bytes(r[8..12].try_into().expect("4"))),
145 ))
146 };
147 let mut escape_row = 0u64;
148 let mut out: Vec<(u64, FullEdge)> = Vec::new();
149 let (mut lat, mut lon, mut lo) = node_rec(0, &mut ncache)?;
150 for u in 0..self.node_count {
151 let (nlat, nlon, hi) = node_rec(u64::from(u) + 1, &mut ncache)?;
152 out.clear();
153 for i in lo..hi {
154 let b = ecache.get(&self.edges, (i / per) as usize).map_err(|e| bad(format!("edges.bin: {e}")))?;
155 let at = (i % per) as usize * 7;
156 let r = &b[at..at + 7];
157 let delta = i16::from_le_bytes([r[0], r[1]]);
158 let dist = u32::from_le_bytes([r[2], r[3], r[4], 0]);
159 let (target, dist_mm) = if delta == TARGET_DELTA_ESCAPE || dist == DIST_MM_ESCAPE {
160 // Escape rows are sorted by edge index, and edges are visited
161 // in index order, so one cursor finds every row.
162 loop {
163 if escape_row >= self.escape_count {
164 return Err(bad(format!("edge {i} is escaped but has no escape row")));
165 }
166 let at = self.escape_rows_off + escape_row as usize * 12;
167 let row = &self.edges_file[at..at + 12];
168 escape_row += 1;
169 if u64::from(u32_at(row, 0)) == i {
170 break (u32_at(row, 4), u32_at(row, 8));
171 }
172 }
173 } else {
174 (u.wrapping_add_signed(i32::from(delta)), dist)
175 };
176 out.push((i, FullEdge { target, dist_mm, type_: r[5], speed_limit: r[6] }));
177 }
178 f(u, lat, lon, &out)?;
179 (lat, lon, lo) = (nlat, nlon, hi);
180 }
181 Ok(())
182 }
183}
184
185fn on_overlay(type_: u8) -> bool {
186 (1..=MAX_CLASS).contains(&(type_ & CLASS_MASK))
187}
188
189/// Build `overlay.bin` beside the graph in `graph_dir` (or at `out`).
190pub fn build(graph_dir: &Path, out: &Path) -> io::Result<OverlayStats> {
191 let meta = std::fs::read(graph_dir.join("metadata.bin"))?;
192 let nodes = map(&graph_dir.join("nodes.bin"))?;
193 let edges = map(&graph_dir.join("edges.bin"))?;
194 build_from(&meta, &nodes, &edges, out)
195}
196
197/// [`build`] over section bytes, so an archive's graph sections can be used
198/// without unpacking them to a directory.
199pub fn build_from(meta: &[u8], nodes: &[u8], edges: &[u8], out: &Path) -> io::Result<OverlayStats> {
200 let walk = GraphWalk::open(meta, nodes, edges)?;
201 let n = walk.node_count as u64;
202 let full_edges = u64_at(meta, 16);
203
204 // Pass 1: every endpoint of an arterial edge is on the overlay.
205 let mut present = vec![0u8; n.div_ceil(8) as usize];
206 let mut set = |id: u32| present[(id / 8) as usize] |= 1 << (id % 8);
207 walk.for_each(|u, _, _, es| {
208 for (_, e) in es.iter().filter(|(_, e)| on_overlay(e.type_)) {
209 if u64::from(e.target) >= n {
210 return Err(bad(format!("edge from {u} targets {} past the node count", e.target)));
211 }
212 set(u);
213 set(e.target);
214 }
215 Ok(())
216 })?;
217
218 // Rank index: set bits before each 64-byte block, then the total.
219 let blocks = n.div_ceil(RANK_BLOCK_BYTES * 8);
220 let mut rank = Vec::with_capacity(blocks as usize + 1);
221 let mut running = 0u64;
222 for b in 0..=blocks {
223 rank.push(running);
224 let lo = (b * RANK_BLOCK_BYTES) as usize;
225 let hi = (lo + RANK_BLOCK_BYTES as usize).min(present.len());
226 if lo < hi {
227 running += present[lo..hi].iter().map(|x| u64::from(x.count_ones())).sum::<u64>();
228 }
229 }
230 let m = running;
231 let of = |id: u32| -> u32 {
232 let byte = u64::from(id) / 8;
233 let block = byte / RANK_BLOCK_BYTES;
234 let mut r = rank[block as usize];
235 for x in &present[(block * RANK_BLOCK_BYTES) as usize..byte as usize] {
236 r += u64::from(x.count_ones());
237 }
238 (r + u64::from((present[byte as usize] & ((1u8 << (id % 8)) - 1)).count_ones())) as u32
239 };
240 let is_set = |id: u32| present[(id / 8) as usize] & (1 << (id % 8)) != 0;
241
242 // Pass 2: emit nodes in full-id order with their arterial out-edges.
243 let tmp = |s: &str| out.with_extension(s);
244 let mut node_w = BlockedStreamWriter::create(NODE_LEN, &tmp("nodes.tmp"))?;
245 let mut edge_w = BlockedStreamWriter::create(EDGE_LEN, &tmp("edges.tmp"))?;
246 let mut k = 0u64;
247 walk.for_each(|u, lat, lon, es| {
248 if !is_set(u) {
249 return Ok(());
250 }
251 let ptr = u32::try_from(k).map_err(|_| bad("overlay edge count past u32"))?;
252 let mut rec = [0u8; NODE_LEN];
253 rec[0..4].copy_from_slice(&lat.to_le_bytes());
254 rec[4..8].copy_from_slice(&lon.to_le_bytes());
255 rec[8..12].copy_from_slice(&ptr.to_le_bytes());
256 rec[12..16].copy_from_slice(&u.to_le_bytes());
257 node_w.push(&rec)?;
258 for (i, e) in es.iter().filter(|(_, e)| on_overlay(e.type_)) {
259 let mut rec = [0u8; EDGE_LEN];
260 rec[0..4].copy_from_slice(&of(e.target).to_le_bytes());
261 rec[4..8].copy_from_slice(&e.dist_mm.to_le_bytes());
262 rec[8..16].copy_from_slice(&i.to_le_bytes());
263 rec[16] = e.type_;
264 rec[17] = e.speed_limit;
265 edge_w.push(&rec)?;
266 k += 1;
267 }
268 Ok(())
269 })?;
270 let mut sentinel = [0u8; NODE_LEN];
271 sentinel[8..12].copy_from_slice(&u32::try_from(k).map_err(|_| bad("overlay edge count past u32"))?.to_le_bytes());
272 sentinel[12..16].copy_from_slice(&u32::MAX.to_le_bytes());
273 node_w.push(&sentinel)?;
274 let nodes_sec = node_w.finish()?;
275 let edges_sec = edge_w.finish()?;
276
277 let mut f = io::BufWriter::new(std::fs::File::create(out)?);
278 f.write_all(&OVERLAY_MAGIC.to_le_bytes())?;
279 f.write_all(&OVERLAY_VERSION.to_le_bytes())?;
280 for v in [n, full_edges, m, k, nodes_sec.len() as u64, edges_sec.len() as u64] {
281 f.write_all(&v.to_le_bytes())?;
282 }
283 let nodes_end = 56 + nodes_sec.len() as u64;
284 let edges_end = align8(nodes_end) + edges_sec.len() as u64;
285 f.write_all(&nodes_sec)?;
286 f.write_all(&vec![0u8; (align8(nodes_end) - nodes_end) as usize])?;
287 f.write_all(&edges_sec)?;
288 f.write_all(&vec![0u8; (align8(edges_end) - edges_end) as usize])?;
289 for r in &rank {
290 f.write_all(&r.to_le_bytes())?;
291 }
292 f.write_all(&present)?;
293 f.flush()?;
294 let bytes = align8(edges_end) + rank.len() as u64 * 8 + present.len() as u64;
295 Ok(OverlayStats { full_nodes: n, full_edges, nodes: m, edges: k, bytes })
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301
302 /// A motorway A-B-C, a motorway_link C-D, residential D-E and B-F.
303 fn sample(tag: &str) -> std::path::PathBuf {
304 let p = |i: i32| (370_000_000 + i * 10_000, -1_220_000_000 + i * 10_000);
305 let nodes: Vec<(i64, i32, i32)> = (1..=6).map(|id| (id as i64, p(id).0, p(id).1)).collect();
306 let nodes = [nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], (6, p(2).0 + 5_000, p(2).1 - 5_000)];
307 let ways: [(i64, &str, &[i64]); 4] = [
308 (10, "motorway", &[1, 2, 3]),
309 (11, "motorway_link", &[3, 4]),
310 (12, "residential", &[4, 5]),
311 (13, "residential", &[2, 6]),
312 ];
313 let (pbf, dir) = crate::testpbf::write_highway_sample(tag, &nodes, &ways);
314 crate::graph_build::build(&pbf, &dir).unwrap();
315 dir
316 }
317
318 struct Decoded {
319 header: [u64; 6],
320 nodes: Vec<(i32, i32, u32, u32)>,
321 edges: Vec<(u32, u32, u64, u8)>,
322 }
323
324 fn decode(bytes: &[u8]) -> Decoded {
325 assert_eq!(u32_at(bytes, 0), OVERLAY_MAGIC);
326 assert_eq!(u32_at(bytes, 4), OVERLAY_VERSION);
327 let header: [u64; 6] = std::array::from_fn(|i| u64_at(bytes, 8 + i * 8));
328 let (nodes_len, edges_len) = (header[4] as usize, header[5] as usize);
329 let inflate = |b: &[u8]| {
330 let v = Blocked::parse(b).unwrap();
331 let mut c = BlockCache::new(0);
332 (0..v.block_count()).flat_map(|i| c.get(&v, i).unwrap().clone()).collect::<Vec<u8>>()
333 };
334 let nb = inflate(&bytes[56..56 + nodes_len]);
335 let edges_at = align8(56 + nodes_len as u64) as usize;
336 let eb = inflate(&bytes[edges_at..edges_at + edges_len]);
337 let nodes = nb
338 .chunks(NODE_LEN)
339 .map(|r| (i32::from_le_bytes(r[0..4].try_into().unwrap()), i32::from_le_bytes(r[4..8].try_into().unwrap()), u32_at(r, 8), u32_at(r, 12)))
340 .collect();
341 let edges = eb.chunks(EDGE_LEN).map(|r| (u32_at(r, 0), u32_at(r, 4), u64_at(r, 8), r[16])).collect();
342 Decoded { header, nodes, edges }
343 }
344
345 #[test]
346 fn the_overlay_holds_the_arterials_and_their_ramps_only() {
347 let dir = sample("overlay_arterials");
348 let out = dir.join("overlay.bin");
349 let stats = build(&dir, &out).unwrap();
350 let d = decode(&std::fs::read(&out).unwrap());
351 assert_eq!(d.header[0], stats.full_nodes);
352 assert_eq!((d.header[2], d.header[3]), (stats.nodes, stats.edges));
353 assert_eq!(d.nodes.len() as u64, stats.nodes + 1, "plus the sentinel");
354 assert_eq!(d.nodes.last().unwrap().2 as u64, stats.edges, "sentinel edge_ptr is K");
355 // Coordinates identify the full nodes regardless of compaction.
356 let p = |i: i32| (370_000_000 + i * 10_000, -1_220_000_000 + i * 10_000);
357 let coords: Vec<(i32, i32)> = d.nodes[..stats.nodes as usize].iter().map(|n| (n.0, n.1)).collect();
358 for id in [1, 4] {
359 assert!(coords.contains(&p(id)), "motorway end / ramp end {id} is on the overlay");
360 }
361 assert!(!coords.contains(&p(5)), "the residential-only end is not");
362 // Each overlay edge is the full edge it names: same source, same target.
363 let meta = std::fs::read(dir.join("metadata.bin")).unwrap();
364 let (nodes, edges) = (map(&dir.join("nodes.bin")).unwrap(), map(&dir.join("edges.bin")).unwrap());
365 let walk = GraphWalk::open(&meta, &nodes, &edges).unwrap();
366 let mut full: Vec<(u32, u64, u32, u8)> = Vec::new();
367 walk.for_each(|u, _, _, es| {
368 full.extend(es.iter().map(|(i, e)| (u, *i, e.target, e.type_)));
369 Ok(())
370 })
371 .unwrap();
372 let mut k = 0usize;
373 for (o, n) in d.nodes[..stats.nodes as usize].iter().enumerate() {
374 let end = d.nodes[o + 1].2 as usize;
375 for &(t, _, full_edge, ty) in &d.edges[n.2 as usize..end] {
376 let &(src, _, tgt, fty) = full.iter().find(|f| f.1 == full_edge).unwrap();
377 assert_eq!(src, n.3, "overlay node {o} owns full edge {full_edge}");
378 assert_eq!(tgt, d.nodes[t as usize].3, "target maps back");
379 assert_eq!(ty, fty);
380 assert!(on_overlay(ty));
381 k += 1;
382 }
383 }
384 assert_eq!(k as u64, stats.edges);
385 assert_eq!(k, full.iter().filter(|f| on_overlay(f.3)).count(), "every arterial edge, nothing else");
386 // Full ids ascend, so the rank map is exact.
387 assert!(d.nodes[..stats.nodes as usize].windows(2).all(|w| w[0].3 < w[1].3));
388 }
389
390 #[test]
391 fn the_overlay_is_byte_identical_across_runs() {
392 let dir = sample("overlay_determinism");
393 build(&dir, &dir.join("a.bin")).unwrap();
394 build(&dir, &dir.join("b.bin")).unwrap();
395 assert_eq!(std::fs::read(dir.join("a.bin")).unwrap(), std::fs::read(dir.join("b.bin")).unwrap());
396 }
397}