Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / tiler.rs
tiler.rs497 lines · 25.3 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 | |
| 97 | use std::cmp::Reverse; |
| 98 | use std::collections::{BTreeMap, BinaryHeap, HashMap}; |
| 99 | use std::path::PathBuf; |
| 100 | use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; |
| 101 | use std::sync::Mutex; |
| 102 | |
| 103 | use rayon::prelude::*; |
| 104 | use tile_build::geom::{self, Geometry, IntGeometry, SigPt, Vertex}; |
| 105 | use tile_build::par; |
| 106 | use tile_build::subdivide; |
| 107 | use tile_build::progress::Progress; |
| 108 | use tile_build::simplify; |
| 109 | use 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 | }; |
| 113 | use tilecodec::mamaps::write::{Options, StreamWriter}; |
| 114 | use tilecodec::pmtiles::tile_id; |
| 115 | use tilecodec::proto::{err, Result}; |
| 116 | |
| 117 | use crate::extract::Feature; |
| 118 | use crate::store::Store; |
| 119 | use crate::tilespill::{self, ChunkRef, ChunkReader, ChunkSpill}; |
| 120 | |
| 121 | /// The tile grid, matching MVT's so nothing downstream rescales. |
| 122 | pub const EXTENT: u32 = 4096; |
| 123 | |
| 124 | /// How aggressively to simplify, as a multiple of `tile_build`'s per-zoom tolerance. |
| 125 | pub 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. |
| 130 | pub 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. |
| 137 | pub 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. |
| 142 | pub 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. |
| 151 | pub 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. |
| 162 | pub 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. |
| 170 | fn 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", "motorway_link", "trunk", "trunk_link", "primary", "primary_link", |
| 181 | "secondary", "secondary_link", "tertiary", "tertiary_link", |
| 182 | ] |
| 183 | .into_iter() |
| 184 | .map(crate::schema::detail) |
| 185 | .collect() |
| 186 | }); |
| 187 | if arterials.contains(&feature.class.kind_detail) { |
| 188 | return true; |
| 189 | } |
| 190 | if feature.lane_count > 0 || !feature.turn_fwd.is_empty() || !feature.turn_bwd.is_empty() { |
| 191 | return true; |
| 192 | } |
| 193 | if !feature.carriageway.is_empty() { |
| 194 | return true; |
| 195 | } |
| 196 | // A one-way's digitising direction is its semantics; simplification |
| 197 | // preserves endpoints but can bow the line, so keep it crisp. |
| 198 | feature.class.flags & FLAG_IS_ONEWAY != 0 |
| 199 | } |
| 200 | |
| 201 | /// The orthogonal-snap tolerance for building rings, in extent units. |
| 202 | /// |
| 203 | /// Edges within half a unit of axis-aligned are snapped exactly so (see |
| 204 | /// [`snap_building_ring`]), turning hand-digitised near-rectangles into rectangles whose |
| 205 | /// varint deltas encode cheaply. Same magnitude as [`BUILDING_TOLERANCE`]: sub-pixel, visually |
| 206 | /// lossless. Runs after the filter on survivors only, so the significance [`simplify::annotate`] |
| 207 | /// measured is never stale; a pure function of the ring, so the archive stays independent of |
| 208 | /// thread count and chunk boundaries like everything else in [`tile_chunk`]. |
| 209 | pub const BUILDING_SNAP: f64 = 0.5; |
| 210 | |
| 211 | /// The building vertex grid: coordinates round to multiples of this (extent |
| 212 | /// units) after snapping. 2 units ≈ 1.2 m / ~1/8 display pixel at z14 — |
| 213 | /// invisible natively, and hand-digitised jitter collapses into repeated |
| 214 | /// constants the varint arena and DEFLATE dictionary encode cheaply. Runs |
| 215 | /// inside the snap (same survivors-only pass, significance untouched), so it |
| 216 | /// inherits the determinism property. |
| 217 | pub const BUILDING_GRID: f64 = 2.0; |
| 218 | |
| 219 | /// Input vertices per chunk handed to one worker. |
| 220 | /// |
| 221 | /// By **vertex** rather than by feature, because feature cost spans four orders of magnitude in the |
| 222 | /// same file: a building is five points and a state boundary is hundreds of thousands, so a chunk of |
| 223 | /// *n* features is not a unit of work at all. A feature bigger than this on its own becomes its own |
| 224 | /// chunk, which is the right answer for a coastline. |
| 225 | /// |
| 226 | /// The size trades two costs against each other. Smaller chunks balance the pool better and give the |
| 227 | /// reader less to get through before a worker can start; larger chunks duplicate fewer `BodyLayer` |
| 228 | /// headers across chunks that touch the same tile, which is the whole of this design's memory |
| 229 | /// overhead. |
| 230 | /// |
| 231 | /// **Raised from 64 Ki after tracing where the cost actually is.** An RSS trace of a California build |
| 232 | /// 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 |
| 233 | /// plateaued across the whole of it. That plateau is this duplication. Raising the chunk to 512 Ki |
| 234 | /// 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 |
| 235 | /// chunks per zoom, and the allocation and merging of that many per-chunk maps dominated both `map` |
| 236 | /// and `encode`. 512 Ki still leaves hundreds of chunks at California z14, which is several per core |
| 237 | /// on a 64-core box, so the pool stays fed. |
| 238 | /// |
| 239 | /// 2 Mi was measured too and was not better — 182 s and 2.21 GB, inside the noise — so this is close |
| 240 | /// to the floor of what the constant alone can buy. |
| 241 | const CHUNK_VERTICES: usize = 512 * 1024; |
| 242 | |
| 243 | /// Worker stack, matching [`par`]'s pool and what the toolchain gives `main` on Windows. |
| 244 | /// |
| 245 | /// The geometry called below is iterative, so 2 MiB would very likely do — but "very likely" is not |
| 246 | /// what you want from a stack, and getting it wrong aborts partway through a build instead of |
| 247 | /// returning an error. |
| 248 | const WORKER_STACK: usize = 8 * 1024 * 1024; |
| 249 | |
| 250 | /// Set only by tests, which build the same archive at several chunk sizes to show the output does |
| 251 | /// not depend on where the boundaries fall. Zero means [`CHUNK_VERTICES`]. |
| 252 | static CHUNK_OVERRIDE: AtomicUsize = AtomicUsize::new(0); |
| 253 | |
| 254 | fn chunk_vertices() -> usize { |
| 255 | match CHUNK_OVERRIDE.load(Ordering::Relaxed) { |
| 256 | 0 => CHUNK_VERTICES, |
| 257 | n => n, |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | #[cfg(test)] |
| 262 | fn set_chunk_vertices(n: usize) { |
| 263 | CHUNK_OVERRIDE.store(n, Ordering::Relaxed); |
| 264 | } |
| 265 | |
| 266 | /// Adopt `RAYON_NUM_THREADS` when nothing else has set the thread budget. |
| 267 | /// |
| 268 | /// [`par::threads`] answers to `--threads` and then `MAPS_THREADS`, spelled that way so that one |
| 269 | /// export governs a whole multi-tool build, and it deliberately ignores rayon's own variable because |
| 270 | /// it builds its own pool. But `RAYON_NUM_THREADS` is the knob anyone reaches for to pin a Rust |
| 271 | /// program to one thread — including whoever is checking that this archive is identical at one |
| 272 | /// thread and at sixty-four — and ignoring it would make that check assert nothing. So it is |
| 273 | /// honoured, below `MAPS_THREADS` rather than above it, once per process. |
| 274 | fn adopt_thread_budget() { |
| 275 | static ONCE: std::sync::Once = std::sync::Once::new(); |
| 276 | ONCE.call_once(|| { |
| 277 | if std::env::var_os("MAPS_THREADS").is_some() { |
| 278 | return; |
| 279 | } |
| 280 | let wanted = std::env::var("RAYON_NUM_THREADS") |
| 281 | .ok() |
| 282 | .and_then(|raw| raw.trim().parse::<usize>().ok()) |
| 283 | .filter(|n| *n > 0); |
| 284 | if let Some(n) = wanted { |
| 285 | par::set_threads(n); |
| 286 | } |
| 287 | }); |
| 288 | } |
| 289 | |
| 290 | /// TEMP-PROFILE: reader-thread wall stash for the mapprofile line. The |
| 291 | /// reader runs on its own thread inside `map_zoom`'s scope; the tally fold |
| 292 | /// (which prints) runs after the scope joins. A process-wide cell carries |
| 293 | /// the wall across. Removed with the probes. |
| 294 | static READER_WALL_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 295 | |
| 296 | /// TEMP-PROFILE: stash the reader wall (millis). Removed with the probes. |
| 297 | pub(crate) fn stash_reader_wall(_z: u8, wall: std::time::Duration) { |
| 298 | READER_WALL_MS.store(wall.as_millis() as u64, std::sync::atomic::Ordering::Relaxed); |
| 299 | } |
| 300 | |
| 301 | /// TEMP-PROFILE: take the stashed reader wall as a Duration. Removed with |
| 302 | /// the probes. |
| 303 | pub(crate) fn take_reader_wall() -> std::time::Duration { |
| 304 | std::time::Duration::from_millis(READER_WALL_MS.load(std::sync::atomic::Ordering::Relaxed)) |
| 305 | } |
| 306 | |
| 307 | /// Per-zoom counts for the build report. |
| 308 | #[derive(Debug, Default, Clone, Copy)] |
| 309 | pub struct ZoomStats { |
| 310 | pub zoom: u8, |
| 311 | pub tiles: u64, |
| 312 | pub features: u64, |
| 313 | pub points: u64, |
| 314 | /// Features dropped because simplification left nothing, or the clip did. |
| 315 | pub dropped: u64, |
| 316 | pub bytes: u64, |
| 317 | /// What stage C had to correct. |
| 318 | pub rings: crate::rings::Stats, |
| 319 | /// What coalescing merged away: an OSM way is an editing unit, not a rendering one. |
| 320 | pub lines: crate::coalesce::Stats, |
| 321 | /// Milliseconds in each phase of this zoom: map, merge, encode, append. |
| 322 | /// |
| 323 | /// Kept because guessing which one dominates has already cost two wrong optimisations. The map |
| 324 | /// and encode phases run on the pool and the other two are serial, so the split is what says |
| 325 | /// whether more cores would help at all or whether Amdahl has already won. |
| 326 | pub map_ms: u64, |
| 327 | pub merge_ms: u64, |
| 328 | pub encode_ms: u64, |
| 329 | pub append_ms: u64, |
| 330 | } |
| 331 | |
| 332 | pub struct Settings { |
| 333 | pub build_id: u64, |
| 334 | /// Where one zoom's chunks go while they wait for the merge. See [`crate::tilespill`]. |
| 335 | /// |
| 336 | /// Beside the output archive, as `<out>.tilechunks`, matching where the feature spill is placed. |
| 337 | /// Truncated at the start of every zoom and removed at the end of each, so it holds one zoom. |
| 338 | pub scratch: PathBuf, |
| 339 | /// Force the tile-chunk spill through the scratch *file* even when the budget gate would pick |
| 340 | /// anonymous pagefile-backed memory. Set from `MAPS_ANON_SPILL` (unset, or any value but |
| 341 | /// `1`/`true`/`yes`, forces files): on a box whose commit headroom is tens of GB against a |
| 342 | /// ~900 GB estimate, anon staging pages the merge to death -- files page too, but against |
| 343 | /// the scratch volume rather than the commit limit that aborts the build. Same chunks, same |
| 344 | /// offsets, same bytes; the merge reads through the same `ChunkReader` either way. |
| 345 | pub force_chunk_spill_file: bool, |
| 346 | /// The DEM heightmap dataset to sample one grid per output tile from. |
| 347 | /// See [`crate::dem::Dem`]. A tile with no DEM under it carries no heightmap |
| 348 | /// section (stays 16-byte). |
| 349 | pub dem: crate::dem::Dem, |
| 350 | /// Place-label id (tagged node) -> the tagged relation id of the admin boundary it names, from |
| 351 | /// stage A. The tiler stamps each `places` label whose id is a key here with the linked id in |
| 352 | /// the body's region-link table, so a tap on the label outlines that exact region. Empty when no |
| 353 | /// links were found (the section is then omitted from every tile). |
| 354 | pub region_links: std::collections::HashMap<u64, u64>, |
| 355 | /// Place-label id (tagged, `country` places only) -> the label's start zoom, from |
| 356 | /// footprint × headcount (see `extract_fallback::country_zoom`). The tiler drops the |
| 357 | /// label below its start zoom — same shape as `region_links`, probe-only so the |
| 358 | /// archive stays deterministic. Absent ids keep the schema floor (z0): a missing |
| 359 | /// score must never hide a country. |
| 360 | pub country_zooms: std::collections::HashMap<u64, u8>, |
| 361 | } |
| 362 | |
| 363 | /// One chunk's share of a zoom, keyed on `(tile id, layer id)`. |
| 364 | /// |
| 365 | /// Keyed on the **tile id**, not on `(x, y)`. Those are different orders: `tile_id` walks a Hilbert |
| 366 | /// curve, so row-major `(x, y)` ascends through it out of sequence and the writer rejects the |
| 367 | /// archive. Cheap to get wrong and caught only by an ordering check, which is why the writer has |
| 368 | /// one. |
| 369 | /// |
| 370 | /// Flat rather than `tile -> layer -> layer`. A nested map pays a whole inner `BTreeMap` node — |
| 371 | /// eleven `BodyLayer` slots, most of a kilobyte — for every tile, and nearly every tile carries one |
| 372 | /// or two layers; with a chunk map per chunk that overhead is multiplied by the chunk count. |
| 373 | /// Flattening puts eleven *entries* in a node instead, and changes no order: `(tile, layer)` |
| 374 | /// ascending is tile-major with layers in id order inside it, which is what the nested form yielded |
| 375 | /// and what the writer needs. |
| 376 | type Chunk = BTreeMap<(u64, u8), ChunkEntry>; |
| 377 | |
| 378 | /// One tile-layer in a chunk map: the geometry plus the label strings its features name. |
| 379 | /// |
| 380 | /// Names ride beside the layer (not inside `BodyLayer`, which is the codec's type) from `push` |
| 381 | /// through the spill and the merge to encode, where per-layer tables fuse into the body's one. |
| 382 | /// A chunk entry's `names` is deduplicated in first-use order, so `name_idx == i` names |
| 383 | /// `names[i - 1]` — the same convention as the body's table, which is what makes the merge's |
| 384 | /// remap a pure index translation. |
| 385 | /// |
| 386 | /// `ids` rides the same way and is simpler: it holds values rather than indices, so a merge |
| 387 | /// concatenates it instead of remapping it. It is empty for every layer but `places` and `poi`, |
| 388 | /// and dense-parallel to `layer.features` for those two — `ids[i]` is the OSM element that |
| 389 | /// produced `features[i]`. |
| 390 | #[derive(Debug, Clone, PartialEq)] |
| 391 | pub struct ChunkEntry { |
| 392 | pub layer: BodyLayer, |
| 393 | pub names: Vec<String>, |
| 394 | pub ids: Vec<u64>, |
| 395 | /// The per-feature turn-lane masks, dense-parallel to `layer.features` on the `roads` layer and |
| 396 | /// empty on every other. Rides the merge the way `ids` does — concatenated, not remapped — and |
| 397 | /// is remapped alongside `ids` when `coalesce` and stage C rebuild the feature vector. |
| 398 | pub turn_lanes: Vec<tilecodec::mamaps::body::LaneTurns>, |
| 399 | /// The per-feature S3DB attributes, dense-parallel to `layer.features` on the `buildings` layer |
| 400 | /// and empty on every other. Rides the merge like `ids` (concatenated, not remapped) and is |
| 401 | /// remapped alongside it when `coalesce` and stage C rebuild the feature vector, so the body's |
| 402 | /// building side table stays aligned to the features it describes. |
| 403 | pub buildings: Vec<BuildingAttrs>, |
| 404 | /// The per-feature directional carriageway split, dense-parallel to `layer.features` on the |
| 405 | /// `roads` layer and empty on every other. Rides the merge like `ids` (concatenated, not |
| 406 | /// remapped) and is remapped alongside it when `coalesce` rebuilds the feature vector. Stage C |
| 407 | /// is not given it: a road is a line, and `rings::normalise` never drops one. |
| 408 | pub carriageways: Vec<tilecodec::mamaps::body::Carriageway>, |
| 409 | } |
| 410 | |
| 411 | impl ChunkEntry { |
| 412 | pub(crate) fn new(layer_id: u8) -> ChunkEntry { |
| 413 | ChunkEntry { |
| 414 | layer: BodyLayer::new(layer_id), |
| 415 | names: Vec::new(), |
| 416 | ids: Vec::new(), |
| 417 | turn_lanes: Vec::new(), |
| 418 | buildings: Vec::new(), |
| 419 | carriageways: Vec::new(), |
| 420 | } |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | /// Intern `name` into a first-use-ordered table, returning its 1-based body index. |
| 425 | fn intern_name(names: &mut Vec<String>, name: Option<&str>) -> u16 { |
| 426 | match name.filter(|n| !n.is_empty()) { |
| 427 | None => tilecodec::mamaps::body::NAME_NONE, |
| 428 | Some(name) => match names.iter().position(|n| n == name) { |
| 429 | Some(at) => at as u16 + 1, |
| 430 | None => { |
| 431 | let idx = names.len() as u16 + 1; |
| 432 | names.push(name.to_string()); |
| 433 | idx |
| 434 | } |
| 435 | }, |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | /// What one chunk contributed to a zoom's counters. Only ever summed, so the order they are summed |
| 440 | /// in cannot change the answer. |
| 441 | #[derive(Debug, Default, Clone, Copy)] |
| 442 | struct Tally { |
| 443 | features: u64, |
| 444 | points: u64, |
| 445 | dropped: u64, |
| 446 | // TEMP-PROFILE: per-stage map walls, summed across chunks (durations |
| 447 | // add; order irrelevant). Removed with the probes. NOT Copy (Duration |
| 448 | // is, but the explicit add below keeps the accounting visible). |
| 449 | profile: TallyProfile, |
| 450 | } |
| 451 | |
| 452 | /// TEMP-PROFILE: per-stage map-phase walls carried in the tally. Removed |
| 453 | /// with the probes. |
| 454 | #[derive(Debug, Default, Clone, Copy)] |
| 455 | struct TallyProfile { |
| 456 | project: std::time::Duration, |
| 457 | annotate: std::time::Duration, |
| 458 | filter: std::time::Duration, |
| 459 | subdiv: std::time::Duration, |
| 460 | } |
| 461 | |
| 462 | impl Tally { |
| 463 | fn add(&mut self, other: Tally) { |
| 464 | self.features += other.features; |
| 465 | self.points += other.points; |
| 466 | self.dropped += other.dropped; |
| 467 | self.profile.project += other.profile.project; |
| 468 | self.profile.annotate += other.profile.annotate; |
| 469 | self.profile.filter += other.profile.filter; |
| 470 | self.profile.subdiv += other.profile.subdiv; |
| 471 | } |
| 472 | |
| 473 | /// TEMP-PROFILE: attach this chunk's stage walls. Removed with the probes. |
| 474 | fn profile_add( |
| 475 | &mut self, |
| 476 | project: std::time::Duration, |
| 477 | annotate: std::time::Duration, |
| 478 | filter: std::time::Duration, |
| 479 | subdiv: std::time::Duration, |
| 480 | ) { |
| 481 | self.profile.project += project; |
| 482 | self.profile.annotate += annotate; |
| 483 | self.profile.filter += filter; |
| 484 | self.profile.subdiv += subdiv; |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | include!("tiler_part1.rs"); |
| 489 | include!("tiler_part2.rs"); |
| 490 | include!("tiler_part3.rs"); |
| 491 | include!("tiler_part5.rs"); |
| 492 | include!("tiler_part6.rs"); |
| 493 | include!("tiler_part7.rs"); |
| 494 | include!("tiler_part8.rs"); |
| 495 | include!("tiler_part9.rs"); |
| 496 | include!("tiler_part10.rs"); |
| 497 | include!("tiler_part11.rs"); |