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

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

tiler_part5.rs356 lines · 17.8 KiBRaw
1fn encode_batch(
2 batch: Vec<(u64, Vec<ChunkEntry>)>,
3 dem: &crate::dem::Dem,
4 conventions: &crate::schema::boundaries::Conventions,
5 region_links: &std::collections::HashMap<u64, u64>,
6) -> Result<Vec<Encoded>> {
7 // Split the batch into tasks by cumulative geometry cost rather than by tile count. A dense
8 // city tile is orders of magnitude more work than a rural one, and `with_min_len` — which forces
9 // contiguous runs of a fixed *count* — cannot give that tile a task of its own: it stays welded
10 // to its cheap neighbours while the rest of the pool drains. Grouping by cost lets the biggest
11 // tiles fall into their own tasks. Order is untouched: the groups are contiguous slices of the
12 // batch in order, each group is encoded in order, and the per-group results are flattened in
13 // group order — so `collect`'s positional guarantee still lands every tile where it was, and the
14 // archive is byte for byte the same.
15 let groups = partition_by_cost(batch, par::encode_task_count());
16 par::install(|| {
17 let grouped: Result<Vec<Vec<Encoded>>> = groups
18 .into_par_iter()
19 // One DEFLATE state and one serialisation buffer per worker, not one per tile.
20 // `compress_to_vec` builds a 65,712-byte `CompressorOxide` every call, and at a tile
21 // each across 64 cores that construction swamps the compression it exists to do -- see
22 // `mamaps::write::compress_body_with`. The `Scratch` is there for the same reason on
23 // the serialisation side: its allocations, not its encoding, were what made
24 // serialisation cost 20.9 s of CPU at 16 threads and 1120 s at 64. Reused across every
25 // tile in a group, not merely once per task.
26 .map_init(
27 || (tilecodec::gz::Compressor::new(), tilecodec::mamaps::body::Scratch::default()),
28 |(deflate, scratch), group| {
29 group
30 .into_iter()
31 .map(|(id, layers)| {
32 encode_tile(id, layers, dem, conventions, region_links, deflate, scratch)
33 })
34 .collect::<Result<Vec<Encoded>>>()
35 },
36 )
37 .collect();
38 Ok(grouped?.into_iter().flatten().collect())
39 })
40}
41
42/// Coalesce, stage C, serialise and DEFLATE one merged tile, reusing the worker's compressor and
43/// serialisation scratch.
44///
45/// Pulled out of [`encode_batch`] so the batch can be split into cost-balanced groups and this run
46/// per tile inside each group; the steps and their order are unchanged, so the encoded bytes are
47/// too. A tile whose layers all empty out under coalescing and stage C comes back as
48/// `(id, None, ..)` rather than being dropped, because its stage C and coalescing counters still
49/// belong in the build report.
50fn encode_tile(
51 id: u64,
52 mut layers: Vec<ChunkEntry>,
53 dem: &crate::dem::Dem,
54 conventions: &crate::schema::boundaries::Conventions,
55 region_links: &std::collections::HashMap<u64, u64>,
56 deflate: &mut tilecodec::gz::Compressor,
57 scratch: &mut tilecodec::mamaps::body::Scratch,
58) -> Result<Encoded> {
59 // **Coalesce first.** An OSM way is an editing unit, not a rendering one, so a road arrives as
60 // hundreds of two-point fragments each carrying its own 28 bytes of header -- see
61 // `crate::coalesce`. Merging them before stage C is also what keeps stage C off tens of
62 // thousands of features it would only copy through.
63 let mut lines = crate::coalesce::Stats::default();
64 for entry in &mut layers {
65 // The traffic layer is one feature per component segment, each carrying a distinct
66 // component_id in the id table. Coalescing merges a class's lines into one feature, which
67 // would collapse every segment's id onto whichever came first — so it is skipped, keeping
68 // the layer one-to-one with its ids.
69 //
70 // The junction layer is skipped for the neighbouring reason: it carries no ids, but each
71 // feature is one lane's connector through an intersection and they all share a class, so
72 // coalescing would chain unrelated connectors — a left turn and the through movement beside
73 // it — into one polyline and draw a ribbon between them.
74 if entry.layer.layer_id == tilecodec::mamaps::dict::LAYER_TRAFFIC
75 || entry.layer.layer_id == tilecodec::mamaps::dict::LAYER_JUNCTION
76 {
77 continue;
78 }
79 lines.add(crate::coalesce::coalesce_lines_with_ids(
80 &mut entry.layer,
81 Some(&mut entry.ids),
82 Some(&mut entry.turn_lanes),
83 Some(&mut entry.buildings),
84 Some(&mut entry.carriageways),
85 ));
86 }
87 // **Stage C**, per tile: winding normalised, hole containment resolved, degenerate rings
88 // dropped. Once, here, in `f64` with no frame budget, instead of every frame on device in `i32`
89 // under one. This is what makes `FLAG_RINGS_VALIDATED` true.
90 let mut rings = crate::rings::Stats::default();
91 for entry in &mut layers {
92 rings.add(crate::rings::normalise_with_ids(
93 &mut entry.layer,
94 Some(&mut entry.ids),
95 Some(&mut entry.turn_lanes),
96 Some(&mut entry.buildings),
97 ));
98 }
99 // A layer that ended up empty - every feature in it fell below the minimum area after
100 // clipping, or lost its exterior to stage C - costs bytes in the archive and a draw call on
101 // device for nothing.
102 layers.retain(|entry| !entry.layer.features.is_empty());
103 if layers.is_empty() {
104 return Ok((id, None, rings, lines));
105 }
106 // Phase B: a full-bleed single-water-polygon tile is water, not a tile. One
107 // water polygon covering the whole tile draws exactly what the style's water
108 // background already paints, so storing it buys a body, an index entry and a
109 // fetch for zero pixels. `None` (not stored) like an emptied tile, and the
110 // reader overzooms the parent whose background shows through.
111 if is_water_background(&layers) {
112 return Ok((id, None, rings, lines));
113 }
114 // What the `u16` feature index in the body format has to hold. Sampled here because this is the
115 // shape that reaches the encoder: after coalescing merged the line fragments and after stage C
116 // dropped what it drops.
117 for entry in &layers {
118 WIDEST_LAYER[entry.layer.layer_id as usize]
119 .fetch_max(entry.layer.features.len() as u64, Ordering::Relaxed);
120 }
121 // Fuse the layers' name tables into the body's one, in layer order, remapping every feature's
122 // index as it goes. First-use order is deterministic (merge order within a layer, layer order
123 // across them), so the same tile always carries the same table. A probe-only `HashMap` keeps the
124 // fusion linear rather than quadratic in the tile's name count; it is never iterated, and a name
125 // is cloned only the first time it is seen, so the table's order and bytes are exactly what a
126 // linear `position` scan produced.
127 let mut names: Vec<String> = Vec::new();
128 let mut name_index: HashMap<String, u16> = HashMap::new();
129 for entry in &mut layers {
130 for feature in &mut entry.layer.features {
131 if feature.name_idx != tilecodec::mamaps::body::NAME_NONE {
132 let name = &entry.names[feature.name_idx as usize - 1];
133 feature.name_idx = match name_index.get(name.as_str()) {
134 Some(&at) => at,
135 None => {
136 let idx = names.len() as u16 + 1;
137 names.push(name.clone());
138 name_index.insert(name.clone(), idx);
139 idx
140 }
141 };
142 }
143 }
144 }
145 // Fuse the layers' id tables into the body's one. Unlike names these are values rather than
146 // indices, so nothing is remapped and nothing is deduplicated — the table is simply the
147 // surviving `places`/`poi` layers' vectors, in layer order, which `Merged` already delivers
148 // ascending.
149 //
150 // Checked against the feature count rather than assumed. `coalesce_lines` rebuilds a layer's
151 // features and `rings::normalise` retains over them, and both now rewrite the id table
152 // alongside. That is easy to get wrong and silent when it is - every id after the first casualty
153 // would describe the wrong feature - so this fails the build instead.
154 let mut ids: Vec<(u8, Vec<u64>)> = Vec::new();
155 for entry in &mut layers {
156 if entry.ids.is_empty() {
157 continue;
158 }
159 if entry.ids.len() != entry.layer.features.len() {
160 return err(format!(
161 "layer {} has {} id(s) for {} feature(s) after coalesce and \
162 stage C",
163 entry.layer.layer_id,
164 entry.ids.len(),
165 entry.layer.features.len(),
166 ));
167 }
168 ids.push((entry.layer.layer_id, std::mem::take(&mut entry.ids)));
169 }
170 // The region-link table: for each `places` label, the tagged relation id of the boundary it
171 // names, looked up from stage A's link map by the label's own (tagged node) id — which is
172 // exactly what the id table above holds. Dense-parallel to the layer's features like the id
173 // table, with REGION_NONE where a label links to no region. Emitted only when at least one
174 // label in the tile links somewhere, so a tile of unlinked labels (or no places at all) carries
175 // no table.
176 let mut region_links_table: Vec<(u8, Vec<u64>)> = Vec::new();
177 if !region_links.is_empty() {
178 for (layer_id, node_ids) in &ids {
179 if *layer_id != tilecodec::mamaps::dict::LAYER_PLACES {
180 continue;
181 }
182 let links: Vec<u64> = node_ids
183 .iter()
184 .map(|id| {
185 region_links
186 .get(id)
187 .copied()
188 .unwrap_or(tilecodec::mamaps::body::REGION_NONE)
189 })
190 .collect();
191 if links.iter().any(|&l| l != tilecodec::mamaps::body::REGION_NONE) {
192 region_links_table.push((*layer_id, links));
193 }
194 }
195 }
196 // The turn-lane table, built the same way as the id table and checked against the feature count
197 // for the same reason: coalesce and stage C rebuild a layer's features and rewrite this
198 // alongside, and a drift would misattribute every lane after the first. Only emitted when some
199 // road actually has turn masks, so a tile with none carries no table at all.
200 let mut turn_lanes: Vec<(u8, Vec<tilecodec::mamaps::body::LaneTurns>)> = Vec::new();
201 for entry in &mut layers {
202 if entry.turn_lanes.is_empty() {
203 continue;
204 }
205 if entry.turn_lanes.len() != entry.layer.features.len() {
206 return err(format!(
207 "layer {} has {} turn record(s) for {} feature(s) after coalesce \
208 and stage C",
209 entry.layer.layer_id,
210 entry.turn_lanes.len(),
211 entry.layer.features.len(),
212 ));
213 }
214 if entry.turn_lanes.iter().all(|t| t.is_empty()) {
215 entry.turn_lanes.clear();
216 continue;
217 }
218 turn_lanes.push((entry.layer.layer_id, std::mem::take(&mut entry.turn_lanes)));
219 }
220 // The building side table, built the same way and checked against the feature count for the same
221 // reason. A tile whose buildings all carried default attrs (no S3DB tags) emits no table at all
222 // — the renderer falls back to its own default height and colour — so the table is paid for only
223 // where 3D data exists.
224 let mut buildings: Vec<(u8, Vec<BuildingAttrs>)> = Vec::new();
225 for entry in &mut layers {
226 if entry.buildings.is_empty() {
227 continue;
228 }
229 if entry.buildings.len() != entry.layer.features.len() {
230 return err(format!(
231 "layer {} has {} building record(s) for {} feature(s) after \
232 coalesce and stage C",
233 entry.layer.layer_id,
234 entry.buildings.len(),
235 entry.layer.features.len(),
236 ));
237 }
238 if entry.buildings.iter().all(|b| *b == BuildingAttrs::default()) {
239 entry.buildings.clear();
240 continue;
241 }
242 buildings.push((entry.layer.layer_id, std::mem::take(&mut entry.buildings)));
243 }
244 // The carriageway side table, built like the two above and checked against the feature count for
245 // the same reason.
246 //
247 // A tile where no road's split was ever surveyed usually emits no table at all, so it costs
248 // nothing for lane data that does not exist. The exception is a tile whose country is not the
249 // default one: the convention only reaches the wire alongside a table, and a tile of untagged
250 // residential streets in Tokyo still has to say that traffic keeps left. So an all-default table
251 // is kept exactly when there is a non-default convention to carry with it.
252 let (z, x, y) = tilecodec::pmtiles::tile_zxy(id);
253 let convention = conventions.at_tile(z, x, y);
254 let mut carriageways: Vec<(u8, Vec<tilecodec::mamaps::body::Carriageway>)> = Vec::new();
255 for entry in &mut layers {
256 if entry.carriageways.is_empty() {
257 continue;
258 }
259 if entry.carriageways.len() != entry.layer.features.len() {
260 return err(format!(
261 "layer {} has {} carriageway record(s) for {} feature(s) after \
262 coalesce and stage C",
263 entry.layer.layer_id,
264 entry.carriageways.len(),
265 entry.layer.features.len(),
266 ));
267 }
268 if convention == tilecodec::mamaps::body::MarkingConvention::default()
269 && entry.carriageways.iter().all(|c| c.is_empty())
270 {
271 entry.carriageways.clear();
272 continue;
273 }
274 carriageways.push((entry.layer.layer_id, std::mem::take(&mut entry.carriageways)));
275 }
276 let convention = (!carriageways.is_empty()).then_some(convention);
277 let body = Body {
278 extent: EXTENT as u16,
279 layers: layers.into_iter().map(|entry| entry.layer).collect(),
280 names,
281 ids,
282 turn_lanes,
283 buildings,
284 // The DEM heightmap is produced by a separate ingest stage keyed by tile, not from OSM
285 // geometry. Sample its grid onto this tile's z/x/y; a tile with no DEM under it (ocean,
286 // off-coverage) gets None and stays 16-byte.
287 heightmap: dem.heightmap_for(z, x, y),
288 carriageways,
289 convention,
290 region_links: region_links_table,
291 };
292 // v10 narrowed records + sparse side tables are the default: same
293 // geometry either way — only the fixed records shrink — so this
294 // changes bytes, never shapes. `MAMAPS_V8=1` opts back out to the
295 // dense v8 bodies (escape hatch for bisecting a suspect build).
296 let encoded_body = if std::env::var("MAMAPS_V8").is_ok() {
297 tilecodec::mamaps::body::serialize_into(&body, scratch)
298 } else {
299 tilecodec::mamaps::body::serialize_into_v10(&body, scratch)
300 }?;
301 let raw_len = encoded_body.len();
302 let stored = tilecodec::mamaps::write::compress_body_with(deflate, encoded_body);
303 // Compute the dedup key here, in the parallel worker, rather than on the serial append thread.
304 // It is a pure function of the stored bytes, so the key — and every dedup decision the writer
305 // makes from it — is unchanged; it just no longer walks the whole body downstream of this phase.
306 let hash = tilecodec::mamaps::write::hash64(&stored);
307 Ok((id, Some((stored, raw_len, hash)), rings, lines))
308}
309
310/// Split a merged batch into contiguous groups of roughly equal cumulative geometry cost.
311///
312/// `target_tasks` is the number of groups aimed for — a few per thread. Cost is a tile's feature
313/// and coordinate count, which is what stage C, serialisation and DEFLATE all scale with; a tile
314/// heavier than the per-group budget on its own becomes its own group, which is the whole point.
315/// The groups are contiguous and in batch order, so flattening their encoded results reproduces the
316/// batch's tile order exactly — the archive does not move.
317fn partition_by_cost(
318 batch: Vec<(u64, Vec<ChunkEntry>)>,
319 target_tasks: usize,
320) -> Vec<Vec<(u64, Vec<ChunkEntry>)>> {
321 let total: u64 = batch.iter().map(|(_, layers)| tile_cost(layers)).sum();
322 let target = (total / target_tasks.max(1) as u64).max(1);
323 let mut groups: Vec<Vec<(u64, Vec<ChunkEntry>)>> = Vec::new();
324 let mut current: Vec<(u64, Vec<ChunkEntry>)> = Vec::new();
325 let mut current_cost = 0u64;
326 for (id, layers) in batch {
327 let cost = tile_cost(&layers);
328 // Flush before adding a tile that would push a non-empty group past the budget, so a heavy
329 // tile does not drag its cheap predecessors into an oversized task.
330 if !current.is_empty() && current_cost + cost > target {
331 groups.push(std::mem::take(&mut current));
332 current_cost = 0;
333 }
334 current.push((id, layers));
335 current_cost += cost;
336 // A group at or over budget is closed; a single tile heavier than the budget closes here on
337 // its own, which is the isolation `with_min_len`'s fixed run length could not provide.
338 if current_cost >= target {
339 groups.push(std::mem::take(&mut current));
340 current_cost = 0;
341 }
342 }
343 if !current.is_empty() {
344 groups.push(current);
345 }
346 groups
347}
348
349/// A tile's encode cost: its features plus its coordinates, summed across layers. Both stage C and
350/// the compressor scale with these, and it is the ratio between tiles that matters, not the unit.
351fn tile_cost(layers: &[ChunkEntry]) -> u64 {
352 layers
353 .iter()
354 .map(|entry| entry.layer.features.len() as u64 + entry.layer.coords.len() as u64)
355 .sum()
356}