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

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

compact.rs445 lines · 14.9 KiBRaw
1//! Degree-2 chain collapsing: the step that turns one graph edge per OSM
2//! geometry vertex into one graph edge per road between junctions.
3//!
4//! Before this stage, `graph_build` emitted an edge for every consecutive pair
5//! of way nodes, so every geometry vertex was a routing node with two
6//! neighbours. California came out at 35.8 M nodes / 74.3 M directed edges — a
7//! ratio of 2.07, the signature of a graph where almost every node is a
8//! pass-through. Those nodes cost 16 bytes each in `nodes.bin`, 14 bytes per
9//! direction in `edges.bin` and 8 bytes per direction in `lanes.bin`, and they
10//! buy nothing: no route ever chooses anything at them.
11//!
12//! Collapsing them moves the vertices into `intermediate.bin` at 4 bytes each
13//! (see [`crate::geom`]) and leaves the road network's shape untouched.
14//!
15//! # What may be collapsed
16//!
17//! A node is interior to a chain only when removing it cannot change a routing
18//! decision or lose data:
19//!
20//! * exactly two incident segments, leading to two *distinct* neighbours that
21//! are both distinct from the node itself;
22//! * both segments agree on road type, speed limit, name and one-way-ness, so
23//! the merged edge can carry a single set of attributes;
24//! * their lane masks agree *in each traversed direction* — checked on mask
25//! contents, not on pool offsets, since two ways with identical lanes intern
26//! them at different offsets;
27//! * one-way segments must actually flow through the node, one in and one out;
28//! * the node carries no transit stop code, because `graph_build`'s isolated
29//! stop reconnection addresses stop nodes directly.
30//!
31//! # Chains that close on themselves
32//!
33//! A ring road whose every node is interior has no anchor to start from. The
34//! lowest-numbered node on such a cycle is promoted back to a real node so the
35//! ring becomes one edge from it to itself. A self-loop is inert for routing —
36//! no shortest path traverses one — but it keeps the ring snappable and drawable,
37//! which is all its interior nodes were doing anyway.
38
39use crate::geom;
40
41/// Sentinel for "this node was collapsed away".
42pub const REMOVED: u32 = u32::MAX;
43
44/// An undirected road segment between two adjacent way nodes: what pass 3
45/// produces before it is split into one or two directed edges.
46///
47/// Road type, speed limit and name come from the way and so are shared by both
48/// directions; only lane masks differ, which is why they are stored per
49/// direction.
50#[derive(Clone, Copy)]
51pub struct Seg {
52 pub u: u32,
53 pub v: u32,
54 pub dist_mm: u32,
55 pub name_offset: u32,
56 pub type_: u8,
57 pub speed_limit: u8,
58 /// True when the way is only traversable `u` -> `v`.
59 pub oneway: bool,
60 pub fwd_lane_off: u32,
61 pub fwd_lane_count: u16,
62 pub bwd_lane_off: u32,
63 pub bwd_lane_count: u16,
64}
65
66impl Seg {
67 /// The endpoint that is not `n`. For a self-loop this is `n` again.
68 #[inline]
69 fn other(&self, n: u32) -> u32 {
70 if self.u == n {
71 self.v
72 } else {
73 self.u
74 }
75 }
76
77 /// Lane pool range for traversal starting at `from`.
78 #[inline]
79 fn lanes_from(&self, from: u32) -> (u32, u16) {
80 if self.u == from {
81 (self.fwd_lane_off, self.fwd_lane_count)
82 } else {
83 (self.bwd_lane_off, self.bwd_lane_count)
84 }
85 }
86}
87
88/// One collapsed run of segments, to be emitted as one directed edge per
89/// permitted direction.
90///
91/// `pts_start`/`pts_len` index [`Compacted::pts`], which holds *original* node
92/// ids: the caller needs their coordinates for the geometry blob, and only its
93/// two endpoints survive into `nodes.bin`.
94pub struct Chain {
95 pub pts_start: u64,
96 pub pts_len: u32,
97 /// Sum of the merged segments' distances, saturating.
98 pub dist_mm: u32,
99 pub name_offset: u32,
100 pub type_: u8,
101 pub speed_limit: u8,
102 pub oneway: bool,
103 /// Lanes for `pts[0]` -> `pts[last]`.
104 pub fwd_lane_off: u32,
105 pub fwd_lane_count: u16,
106 /// Lanes for `pts[last]` -> `pts[0]`. Meaningless when `oneway`.
107 pub bwd_lane_off: u32,
108 pub bwd_lane_count: u16,
109}
110
111impl Chain {
112 /// Original node ids from tail to head.
113 pub fn pts<'a>(&self, all: &'a [u32]) -> &'a [u32] {
114 let s = self.pts_start as usize;
115 &all[s..s + self.pts_len as usize]
116 }
117}
118
119pub struct Compacted {
120 /// Original node id -> surviving node id, or [`REMOVED`].
121 pub new_id: Vec<u32>,
122 /// How many nodes survived.
123 pub kept: u32,
124 pub chains: Vec<Chain>,
125 pub pts: Vec<u32>,
126 /// Chains that had to be cut because their geometry would not fit one edge.
127 pub splits: usize,
128}
129
130/// Collapse every eligible degree-2 chain in `segs`.
131///
132/// `point` supplies a node's coordinates (needed to budget the geometry blob),
133/// `is_stop` reports whether it carries a transit stop code, and `lane_pool` is
134/// the interned lane-mask pool the segments' offsets point into.
135pub fn compact(
136 node_count: u32,
137 segs: &[Seg],
138 lane_pool: &[u16],
139 point: impl Fn(u32) -> geom::Pt,
140 is_stop: impl Fn(u32) -> bool,
141) -> Compacted {
142 let n = node_count as usize;
143 let inc = Incidence::build(n, segs);
144 let mut interior = classify(n, segs, lane_pool, &inc, &is_stop);
145
146 let mut out = Compacted {
147 new_id: Vec::new(),
148 kept: 0,
149 chains: Vec::new(),
150 pts: Vec::new(),
151 splits: 0,
152 };
153 let mut seg_used = vec![false; segs.len()];
154
155 // Walk every chain that has at least one real endpoint.
156 for a in 0..n as u32 {
157 if interior[a as usize] {
158 continue;
159 }
160 for si in inc.at(a) {
161 walk_chain(a, si, segs, &inc, &mut interior, &mut seg_used, &point, &mut out);
162 }
163 }
164
165 // Anything still unused is a cycle of interior nodes with no anchor. Break
166 // it at its lowest-numbered node and walk again. Each pass consumes at
167 // least one cycle, so this terminates.
168 for si in 0..segs.len() {
169 if seg_used[si] {
170 continue;
171 }
172 let anchor = cycle_anchor(si, segs, &inc);
173 interior[anchor as usize] = false;
174 for sj in inc.at(anchor) {
175 walk_chain(anchor, sj, segs, &inc, &mut interior, &mut seg_used, &point, &mut out);
176 }
177 }
178
179 // Renumber. Survivors keep their relative order, so the Morton sort the
180 // device binary-searches is preserved for free.
181 out.new_id = vec![REMOVED; n];
182 let mut next = 0u32;
183 for i in 0..n {
184 if !interior[i] {
185 out.new_id[i] = next;
186 next += 1;
187 }
188 }
189 out.kept = next;
190 out
191}
192
193/// Segment ids incident to each node, as a CSR.
194struct Incidence {
195 start: Vec<u64>,
196 seg: Vec<u32>,
197}
198
199impl Incidence {
200 fn build(n: usize, segs: &[Seg]) -> Incidence {
201 let mut start = vec![0u64; n + 2];
202 for s in segs {
203 start[s.u as usize + 1] += 1;
204 start[s.v as usize + 1] += 1;
205 }
206 for i in 0..=n {
207 start[i + 1] += start[i];
208 }
209 let mut seg = vec![0u32; start[n] as usize];
210 let mut cursor: Vec<u64> = start[..=n].to_vec();
211 for (i, s) in segs.iter().enumerate() {
212 for endpoint in [s.u, s.v] {
213 let c = &mut cursor[endpoint as usize];
214 seg[*c as usize] = i as u32;
215 *c += 1;
216 }
217 }
218 start.truncate(n + 1);
219 Incidence { start, seg }
220 }
221
222 #[inline]
223 fn at(&self, n: u32) -> impl Iterator<Item = u32> + '_ {
224 let (a, b) = (self.start[n as usize] as usize, self.start[n as usize + 1] as usize);
225 self.seg[a..b].iter().copied()
226 }
227
228 #[inline]
229 fn degree(&self, n: u32) -> u64 {
230 self.start[n as usize + 1] - self.start[n as usize]
231 }
232}
233
234/// Decide, for every node, whether it is a pass-through vertex that can be
235/// folded into an edge's geometry.
236fn classify(
237 n: usize,
238 segs: &[Seg],
239 lane_pool: &[u16],
240 inc: &Incidence,
241 is_stop: &impl Fn(u32) -> bool,
242) -> Vec<bool> {
243 let lanes = |off: u32, count: u16| -> &[u16] {
244 if count == 0 || off == u32::MAX {
245 return &[];
246 }
247 let s = off as usize;
248 &lane_pool[s..s + count as usize]
249 };
250
251 let mut interior = vec![false; n];
252 for w in 0..n as u32 {
253 if is_stop(w) {
254 continue;
255 }
256 // Degree 0 is dropped rather than kept: a node with no incident segment
257 // is a way the region filter removed, dead weight in `nodes.bin` with no
258 // edge ever addressing it. Marked interior so the renumber below hands
259 // it REMOVED; no walk can reach a node with no segments, so the mark is
260 // unreachable by construction.
261 if inc.degree(w) == 0 {
262 interior[w as usize] = true;
263 continue;
264 }
265 if inc.degree(w) != 2 {
266 continue;
267 }
268 let mut it = inc.at(w);
269 let (i1, i2) = match (it.next(), it.next()) {
270 (Some(a), Some(b)) => (a, b),
271 _ => continue,
272 };
273 let (s1, s2) = (&segs[i1 as usize], &segs[i2 as usize]);
274 let (a, b) = (s1.other(w), s2.other(w));
275 // Distinct neighbours, neither of them w. `a == b` means two parallel
276 // segments between the same pair of nodes; collapsing that would fuse
277 // two genuinely different roads into one polyline.
278 if a == w || b == w || a == b {
279 continue;
280 }
281 if s1.type_ != s2.type_
282 || s1.speed_limit != s2.speed_limit
283 || s1.name_offset != s2.name_offset
284 || s1.oneway != s2.oneway
285 {
286 continue;
287 }
288 if s1.oneway {
289 // Traffic has to pass through: one segment must end at w and the
290 // other start there. Two one-ways both pointing at w make it a
291 // sink, which is a real feature of the network, not a pass-through.
292 let flows = (s1.v == w && s2.u == w) || (s2.v == w && s1.u == w);
293 if !flows {
294 continue;
295 }
296 }
297 // Lane masks must agree along each direction actually traversed.
298 let (o1, c1) = s1.lanes_from(a);
299 let (o2, c2) = s2.lanes_from(w);
300 if lanes(o1, c1) != lanes(o2, c2) {
301 continue;
302 }
303 if !s1.oneway {
304 let (o3, c3) = s2.lanes_from(b);
305 let (o4, c4) = s1.lanes_from(w);
306 if lanes(o3, c3) != lanes(o4, c4) {
307 continue;
308 }
309 }
310 interior[w as usize] = true;
311 }
312 interior
313}
314
315/// Follow the chain that leaves anchor `a` through segment `si`, emitting one or
316/// more [`Chain`]s. Does nothing if the segment was already consumed from the
317/// other end.
318#[allow(clippy::too_many_arguments)]
319fn walk_chain(
320 a: u32,
321 si: u32,
322 segs: &[Seg],
323 inc: &Incidence,
324 interior: &mut [bool],
325 seg_used: &mut [bool],
326 point: &impl Fn(u32) -> geom::Pt,
327 out: &mut Compacted,
328) {
329 if seg_used[si as usize] {
330 return;
331 }
332 let mut path = vec![a];
333 // One entry per hop in `path`, so a split run can take its own distances
334 // rather than look them up again. The lookup would have to match a segment by
335 // its endpoints, which is ambiguous for a two-node run between two junctions
336 // joined by more than one way.
337 let mut hops: Vec<u32> = Vec::new();
338 let mut prev_seg = si;
339 let mut cur = segs[si as usize].other(a);
340 seg_used[si as usize] = true;
341 hops.push(segs[si as usize].dist_mm);
342 path.push(cur);
343
344 while interior[cur as usize] {
345 // Interior nodes have exactly two incident segments by construction, so
346 // "the one we did not arrive on" is well defined.
347 let next_seg = match inc.at(cur).find(|s| *s != prev_seg) {
348 Some(s) => s,
349 None => break,
350 };
351 if seg_used[next_seg as usize] {
352 break;
353 }
354 seg_used[next_seg as usize] = true;
355 hops.push(segs[next_seg as usize].dist_mm);
356 cur = segs[next_seg as usize].other(cur);
357 path.push(cur);
358 prev_seg = next_seg;
359 }
360
361 // A one-way chain must be emitted along its traffic flow, not along whichever
362 // end the walk happened to start from. `classify` guarantees every segment in
363 // it is consistently oriented, so the first segment decides: if the walk came
364 // in against the flow, turn the whole path around.
365 let mut first_seg = si;
366 let mut last_seg = prev_seg;
367 if segs[si as usize].oneway && segs[si as usize].u != path[0] {
368 path.reverse();
369 hops.reverse();
370 std::mem::swap(&mut first_seg, &mut last_seg);
371 }
372
373 // The chain's attributes are those of its first segment; every segment in it
374 // was required to agree.
375 let head = &segs[first_seg as usize];
376 let (fwd_lane_off, fwd_lane_count) = head.lanes_from(path[0]);
377 let last = path[path.len() - 1];
378 let (bwd_lane_off, bwd_lane_count) = segs[last_seg as usize].lanes_from(last);
379
380 let runs = split_runs(&path, point);
381 if runs.len() > 1 {
382 out.splits += runs.len() - 1;
383 }
384 for (lo, hi) in runs {
385 // A cut point becomes a real node again.
386 if lo != 0 {
387 interior[path[lo] as usize] = false;
388 }
389 let pts_start = out.pts.len() as u64;
390 out.pts.extend_from_slice(&path[lo..=hi]);
391 out.chains.push(Chain {
392 pts_start,
393 pts_len: (hi - lo + 1) as u32,
394 dist_mm: hops[lo..hi].iter().fold(0u32, |a, d| a.saturating_add(*d)),
395 name_offset: head.name_offset,
396 type_: head.type_,
397 speed_limit: head.speed_limit,
398 oneway: head.oneway,
399 fwd_lane_off,
400 fwd_lane_count,
401 bwd_lane_off,
402 bwd_lane_count,
403 });
404 }
405}
406
407/// Cut `path` into runs that each fit one edge's geometry.
408///
409/// Returns inclusive index ranges. A run of two nodes is always allowed even if
410/// its single segment is too long to delta-encode: the caller stores no geometry
411/// for it, and the reader's straight-chord fallback is then exactly right,
412/// because a two-node run *is* a straight chord.
413fn split_runs(path: &[u32], point: &impl Fn(u32) -> geom::Pt) -> Vec<(usize, usize)> {
414 let mut runs = Vec::new();
415 let mut start = 0usize;
416 let mut cost = 1u64;
417 let mut i = 1usize;
418 while i < path.len() {
419 let step = geom::segment_points(point(path[i - 1]), point(path[i]));
420 if cost + step <= u64::from(geom::MAX_POINTS) {
421 cost += step;
422 i += 1;
423 continue;
424 }
425 if i - 1 > start {
426 // Close the run before this segment and retry it with a fresh
427 // budget starting at the shared node.
428 runs.push((start, i - 1));
429 start = i - 1;
430 cost = 1;
431 } else {
432 // One segment that cannot be encoded at all, even alone.
433 runs.push((start, i));
434 start = i;
435 cost = 1;
436 i += 1;
437 }
438 }
439 if start < path.len() - 1 {
440 runs.push((start, path.len() - 1));
441 }
442 runs
443}
444
445include!("compact_part1.rs");