Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / pyramid_part1.rs
pyramid_part1.rs389 lines · 14.2 KiBRaw
| 1 | /// Encode the largest prefix of `candidates` that fits the byte budget. |
| 2 | /// |
| 3 | /// Binary search on the prefix length: `O(log n)` gzip calls per tile rather than |
| 4 | /// one per dropped feature, and the answer does not depend on the search order. |
| 5 | /// Returns the gzipped body, how many features it holds, and whether it is still |
| 6 | /// over budget -- which happens when even a single feature does not fit, and is the |
| 7 | /// one case worth telling the operator about. |
| 8 | fn fit_tile( |
| 9 | candidates: &[TileCandidate], |
| 10 | layer_name: &str, |
| 11 | geom_type: GeomType, |
| 12 | opts: &Options, |
| 13 | gz: &mut crate::gz::Compressor, |
| 14 | ) -> Result<(Vec<u8>, usize, bool)> { |
| 15 | // Geometry command integers, computed ONCE for the whole tile. |
| 16 | // |
| 17 | // These do not depend on `n`, and the binary search calls `encode` about |
| 18 | // `log2(len)` times -- so building them inside the probe re-did the same work |
| 19 | // eleven times over, one fresh `Vec<u32>` allocation per candidate per probe. On |
| 20 | // California z11 that is 4.36 M records x ~11 probes of pure waste, and it was |
| 21 | // most of the 92 s that zoom spent encoding. |
| 22 | let geoms: Vec<Vec<u32>> = candidates |
| 23 | .iter() |
| 24 | .map(|c| match c.geom { |
| 25 | IntGeometry::Points(p) => mvt::encode_points(p), |
| 26 | IntGeometry::Lines(l) => mvt::encode_lines(l), |
| 27 | IntGeometry::Polygons(p) => mvt::encode_polygons(p), |
| 28 | }) |
| 29 | .collect(); |
| 30 | // Candidates whose geometry survived, ascending. A candidate that clips away to |
| 31 | // nothing is skipped rather than emitted, exactly as before. |
| 32 | let live: Vec<usize> = (0..candidates.len()) |
| 33 | .filter(|&i| !geoms[i].is_empty()) |
| 34 | .collect(); |
| 35 | |
| 36 | let mut encode = |n: usize| -> Vec<u8> { |
| 37 | // `live` is ascending, so this is precisely the surviving candidates among the |
| 38 | // first `n` -- the same set the old per-probe loop produced. |
| 39 | let refs = live |
| 40 | .iter() |
| 41 | .take_while(|&&i| i < n) |
| 42 | .map(|&i| MvtFeature { |
| 43 | id: None, |
| 44 | geom_type, |
| 45 | geometry: &geoms[i], |
| 46 | // Properties are BORROWED. Cloning them per candidate per tile was |
| 47 | // ~35% of this function's cost, and a feature reaching many tiles paid |
| 48 | // it once per tile. See `mvt::FeatureRef`. |
| 49 | props: candidates[i].props, |
| 50 | }); |
| 51 | let t0 = std::time::Instant::now(); |
| 52 | let body = mvt::encode_tile_from(layer_name, opts.extent, refs); |
| 53 | let t1 = std::time::Instant::now(); |
| 54 | let out = gz.compress(&body); |
| 55 | MVT_NANOS.fetch_add( |
| 56 | (t1 - t0).as_nanos() as u64, |
| 57 | std::sync::atomic::Ordering::Relaxed, |
| 58 | ); |
| 59 | GZIP_NANOS.fetch_add( |
| 60 | t1.elapsed().as_nanos() as u64, |
| 61 | std::sync::atomic::Ordering::Relaxed, |
| 62 | ); |
| 63 | out |
| 64 | }; |
| 65 | |
| 66 | let all = encode(candidates.len()); |
| 67 | if all.len() <= opts.max_tile_bytes { |
| 68 | return Ok((all, candidates.len(), false)); |
| 69 | } |
| 70 | |
| 71 | // Largest n in 1..len with encode(n) within budget. `lo` is always known to |
| 72 | // fit or to be the floor of 1; `hi` is known not to. |
| 73 | // |
| 74 | // The probe SEQUENCE is part of the output contract, so do not "improve" this into |
| 75 | // a galloping search. Gzipped size is not strictly monotone in n -- adding a |
| 76 | // feature can occasionally compress to fewer bytes -- so a search that visits |
| 77 | // different n lands on a different boundary. Tried on California: galloping up |
| 78 | // from 1 changed the drop count from 710,215 to 710,217 and moved the archive, |
| 79 | // while saving nothing, because the cost here is not the number of probes. |
| 80 | let mut lo = 1usize; |
| 81 | let mut hi = candidates.len(); |
| 82 | let mut best = encode(1); |
| 83 | while lo < hi { |
| 84 | let mid = lo + (hi - lo).div_ceil(2); |
| 85 | let body = encode(mid); |
| 86 | if body.len() <= opts.max_tile_bytes { |
| 87 | best = body; |
| 88 | lo = mid; |
| 89 | } else { |
| 90 | hi = mid - 1; |
| 91 | } |
| 92 | } |
| 93 | // One feature that does not fit is kept anyway: an empty tile is a hole in the |
| 94 | // map, an oversized one is merely slow. |
| 95 | let over = best.len() > opts.max_tile_bytes; |
| 96 | Ok((best, lo, over)) |
| 97 | } |
| 98 | |
| 99 | /// A cheap importance proxy: the geometry's span in tile units, as a single |
| 100 | /// number. Bigger means more of the tile is affected by keeping it. |
| 101 | fn extent_of(g: &IntGeometry) -> i64 { |
| 102 | let mut min = (i32::MAX, i32::MAX); |
| 103 | let mut max = (i32::MIN, i32::MIN); |
| 104 | let mut seen = false; |
| 105 | let mut add = |(x, y): (i32, i32)| { |
| 106 | seen = true; |
| 107 | min = (min.0.min(x), min.1.min(y)); |
| 108 | max = (max.0.max(x), max.1.max(y)); |
| 109 | }; |
| 110 | match g { |
| 111 | IntGeometry::Points(p) => p.iter().for_each(|p| add(*p)), |
| 112 | IntGeometry::Lines(l) => l.iter().flatten().for_each(|p| add(*p)), |
| 113 | IntGeometry::Polygons(p) => p.iter().flatten().flatten().for_each(|p| add(*p)), |
| 114 | } |
| 115 | if !seen { |
| 116 | return 0; |
| 117 | } |
| 118 | (max.0 as i64 - min.0 as i64) + (max.1 as i64 - min.1 as i64) |
| 119 | } |
| 120 | |
| 121 | /// The MVT geometry type for the layer. |
| 122 | /// |
| 123 | /// MVT tags each feature individually, but a layer is styled as one thing, so a |
| 124 | /// mixed layer is a mistake somewhere upstream. Taking the first feature's type |
| 125 | /// and applying it throughout makes that mistake visible as wrong rendering rather |
| 126 | /// than hiding it as a silently split layer. |
| 127 | fn dominant_geom_type(features: &[Feature]) -> GeomType { |
| 128 | geom_type_of(features.first().map(|f| GeomKind::of(&f.geometry))) |
| 129 | } |
| 130 | |
| 131 | /// The same rule, from a kind a source reported rather than a feature in hand. |
| 132 | fn geom_type_of(kind: Option<GeomKind>) -> GeomType { |
| 133 | match kind { |
| 134 | Some(GeomKind::Points) => GeomType::Point, |
| 135 | Some(GeomKind::Lines) => GeomType::LineString, |
| 136 | Some(GeomKind::Polygons) => GeomType::Polygon, |
| 137 | None => GeomType::Unknown, |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | fn lonlat_bounds(features: &[Feature]) -> Option<geom::Rect> { |
| 142 | features.iter().fold(None, |acc, f| fold_bounds(acc, &f.geometry)) |
| 143 | } |
| 144 | |
| 145 | /// Grow `acc` to cover `g`. The whole of [`lonlat_bounds`], so the streaming path can |
| 146 | /// fold the same function over a source it only ever sees one feature at a time and |
| 147 | /// arrive at the same header bytes. |
| 148 | pub fn fold_bounds(acc: Option<geom::Rect>, g: &Geometry) -> Option<geom::Rect> { |
| 149 | let Some(b) = geom::bounds(g) else { return acc }; |
| 150 | Some(match acc { |
| 151 | None => b, |
| 152 | Some(a) => geom::Rect { |
| 153 | min_x: a.min_x.min(b.min_x), |
| 154 | min_y: a.min_y.min(b.min_y), |
| 155 | max_x: a.max_x.max(b.max_x), |
| 156 | max_y: a.max_y.max(b.max_y), |
| 157 | }, |
| 158 | }) |
| 159 | } |
| 160 | |
| 161 | pub(crate) fn e7(deg: f64) -> i32 { |
| 162 | (deg * 1e7).round().clamp(i32::MIN as f64, i32::MAX as f64) as i32 |
| 163 | } |
| 164 | |
| 165 | /// The `json` metadata blob a PMTiles archive carries. MapLibre does not need it to |
| 166 | /// render a styled layer, but `pmtiles show` and friends read it, so emitting a |
| 167 | /// truthful `vector_layers` list keeps the archive introspectable. |
| 168 | fn metadata(layer_name: &str, min_zoom: u8, max_zoom: u8) -> String { |
| 169 | format!( |
| 170 | "{{\"vector_layers\":[{{\"id\":\"{layer_name}\",\"minzoom\":{min_zoom},\ |
| 171 | \"maxzoom\":{max_zoom}}}]}}" |
| 172 | ) |
| 173 | } |
| 174 | |
| 175 | // --- the streaming producer ----------------------------------------------- |
| 176 | |
| 177 | /// How much disk and recursion the streaming producer may use. |
| 178 | pub struct StreamLimits { |
| 179 | /// Buckets per partition level. Must be a power of four so a bucket is exactly one |
| 180 | /// quadtree cell's descendants, and must stay under the process's file-descriptor |
| 181 | /// limit — see [`crate::spill::BucketSet`]. |
| 182 | pub buckets: usize, |
| 183 | /// A bucket over this many bytes is re-partitioned rather than loaded. This is the |
| 184 | /// number that sets peak memory, because a loaded bucket is resident. |
| 185 | pub bucket_budget_bytes: u64, |
| 186 | pub max_repartition_depth: u32, |
| 187 | } |
| 188 | |
| 189 | /// 256 buckets: four levels of the quadtree per partition, and well under any |
| 190 | /// descriptor limit. |
| 191 | pub const DEFAULT_BUCKETS: usize = 256; |
| 192 | |
| 193 | /// 512 MiB of encoded records per bucket. Decoded they cost more, so this is a budget |
| 194 | /// on the spill bytes rather than a promise about RSS; Phase 6's measurement is what |
| 195 | /// turns it into one. |
| 196 | pub const DEFAULT_BUCKET_BUDGET_BYTES: u64 = 512 << 20; |
| 197 | |
| 198 | /// Recursion cap, so a pathological range cannot spin. |
| 199 | /// |
| 200 | /// Not the thing that terminates the recursion: a child's span is its parent's range |
| 201 | /// divided by the bucket count, so it strictly shrinks and the single-`tile_id` floor is |
| 202 | /// always reached. This is the backstop, and it has to have room for the smallest useful |
| 203 | /// bucket count — 4 buckets need one level per zoom, so 24 covers z16 with headroom |
| 204 | /// while 8 would refuse a build the partition could have finished. |
| 205 | pub const DEFAULT_MAX_REPARTITION_DEPTH: u32 = 24; |
| 206 | |
| 207 | impl Default for StreamLimits { |
| 208 | fn default() -> StreamLimits { |
| 209 | StreamLimits { |
| 210 | buckets: DEFAULT_BUCKETS, |
| 211 | bucket_budget_bytes: DEFAULT_BUCKET_BUDGET_BYTES, |
| 212 | max_repartition_depth: DEFAULT_MAX_REPARTITION_DEPTH, |
| 213 | } |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | /// A rewindable feature stream, which is all [`build_archive_to`] needs of its input. |
| 218 | /// |
| 219 | /// Rewindable because the producer makes one pass per zoom: six passes over a compact |
| 220 | /// binary is far cheaper than six re-parses of planet GeoJSON, and it is what lets the |
| 221 | /// features not be resident. |
| 222 | /// |
| 223 | /// `bounds` and `geom_kind` come from a fold the caller already did while writing the |
| 224 | /// source, so there is no bounds pre-pass: |
| 225 | /// [`crate::pmtiles::StreamBuilder`] serialises its header last. |
| 226 | pub trait FeatureSource { |
| 227 | fn rewind(&mut self) -> Result<()>; |
| 228 | fn next(&mut self) -> Result<Option<Feature>>; |
| 229 | /// How many features a pass will yield, for the progress bar. |
| 230 | fn len(&self) -> u64; |
| 231 | fn is_empty(&self) -> bool { |
| 232 | self.len() == 0 |
| 233 | } |
| 234 | fn bounds(&self) -> Option<geom::Rect>; |
| 235 | /// The FIRST feature's kind, the rule [`dominant_geom_type`] already applies. |
| 236 | fn geom_kind(&self) -> Option<GeomKind>; |
| 237 | |
| 238 | /// A positionally-readable view of the same features, when there is one. |
| 239 | /// |
| 240 | /// `Some` lets the bucket pass read and decode the source across the pool rather |
| 241 | /// than through this cursor; `None` keeps it sequential. Only the file-backed source |
| 242 | /// has one: [`SliceSource`]'s features are already resident and there is nothing to |
| 243 | /// read. It is also `None` for a file written before the index existed, or an empty |
| 244 | /// one, so the sequential path stays the fallback rather than a special case. |
| 245 | fn chunks(&self) -> Option<&spill::NormalizedChunks> { |
| 246 | None |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | /// A [`FeatureSource`] over features already in memory. |
| 251 | /// |
| 252 | /// What the byte-identity tests drive the streaming producer from, so they need no |
| 253 | /// temporary input file and compare exactly the same features the in-memory path saw. |
| 254 | pub struct SliceSource<'a> { |
| 255 | features: &'a [Feature], |
| 256 | at: usize, |
| 257 | bounds: Option<geom::Rect>, |
| 258 | kind: Option<GeomKind>, |
| 259 | } |
| 260 | |
| 261 | impl<'a> SliceSource<'a> { |
| 262 | pub fn new(features: &'a [Feature]) -> SliceSource<'a> { |
| 263 | SliceSource { |
| 264 | features, |
| 265 | at: 0, |
| 266 | bounds: lonlat_bounds(features), |
| 267 | kind: features.first().map(|f| GeomKind::of(&f.geometry)), |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | impl FeatureSource for SliceSource<'_> { |
| 273 | fn rewind(&mut self) -> Result<()> { |
| 274 | self.at = 0; |
| 275 | Ok(()) |
| 276 | } |
| 277 | |
| 278 | fn next(&mut self) -> Result<Option<Feature>> { |
| 279 | let f = self.features.get(self.at).cloned(); |
| 280 | if f.is_some() { |
| 281 | self.at += 1; |
| 282 | } |
| 283 | Ok(f) |
| 284 | } |
| 285 | |
| 286 | fn len(&self) -> u64 { |
| 287 | self.features.len() as u64 |
| 288 | } |
| 289 | |
| 290 | fn bounds(&self) -> Option<geom::Rect> { |
| 291 | self.bounds |
| 292 | } |
| 293 | |
| 294 | fn geom_kind(&self) -> Option<GeomKind> { |
| 295 | self.kind |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | /// A [`FeatureSource`] over [`crate::spill`]'s normalized file. The production path. |
| 300 | pub struct NormalizedSource { |
| 301 | reader: spill::NormalizedReader, |
| 302 | summary: spill::NormalizedSummary, |
| 303 | chunks: Option<spill::NormalizedChunks>, |
| 304 | } |
| 305 | |
| 306 | impl NormalizedSource { |
| 307 | /// `summary` is what [`crate::spill::NormalizedWriter::finish`] returned for this |
| 308 | /// file. Passed in rather than re-derived, because deriving it would be the pre-pass |
| 309 | /// the design exists to avoid. |
| 310 | pub fn open( |
| 311 | path: impl Into<std::path::PathBuf>, |
| 312 | summary: spill::NormalizedSummary, |
| 313 | ) -> Result<NormalizedSource> { |
| 314 | let path = path.into(); |
| 315 | // A second handle on the same file, for the chunked reads. Separate because the |
| 316 | // sequential reader owns a cursor and positional reads must not disturb it. |
| 317 | let chunks = if summary.chunk_count() == 0 { |
| 318 | None |
| 319 | } else { |
| 320 | Some(spill::NormalizedChunks::open( |
| 321 | path.clone(), |
| 322 | summary.chunks.clone(), |
| 323 | )?) |
| 324 | }; |
| 325 | Ok(NormalizedSource { |
| 326 | reader: spill::NormalizedReader::open(path)?, |
| 327 | summary, |
| 328 | chunks, |
| 329 | }) |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | impl FeatureSource for NormalizedSource { |
| 334 | fn rewind(&mut self) -> Result<()> { |
| 335 | self.reader.rewind() |
| 336 | } |
| 337 | |
| 338 | fn next(&mut self) -> Result<Option<Feature>> { |
| 339 | Ok(self.reader.next()?.map(|f| Feature { |
| 340 | geometry: f.geometry, |
| 341 | props: f.props, |
| 342 | })) |
| 343 | } |
| 344 | |
| 345 | fn len(&self) -> u64 { |
| 346 | self.summary.count |
| 347 | } |
| 348 | |
| 349 | fn bounds(&self) -> Option<geom::Rect> { |
| 350 | self.summary.bounds |
| 351 | } |
| 352 | |
| 353 | fn geom_kind(&self) -> Option<GeomKind> { |
| 354 | self.summary.geom_kind |
| 355 | } |
| 356 | |
| 357 | fn chunks(&self) -> Option<&spill::NormalizedChunks> { |
| 358 | self.chunks.as_ref() |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | /// Features bucketed in one zoom's first pass. |
| 363 | const BUCKETED: &str = "feature(s) bucketed"; |
| 364 | |
| 365 | /// Spill records encoded in one zoom's second pass. |
| 366 | const ENCODED: &str = "record(s) encoded"; |
| 367 | |
| 368 | /// One zoom's bucket pass: project every feature, clip it into each tile it reaches, and |
| 369 | /// write a spill record per `(feature, tile)`. |
| 370 | /// |
| 371 | /// Two read shapes, one output. Both derive `seq` from the feature's index in the source |
| 372 | /// rather than from arrival order, which is what makes them interchangeable: |
| 373 | /// `encode_buckets` sorts each bucket by the total key `(tile_id, extent, seq)`, so push |
| 374 | /// order never reaches the archive. |
| 375 | #[allow(clippy::too_many_arguments)] |
| 376 | fn bucket_pass( |
| 377 | src: &mut impl FeatureSource, |
| 378 | z: u8, |
| 379 | opts: &Options, |
| 380 | buffer: f64, |
| 381 | tolerance: f64, |
| 382 | set: &mut spill::BucketSet, |
| 383 | bar: &mut Progress, |
| 384 | ) -> Result<()> { |
| 385 | if let Some(chunks) = src.chunks() { |
| 386 | return bucket_chunked(chunks, z, opts, buffer, tolerance, set, bar); |
| 387 | } |
| 388 | bucket_serial(src, z, opts, buffer, tolerance, set, bar) |
| 389 | } |