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

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

chains.rs551 lines · 21.0 KiBRaw
1//! Within-way chain building: degree-2 collapsing that never materialises a
2//! segment array.
3//!
4//! [`crate::compact`] does the same job by building every segment, indexing them
5//! into a CSR of incidences, and walking chains across way boundaries. That is
6//! the better graph and the wrong shape for a planet: the segment array and its
7//! incidence index are 114 GB of a 217 GB working set, and no amount of shrinking
8//! records closes that on a 94 GB machine.
9//!
10//! This module gets the same collapse from two much smaller structures:
11//!
12//! * **one byte of degree per node**, accumulated by a pass that reads the way
13//! blobs and keeps nothing;
14//! * **the way's own ref list**, walked positionally as it is decoded.
15//!
16//! # What it costs
17//!
18//! Chains may not cross from one OSM way into another. Every segment in a chain
19//! then shares its way's type, speed limit, name, one-way-ness and lane masks *by
20//! construction*, so the entire attribute-agreement half of
21//! `compact::classify` — and the segment records it compared — disappears.
22//!
23//! The price is real and is an accepted regression: a node where two different
24//! ways meet end-to-end with matching tags is collapsed by `compact` and kept
25//! here. OSM splits long roads constantly, at every tag change and at the
26//! 2000-node way ceiling, so this is not a rare case. Two things soften it: the
27//! 256-point budget already forces cuts on long dense roads anyway, and more
28//! surviving nodes strictly *improves* snapping.
29//!
30//! # What it buys beyond memory
31//!
32//! Two correctness simplifications fall out of walking positions instead of a
33//! graph:
34//!
35//! * the walk cannot loop, because it advances through a finite ref list, so
36//! there is no "used" flag per segment and no anchorless-cycle phase — a ring
37//! way closes on its own first node for free;
38//! * within one way every segment runs along ref order, so a one-way chain is
39//! already oriented along its traffic and there is no reorientation step to get
40//! the forward and backward lane masks the wrong way round.
41//!
42//! Both of those were bugs that had to be fixed once already.
43
44use std::fs::File;
45use std::io::{BufReader, BufWriter, Read, Write};
46use std::path::{Path, PathBuf};
47
48use crate::compact::Chain;
49use crate::geom;
50use crate::graph_build::{way_attrs, Bitset, NodeIndex, WayAttrs, BITSET_SIZE};
51use crate::names::{LocalNames, NamePool, NO_NAME};
52use crate::osm::{visit_block, Element};
53use crate::pbf::{self, BlobLoc, KIND_NODES, KIND_WAYS};
54use crate::proto::{Error, Result};
55use crate::spatial::accurate_dist_mm;
56use crate::tags;
57
58/// Is this consecutive pair of way refs a segment of the graph?
59///
60/// **Both the degree pass and the chain walk must ask this and nothing else.**
61/// The degree array is what decides where a chain is cut, so a disagreement
62/// between the two would either dead-end a chain at a node the degree array
63/// thinks is a pass-through, or walk a chain straight through one it thinks is a
64/// junction. Every other invariant here is recoverable; this one is not.
65#[inline]
66pub(crate) fn segment(index: &NodeIndex, a: i64, b: i64) -> Option<(u32, u32)> {
67 let (u, v) = (index.dense(a)?, index.dense(b)?);
68 // A way listing the same node twice in a row is a mapping artefact, not a
69 // zero-length road. Counting it would give that node two phantom incidences
70 // and so promote a genuine pass-through into a junction.
71 (u != v).then_some((u, v))
72}
73
74/// Nodes with more incidences than a byte can hold are junctions whatever the
75/// true count is, so the counter saturates. Only `== 2` changes a decision, and
76/// no node with 255 incidences is a pass-through.
77#[derive(Default)]
78struct DegreePass {
79 /// Both endpoints of every segment, in decode order. Per chunk, so the
80 /// random scatter into the global array happens once, single-threaded, in the
81 /// sink.
82 endpoints: Vec<u32>,
83}
84
85/// One saturating incidence count per dense node id.
86///
87/// `filter` drops segments the same way the chain walk does: a way no node of
88/// which touches the region contributes no incidence, so its nodes stay degree
89/// 0 and never survive. Both this and [`build`] must ask the same question —
90/// see [`segment`] — or a chain dead-ends where the degrees say pass-through.
91pub(crate) fn count_degrees(
92 input: &Path,
93 blobs: &[BlobLoc],
94 blob_kinds: &[u8],
95 index: &NodeIndex,
96 slots: u32,
97 filter: crate::graph_build::RegionFilter,
98) -> Result<Vec<u8>> {
99 let mut degree = vec![0u8; slots as usize];
100 if filter.is_none() {
101 // World build: the fast path, unchanged. Every routable way's segments
102 // count, and no coordinate table is needed.
103 let _ = pbf::run_pass_sink(
104 input,
105 blobs,
106 Some(blob_kinds),
107 KIND_WAYS,
108 "Pass 3: node degrees",
109 DegreePass::default,
110 |state: &mut DegreePass, block| {
111 let mut kinds = 0u8;
112 visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {
113 if let Element::Way(w) = el {
114 if tags::get_hw_id(w.tags.get_str("highway")) != 0 {
115 for pair in w.refs.windows(2) {
116 if let Some((u, v)) = segment(index, pair[0], pair[1]) {
117 state.endpoints.push(u);
118 state.endpoints.push(v);
119 }
120 }
121 }
122 }
123 Ok(())
124 })?;
125 Ok(kinds)
126 },
127 |chunk| {
128 for e in chunk.endpoints {
129 let d = &mut degree[e as usize];
130 *d = d.saturating_add(1);
131 }
132 Ok(())
133 },
134 )?;
135 return Ok(degree);
136 }
137 // Region build: degrees must agree with the chain walk's filter, or a
138 // chain dead-ends where the degrees say pass-through. The filter needs
139 // coordinates, which live in pass 2's `coords` — not visible here — so
140 // this resolves the marked nodes' locations in a side table first. One
141 // extra node-region scan; dwarfed by what the region saves downstream.
142 let bbox = filter.expect("checked above");
143 let mut locs: Vec<Option<(i32, i32)>> = vec![None; slots as usize];
144 {
145 // (dense id, lat_e7, lon_e7), folded in chunk order.
146 let _ = pbf::run_pass_sink(
147 input,
148 blobs,
149 Some(blob_kinds),
150 KIND_NODES,
151 "Pass 3: region locations",
152 Vec::<(u32, i32, i32)>::new,
153 |state: &mut Vec<(u32, i32, i32)>, block| {
154 let mut kinds = 0u8;
155 visit_block(block, KIND_NODES, &mut kinds, &mut |el: Element| {
156 if let Element::Node(n) = el {
157 if n.id >= 0 && (n.id as u64) < BITSET_SIZE && index.mask.get(n.id as u64) {
158 let d = index.mask.dense(n.id as u64);
159 state.push((d, n.lat_e7, n.lon_e7));
160 }
161 }
162 Ok(())
163 })?;
164 Ok(kinds)
165 },
166 |chunk| {
167 for (d, lat, lon) in chunk {
168 locs[d as usize] = Some((lat, lon));
169 }
170 Ok(())
171 },
172 )?;
173 }
174 let touches = |refs: &[i64]| -> bool {
175 refs.iter().any(|r| {
176 index.dense(*r).and_then(|d| locs[d as usize]).is_some_and(|(lat, lon)| {
177 bbox.contains_e7(lat, lon)
178 })
179 })
180 };
181 let _ = pbf::run_pass_sink(
182 input,
183 blobs,
184 Some(blob_kinds),
185 KIND_WAYS,
186 "Pass 3: node degrees",
187 DegreePass::default,
188 |state: &mut DegreePass, block| {
189 let mut kinds = 0u8;
190 visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {
191 if let Element::Way(w) = el {
192 if tags::get_hw_id(w.tags.get_str("highway")) != 0 && touches(w.refs) {
193 for pair in w.refs.windows(2) {
194 if let Some((u, v)) = segment(index, pair[0], pair[1]) {
195 state.endpoints.push(u);
196 state.endpoints.push(v);
197 }
198 }
199 }
200 }
201 Ok(())
202 })?;
203 Ok(kinds)
204 },
205 |chunk| {
206 for e in chunk.endpoints {
207 let d = &mut degree[e as usize];
208 *d = d.saturating_add(1);
209 }
210 Ok(())
211 },
212 )?;
213 Ok(degree)
214}
215
216/// Every chain in the file, plus the lane pool their offsets point into.
217/// What the chain pass leaves behind. The chains themselves are on disk.
218pub(crate) struct Chains {
219 pub chain_count: u64,
220 pub lanes: Vec<u16>,
221 /// Dense ids a chain starts or ends at. Together with "degree is not 2" this
222 /// is the surviving-node set.
223 pub endpoints: Bitset,
224 /// Chains cut because their geometry would not fit one edge.
225 pub splits: usize,
226 /// Directed edges an uncompacted build would have produced. Runs tile every
227 /// segment exactly once, so this is exact without keeping the segments.
228 pub raw_edge_count: u64,
229 /// Which blobs the chain pass actually had to read. The load-bearing
230 /// measurement for re-reading the way blobs rather than caching them.
231 pub kinds: Vec<u8>,
232}
233
234#[derive(Default)]
235struct ChainPass {
236 chains: Vec<Chain>,
237 pts: Vec<u32>,
238 lanes: Vec<u16>,
239 names: LocalNames,
240 endpoints: Vec<u32>,
241 splits: usize,
242 raw_edge_count: u64,
243}
244
245/// Walk every routable way, cutting chains at nodes that must survive, and stream
246/// the result into `spill`.
247///
248/// `degree` comes from [`count_degrees`] and `stop` marks nodes carrying a
249/// transit stop code; both are indexed by dense id, as is `coords`.
250///
251/// Nothing chain-shaped is retained. Only one chunk's worth exists at a time,
252/// which is what keeps this pass's footprint proportional to a chunk rather than
253/// to the road network.
254#[allow(clippy::too_many_arguments)]
255pub(crate) fn build<W: Write + Send>(
256 input: &Path,
257 blobs: &[BlobLoc],
258 blob_kinds: &[u8],
259 index: &NodeIndex,
260 coords: &[geom::Pt],
261 degree: &[u8],
262 stop: &Bitset,
263 slots: u32,
264 filter: crate::graph_build::RegionFilter,
265 pool: &mut NamePool<W>,
266 spill: &Spill,
267) -> Result<Chains> {
268 let mut out = Chains {
269 chain_count: 0,
270 lanes: Vec::new(),
271 endpoints: Bitset::new(u64::from(slots)),
272 splits: 0,
273 raw_edge_count: 0,
274 kinds: Vec::new(),
275 };
276 let mut writer = spill.writer()?;
277 out.kinds = pbf::run_pass_sink(
278 input,
279 blobs,
280 Some(blob_kinds),
281 KIND_WAYS,
282 "Pass 4: chains",
283 ChainPass::default,
284 |state: &mut ChainPass, block| chain_blob(state, block, index, coords, degree, stop, filter),
285 |chunk| {
286 let name_map = chunk
287 .names
288 .flush(pool)
289 .map_err(|e| Error(e.to_string()))?;
290 let lane_base = out.lanes.len() as u32;
291 out.lanes.extend_from_slice(&chunk.lanes);
292 crate::graph_build::cap_lane_pool(out.lanes.len())?;
293 for mut c in chunk.chains {
294 let lo = c.pts_start as usize;
295 let ids = &chunk.pts[lo..lo + c.pts_len as usize];
296 c.name_offset = if c.name_offset == u32::MAX {
297 NO_NAME
298 } else {
299 name_map[c.name_offset as usize]
300 };
301 if c.fwd_lane_count > 0 {
302 c.fwd_lane_off += lane_base;
303 }
304 if c.bwd_lane_count > 0 {
305 c.bwd_lane_off += lane_base;
306 }
307 // `pts_start` is assigned by the writer, so the chunk-local value
308 // is only used to find the ids above.
309 writer.push(&c, ids, coords)?;
310 }
311 for e in chunk.endpoints {
312 out.endpoints.set(u64::from(e));
313 }
314 out.splits += chunk.splits;
315 out.raw_edge_count += chunk.raw_edge_count;
316 Ok(())
317 },
318 )?;
319 out.chain_count = writer.finish()?;
320 Ok(out)
321}
322
323fn chain_blob(
324 state: &mut ChainPass,
325 block: &pbf::PrimitiveBlock,
326 index: &NodeIndex,
327 coords: &[geom::Pt],
328 degree: &[u8],
329 stop: &Bitset,
330 filter: crate::graph_build::RegionFilter,
331) -> Result<u8> {
332 let mut kinds = 0u8;
333 let mut path: Vec<u32> = Vec::new();
334 let mut hops: Vec<u32> = Vec::new();
335 visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {
336 let Element::Way(w) = el else {
337 return Ok(());
338 };
339 let type_ = tags::get_hw_id(w.tags.get_str("highway"));
340 if type_ == 0 {
341 return Ok(());
342 }
343 // Region filter: keep the way when ANY node touches the box. Coords
344 // are resolved by now so this is a direct test, same rule as the
345 // reference path's `way_blob`.
346 if let Some(b) = filter.as_ref() {
347 let mut touches = false;
348 for r in w.refs {
349 if let Some(d) = index.dense(*r) {
350 let (lat_e7, lon_e7) = coords[d as usize];
351 if b.contains_e7(lat_e7, lon_e7) {
352 touches = true;
353 break;
354 }
355 }
356 }
357 if !touches {
358 return Ok(());
359 }
360 }
361 let attrs = way_attrs(&w, type_, &mut state.lanes, &mut state.names);
362 path.clear();
363 hops.clear();
364 for pair in w.refs.windows(2) {
365 let Some((u, v)) = segment(index, pair[0], pair[1]) else {
366 // Not a segment — a dangling ref, or the way listing one node
367 // twice in a row. Skip it and let the next accepted pair decide
368 // whether it continues this run.
369 continue;
370 };
371 if path.last() != Some(&u) {
372 // The start of the way, the far side of a gap the graph does not
373 // bridge, or the node the previous cut ended on.
374 flush(state, &path, &hops, &attrs, coords);
375 path.clear();
376 hops.clear();
377 path.push(u);
378 }
379 let (a, b) = (coords[u as usize], coords[v as usize]);
380 hops.push(accurate_dist_mm(a.0, a.1, b.0, b.1));
381 path.push(v);
382 // `v` must survive when it is a junction, a dead end, or a transit
383 // stop the reconnect pass addresses directly. Cut there; the next pair
384 // restarts from it by the rule above.
385 if degree[v as usize] != 2 || stop.get(u64::from(v)) {
386 flush(state, &path, &hops, &attrs, coords);
387 path.clear();
388 hops.clear();
389 }
390 }
391 // The way's last node is a chain boundary whatever its degree: a chain may
392 // not continue into the next way.
393 flush(state, &path, &hops, &attrs, coords);
394 Ok(())
395 })?;
396 Ok(kinds)
397}
398
399/// Emit `path` as one or more chains, splitting it to fit the geometry budget.
400fn flush(
401 state: &mut ChainPass,
402 path: &[u32],
403 hops: &[u32],
404 attrs: &WayAttrs,
405 coords: &[geom::Pt],
406) {
407 if path.len() < 2 {
408 return;
409 }
410 debug_assert_eq!(hops.len(), path.len() - 1);
411 let runs = split_runs(path, coords);
412 if runs.len() > 1 {
413 state.splits += runs.len() - 1;
414 }
415 for (lo, hi) in runs {
416 state.endpoints.push(path[lo]);
417 state.endpoints.push(path[hi]);
418 let pts_start = state.pts.len() as u64;
419 state.pts.extend_from_slice(&path[lo..=hi]);
420 // Directed edges an uncompacted build would have emitted for this run:
421 // one per segment per permitted direction. Runs tile every segment of the
422 // way exactly once, so summing them is exact without keeping the segments.
423 state.raw_edge_count += (hi - lo) as u64 * if attrs.oneway { 1 } else { 2 };
424 state.chains.push(Chain {
425 pts_start,
426 pts_len: (hi - lo + 1) as u32,
427 dist_mm: hops[lo..hi].iter().fold(0u32, |a, d| a.saturating_add(*d)),
428 name_offset: attrs.name,
429 type_: attrs.type_,
430 speed_limit: attrs.speed_limit,
431 oneway: attrs.oneway,
432 // Forward is along ref order, and so is the chain: no reorientation,
433 // so no chance of handing the masks to the wrong end.
434 fwd_lane_off: attrs.fwd_lane_off,
435 fwd_lane_count: attrs.fwd_lane_count,
436 bwd_lane_off: attrs.bwd_lane_off,
437 bwd_lane_count: attrs.bwd_lane_count,
438 });
439 }
440}
441
442/// Cut `path` into runs that each fit one edge's geometry.
443///
444/// Returns inclusive index ranges. A run of two nodes is always allowed even if
445/// its single segment is too long to delta-encode: the caller stores no geometry
446/// for it, and the reader's straight-chord fallback is then exactly right,
447/// because a two-node run *is* a straight chord.
448fn split_runs(path: &[u32], coords: &[geom::Pt]) -> Vec<(usize, usize)> {
449 let point = |n: u32| coords[n as usize];
450 let mut runs = Vec::new();
451 let mut start = 0usize;
452 let mut cost = 1u64;
453 let mut i = 1usize;
454 while i < path.len() {
455 let step = geom::segment_points(point(path[i - 1]), point(path[i]));
456 if cost + step <= u64::from(geom::MAX_POINTS) {
457 cost += step;
458 i += 1;
459 continue;
460 }
461 if i - 1 > start {
462 // Close the run before this segment and retry it with a fresh budget
463 // starting at the shared node.
464 runs.push((start, i - 1));
465 start = i - 1;
466 cost = 1;
467 } else {
468 // One segment that cannot be encoded at all, even alone.
469 runs.push((start, i));
470 start = i;
471 cost = 1;
472 i += 1;
473 }
474 }
475 if start < path.len() - 1 {
476 runs.push((start, path.len() - 1));
477 }
478 runs
479}
480
481/// Does dense node `n` survive as a graph node?
482///
483/// A chain endpoint always does. Anything of degree 1 or 3+ is a junction, a
484/// dead end or an anchor the walks must address. Degree 2 is the only
485/// collapsible case and is handled by the walk, not here.
486///
487/// Degree 0 is dropped unless it carries a transit stop: a node with no
488/// incident segment is a way the region filter removed (every road node outside
489/// the region reads degree 0 once its ways are skipped), dead weight in
490/// `nodes.bin` with no edge ever addressing it. An isolated stop is the one
491/// exception — the reconnect pass addresses stop nodes directly.
492#[inline]
493pub(crate) fn survives(endpoints: &Bitset, degree: &[u8], stop: &Bitset, n: u32) -> bool {
494 if endpoints.get(u64::from(n)) {
495 return true;
496 }
497 let d = degree[n as usize];
498 d != 2 && (d != 0 || stop.get(u64::from(n)))
499}
500
501// ---- the spill -----------------------------------------------------------
502//
503// Chains are the last structure in the build that scales with the road network
504// rather than with the node set, and every stage after them is a sequential scan.
505// So they go to two flat files and the stages read them back: the CSR build, the
506// reconnect BFS and each write round all stream, and none of them needs the chain
507// set resident.
508//
509// Two properties are worth the redundancy in the record:
510//
511// * **The header is fixed size**, so the chain count is the file's length divided
512// by the record size, and any stage can seek straight to chain *k* and process a
513// contiguous slice of chains without reading the ones before it.
514// * **`chains.pts` holds coordinates, not node ids**, so `coords` — the largest
515// array in the build, and the only one indexed by *marked* rather than surviving
516// node — can be freed the moment the spill is written. The cost is that the two
517// endpoint node ids have to be repeated in the header, which is eight bytes a
518// chain against gigabytes of coordinates.
519
520/// Bytes per record in `chains.hdr`. The trailing padding is reserved and written
521/// as zero, so the record can grow a field without changing the stride.
522pub(crate) const CHAIN_REC_BYTES: u64 = 48;
523
524/// Bytes per point in `chains.pts`: `i32 lat_e7`, `i32 lon_e7`.
525const CHAIN_PT_BYTES: u64 = 8;
526
527/// One chain, as `chains.hdr` stores it.
528#[derive(Clone, Copy)]
529pub(crate) struct ChainRec {
530 /// First point's index in `chains.pts`.
531 pub pts_start: u64,
532 pub pts_len: u32,
533 /// Dense id of the first point. Kept even though the point itself is stored,
534 /// because the writer needs the *node* to map to a final id and the
535 /// coordinates cannot be mapped back to one.
536 pub first: u32,
537 /// Dense id of the last point.
538 pub last: u32,
539 pub dist_mm: u32,
540 pub name_offset: u32,
541 pub fwd_lane_off: u32,
542 pub bwd_lane_off: u32,
543 pub fwd_lane_count: u16,
544 pub bwd_lane_count: u16,
545 pub type_: u8,
546 pub speed_limit: u8,
547 pub oneway: bool,
548}
549
550include!("chains_part1.rs");
551include!("chains_part2.rs");