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

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

graph_build.rs429 lines · 19.6 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};
61use std::sync::atomic::Ordering;
62
63use crate::chains;
64use crate::compact::{self, Seg, REMOVED};
65use crate::geom;
66use crate::names::{LocalNames, NamePool, NO_NAME};
67use crate::osm::{visit_block, Element};
68use crate::par;
69use crate::pbf::{self, KIND_NODES, KIND_WAYS};
70use crate::proto::{Error, Result};
71use crate::spatial::{accurate_dist_mm, spatial_from_e7};
72use crate::tags;
73use rayon::prelude::*;
74
75/// Node ids at or above this are skipped, exactly as in the C++. The bitset that
76/// tracks "is this node part of the graph" is sized from it (2.5 GB).
77pub const BITSET_SIZE: u64 = 20_000_000_000;
78
79/// `"MARG"` little-endian — `GRAPH_MAGIC` in `graph.rs`.
80const GRAPH_MAGIC: u32 = 0x4752_414D;
81/// Version 5 narrows an `edges.bin` record from 14 bytes to 11: `target` becomes an
82/// `i16` delta from the edge's source and `dist_mm` a `u24`, with one escape table
83/// behind the record array for the 0.3% that do not fit. Planet goes ~29.0 -> ~25.8
84/// GB, and every value stays *exact*.
85/// Version 6 moves `name_offset` out of the record into a sparse side table — two
86/// thirds of edges have no name — taking the record to 7 bytes and planet to ~23.3 GB.
87/// Version 7 blocked-compresses `nodes.bin`, `edges.bin` records and
88/// `elevation.bin` (ZBLK sections: zstd frames over 4096-record blocks behind
89/// a `u64` offset table). Same records, same order — only the container
90/// changes. Readers accept 6 and 7; writers emit 7.
91const GRAPH_VERSION: u32 = 7;
92/// Geometry edges per coarse block in `intermediate.bin`'s two-level offset table
93/// — `INTERMEDIATE_BLOCK` in `graph.rs`, and the two must agree.
94///
95/// A per-edge blob is at most 1016 bytes ([`geom::MAX_POINTS`] points, of which
96/// only the interior is stored, 4 bytes each), so a block spans at most 32,512
97/// bytes and the within-block half fits a `u16`. [`GeomFile::push_entry`] asserts
98/// it. The table is indexed by an edge's *rank in the presence bitmap*, not by its
99/// edge index, so every entry in a block describes a real blob.
100const INTERMEDIATE_BLOCK: u64 = 32;
101
102/// Smallest connected component that counts as a real road network for the
103/// purpose of [`reconnect_isolated_stops`].
104///
105/// A stop already attached to a component this size is left alone; anything
106/// smaller is treated as a mapping artefact and reconnected. The threshold is
107/// capped at the largest component that actually exists, so a tiny graph — every
108/// fixture in this file — still reconnects against its own road network.
109const MIN_ROUTABLE_COMPONENT: u32 = 1000;
110
111/// Synthetic edges that reattach an isolated transit stop to the routable graph.
112const RECONNECT_TYPE: u8 = 12;
113const RECONNECT_SPEED: u8 = 5;
114
115/// Sentinel in a `CachedWay`/`TmpEdge` lane offset meaning "no lane data".
116const NO_LANES: u32 = 0xFFFF_FFFF;
117
118/// Sentinel in `TmpEdge::chain` meaning "this edge came from nowhere in
119/// particular" — currently only the synthetic transit-stop connectors, which are
120/// straight lines and so need no stored geometry.
121const NO_CHAIN: u32 = 0xFFFF_FFFF;
122
123/// `REVERSE_GEOMETRY_FLAG` in `graph.rs`: set in an edge's `type_` byte to mean
124/// "my geometry is my twin's, read backwards". Only one edge of a bidirectional
125/// pair stores the polyline, which halves the blob.
126///
127/// The reader locates the twin by scanning the *target's* edge range for an edge
128/// pointing back at the source, and takes the first match — so this may only be
129/// set when exactly one such edge exists. See [`twin_is_unique`].
130const REVERSE_GEOMETRY_FLAG: u8 = 0x40;
131
132/// Fallback stop code for a transit stop node with no `name`.
133const UNNAMED_STOP: &[u8] = b"OSM_STOP";
134
135/// Sentinel in a narrowed `target` delta meaning "this record's `target` and
136/// `dist_mm` both live in the escape table".
137///
138/// An `edges.bin` record stores `target` as an `i16` delta from the edge's own
139/// source rather than absolutely, which is only possible because the nodes are
140/// sorted by a space-filling curve and an edge is short: [`Census`] measures how
141/// often that fails. `i16::MIN` is reserved rather than used, so the representable
142/// range is symmetric at ±32767.
143const TARGET_DELTA_ESCAPE: i16 = i16::MIN;
144
145/// Sentinel in a narrowed `u24 dist_mm` meaning the same thing.
146///
147/// 0xFFFFFF mm is 16.78 km, which a collapsed degree-2 chain can exceed in empty
148/// country. One sentinel shared with [`TARGET_DELTA_ESCAPE`] means a single escape
149/// table serves both fields, so a `dist_mm` outlier costs no extra branch and no
150/// extra table.
151const DIST_MM_ESCAPE: u32 = 0xFF_FFFF;
152
153/// Bytes per `edges.bin` record — `EdgeRec` in `graph.rs`, and an on-disk contract
154/// with it: `i16 target_delta, u24 dist_mm, u8 type_, u8 speed_limit`. `name_offset`
155/// is not a field; it is a sparse side table behind the record array.
156const EDGE_REC_BYTES: u64 = 7;
157
158/// Directed edges per entry of `edges.bin`'s escape block index — `ESCAPE_BLOCK` in
159/// `graph.rs`, and the two must agree.
160const ESCAPE_BLOCK: u64 = 1024;
161
162/// Alignment each section of a multi-section file starts on — `SECTION_ALIGN` in
163/// `graph.rs`.
164const SECTION_ALIGN: u64 = 8;
165
166/// Round `n` up to the next multiple of `align`, which must be a power of two.
167const fn align_up(n: u64, align: u64) -> u64 {
168 (n + align - 1) & !(align - 1)
169}
170
171/// `target - source` when it fits the `i16` a record stores, `None` when the edge
172/// has to escape.
173///
174/// This is *the* escape predicate: [`Census`] counts with it and [`EdgeFile::push`]
175/// narrows with it, so the two cannot disagree by one and produce a pack that loads
176/// while reading the wrong node.
177#[inline]
178fn target_delta(source: u32, target: u32) -> Option<i16> {
179 let d = i64::from(target) - i64::from(source);
180 i16::try_from(d).ok().filter(|d| *d != TARGET_DELTA_ESCAPE)
181}
182
183/// True when either field of this edge is unrepresentable inline.
184#[inline]
185fn edge_escapes(source: u32, target: u32, dist_mm: u32) -> bool {
186 target_delta(source, target).is_none() || dist_mm >= DIST_MM_ESCAPE
187}
188
189/// One bucket per possible bit width of `|target - source|`, from a zero delta up
190/// to a full `u32`. A named type only because arrays this long do not derive
191/// `Default`.
192pub struct DeltaBits([u64; 33]);
193
194impl Default for DeltaBits {
195 fn default() -> DeltaBits {
196 DeltaBits([0u64; 33])
197 }
198}
199
200impl std::ops::Deref for DeltaBits {
201 type Target = [u64; 33];
202 fn deref(&self) -> &[u64; 33] {
203 &self.0
204 }
205}
206
207impl std::ops::DerefMut for DeltaBits {
208 fn deref_mut(&mut self) -> &mut [u64; 33] {
209 &mut self.0
210 }
211}
212
213/// What a narrower `edges.bin` record would cost, measured by the encoder itself
214/// rather than by a script that might disagree with it by one.
215///
216/// Reported by `road_graph --stats`. Everything here is a *property of one
217/// extract*, and the design that consumes it extrapolates to a planet 22x larger,
218/// so the histogram matters more than any single rate: for nodes ordered by a
219/// space-filling curve the tail should decay as `P(|delta| > n) ~ c * n^(-1/2)`,
220/// and `c` is what transfers between extracts, not the escape rate itself.
221#[derive(Default)]
222pub struct Census {
223 /// `delta_bits[b]` counts edges needing exactly `b` bits to be exceeded, i.e.
224 /// for which `b` is the number of `k` with `2^k < |target - source|`. Suffix
225 /// sums of it are the tail counts; see [`Census::delta_tail`].
226 pub delta_bits: DeltaBits,
227 /// Edges whose `|target - source|` will not fit an `i16`.
228 pub delta_escapes: u64,
229 /// Edges whose `dist_mm` reaches [`DIST_MM_ESCAPE`].
230 pub dist_escapes: u64,
231 /// Edges either sentinel forces into the escape table. Not the sum of the two
232 /// above: an edge can fail both tests and still be one row.
233 pub escapes: u64,
234 pub max_delta: u32,
235 pub max_dist_mm: u32,
236 /// Largest out-degree of any node, which bounds a per-node `u8 degree` field.
237 pub max_degree: u32,
238 /// Nodes with no outgoing edge. These make several nodes share an `edge_ptr`,
239 /// which is what makes `find_node_idx_for_edge`'s tie-break observable.
240 pub degree_zero_nodes: u64,
241 pub named_edges: u64,
242}
243
244impl Census {
245 /// Edges whose `|target - source|` exceeds `1 << k`, for `k` in `0..32`.
246 pub fn delta_tail(&self, k: u32) -> u64 {
247 self.delta_bits[(k as usize + 1).min(32)..].iter().sum()
248 }
249
250 /// Record one directed edge.
251 #[inline]
252 fn edge(&mut self, source: u32, target: u32, dist_mm: u32, named: bool) {
253 let delta = source.abs_diff(target);
254 // The bucket is the count of `k` with `2^k < delta`, so a plain suffix sum
255 // turns the histogram into the tail without a per-edge loop.
256 let bits = if delta == 0 { 0 } else { 32 - (delta - 1).leading_zeros() };
257 self.delta_bits[bits as usize] += 1;
258 self.max_delta = self.max_delta.max(delta);
259 self.max_dist_mm = self.max_dist_mm.max(dist_mm);
260 if target_delta(source, target).is_none() {
261 self.delta_escapes += 1;
262 }
263 if dist_mm >= DIST_MM_ESCAPE {
264 self.dist_escapes += 1;
265 }
266 if edge_escapes(source, target, dist_mm) {
267 self.escapes += 1;
268 }
269 if named {
270 self.named_edges += 1;
271 }
272 }
273
274 #[inline]
275 fn node(&mut self, degree: u32) {
276 self.max_degree = self.max_degree.max(degree);
277 if degree == 0 {
278 self.degree_zero_nodes += 1;
279 }
280 }
281}
282
283pub struct Stats {
284 pub node_count: u64,
285 pub edge_count: u64,
286 pub unique_names: usize,
287 pub name_bytes: u32,
288 pub lcc_size: u64,
289 /// Stops left alone because their own component is already routable.
290 pub stops_already_connected: usize,
291 pub reconnected_stops: usize,
292 /// Stops that needed reconnecting and found no routable node in range.
293 pub stops_unreachable: usize,
294 /// Nodes before compaction, i.e. one per OSM geometry vertex.
295 pub raw_node_count: u64,
296 /// Directed edges an uncompacted build would have produced.
297 pub raw_edge_count: u64,
298 /// Chains cut because their geometry would not fit a single edge.
299 pub chain_splits: usize,
300 /// Edges carrying a stored polyline.
301 pub geometry_edges: u64,
302 /// Edges deferring to their twin's polyline.
303 pub reversed_edges: u64,
304 pub intermediate_bytes: u64,
305 pub edges_bytes: u64,
306 /// Edges whose `target` or `dist_mm` needed the escape table.
307 pub escape_count: u64,
308 /// Edges with a name at all, i.e. the length of the sparse name table.
309 pub named_edges: u64,
310 /// What a narrower record would cost. Always collected — it is a handful of
311 /// adds per edge — and reported by `--stats`.
312 pub census: Census,
313}
314
315/// Bytes per rank block. 64 bytes is 512 bits and one cache line, so a rank
316/// costs one `u64` load plus at most eight `popcount`s while the index itself is
317/// only 1/64th of the bitset it indexes.
318///
319/// Both the in-memory [`Bitset`] and `intermediate.bin`'s on-disk presence bitmap
320/// use it, and for the latter it is an on-disk contract with `graph.rs`.
321const RANK_BLOCK_BYTES: usize = 64;
322
323/// Bits \u2014 for `intermediate.bin`, directed edges \u2014 one rank block covers.
324const RANK_BLOCK_BITS: u64 = RANK_BLOCK_BYTES as u64 * 8;
325
326/// A plain (non-atomic) bitset, optionally carrying a rank index.
327///
328/// Bits are set from a single thread during the merge and only read afterwards,
329/// so no atomics are needed.
330///
331/// [`Bitset::build_rank`] turns it into a *dense addressing scheme*: the node
332/// array becomes implicitly ordered by OSM id, with a node's index being the
333/// number of set bits before its own. That is what removes the sorted
334/// `(osm_id, local_id)` side table the edge pass used to binary-search, and with
335/// it the need to store an `osm_id` per node at all.
336pub(crate) struct Bitset {
337 bits: Vec<u8>,
338 /// Set bits before each [`RANK_BLOCK_BYTES`] block, with a total appended.
339 /// Empty until [`Bitset::build_rank`].
340 rank: Vec<u64>,
341}
342
343impl Bitset {
344 pub(crate) fn new(size_bits: u64) -> Bitset {
345 Bitset { bits: vec![0u8; (size_bits / 8 + 1) as usize], rank: Vec::new() }
346 }
347
348 /// Returns true when this call is what set the bit.
349 pub(crate) fn set(&mut self, idx: u64) -> bool {
350 let byte = &mut self.bits[(idx / 8) as usize];
351 let mask = 1u8 << (idx % 8);
352 let was = *byte & mask != 0;
353 *byte |= mask;
354 !was
355 }
356
357 pub(crate) fn get(&self, idx: u64) -> bool {
358 self.bits[(idx / 8) as usize] & (1u8 << (idx % 8)) != 0
359 }
360
361 /// A shared, atomic view of the bits for marking from many threads at once.
362 ///
363 /// Setting bits is a set union, which is commutative and idempotent, so the
364 /// final bits — and the count of bits that went from clear to set, which
365 /// [`AtomicBits::set`] reports exactly once per bit — are independent of
366 /// which thread got there first. That is what lets the PBF passes mark from
367 /// their decode workers instead of a single-threaded sink.
368 pub(crate) fn atomic(&mut self) -> AtomicBits<'_> {
369 let bytes: &mut [u8] = &mut self.bits;
370 // SAFETY: `AtomicU8` has the size, alignment and bit validity of `u8`,
371 // and the exclusive borrow of `self.bits` is held for the view's
372 // lifetime, so no plain access can race with the atomic ones.
373 AtomicBits(unsafe { &*(bytes as *mut [u8] as *const [std::sync::atomic::AtomicU8]) })
374 }
375
376 /// Index the blocks covering ids up to and including `max_id`, returning the
377 /// total number of set bits.
378 ///
379 /// Sized from the largest id actually seen rather than from the bitset's
380 /// nominal width: `BITSET_SIZE` is 20 G ids, and indexing all of it would
381 /// cost 313 MB to describe blocks no id reaches. `bits` itself is left at
382 /// full width, because [`Bitset::get`] is still asked about ids past the
383 /// largest marked one.
384 fn build_rank(&mut self, max_id: u64) -> u64 {
385 let used = (max_id / 8 + 1) as usize;
386 let blocks = used.div_ceil(RANK_BLOCK_BYTES);
387 // Per-block popcounts on the pool, then one serial prefix sum: the
388 // counts are integers, so the result cannot depend on the split.
389 let bits = &self.bits[..used];
390 let mut rank: Vec<u64> = par::install(|| {
391 bits.par_chunks(RANK_BLOCK_BYTES)
392 .map(|c| c.iter().map(|b| u64::from(b.count_ones())).sum::<u64>())
393 .collect()
394 });
395 debug_assert_eq!(rank.len(), blocks);
396 let mut total = 0u64;
397 for r in rank.iter_mut() {
398 let n = *r;
399 *r = total;
400 total += n;
401 }
402 rank.push(total);
403 self.rank = rank;
404 total
405 }
406
407 /// How many set bits come before `idx`. For a *set* bit that is its position
408 /// in the sequence of set bits, i.e. its dense id.
409 ///
410 /// Meaningless for a clear bit: it returns the id of whichever node comes
411 /// next, so callers must test [`Bitset::get`] first or they will silently
412 /// alias two nodes together.
413 #[inline]
414 pub(crate) fn dense(&self, idx: u64) -> u32 {
415 let byte = (idx / 8) as usize;
416 let block = byte / RANK_BLOCK_BYTES;
417 let start = block * RANK_BLOCK_BYTES;
418 let whole: u32 = self.bits[start..byte].iter().map(|b| b.count_ones()).sum();
419 let below = (self.bits[byte] & ((1u8 << (idx % 8)) - 1)).count_ones();
420 let n = self.rank[block] + u64::from(whole) + u64::from(below);
421 debug_assert!(n <= u64::from(u32::MAX), "dense id {n} does not fit a u32");
422 n as u32
423 }
424}
425
426/// See [`Bitset::atomic`].
427pub(crate) struct AtomicBits<'a>(&'a [std::sync::atomic::AtomicU8]);
428
429include!("graph_build_s1.rs");