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

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

coalesce.rs379 lines · 17.2 KiBRaw
1//! Merging a layer's line features into one per class, and joining the fragments that continue each
2//! other.
3//!
4//! # Why this exists
5//!
6//! An OSM way is an **editing** unit. It is split at every junction, bridge, surface change and tag
7//! edit, none of which has anything to do with what gets drawn. Carrying one way as one rendering
8//! feature therefore pays a feature header and a part entry for each fragment of a road, and on a
9//! us-west z7 tile that came to:
10//!
11//! | | count | width | bytes |
12//! |---|---|---|---|
13//! | feature records | 57,218 | 16 | 916 KB |
14//! | part entries | 57,218 | 12 | 687 KB |
15//! | coordinate arena | 189,484 points | ~2-3 | ~0.5 MB |
16//!
17//! Three quarters of the layer was bookkeeping, 61% of its parts held exactly two points, and the
18//! mean was 3.31 points per part. The same tile's `boundaries` layer -- whose relations arrive
19//! already merged -- ran 139 features over 667 parts, which is what healthy looks like.
20//!
21//! It compounds three ways. The headers are the obvious cost. Less obvious is that
22//! [`tilecodec::mamaps::body`] restarts its coordinate deltas at every part so a part decodes
23//! independently, so at 3.3 points per part most points are the *first* of their part and pay a full
24//! absolute coordinate where a continued line would pay one byte. And a `.mamaps` layer indexes its
25//! features with a `u16`, so a North America build stopped outright at `layer 4 has 79407 features,
26//! past the 65535 a .mamaps body can index`.
27//!
28//! This is not a container-format problem -- MVT has the same one, which is why `tippecanoe` ships
29//! `--coalesce`. It is that nothing in this pipeline ever merged what OSM had split.
30//!
31//! # What it does
32//!
33//! Two steps, and the first is the one that matters for the `u16`:
34//!
35//! 1. **Group by class.** Line features drawn identically -- same `kind`, `kind_detail`, `flags`
36//! and `transit_color` -- become one multi-part feature. Nothing about the geometry changes; a
37//! `.mamaps` line feature has always been able to hold many parts, and `boundaries` already did.
38//! 2. **Join what continues.** Within a group, a part whose last point is another's first point is
39//! the same line cut in half, so they are spliced into one part. That removes the part entry and
40//! lets the delta run through the joint instead of restarting.
41//!
42//! # Why it is safe
43//!
44//! A `.mamaps` feature carries no identity of its own: [`Feature`] is `kind`, `kind_detail`,
45//! `geom_type`, `flags`, `transit_color`, the three transit lane fields and a part range, and
46//! nothing else.
47//! Two line features that
48//! agree on all of those are indistinguishable to a renderer, so merging them cannot change a pixel.
49//! There are no names or ids on a feature to lose, and `winding` is meaningless on an open path --
50//! which [`crate::rings::normalise`] states outright.
51//!
52//! `transit_color` is part of the key rather than dropped from it because it is the one per-feature
53//! field a renderer reads directly. Two subway lines of different operator colours crossing a tile
54//! are the same `kind` and would otherwise collapse into one feature wearing whichever colour came
55//! first. The lane fields join it for the same reason one step on: two routes of *one* colour on
56//! different corridor ordinals are drawn as two parallel lines, and merging them would put both
57//! on whichever ordinal came first.
58//!
59//! The carriageway joins the key too, and it is the one part of the key that is **not** on the
60//! feature: the directional split lives in a side table because it is present on a minority of
61//! roads. It has to be in the key all the same, because two four-lane roads that divide 3/1 and
62//! 1/3 are drawn as different surfaces with the centre line in different places. A one-way and a
63//! two-way are already separated for free, because that one is a flag.
64//!
65//! Direction is not preserved through a join and does not need to be: nothing in
66//! [`tilecodec::mamaps::body`]'s flag set reads a line's direction, so `A -> B` and `B -> A` draw
67//! the same. Joins are made head-to-tail only, so a part is never reversed anyway.
68//!
69//! # Ordering, and why the archive stays reproducible
70//!
71//! Called on a tile that the merge has already assembled, so it sees a layer's features in the order
72//! the store yielded them, and it emits each class at the position of that class's **first** feature.
73//! A group's parts stay in feature-then-part order and chains are built by walking them in that
74//! order, so nothing here depends on a hash map's iteration order or on how the map phase chunked
75//! its input.
76
77use std::collections::HashMap;
78
79use crate::coalesce_extra::Run;
80use tilecodec::mamaps::body::{
81 BuildingAttrs, Carriageway, LaneTurns, Layer, Part, GEOM_LINE, WINDING_OUTER,
82};
83
84/// What coalescing a build saved, for the report.
85#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
86pub struct Stats {
87 pub features_before: u64,
88 pub features_after: u64,
89 pub parts_before: u64,
90 pub parts_after: u64,
91}
92
93impl Stats {
94 pub fn add(&mut self, other: Stats) {
95 self.features_before += other.features_before;
96 self.features_after += other.features_after;
97 self.parts_before += other.parts_before;
98 self.parts_after += other.parts_after;
99 }
100}
101
102/// What makes two line features interchangeable to a renderer. The trailing `name_idx` keeps two
103/// differently-named roads or rivers of the same class apart, so a curved label is never attached
104/// to a line that merged with a neighbour of another name; same-named fragments still merge.
105///
106/// The last three come from the carriageway side table rather than from the feature, and they are
107/// in the key for the same reason `transit_color` is: two four-lane roads of one class that divide
108/// 3/1 and 1/3 are drawn as different surfaces, and merging them would put both on whichever split
109/// came first. `flags` already separates a one-way from a two-way, because that is a flag.
110type Class = (u16, u16, u8, u32, u8, u8, u8, u8, u16, u8, u8, u32);
111
112/// One line part, as `(coord_start, point_count)` into a layer's existing arena.
113///
114/// Indices rather than copied points: a group can hold tens of thousands of parts, and a `Vec` of
115/// points each would be the allocation this module exists to remove.
116pub(crate) type Span = (u32, u32);
117
118/// Merge a layer's line features by class and splice the parts that continue each other.
119///
120/// Polygon features are left exactly as they were, in place; only the parts table and the arena are
121/// rebuilt around them, which [`crate::rings::normalise`] does immediately afterwards anyway.
122pub fn coalesce_lines(layer: &mut Layer) -> Stats {
123 coalesce_lines_with_ids(layer, None, None, None, None)
124}
125
126/// As [`coalesce_lines`], but also rewrites an id side table, a turn-lane side table and a
127/// carriageway side table so they stay parallel to the features.
128///
129/// The tables are indexed by feature position, so merging lines without rewriting them leaves more
130/// entries than features and the encoder rejects the tile. A merged line takes the id of the first
131/// feature of its class, which is arbitrary — that is why only layers whose id-carrying features
132/// are *not* lines populate the id table at all (see `extract::tracks_ids`). Turn masks are the
133/// opposite: they belong to a *road* line, so a line that carries any is held out of merging
134/// entirely (each becomes its own survivor) rather than folded into a neighbour and losing them.
135/// A carriageway takes the third route: it is part of the merge key, so a survivor's split is by
136/// construction the split every line it absorbed had.
137pub fn coalesce_lines_with_ids(
138 layer: &mut Layer,
139 ids: Option<&mut Vec<u64>>,
140 turns: Option<&mut Vec<LaneTurns>>,
141 buildings: Option<&mut Vec<BuildingAttrs>>,
142 carriageways: Option<&mut Vec<Carriageway>>,
143) -> Stats {
144 let mut stats = Stats {
145 features_before: layer.features.len() as u64,
146 parts_before: layer.parts.len() as u64,
147 ..Stats::default()
148 };
149 let lines = layer.features.iter().filter(|f| f.geom_type == GEOM_LINE).count();
150 // One line feature cannot be merged with anything, and a layer of pure polygons is the common
151 // case: both would only pay for a rebuild that changes nothing.
152 //
153 // Boundaries are never merged at all: their relations arrive one feature per member way,
154 // and merging them by class would chain the US-Canada border to the US-Mexico border
155 // across the continent into one part — destroying the per-way tile locality that keeps
156 // border tiles small and complete. The u16 feature cap this exists to relieve does not
157 // bind here (relations are already merged); roads are the layer that needs it.
158 if lines < 2 || layer.layer_id == tilecodec::mamaps::dict::LAYER_BOUNDARIES {
159 stats.features_after = stats.features_before;
160 stats.parts_after = stats.parts_before;
161 return stats;
162 }
163
164 // A line that carries turn masks is never merged — its arrows belong to that exact segment —
165 // so it is copied through at its position like a non-line. `false` everywhere when the layer
166 // has no turn table, which is every layer but a `roads` tile that had `turn:lanes` in it.
167 let unmergeable: Vec<bool> = match turns.as_deref() {
168 Some(t) => layer.features.iter().enumerate().map(|(i, _)| {
169 t.get(i).is_some_and(|lt| !lt.is_empty())
170 }).collect(),
171 None => vec![false; layer.features.len()],
172 };
173
174 // The split a feature's key carries, read out before the tables are borrowed mutably below.
175 // Default when the layer has no carriageway table, which is every layer but `roads`.
176 let split = |at: usize| -> Carriageway {
177 carriageways.as_deref().and_then(|c| c.get(at).copied()).unwrap_or_default()
178 };
179
180 // Every line part, grouped by class, in feature-then-part order.
181 let mut order: Vec<Class> = Vec::new();
182 let mut group_of: HashMap<Class, usize> = HashMap::new();
183 let mut groups: Vec<Vec<Span>> = Vec::new();
184 for (index, feature) in layer.features.iter().enumerate() {
185 if feature.geom_type != GEOM_LINE || unmergeable[index] {
186 continue;
187 }
188 let class = class_of(feature, split(index));
189 let at = *group_of.entry(class).or_insert_with(|| {
190 order.push(class);
191 groups.push(Vec::new());
192 groups.len() - 1
193 });
194 let from = feature.parts_offset as usize;
195 for part in &layer.parts[from..from + feature.part_count as usize] {
196 groups[at].push((part.coord_start, part.point_count));
197 }
198 }
199
200 // Chains first, so the arena can be laid down in one pass below.
201 let chains: Vec<Vec<Run>> =
202 groups.iter().map(|parts| chain(parts, &layer.coords)).collect();
203
204 let mut features = Vec::with_capacity(layer.features.len() - lines + order.len());
205 // The original position of each surviving feature, for remapping the side tables below.
206 let mut kept: Vec<usize> = Vec::with_capacity(features.capacity());
207 let mut parts: Vec<Part> = Vec::with_capacity(layer.parts.len());
208 let mut coords: Vec<(i16, i16)> = Vec::with_capacity(layer.coords.len());
209 let mut emitted: Vec<bool> = vec![false; order.len()];
210
211 for (index, feature) in layer.features.iter().enumerate() {
212 if feature.geom_type != GEOM_LINE || unmergeable[index] {
213 // Copied through at its original position, so a mixed layer keeps its feature order and
214 // a turn-masked road keeps its own geometry and its arrows.
215 let from = feature.parts_offset as usize;
216 let start = parts.len() as u32;
217 for part in &layer.parts[from..from + feature.part_count as usize] {
218 let points = points_of(&layer.coords, *part);
219 parts.push(Part {
220 coord_start: coords.len() as u32,
221 point_count: points.len() as u32,
222 winding: part.winding,
223 });
224 coords.extend_from_slice(points);
225 }
226 let mut copy = *feature;
227 copy.parts_offset = start;
228 features.push(copy);
229 kept.push(index);
230 continue;
231 }
232 let class = class_of(feature, split(index));
233 let at = group_of[&class];
234 if emitted[at] {
235 continue;
236 }
237 emitted[at] = true;
238 let start = parts.len() as u32;
239 for run in &chains[at] {
240 let first = coords.len() as u32;
241 for (i, &(coord_start, point_count)) in run.iter().enumerate() {
242 let points = points_of(
243 &layer.coords,
244 Part { coord_start, point_count, winding: WINDING_OUTER },
245 );
246 // The joint is one point in two parts; the second copy would be a zero-length
247 // segment and `geom::quantize` is no longer around to drop it.
248 let points = if i == 0 { points } else { &points[1..] };
249 coords.extend_from_slice(points);
250 }
251 parts.push(Part {
252 coord_start: first,
253 point_count: coords.len() as u32 - first,
254 winding: WINDING_OUTER,
255 });
256 }
257 let mut merged = *feature;
258 merged.parts_offset = start;
259 merged.part_count = parts.len() as u32 - start;
260 features.push(merged);
261 kept.push(index);
262 }
263
264 if let Some(ids) = ids {
265 if !ids.is_empty() {
266 *ids = kept.iter().map(|&at| ids[at]).collect();
267 }
268 }
269 if let Some(turns) = turns {
270 if !turns.is_empty() {
271 *turns = kept.iter().map(|&at| turns[at].clone()).collect();
272 }
273 }
274 if let Some(buildings) = buildings {
275 if !buildings.is_empty() {
276 *buildings = kept.iter().map(|&at| buildings[at]).collect();
277 }
278 }
279 if let Some(carriageways) = carriageways {
280 if !carriageways.is_empty() {
281 *carriageways = kept.iter().map(|&at| carriageways[at]).collect();
282 }
283 }
284
285 layer.features = features;
286 layer.parts = parts;
287 layer.coords = coords;
288 stats.features_after = layer.features.len() as u64;
289 stats.parts_after = layer.parts.len() as u64;
290 stats
291}
292
293fn class_of(feature: &tilecodec::mamaps::body::Feature, carriageway: Carriageway) -> Class {
294 (
295 feature.kind,
296 feature.kind_detail,
297 feature.flags,
298 feature.transit_color,
299 feature.transit_ordinal,
300 feature.transit_lanes,
301 feature.transit_taper,
302 feature.lane_count,
303 feature.name_idx,
304 carriageway.forward,
305 carriageway.backward,
306 carriageway.solid_dividers,
307 )
308}
309
310pub(crate) fn points_of(coords: &[(i16, i16)], part: Part) -> &[(i16, i16)] {
311 let at = part.coord_start as usize;
312 &coords[at..at + part.point_count as usize]
313}
314
315/// Group `parts` into runs that each form one continuous polyline.
316///
317/// Head-to-tail only: a part joins the chain when its first point is the chain's last. Parts are
318/// never reversed, so the result is a subset of the joins a reversing walk would find -- and it is
319/// the subset that needs no argument about direction.
320///
321/// Chains start at parts nothing runs into, so a road is grown from its end rather than from its
322/// middle; only then are the leftovers taken, which is what closes a ring road onto itself. Both
323/// loops walk `parts` in order, so the output does not depend on the hash map.
324fn chain(parts: &[Span], coords: &[(i16, i16)]) -> Vec<Run> {
325 let ends: Vec<((i16, i16), (i16, i16))> = parts
326 .iter()
327 .map(|&(coord_start, point_count)| {
328 let points = points_of(coords, Part { coord_start, point_count, winding: WINDING_OUTER });
329 // A part with nothing in it cannot join anything; a sentinel keeps the index aligned.
330 match (points.first(), points.last()) {
331 (Some(a), Some(b)) => (*a, *b),
332 _ => ((i16::MIN, i16::MIN), (i16::MAX, i16::MAX)),
333 }
334 })
335 .collect();
336
337 let mut by_start: HashMap<(i16, i16), Vec<usize>> = HashMap::new();
338 for (i, (first, _)) in ends.iter().enumerate() {
339 by_start.entry(*first).or_default().push(i);
340 }
341 // Whether anything ends where this part starts. A part that nothing runs into is a chain head.
342 let mut continued = vec![false; parts.len()];
343 for (_, last) in &ends {
344 if let Some(hits) = by_start.get(last) {
345 for &i in hits {
346 continued[i] = true;
347 }
348 }
349 }
350
351 let mut used = vec![false; parts.len()];
352 let mut out: Vec<Run> = Vec::new();
353 let grow = |from: usize, used: &mut Vec<bool>, out: &mut Vec<Run>| {
354 let mut run: Run = vec![parts[from]];
355 used[from] = true;
356 let mut tail = ends[from].1;
357 while let Some(next) =
358 by_start.get(&tail).and_then(|hits| hits.iter().copied().find(|&j| !used[j]))
359 {
360 used[next] = true;
361 run.push(parts[next]);
362 tail = ends[next].1;
363 }
364 out.push(run);
365 };
366 for i in 0..parts.len() {
367 if !used[i] && !continued[i] {
368 grow(i, &mut used, &mut out);
369 }
370 }
371 // Whatever is left is a cycle: every part in it is continued by another, so none is a head.
372 for i in 0..parts.len() {
373 if !used[i] {
374 grow(i, &mut used, &mut out);
375 }
376 }
377 out
378}
379