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

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

tiler.rs435 lines · 21.6 KiBRaw
1//! Stages B, D and E: features in, one `.mamaps` archive out.
2//!
3//! Zoom by zoom, and within a zoom tile by tile in ascending tile-id order, which is exactly what
4//! [`StreamWriter`] requires. That ordering is free rather than arranged: `pmtiles::tile_id` is
5//! zoom-major, so every id at z*n* precedes every id at z*n+1*, and sorting within a zoom finishes
6//! it.
7//!
8//! # What is reused
9//!
10//! All of the geometry, from `tile_build`:
11//!
12//! * [`geom::project_geometry`] to web-mercator tile units, carrying per-vertex significance.
13//! * [`simplify::annotate`] then [`simplify::filter`], which is significance-first simplification:
14//! a vertex's importance is computed **once** on the whole geometry and only then filtered per
15//! zoom, so the same vertex survives or does not regardless of which tile it lands in. Doing it
16//! the other way round is what lets a shared edge simplify differently on each side and open a
17//! seam.
18//! * [`subdivide::subdivide`], which walks a feature down the tile quadtree instead of clipping it
19//! in full against every tile it touches. A feature inside one tile is clipped once, exactly as
20//! before; one spanning three states pays one vertex pass per zoom level rather than one per tile.
21//! * [`clip`](tile_build::clip)'s Liang-Barsky for lines and Sutherland-Hodgman for rings, against a
22//! tile rect with a buffer so a stroke at the edge has geometry to join to.
23//!
24//! # Memory
25//!
26//! One zoom's chunks, **on disk**, through [`crate::tilespill`]. Peak is a function of the thread
27//! count and a fixed read budget rather than of the extract: `O(threads)` in-flight features and
28//! per-worker chunk maps, plus [`tilespill::READ_BUDGET`] of merge cursors.
29//!
30//! It was in memory until it could not be. A north-america z14 is 267 M features, 461 M parts and
31//! 3.07 G points — about 23 GB of raw arena, and 53 GB resident once `BTreeMap` nodes, `Vec`
32//! capacity slack and the duplicated `BodyLayer` header per `(chunk, tile, layer)` are counted. A
33//! planet z14 projects to ~244 GB, which is not a tuning problem.
34//!
35//! The spill is created and dropped **per zoom**, so peak scratch is the largest single zoom rather
36//! than the sum: ~23 GB at a north-america z14, ~100 GB at a planet one. The stage-A feature
37//! store is a within-build temporary, removed on success; this is a within-zoom temporary, and
38//! keeping either would strand gigabytes for nothing.
39//!
40//! # Parallelism, and why the bytes do not move
41//!
42//! Tiling was 301 s of a 355 s California build, on one of 64 cores, and z14 alone is 68% of it
43//! (180.7 M of 263 M output points) — so the split that matters is *within* a zoom, not across
44//! them. A zoom is therefore a map/reduce:
45//!
46//! 1. **Map.** One reader thread cuts the feature stream into chunks of roughly
47//! [`CHUNK_VERTICES`] input vertices and hands them over a bounded channel to a pool of workers.
48//! Each worker projects, simplifies and clips its own chunk into a private [`Chunk`] map,
49//! touching nothing shared.
50//! 2. **Reduce.** The chunks are ordered by the index they were *read* at — never by the order they
51//! finished in — and k-way merged on the tile id.
52//! 3. **Encode.** Stage C and body serialisation are pure functions of one tile, so a batch of
53//! merged tiles is encoded in parallel and appended in tile order on one thread.
54//!
55//! Steps 2 and 3 alternate, and **overlapping them has been tried and made the build slower.** The
56//! reduce is single-threaded and the encode is the whole pool, so a merge thread behind a
57//! one-batch channel looks like free time: 33 s of a 351 s us-west tiling stage with sixty-three
58//! cores idle. Measured, it cost 53 s instead — 351 s to 404 s, byte-identical — and the merge's own
59//! busy time went 33 s to 217 s. Two reasons, both about the machine rather than the code. The pool
60//! is already one thread per logical CPU, so the merge thread is a sixty-fifth on sixty-four and has
61//! to be timesliced against threads that never yield; and the merge is a pointer walk over
62//! `BTreeMap` nodes, which was fast because it had L3 to itself and is not once sixty-four encode
63//! workers are streaming gigabytes through it. This is the same shape as the parallel spill refill
64//! in [`crate::store`], and it is recorded here for the same reason: it reads like an obvious win
65//! and it is not one.
66//!
67//! The reason this is byte-identical is stronger than "the merge is sorted". Concatenating a
68//! partition of a sequence in partition order reproduces the sequence, so a tile layer's features
69//! land in exactly the order the store yielded them — which makes the archive independent not only
70//! of the thread count but of *where the chunk boundaries fall*. Both halves are asserted, in
71//! `the_archive_is_identical_at_every_thread_count` and
72//! `the_archive_is_identical_however_the_features_are_chunked`.
73//!
74//! What would break it, and what this module is shaped to avoid:
75//!
76//! * A `HashMap` anywhere a tile, a layer or a feature is emitted from. Both maps here are
77//! `BTreeMap`s, and the only hash map in the path is the writer's dedup bucket table, which is
78//! probed and never walked.
79//! * A reduce that folds partial results as they *complete* — a `reduce`, a `fold`, a channel of
80//! finished work. A layer's feature order would then follow the scheduler, and the damage would
81//! be a different feature *ordering* within a tile rather than a different picture: every pixel
82//! would still be right and every byte would be wrong.
83//! * Emitting from the workers. Tile ids must ascend for [`StreamWriter`], so the append stays on
84//! one thread and only the pure work fans out.
85//!
86//! Memory was what this cost, and the spill is what took it back. A chunk is written out and freed
87//! as soon as its worker finishes it, so what is live at the end of the map phase is a handful of
88//! [`ChunkRef`]s rather than every chunk's arenas. In flight are at most `2 * threads` chunks of raw
89//! features and one chunk map per worker. [`CHUNK_VERTICES`] is still large for the other half of
90//! the same reason: smaller chunks balance the pool better and duplicate more `BodyLayer` headers,
91//! and now also more entry headers on disk.
92//!
93//! What the spill costs instead is a decode on the **merge thread**, which is serial, and this
94//! module has already been burned once by treating the merge as cheap — see the paragraph above.
95//! `merge_ms` is the number to watch; a parallel run-merge cascade is the escape hatch if it is bad.
96
97use std::cmp::Reverse;
98use std::collections::{BTreeMap, BinaryHeap, HashMap};
99use std::path::PathBuf;
100use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
101use std::sync::Mutex;
102
103use rayon::prelude::*;
104use tile_build::geom::{self, Geometry, IntGeometry, SigPt, Vertex};
105use tile_build::par;
106use tile_build::progress::Progress;
107use tile_build::simplify;
108use tile_build::subdivide;
109use tilecodec::mamaps::body::{
110 Body, BuildingAttrs, Feature as BodyFeature, Layer as BodyLayer, Part, GEOM_LINE, GEOM_POINT,
111 GEOM_POLYGON, WINDING_HOLE, WINDING_OUTER,
112};
113use tilecodec::mamaps::write::{Options, StreamWriter};
114use tilecodec::pmtiles::tile_id;
115use tilecodec::proto::{err, Result};
116
117use crate::extract::Feature;
118use crate::store::Store;
119use crate::tilespill::{self, ChunkReader, ChunkRef, ChunkSpill};
120
121/// The tile grid, matching MVT's so nothing downstream rescales.
122pub const EXTENT: u32 = 4096;
123
124/// How aggressively to simplify, as a multiple of `tile_build`'s per-zoom tolerance.
125pub const DEFAULT_SIMPLIFICATION: f64 = 1.0;
126
127/// Extra simplification for the boundary wash: a multiple of the per-zoom policy tolerance,
128/// applied in `tolerance_for_layer` beside the buildings floor. 1.5x — boundaries are lines,
129/// and lines carry sub-10m wiggles a 2x grid stretch could straighten.
130pub const WASH_SIMPLIFICATION: f64 = 1.5;
131
132/// Extra simplification for the landtype wash: natural boundaries are looked
133/// at closer than admin ones, so the factor stays at the wash level rather
134/// than above it — except at z13, where a tile spans ~5 km and even tripled
135/// tolerance is deep sub-pixel. Same mechanism as [`WASH_SIMPLIFICATION`],
136/// own constants so the two zooms tune independently.
137pub const LANDTYPE_SIMPLIFICATION: f64 = 1.5;
138
139/// The z13 landtype factor: forest edges, shorelines and farmland at 3x the
140/// per-zoom policy tolerance. z14 stays at 1.5x (crisp parks under streets);
141/// z13 is viewed from high, where a ~4 m tolerance is a fraction of a pixel.
142pub const LANDTYPE_Z13_SIMPLIFICATION: f64 = 3.0;
143
144/// The simplification floor for the `buildings` layer, in extent units.
145///
146/// Buildings live only at z14 and up, where [`simplify::tolerance_for`] is 0.0 at max zoom
147/// (full detail). Half a unit is ~0.3 m at z14 — sub-pixel on any screen the style draws at —
148/// and only drops exactly-collinear midpoints (significance 0) and sub-pixel jaggies. Applied
149/// as a floor in [`tolerance_for_layer`], so a coarser global tolerance still wins. The
150/// prototype at `analysis/mamaps_building_savings.py` estimates ~2% of building-tile bytes.
151pub const BUILDING_TOLERANCE: f64 = 0.5;
152
153/// The simplification floor for washable `roads` at the archive max, in extent units.
154///
155/// z14 policy tolerance is 0.0 (full detail for carriageway/lane alignment), but only
156/// a minority of roads needs it: arterials, and roads carrying lane masks or a
157/// carriageway split, whose centre line the renderer places from geometry (see
158/// `needs_crisp`). A residential street's centre line has no such reader — a
159/// half-unit floor drops only collinear midpoints and sub-pixel jaggies,
160/// invisible at z14 where 16 units are a display pixel. Same magnitude as
161/// [`BUILDING_TOLERANCE`] for the same reason.
162pub const ROAD_DETAIL_FLOOR: f64 = 0.5;
163
164/// True when a road's geometry must stay exactly as digitised: an arterial
165/// (motorway through tertiary, mainlines and `_link`s), or any road carrying
166/// lane masks, a lane count, or a non-default carriageway split — the only
167/// roads whose centre-line placement reads geometry. Everything else
168/// (residential, service, track, path…) takes [`ROAD_DETAIL_FLOOR`] at z14:
169/// a principled rule about readers, not a cap.
170fn needs_crisp(feature: &crate::extract::Feature) -> bool {
171 use tilecodec::mamaps::body::FLAG_IS_ONEWAY;
172 // Arterials by interned kind_detail id: the HIGHWAYS table's
173 // motorway→tertiary rows (schema/roads.rs). Links share the rule: a
174 // motorway_link's curve places the same carriageway its mainline does.
175 // Built once (read-only after init, so deterministic across threads).
176 static ARTERIALS: std::sync::OnceLock<std::collections::HashSet<u16>> =
177 std::sync::OnceLock::new();
178 let arterials = ARTERIALS.get_or_init(|| {
179 [
180 "motorway",
181 "motorway_link",
182 "trunk",
183 "trunk_link",
184 "primary",
185 "primary_link",
186 "secondary",
187 "secondary_link",
188 "tertiary",
189 "tertiary_link",
190 ]
191 .into_iter()
192 .map(crate::schema::detail)
193 .collect()
194 });
195 if arterials.contains(&feature.class.kind_detail) {
196 return true;
197 }
198 if feature.lane_count > 0 || !feature.turn_fwd.is_empty() || !feature.turn_bwd.is_empty() {
199 return true;
200 }
201 if !feature.carriageway.is_empty() {
202 return true;
203 }
204 // A one-way's digitising direction is its semantics; simplification
205 // preserves endpoints but can bow the line, so keep it crisp.
206 feature.class.flags & FLAG_IS_ONEWAY != 0
207}
208
209/// The orthogonal-snap tolerance for building rings, in extent units.
210///
211/// Edges within half a unit of axis-aligned are snapped exactly so (see
212/// [`snap_building_ring`]), turning hand-digitised near-rectangles into rectangles whose
213/// varint deltas encode cheaply. Same magnitude as [`BUILDING_TOLERANCE`]: sub-pixel, visually
214/// lossless. Runs after the filter on survivors only, so the significance [`simplify::annotate`]
215/// measured is never stale; a pure function of the ring, so the archive stays independent of
216/// thread count and chunk boundaries like everything else in [`tile_chunk`].
217pub const BUILDING_SNAP: f64 = 0.5;
218
219/// The building vertex grid: coordinates round to multiples of this (extent
220/// units) after snapping. 2 units ≈ 1.2 m / ~1/8 display pixel at z14 —
221/// invisible natively, and hand-digitised jitter collapses into repeated
222/// constants the varint arena and DEFLATE dictionary encode cheaply. Runs
223/// inside the snap (same survivors-only pass, significance untouched), so it
224/// inherits the determinism property.
225pub const BUILDING_GRID: f64 = 2.0;
226
227/// Input vertices per chunk handed to one worker.
228///
229/// By **vertex** rather than by feature, because feature cost spans four orders of magnitude in the
230/// same file: a building is five points and a state boundary is hundreds of thousands, so a chunk of
231/// *n* features is not a unit of work at all. A feature bigger than this on its own becomes its own
232/// chunk, which is the right answer for a coastline.
233///
234/// The size trades two costs against each other. Smaller chunks balance the pool better and give the
235/// reader less to get through before a worker can start; larger chunks duplicate fewer `BodyLayer`
236/// headers across chunks that touch the same tile, which is the whole of this design's memory
237/// overhead.
238///
239/// **Raised from 64 Ki after tracing where the cost actually is.** An RSS trace of a California build
240/// put stage A at 15 s under 1.6 GB and the real peak at t+256 s — 2.45 GB, deep in z13/z14 and
241/// plateaued across the whole of it. That plateau is this duplication. Raising the chunk to 512 Ki
242/// took the build from 325 s to 181 s and the peak from 2.45 GB to 2.19 GB: at 64 Ki there were ~3 300
243/// chunks per zoom, and the allocation and merging of that many per-chunk maps dominated both `map`
244/// and `encode`. 512 Ki still leaves hundreds of chunks at California z14, which is several per core
245/// on a 64-core box, so the pool stays fed.
246///
247/// 2 Mi was measured too and was not better — 182 s and 2.21 GB, inside the noise — so this is close
248/// to the floor of what the constant alone can buy.
249const CHUNK_VERTICES: usize = 512 * 1024;
250
251/// Worker stack, matching [`par`]'s pool and what the toolchain gives `main` on Windows.
252///
253/// The geometry called below is iterative, so 2 MiB would very likely do — but "very likely" is not
254/// what you want from a stack, and getting it wrong aborts partway through a build instead of
255/// returning an error.
256const WORKER_STACK: usize = 8 * 1024 * 1024;
257
258/// Set only by tests, which build the same archive at several chunk sizes to show the output does
259/// not depend on where the boundaries fall. Zero means [`CHUNK_VERTICES`].
260static CHUNK_OVERRIDE: AtomicUsize = AtomicUsize::new(0);
261
262fn chunk_vertices() -> usize {
263 match CHUNK_OVERRIDE.load(Ordering::Relaxed) {
264 0 => CHUNK_VERTICES,
265 n => n,
266 }
267}
268
269#[cfg(test)]
270fn set_chunk_vertices(n: usize) {
271 CHUNK_OVERRIDE.store(n, Ordering::Relaxed);
272}
273
274/// Adopt `RAYON_NUM_THREADS` when nothing else has set the thread budget.
275///
276/// [`par::threads`] answers to `--threads` and then `MAPS_THREADS`, spelled that way so that one
277/// export governs a whole multi-tool build, and it deliberately ignores rayon's own variable because
278/// it builds its own pool. But `RAYON_NUM_THREADS` is the knob anyone reaches for to pin a Rust
279/// program to one thread — including whoever is checking that this archive is identical at one
280/// thread and at sixty-four — and ignoring it would make that check assert nothing. So it is
281/// honoured, below `MAPS_THREADS` rather than above it, once per process.
282fn adopt_thread_budget() {
283 static ONCE: std::sync::Once = std::sync::Once::new();
284 ONCE.call_once(|| {
285 if std::env::var_os("MAPS_THREADS").is_some() {
286 return;
287 }
288 let wanted = std::env::var("RAYON_NUM_THREADS")
289 .ok()
290 .and_then(|raw| raw.trim().parse::<usize>().ok())
291 .filter(|n| *n > 0);
292 if let Some(n) = wanted {
293 par::set_threads(n);
294 }
295 });
296}
297
298/// TEMP-PROFILE: reader-thread wall stash for the mapprofile line. The
299/// reader runs on its own thread inside `map_zoom`'s scope; the tally fold
300/// (which prints) runs after the scope joins. A process-wide cell carries
301/// the wall across. Removed with the probes.
302static READER_WALL_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
303
304/// TEMP-PROFILE: stash the reader wall (millis). Removed with the probes.
305pub(crate) fn stash_reader_wall(_z: u8, wall: std::time::Duration) {
306 READER_WALL_MS.store(wall.as_millis() as u64, std::sync::atomic::Ordering::Relaxed);
307}
308
309/// TEMP-PROFILE: take the stashed reader wall as a Duration. Removed with
310/// the probes.
311pub(crate) fn take_reader_wall() -> std::time::Duration {
312 std::time::Duration::from_millis(READER_WALL_MS.load(std::sync::atomic::Ordering::Relaxed))
313}
314
315/// Per-zoom counts for the build report.
316#[derive(Debug, Default, Clone, Copy)]
317pub struct ZoomStats {
318 pub zoom: u8,
319 pub tiles: u64,
320 pub features: u64,
321 pub points: u64,
322 /// Features dropped because simplification left nothing, or the clip did.
323 pub dropped: u64,
324 pub bytes: u64,
325 /// What stage C had to correct.
326 pub rings: crate::rings::Stats,
327 /// What coalescing merged away: an OSM way is an editing unit, not a rendering one.
328 pub lines: crate::coalesce::Stats,
329 /// Milliseconds in each phase of this zoom: map, merge, encode, append.
330 ///
331 /// Kept because guessing which one dominates has already cost two wrong optimisations. The map
332 /// and encode phases run on the pool and the other two are serial, so the split is what says
333 /// whether more cores would help at all or whether Amdahl has already won.
334 pub map_ms: u64,
335 pub merge_ms: u64,
336 pub encode_ms: u64,
337 pub append_ms: u64,
338}
339
340/// Planet-size prototype knobs (exp/planet-size). Every field's default reproduces today's
341/// archive byte for byte; a non-default value is folded into the build id (see
342/// `derive_build_id`). Set once by `main` before tiling, read everywhere after.
343#[derive(Debug, Clone, Copy, PartialEq)]
344pub struct SizeOpts {
345 /// `--body-zstd LEVEL`: zstd bodies (header compression 2, which the shipping reader already
346 /// decodes with `ruzstd`) instead of DEFLATE-9. 0 = DEFLATE (today).
347 pub zstd_level: i32,
348 /// `--dem-max-error M`: error-bounded adaptive heightmap grids (coarsest aligned sub-grid +
349 /// elevation step whose reconstruction stays within M metres of the full grid). 0 = today's
350 /// relief-gated 5x5 coarsening.
351 pub dem_max_error_m: f64,
352 /// `--dem-px K`: zoom-adaptive DEM bound — the error allowed on a tile is K times its ground
353 /// resolution (metres per 256-px-tile pixel at the tile's latitude), floored at
354 /// `dem_max_error_m` (or 1 m). 0 = off.
355 pub dem_px: f64,
356 /// `--simplify-scale S`: multiply every below-max-zoom simplification tolerance. 1 = today.
357 pub simplify_scale: f64,
358 /// `--z14-tolerance T`: extent-unit DP floor at z14 for landtype, boundaries, buildings and
359 /// washable roads (crisp roads keep full detail). 0 = today's floors.
360 pub z14_tolerance: f64,
361 /// `--coord-quant`: snap tile coordinates below z14 to a zoom-scaled grid (2 units at z13,
362 /// 4 at z<=12; points and the junction layer untouched). false = today.
363 pub coord_quant: bool,
364 /// `--keep-z13-wash`: exempt z13 landtype from `--simplify-scale`. The app draws the z13
365 /// parent's wash under every z14 tile (z14 drops wash areas), so z13 landtype is what users
366 /// see at street zooms and its deviation is magnified 2^(view-13) times.
367 pub keep_z13_wash: bool,
368 /// `--no-junction-layer`: build no lane connectors. The only style layer that reads them
369 /// (`junction-connector`) is a carriageway layer, dropped from the release style while
370 /// `library/map` `style::LANE_RENDERING` is off, so the layer is ~8% of z14 bytes no app
371 /// draws (planet5 ~50 GB revision).
372 pub no_junction: bool,
373}
374
375impl SizeOpts {
376 pub const DEFAULT: SizeOpts = SizeOpts {
377 zstd_level: 0,
378 dem_max_error_m: 0.0,
379 dem_px: 0.0,
380 simplify_scale: 1.0,
381 z14_tolerance: 0.0,
382 coord_quant: false,
383 keep_z13_wash: false,
384 no_junction: false,
385 };
386 pub fn is_default(&self) -> bool {
387 *self == SizeOpts::DEFAULT
388 }
389 /// Stable text for the build id (only hashed when non-default).
390 pub fn tag(&self) -> String {
391 format!(
392 "size/zstd={};dem={};dempx={};simp={};z14={};q={};kw={}{}",
393 self.zstd_level,
394 self.dem_max_error_m,
395 self.dem_px,
396 self.simplify_scale,
397 self.z14_tolerance,
398 self.coord_quant,
399 self.keep_z13_wash,
400 if self.no_junction { ";nojunction" } else { "" }
401 )
402 }
403 /// The coordinate grid step for zoom `z` under `--coord-quant` (1 = untouched).
404 pub fn quant_step(&self, z: u8, layer: u8) -> i32 {
405 if !self.coord_quant || layer == tilecodec::mamaps::dict::LAYER_JUNCTION {
406 return 1;
407 }
408 match z {
409 0..=12 => 4,
410 13 => 2,
411 _ => 1,
412 }
413 }
414}
415
416pub static SIZE_OPTS: std::sync::OnceLock<SizeOpts> = std::sync::OnceLock::new();
417
418pub fn size_opts() -> SizeOpts {
419 *SIZE_OPTS.get().unwrap_or(&SizeOpts::DEFAULT)
420}
421
422/// `--v8-bodies`: encode dense v8 bodies (set once by `main` before tiling).
423pub static V8_BODIES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
424
425include!("tiler_s1.rs");
426include!("tiler_part1.rs");
427include!("tiler_part2.rs");
428include!("tiler_part3.rs");
429include!("tiler_part5.rs");
430include!("tiler_part6.rs");
431include!("tiler_part7.rs");
432include!("tiler_part8.rs");
433include!("tiler_part9.rs");
434include!("tiler_part10.rs");
435include!("tiler_part11.rs");