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

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

graph_build.rs470 lines · 20.9 KiBRaw
1//! Road-graph build: `.osm.pbf` -> `metadata.bin` / `nodes.bin` / `edges.bin` /
2//! `lanes.bin` / `intermediate.bin` / `road_names.bin` (+ optional `elevation.bin`).
3//!
4//! A port of the former `scripts/maps/generator.cpp`, preserving the on-disk
5//! contract byte for byte. The reader is `maps/src/main/rust/src/graph.rs`, which
6//! is the authority for every layout decision here:
7//!
8//! | File | Layout |
9//! |---|---|
10//! | `metadata.bin` | `u32 magic "MARG"`, `u32 version`, `u64 node_count`, `u64 edge_count`, `u64 escape_count`, `u64 named_edges` (40 B) |
11//! | `nodes.bin` | `NodeRec[node_count + 1]`, **12 bytes each**: `i32 lat_e7, i32 lon_e7, u32 edge_ptr`; the trailing sentinel's `edge_ptr` is `edge_count` |
12//! | `edges.bin` | `EdgeRec[edge_count]`, **7 bytes each**: `i16 target_delta, u24 dist_mm, u8 type, u8 speed_limit`; then padding, `u32 escape_first[E.div_ceil(1024) + 1]`, `(u32 edge_idx, u32 target, u32 dist_mm) x escape_count`, padding, and the sparse name table — a presence bitmap with a rank index plus `u32 name_off[named_edges]`. See [`EdgeFile`] |
13//! | `lanes.bin` | `u32 n`, then `(u32 edge_idx, u32 blob_byte_off) x (n + 1)` ascending by `edge_idx`, then the packed `u16` mask blob — **sparse**, only lane-bearing edges appear |
14//! | `intermediate.bin` | the delta-encoded polyline blob ([`crate::geom`]) at offset 0, then a trailer: `u64 rank[..]`, `u8 present[..]` (one bit per directed edge), `u64 coarse[..]`, `u16 within[..]` over the *geometry* edges, and `u64 G`. See [`GeomFile`] |
15//! | `road_names.bin` | deduped NUL-terminated string pool |
16//! | `elevation.bin` | **optional** `i16[node_count]` of per-node ground elevation in metres (WS-G), written only with `--dem`; a build without it is still valid and the device reads every node's elevation as 0 |
17//!
18//! Every file's length is now an exact function of `metadata.bin`'s counts, and
19//! the reader checks each one. `road_names.bin` is the exception: it is a byte pool
20//! with no count of its own, and reads into it are bounds-checked instead.
21//!
22//! Three behavioural notes where this differs from the C++:
23//!
24//! * It is **deterministic**. The C++ filled its node array via
25//! `idx.fetch_add(1)` from concurrent workers and interned names in
26//! thread-scheduling order, so its node order, `name_offset` values and
27//! therefore all of `road_names.bin`/`edges.bin`/`nodes.bin` differed between
28//! two runs of itself. Here every parallel stage merges per-chunk results in
29//! chunk order, so the output is a pure function of the input.
30//! * The C++ kept two bitsets, `useful_nodes_mask` and `road_nodes_mask`, but
31//! set and cleared them in exactly the same places, so they always held
32//! identical contents. One bitset does the same job for half the memory.
33//! * **Degree-2 chains are collapsed** ([`crate::compact`]) and the geometry they
34//! carried moves into `intermediate.bin`. Pass 3 therefore builds *undirected*
35//! segments and defers the split into directed edges until after compaction,
36//! because pairing a `u -> v` edge with its `v -> u` twin — which
37//! `REVERSE_GEOMETRY_FLAG` depends on — is only unambiguous while the two are
38//! still one object.
39//!
40//! # Passes, and why there are four
41//!
42//! 1. **Refs + stops** (nodes and ways): mark the node bitset. Nothing about a
43//! way is retained.
44//! 2. **Rank index**: `popcount` below an id becomes that node's address, so the
45//! node array is implicitly ordered by OSM id. That deletes the sorted
46//! `(osm_id, local_id)` table the edge pass used to binary-search, the
47//! per-node `osm_id`, and the per-node spatial key.
48//! 3. **Node scan**: scatter coordinates into their dense slots and record which
49//! slots a blob actually filled.
50//! 4. **Ways** (way blobs only): re-read them and emit segments directly.
51//!
52//! The order is not the obvious one. Pass 1 marks *every* ref of every routable
53//! way, including refs to nodes no blob in the file defines — an extract clipped
54//! at a boundary is full of them. Under dense addressing those refs own slots, so
55//! coordinates must be scattered, and their arrival recorded, *before* anything
56//! reads the node array; otherwise a dangling ref reads as `(0, 0)`.
57
58use std::fs::File;
59use std::io::{BufReader, BufWriter, Write};
60use std::path::{Path, PathBuf};
61
62use crate::compact::{self, Seg, REMOVED};
63use crate::chains;
64use crate::geom;
65use crate::names::{LocalNames, NamePool, NO_NAME};
66use crate::osm::{visit_block, Element};
67use crate::par;
68use crate::pbf::{self, KIND_NODES, KIND_WAYS};
69use crate::proto::{Error, Result};
70use crate::spatial::{accurate_dist_mm, spatial_from_e7};
71use rayon::prelude::*;
72use crate::tags;
73
74/// Node ids at or above this are skipped, exactly as in the C++. The bitset that
75/// tracks "is this node part of the graph" is sized from it (2.5 GB).
76pub const BITSET_SIZE: u64 = 20_000_000_000;
77
78/// `"MARG"` little-endian — `GRAPH_MAGIC` in `graph.rs`.
79const GRAPH_MAGIC: u32 = 0x4752_414D;
80/// Version 5 narrows an `edges.bin` record from 14 bytes to 11: `target` becomes an
81/// `i16` delta from the edge's source and `dist_mm` a `u24`, with one escape table
82/// behind the record array for the 0.3% that do not fit. Planet goes ~29.0 -> ~25.8
83/// GB, and every value stays *exact*.
84/// Version 6 moves `name_offset` out of the record into a sparse side table — two
85/// thirds of edges have no name — taking the record to 7 bytes and planet to ~23.3 GB.
86/// Version 7 blocked-compresses `nodes.bin`, `edges.bin` records and
87/// `elevation.bin` (ZBLK sections: zstd frames over 4096-record blocks behind
88/// a `u64` offset table). Same records, same order — only the container
89/// changes. Readers accept 6 and 7; writers emit 7.
90const GRAPH_VERSION: u32 = 7;
91/// Oldest graph version accepted: v6 raw tables still decode.
92const GRAPH_VERSION_MIN: u32 = 6;
93
94/// Geometry edges per coarse block in `intermediate.bin`'s two-level offset table
95/// — `INTERMEDIATE_BLOCK` in `graph.rs`, and the two must agree.
96///
97/// A per-edge blob is at most 1016 bytes ([`geom::MAX_POINTS`] points, of which
98/// only the interior is stored, 4 bytes each), so a block spans at most 32,512
99/// bytes and the within-block half fits a `u16`. [`GeomFile::push_entry`] asserts
100/// it. The table is indexed by an edge's *rank in the presence bitmap*, not by its
101/// edge index, so every entry in a block describes a real blob.
102const INTERMEDIATE_BLOCK: u64 = 32;
103
104/// Smallest connected component that counts as a real road network for the
105/// purpose of [`reconnect_isolated_stops`].
106///
107/// A stop already attached to a component this size is left alone; anything
108/// smaller is treated as a mapping artefact and reconnected. The threshold is
109/// capped at the largest component that actually exists, so a tiny graph — every
110/// fixture in this file — still reconnects against its own road network.
111const MIN_ROUTABLE_COMPONENT: u32 = 1000;
112
113/// Synthetic edges that reattach an isolated transit stop to the routable graph.
114const RECONNECT_TYPE: u8 = 12;
115const RECONNECT_SPEED: u8 = 5;
116
117/// Sentinel in a `CachedWay`/`TmpEdge` lane offset meaning "no lane data".
118const NO_LANES: u32 = 0xFFFF_FFFF;
119
120/// Sentinel in `TmpEdge::chain` meaning "this edge came from nowhere in
121/// particular" — currently only the synthetic transit-stop connectors, which are
122/// straight lines and so need no stored geometry.
123const NO_CHAIN: u32 = 0xFFFF_FFFF;
124
125/// `REVERSE_GEOMETRY_FLAG` in `graph.rs`: set in an edge's `type_` byte to mean
126/// "my geometry is my twin's, read backwards". Only one edge of a bidirectional
127/// pair stores the polyline, which halves the blob.
128///
129/// The reader locates the twin by scanning the *target's* edge range for an edge
130/// pointing back at the source, and takes the first match — so this may only be
131/// set when exactly one such edge exists. See [`twin_is_unique`].
132const REVERSE_GEOMETRY_FLAG: u8 = 0x40;
133
134/// Fallback stop code for a transit stop node with no `name`.
135const UNNAMED_STOP: &[u8] = b"OSM_STOP";
136
137/// Sentinel in a narrowed `target` delta meaning "this record's `target` and
138/// `dist_mm` both live in the escape table".
139///
140/// An `edges.bin` record stores `target` as an `i16` delta from the edge's own
141/// source rather than absolutely, which is only possible because the nodes are
142/// sorted by a space-filling curve and an edge is short: [`Census`] measures how
143/// often that fails. `i16::MIN` is reserved rather than used, so the representable
144/// range is symmetric at ±32767.
145const TARGET_DELTA_ESCAPE: i16 = i16::MIN;
146
147/// Sentinel in a narrowed `u24 dist_mm` meaning the same thing.
148///
149/// 0xFFFFFF mm is 16.78 km, which a collapsed degree-2 chain can exceed in empty
150/// country. One sentinel shared with [`TARGET_DELTA_ESCAPE`] means a single escape
151/// table serves both fields, so a `dist_mm` outlier costs no extra branch and no
152/// extra table.
153const DIST_MM_ESCAPE: u32 = 0xFF_FFFF;
154
155/// Bytes per `edges.bin` record — `EdgeRec` in `graph.rs`, and an on-disk contract
156/// with it: `i16 target_delta, u24 dist_mm, u8 type_, u8 speed_limit`. `name_offset`
157/// is not a field; it is a sparse side table behind the record array.
158const EDGE_REC_BYTES: u64 = 7;
159
160/// Directed edges per entry of `edges.bin`'s escape block index — `ESCAPE_BLOCK` in
161/// `graph.rs`, and the two must agree.
162const ESCAPE_BLOCK: u64 = 1024;
163
164/// Alignment each section of a multi-section file starts on — `SECTION_ALIGN` in
165/// `graph.rs`.
166const SECTION_ALIGN: u64 = 8;
167
168/// Round `n` up to the next multiple of `align`, which must be a power of two.
169const fn align_up(n: u64, align: u64) -> u64 {
170 (n + align - 1) & !(align - 1)
171}
172
173/// `target - source` when it fits the `i16` a record stores, `None` when the edge
174/// has to escape.
175///
176/// This is *the* escape predicate: [`Census`] counts with it and [`EdgeFile::push`]
177/// narrows with it, so the two cannot disagree by one and produce a pack that loads
178/// while reading the wrong node.
179#[inline]
180fn target_delta(source: u32, target: u32) -> Option<i16> {
181 let d = i64::from(target) - i64::from(source);
182 i16::try_from(d).ok().filter(|d| *d != TARGET_DELTA_ESCAPE)
183}
184
185/// True when either field of this edge is unrepresentable inline.
186#[inline]
187fn edge_escapes(source: u32, target: u32, dist_mm: u32) -> bool {
188 target_delta(source, target).is_none() || dist_mm >= DIST_MM_ESCAPE
189}
190
191/// One bucket per possible bit width of `|target - source|`, from a zero delta up
192/// to a full `u32`. A named type only because arrays this long do not derive
193/// `Default`.
194pub struct DeltaBits([u64; 33]);
195
196impl Default for DeltaBits {
197 fn default() -> DeltaBits {
198 DeltaBits([0u64; 33])
199 }
200}
201
202impl std::ops::Deref for DeltaBits {
203 type Target = [u64; 33];
204 fn deref(&self) -> &[u64; 33] {
205 &self.0
206 }
207}
208
209impl std::ops::DerefMut for DeltaBits {
210 fn deref_mut(&mut self) -> &mut [u64; 33] {
211 &mut self.0
212 }
213}
214
215/// What a narrower `edges.bin` record would cost, measured by the encoder itself
216/// rather than by a script that might disagree with it by one.
217///
218/// Reported by `road_graph --stats`. Everything here is a *property of one
219/// extract*, and the design that consumes it extrapolates to a planet 22x larger,
220/// so the histogram matters more than any single rate: for nodes ordered by a
221/// space-filling curve the tail should decay as `P(|delta| > n) ~ c * n^(-1/2)`,
222/// and `c` is what transfers between extracts, not the escape rate itself.
223#[derive(Default)]
224pub struct Census {
225 /// `delta_bits[b]` counts edges needing exactly `b` bits to be exceeded, i.e.
226 /// for which `b` is the number of `k` with `2^k < |target - source|`. Suffix
227 /// sums of it are the tail counts; see [`Census::delta_tail`].
228 pub delta_bits: DeltaBits,
229 /// Edges whose `|target - source|` will not fit an `i16`.
230 pub delta_escapes: u64,
231 /// Edges whose `dist_mm` reaches [`DIST_MM_ESCAPE`].
232 pub dist_escapes: u64,
233 /// Edges either sentinel forces into the escape table. Not the sum of the two
234 /// above: an edge can fail both tests and still be one row.
235 pub escapes: u64,
236 pub max_delta: u32,
237 pub max_dist_mm: u32,
238 /// Largest out-degree of any node, which bounds a per-node `u8 degree` field.
239 pub max_degree: u32,
240 /// Nodes with no outgoing edge. These make several nodes share an `edge_ptr`,
241 /// which is what makes `find_node_idx_for_edge`'s tie-break observable.
242 pub degree_zero_nodes: u64,
243 pub named_edges: u64,
244}
245
246impl Census {
247 /// Edges whose `|target - source|` exceeds `1 << k`, for `k` in `0..32`.
248 pub fn delta_tail(&self, k: u32) -> u64 {
249 self.delta_bits[(k as usize + 1).min(32)..].iter().sum()
250 }
251
252 /// Record one directed edge.
253 #[inline]
254 fn edge(&mut self, source: u32, target: u32, dist_mm: u32, named: bool) {
255 let delta = source.abs_diff(target);
256 // The bucket is the count of `k` with `2^k < delta`, so a plain suffix sum
257 // turns the histogram into the tail without a per-edge loop.
258 let bits = if delta == 0 { 0 } else { 32 - (delta - 1).leading_zeros() };
259 self.delta_bits[bits as usize] += 1;
260 self.max_delta = self.max_delta.max(delta);
261 self.max_dist_mm = self.max_dist_mm.max(dist_mm);
262 if target_delta(source, target).is_none() {
263 self.delta_escapes += 1;
264 }
265 if dist_mm >= DIST_MM_ESCAPE {
266 self.dist_escapes += 1;
267 }
268 if edge_escapes(source, target, dist_mm) {
269 self.escapes += 1;
270 }
271 if named {
272 self.named_edges += 1;
273 }
274 }
275
276 #[inline]
277 fn node(&mut self, degree: u32) {
278 self.max_degree = self.max_degree.max(degree);
279 if degree == 0 {
280 self.degree_zero_nodes += 1;
281 }
282 }
283}
284
285pub struct Stats {
286 pub node_count: u64,
287 pub edge_count: u64,
288 pub unique_names: usize,
289 pub name_bytes: u32,
290 pub lcc_size: u64,
291 /// Stops left alone because their own component is already routable.
292 pub stops_already_connected: usize,
293 pub reconnected_stops: usize,
294 /// Stops that needed reconnecting and found no routable node in range.
295 pub stops_unreachable: usize,
296 /// Nodes before compaction, i.e. one per OSM geometry vertex.
297 pub raw_node_count: u64,
298 /// Directed edges an uncompacted build would have produced.
299 pub raw_edge_count: u64,
300 /// Chains cut because their geometry would not fit a single edge.
301 pub chain_splits: usize,
302 /// Edges carrying a stored polyline.
303 pub geometry_edges: u64,
304 /// Edges deferring to their twin's polyline.
305 pub reversed_edges: u64,
306 pub intermediate_bytes: u64,
307 pub edges_bytes: u64,
308 /// Edges whose `target` or `dist_mm` needed the escape table.
309 pub escape_count: u64,
310 /// Edges with a name at all, i.e. the length of the sparse name table.
311 pub named_edges: u64,
312 /// What a narrower record would cost. Always collected — it is a handful of
313 /// adds per edge — and reported by `--stats`.
314 pub census: Census,
315}
316
317/// Bytes per rank block. 64 bytes is 512 bits and one cache line, so a rank
318/// costs one `u64` load plus at most eight `popcount`s while the index itself is
319/// only 1/64th of the bitset it indexes.
320///
321/// Both the in-memory [`Bitset`] and `intermediate.bin`'s on-disk presence bitmap
322/// use it, and for the latter it is an on-disk contract with `graph.rs`.
323const RANK_BLOCK_BYTES: usize = 64;
324
325/// Bits \u2014 for `intermediate.bin`, directed edges \u2014 one rank block covers.
326const RANK_BLOCK_BITS: u64 = RANK_BLOCK_BYTES as u64 * 8;
327
328/// A plain (non-atomic) bitset, optionally carrying a rank index.
329///
330/// Bits are set from a single thread during the merge and only read afterwards,
331/// so no atomics are needed.
332///
333/// [`Bitset::build_rank`] turns it into a *dense addressing scheme*: the node
334/// array becomes implicitly ordered by OSM id, with a node's index being the
335/// number of set bits before its own. That is what removes the sorted
336/// `(osm_id, local_id)` side table the edge pass used to binary-search, and with
337/// it the need to store an `osm_id` per node at all.
338pub(crate) struct Bitset {
339 bits: Vec<u8>,
340 /// Set bits before each [`RANK_BLOCK_BYTES`] block, with a total appended.
341 /// Empty until [`Bitset::build_rank`].
342 rank: Vec<u64>,
343}
344
345impl Bitset {
346 pub(crate) fn new(size_bits: u64) -> Bitset {
347 Bitset {
348 bits: vec![0u8; (size_bits / 8 + 1) as usize],
349 rank: Vec::new(),
350 }
351 }
352
353 /// Returns true when this call is what set the bit.
354 pub(crate) fn set(&mut self, idx: u64) -> bool {
355 let byte = &mut self.bits[(idx / 8) as usize];
356 let mask = 1u8 << (idx % 8);
357 let was = *byte & mask != 0;
358 *byte |= mask;
359 !was
360 }
361
362 pub(crate) fn get(&self, idx: u64) -> bool {
363 self.bits[(idx / 8) as usize] & (1u8 << (idx % 8)) != 0
364 }
365
366 /// Index the blocks covering ids up to and including `max_id`, returning the
367 /// total number of set bits.
368 ///
369 /// Sized from the largest id actually seen rather than from the bitset's
370 /// nominal width: `BITSET_SIZE` is 20 G ids, and indexing all of it would
371 /// cost 313 MB to describe blocks no id reaches. `bits` itself is left at
372 /// full width, because [`Bitset::get`] is still asked about ids past the
373 /// largest marked one.
374 fn build_rank(&mut self, max_id: u64) -> u64 {
375 let used = (max_id / 8 + 1) as usize;
376 let blocks = used.div_ceil(RANK_BLOCK_BYTES);
377 self.rank = Vec::with_capacity(blocks + 1);
378 let mut total = 0u64;
379 let mut prog = crate::progress::Progress::new("Rank index", blocks as u64);
380 for b in 0..blocks {
381 self.rank.push(total);
382 let start = b * RANK_BLOCK_BYTES;
383 let end = (start + RANK_BLOCK_BYTES).min(used);
384 total += self.bits[start..end]
385 .iter()
386 .map(|byte| u64::from(byte.count_ones()))
387 .sum::<u64>();
388 prog.inc();
389 }
390 prog.finish();
391 self.rank.push(total);
392 total
393 }
394
395 /// How many set bits come before `idx`. For a *set* bit that is its position
396 /// in the sequence of set bits, i.e. its dense id.
397 ///
398 /// Meaningless for a clear bit: it returns the id of whichever node comes
399 /// next, so callers must test [`Bitset::get`] first or they will silently
400 /// alias two nodes together.
401 #[inline]
402 pub(crate) fn dense(&self, idx: u64) -> u32 {
403 let byte = (idx / 8) as usize;
404 let block = byte / RANK_BLOCK_BYTES;
405 let start = block * RANK_BLOCK_BYTES;
406 let whole: u32 = self.bits[start..byte].iter().map(|b| b.count_ones()).sum();
407 let below = (self.bits[byte] & ((1u8 << (idx % 8)) - 1)).count_ones();
408 let n = self.rank[block] + u64::from(whole) + u64::from(below);
409 debug_assert!(n <= u64::from(u32::MAX), "dense id {n} does not fit a u32");
410 n as u32
411 }
412}
413
414/// Dense addressing for the graph's nodes: which OSM ids are in the graph, and
415/// which of those the file actually supplied coordinates for.
416///
417/// Both tests matter, and for different reasons. The mask is what makes
418/// [`Bitset::dense`] meaningful. `present` is what keeps *dangling references*
419/// out: pass 1 marks every ref of every routable way, including refs to nodes no
420/// blob in the file defines — an extract clipped at a boundary is full of them —
421/// and those slots never receive coordinates. Left in, each would read as
422/// `(0, 0)`, a point in the Atlantic that corrupts distances, spatial keys and
423/// polylines while leaving every count looking plausible.
424pub(crate) struct NodeIndex {
425 pub(crate) mask: Bitset,
426 present: Bitset,
427}
428
429impl NodeIndex {
430 /// Dense id of a node that is both in the graph and really in the file.
431 #[inline]
432 pub(crate) fn dense(&self, osm_id: i64) -> Option<u32> {
433 if osm_id < 0 || osm_id as u64 >= BITSET_SIZE || !self.mask.get(osm_id as u64) {
434 return None;
435 }
436 let d = self.mask.dense(osm_id as u64);
437 self.present.get(u64::from(d)).then_some(d)
438 }
439}
440
441#[derive(Default)]
442struct Pass1 {
443 /// Node ids referenced by a routable way, and the ids of stop-tagged nodes.
444 /// Per chunk and freed by the sink: nothing about a way is retained, because
445 /// the ways pass re-reads them.
446 refs: Vec<i64>,
447 stop_nodes: Vec<i64>,
448}
449
450/// A region bbox filter, or `None` for a world build.
451///
452/// Passed by value into the block visitors (it is `Copy`): every routable way
453/// whose nodes all fall outside is dropped, and a stop outside never enters
454/// the graph. Ways are kept whole when any node touches — the same
455/// `complete_ways` rule [`crate::bbox`] documents — so a road straddling the
456/// border keeps its boundary stub rather than ending mid-segment.
457pub type RegionFilter = Option<crate::bbox::BBox>;
458
459include!("graph_build_part1.rs");
460include!("graph_build_part2.rs");
461include!("graph_build_part3.rs");
462include!("graph_build_part4.rs");
463include!("graph_build_part5.rs");
464#[cfg(test)]
465mod tests {
466include!("graph_build_part6.rs");
467include!("graph_build_part7.rs");
468include!("graph_build_part8.rs");
469include!("graph_build_part9.rs");
470include!("graph_build_part10.rs");}