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

Modern-Apps.git / scripts / maps / mamaps_build / src / corridor.rs

corridor.rs232 lines · 9.7 KiBRaw
1//! Corridor generalisation: make a numbered road appear and disappear as one thing.
2//!
3//! [`schema::roads`](crate::schema::roads) assigns `min_zoom` from the OSM `highway` tag
4//! alone, and that is right for a way considered on its own. A real corridor is not one
5//! way, though, and it does not hold one class along its length: CA-99 is `motorway`
6//! (min_zoom 3) for long stretches and `trunk` (5) or `primary` (7) through the towns it
7//! passes. At z6 the tile carries the motorway parts and not the rest, so the road draws
8//! as a handful of disconnected stubs with nothing joining them — the map's most visible
9//! defect at continental zooms, and the reason this module exists.
10//!
11//! The fix is the standard generalisation one: decide `min_zoom` for the **corridor**
12//! rather than for the way, by taking the shallowest `min_zoom` any of its ways asks for.
13//! A corridor that is worth drawing at z3 anywhere is worth drawing at z3 everywhere, or
14//! it should not be drawn at z3 at all.
15//!
16//! # What counts as one corridor
17//!
18//! Two conditions, both required:
19//!
20//! * **The same route identity** — the `ref` tag, so "CA 99" joins "CA 99". Without this
21//! every road that happens to touch a motorway junction would be promoted to the
22//! motorway's zoom, which is the whole network.
23//! * **Connected end to end** — they share an endpoint node. Without this, "CA 1" in
24//! California and an unrelated "CA 1" elsewhere in the extract would merge, and a
25//! corridor's promotion would leak across a gap it does not actually cross.
26//!
27//! Endpoints only, not every node: two roads that merely cross at a junction are not one
28//! corridor, and OSM splits a way at the junction anyway, so a genuine continuation
29//! shares an endpoint.
30//!
31//! Slip roads are excluded by the caller. A `motorway_link` often carries its parent's
32//! `ref` and touches the corridor at both ends, so it would be promoted with it — putting
33//! a scatter of junction stubs on the map at world zoom, where the corridor itself is a
34//! single line. A ramp is not part of the through route.
35//!
36//! # Cost
37//!
38//! One `Segment` per road way carrying a `ref`, which is a small minority of ways, and a
39//! sort of twice that many endpoint records. No node geometry and no second pass over the
40//! PBF: pass 1 already decodes the tags and the refs this needs.
41
42/// One road way's corridor identity, as pass 1 sees it.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct Segment {
45 pub way_id: i64,
46 /// The route identity, interned by the caller. Ways only join a corridor with a peer
47 /// carrying the same one.
48 pub route: u64,
49 /// First and last node of the way. A way with fewer than two nodes is not a corridor
50 /// segment and should not be offered here.
51 pub first_node: i64,
52 pub last_node: i64,
53 /// What [`crate::schema::roads::classify`] asked for, before promotion.
54 pub min_zoom: u8,
55}
56
57/// Promote each segment's `min_zoom` to the shallowest in its corridor.
58///
59/// Returns `(way id, promoted min_zoom)` for the ways that actually move, ascending by
60/// way id so the materialise pass can binary-search it. Ways whose corridor does not
61/// change their zoom are left out — on a typical extract most of them.
62pub fn promote(segments: &[Segment]) -> Vec<(i64, u8)> {
63 if segments.is_empty() {
64 return Vec::new();
65 }
66 let mut parent: Vec<u32> = (0..segments.len() as u32).collect();
67
68 // Union ways that share a route AND an endpoint. Sorting the endpoint records puts
69 // every such pair in one run, which avoids a hash map over twice the segment count -
70 // the largest thing this pass would otherwise allocate.
71 let mut endpoints: Vec<(u64, i64, u32)> = Vec::with_capacity(segments.len() * 2);
72 for (index, segment) in segments.iter().enumerate() {
73 endpoints.push((segment.route, segment.first_node, index as u32));
74 if segment.last_node != segment.first_node {
75 endpoints.push((segment.route, segment.last_node, index as u32));
76 }
77 }
78 endpoints.sort_unstable();
79 for run in endpoints.chunk_by(|a, b| a.0 == b.0 && a.1 == b.1) {
80 for pair in run.windows(2) {
81 union(&mut parent, pair[0].2, pair[1].2);
82 }
83 }
84
85 // Shallowest min_zoom per corridor, then anything that moves.
86 let mut shallowest: Vec<u8> = vec![u8::MAX; segments.len()];
87 for (index, segment) in segments.iter().enumerate() {
88 let root = find(&mut parent, index as u32) as usize;
89 shallowest[root] = shallowest[root].min(segment.min_zoom);
90 }
91 let mut promoted: Vec<(i64, u8)> = Vec::new();
92 for (index, segment) in segments.iter().enumerate() {
93 let root = find(&mut parent, index as u32) as usize;
94 let zoom = shallowest[root];
95 if zoom < segment.min_zoom {
96 promoted.push((segment.way_id, zoom));
97 }
98 }
99 promoted.sort_unstable_by_key(|(id, _)| *id);
100 promoted
101}
102
103fn find(parent: &mut [u32], mut node: u32) -> u32 {
104 while parent[node as usize] != node {
105 // Path halving: keeps the trees flat without a second pass.
106 parent[node as usize] = parent[parent[node as usize] as usize];
107 node = parent[node as usize];
108 }
109 node
110}
111
112fn union(parent: &mut [u32], a: u32, b: u32) {
113 let (ra, rb) = (find(parent, a), find(parent, b));
114 if ra != rb {
115 parent[ra.max(rb) as usize] = ra.min(rb);
116 }
117}
118
119/// Intern a route identity. `None` for a way that is not part of a numbered route.
120///
121/// The `ref` tag and nothing else. `name` was considered and rejected: "Main Street"
122/// names thousands of unconnected roads, and the connectivity condition is not enough to
123/// keep them apart where two of them meet at a junction.
124pub fn route_key(tags: &(impl crate::schema::TagSource + ?Sized)) -> Option<u64> {
125 let value = tags.get("ref")?.trim();
126 if value.is_empty() {
127 return None;
128 }
129 use std::hash::{Hash, Hasher};
130 let mut hasher = std::collections::hash_map::DefaultHasher::new();
131 value.hash(&mut hasher);
132 Some(hasher.finish())
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 fn segment(way_id: i64, route: u64, first: i64, last: i64, min_zoom: u8) -> Segment {
140 Segment { way_id, route, first_node: first, last_node: last, min_zoom }
141 }
142
143 /// THE case this module exists for: a numbered route that is motorway, then trunk,
144 /// then motorway again draws as three stubs at z6 unless the middle is promoted.
145 #[test]
146 fn a_trunk_between_two_motorway_stretches_is_promoted_to_the_motorways_zoom() {
147 let corridor = [
148 segment(1, 99, 10, 11, 3), // motorway
149 segment(2, 99, 11, 12, 5), // trunk through a town
150 segment(3, 99, 12, 13, 3), // motorway again
151 ];
152 assert_eq!(promote(&corridor), vec![(2, 3)], "only the trunk moves, and it moves to 3");
153 }
154
155 /// Promotion runs the length of the corridor, not just to the neighbour: a primary
156 /// two hops from the motorway is still part of the same road.
157 #[test]
158 fn promotion_reaches_the_whole_connected_run() {
159 let corridor = [
160 segment(1, 99, 10, 11, 3),
161 segment(2, 99, 11, 12, 5),
162 segment(3, 99, 12, 13, 7),
163 segment(4, 99, 13, 14, 7),
164 ];
165 assert_eq!(promote(&corridor), vec![(2, 3), (3, 3), (4, 3)]);
166 }
167
168 /// Without the route condition, every road touching a motorway junction would be
169 /// promoted to the motorway's zoom, which is most of the network.
170 #[test]
171 fn a_different_route_sharing_a_junction_is_not_promoted() {
172 let roads = [
173 segment(1, 99, 10, 11, 3), // CA 99, motorway
174 segment(2, 50, 11, 12, 9), // a different route leaving the same junction
175 ];
176 assert!(promote(&roads).is_empty(), "a junction is not a corridor");
177 }
178
179 /// Without the connectivity condition, two unconnected roads that happen to share a
180 /// `ref` would merge and promotion would leak across the gap.
181 #[test]
182 fn the_same_ref_in_two_disconnected_places_stays_two_corridors() {
183 let roads = [
184 segment(1, 1, 10, 11, 3),
185 segment(2, 1, 500, 501, 9), // same ref, nowhere near
186 ];
187 assert!(promote(&roads).is_empty());
188 }
189
190 /// A corridor already uniform costs nothing and produces no entries, which is what
191 /// keeps the promotion table small on a real extract.
192 #[test]
193 fn a_uniform_corridor_produces_no_entries() {
194 let corridor = [segment(1, 99, 10, 11, 3), segment(2, 99, 11, 12, 3)];
195 assert!(promote(&corridor).is_empty());
196 }
197
198 /// Direction is not guaranteed: OSM splits a way wherever it likes and the halves may
199 /// meet head-to-head or tail-to-tail.
200 #[test]
201 fn segments_join_whichever_way_round_they_are_drawn() {
202 for (first, last) in [(12, 11), (11, 12)] {
203 let corridor = [segment(1, 99, 10, 11, 3), segment(2, 99, first, last, 7)];
204 assert_eq!(promote(&corridor), vec![(2, 3)], "{first}->{last} must join");
205 }
206 }
207
208 /// A closed loop (a ring road tagged with a ref) has one endpoint, and must not
209 /// confuse the endpoint index or be dropped.
210 #[test]
211 fn a_closed_way_is_still_a_segment() {
212 let corridor = [segment(1, 99, 10, 10, 7), segment(2, 99, 10, 11, 3)];
213 assert_eq!(promote(&corridor), vec![(1, 3)]);
214 }
215
216 #[test]
217 fn the_table_comes_back_sorted_by_way_id() {
218 let corridor = [
219 segment(90, 7, 1, 2, 9),
220 segment(10, 7, 2, 3, 3),
221 segment(50, 7, 3, 4, 9),
222 ];
223 let promoted = promote(&corridor);
224 let ids: Vec<i64> = promoted.iter().map(|(id, _)| *id).collect();
225 assert_eq!(ids, vec![50, 90], "ascending, so the materialise pass can bisect");
226 }
227
228 #[test]
229 fn nothing_in_nothing_out() {
230 assert!(promote(&[]).is_empty());
231 }
232}