Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / subdivide.rs
subdivide.rs374 lines · 17.1 KiBRaw
| 1 | //! Tile one feature by descending the tile quadtree, instead of once per tile. |
| 2 | //! |
| 3 | //! The tiling loops used to have one shape: ask [`crate::geom::tiles_touched`] for |
| 4 | //! every tile a feature reaches, then clip **the whole feature** against each of |
| 5 | //! them. That is `O(T * V)`, and both factors grow with the feature's geographic |
| 6 | //! extent: a state-sized polygon at z13 has `T` in the hundreds of thousands and |
| 7 | //! `V` in the hundreds of thousands, and every one of those tiles paid a full |
| 8 | //! vertex walk -- including the vast majority that are strictly interior and whose |
| 9 | //! answer is just the tile rectangle. |
| 10 | //! |
| 11 | //! [`subdivide`] walks the quadtree instead: |
| 12 | //! |
| 13 | //! 1. Find the deepest cell that already contains the whole geometry. A building at |
| 14 | //! z14 gets the leaf itself and no recursion at all, so the leaf clip is the only |
| 15 | //! clip -- exactly what the old loop did. A coastline gets a shallow cell. |
| 16 | //! 2. At each level, clip the geometry **already clipped to this cell** into each of |
| 17 | //! the four children, and recurse into the ones that survive. |
| 18 | //! 3. A level-`z` cell rect *is* [`crate::geom::tile_rect`], so the leaf sees the |
| 19 | //! same rectangle as before. |
| 20 | //! |
| 21 | //! Cost becomes `O(V * (z - level))` for the vertex walks plus `O(T)` small clips at |
| 22 | //! the bottom, rather than `O(V * T)`. |
| 23 | //! |
| 24 | //! ## Why clipping progressively is sound |
| 25 | //! |
| 26 | //! The buffer is the same world-unit constant at every level. A child cell is a |
| 27 | //! subset of its parent, and growing both by the same Minkowski sum keeps that: |
| 28 | //! `child (+) buffer` is a subset of `parent (+) buffer`. Clipping is intersection, so |
| 29 | //! `clip(clip(g, A), B)` is `clip(g, B)` whenever `B` is inside `A`, and the whole |
| 30 | //! descent is that identity applied `z - level` times. |
| 31 | //! |
| 32 | //! Sutherland-Hodgman makes that worth checking rather than assuming. It returns a |
| 33 | //! clipped *concave* ring as a single self-touching ring joined by zero-width slivers |
| 34 | //! (see [`crate::clip`]'s module docs), which is not the intersection as a simple |
| 35 | //! polygon -- so composing through one is not obviously sound. |
| 36 | //! `clipping_twice_is_clipping_once_for_a_nested_rect` searches for a counterexample |
| 37 | //! over random concave rings, random holes and random nested rect pairs, and finds |
| 38 | //! none: the sliver runs along the shared boundary and the next clip either keeps that |
| 39 | //! boundary or removes the sliver with it. |
| 40 | //! |
| 41 | //! It is the same argument [`crate::geom::tiles_touched`]'s bisection rests on: a |
| 42 | //! recursive subdivision is safe exactly when each step preserves what the next needs. |
| 43 | //! |
| 44 | //! ## Points do not descend |
| 45 | //! |
| 46 | //! [`crate::clip::clip_geometry`] on `Points` filters the whole list per tile, which |
| 47 | //! is its own `O(T * V)`. A point's tiles are just the tiles its own padded box |
| 48 | //! covers, so points are bucketed straight into them -- which is what |
| 49 | //! `tiles_touched` followed by a `contains` test worked out to anyway, one point at a |
| 50 | //! time. |
| 51 | //! |
| 52 | //! ## What this costs in output |
| 53 | //! |
| 54 | //! **Not byte-identity to a direct clip, and not the vertices that were expected to |
| 55 | //! cost it.** Clipping to an ancestor cell does insert vertices on that ancestor's |
| 56 | //! boundary, and [`crate::geom::Vertex::boundary`] does stamp them unremovable -- but |
| 57 | //! none of them survive to a leaf as a vertex the leaf's own clip would not have |
| 58 | //! invented. A child cell is a subset of its parent and both are grown by the *same* |
| 59 | //! buffer, so a parent boundary line either coincides with the child's line on that |
| 60 | //! side, when the child sits on that border, or lies strictly outside the child, |
| 61 | //! where the next clip removes it. Coincident lines give coincident crossings. |
| 62 | //! |
| 63 | //! Measured over the corpus in this module's tests, the descent emits **fewer** |
| 64 | //! vertices than a direct clip, not more, so there is no collinear-reduction pass and |
| 65 | //! the archive does not grow. Three differences remain, none of them a shape: |
| 66 | //! |
| 67 | //! | difference | why | visible? | |
| 68 | //! |---|---|---| |
| 69 | //! | a ring's starting vertex | Sutherland-Hodgman keeps its input's rotation, and the descent's input is its parent's answer | same polygon; MVT re-states the start as a `MoveTo` | |
| 70 | //! | fewer collinear spurs | a concave ring's zero-area run along a clip boundary is shorter when built in stages | zero-area either way | |
| 71 | //! | last-bit drift on a line crossing | Liang-Barsky interpolates both coordinates, so a crossing taken off an already-interpolated vertex can land an ULP away | 1e-12 world units against a quantisation grid of 1 | |
| 72 | //! |
| 73 | //! The tests hold the descent to being the same *shape* -- same tiles, same parts, |
| 74 | //! same corners up to rotation, same signed area, same length -- and record the byte |
| 75 | //! divergence rather than asserting it away. |
| 76 | |
| 77 | use crate::clip::clip_geometry; |
| 78 | use crate::geom::{self, Geometry, Pt, Rect, Vertex}; |
| 79 | |
| 80 | /// Clip `g` into every tile of zoom `z` it reaches, calling `emit` once per tile. |
| 81 | /// |
| 82 | /// `g` must already be in world coordinates for `z` (see [`crate::geom`]'s module |
| 83 | /// docs). `buffer` is the same overspill the old per-tile loop passed to both |
| 84 | /// `tiles_touched` and `tile_rect`, and it is applied at every level of the descent. |
| 85 | /// |
| 86 | /// A tile whose clip is empty is not emitted. The old loop reached those tiles and |
| 87 | /// then skipped them, so nothing downstream sees a difference. |
| 88 | /// |
| 89 | /// Tiles arrive in quadtree order, which is neither the old `(x, y)` order nor |
| 90 | /// `tile_id` order. Every caller either keys a map by tile or sorts afterwards, so |
| 91 | /// the order is deterministic rather than significant. |
| 92 | pub fn subdivide<V, F>(g: &Geometry<V>, z: u8, extent: u32, buffer: f64, emit: &mut F) |
| 93 | where |
| 94 | V: Vertex, |
| 95 | F: FnMut(u64, u64, &Geometry<V>), |
| 96 | { |
| 97 | if let Geometry::Points(pts) = g { |
| 98 | bucket_points(pts, z, extent, buffer, emit); |
| 99 | return; |
| 100 | } |
| 101 | let Some(box_) = geom::bounds(g) else { return }; |
| 102 | // The same padded range the old loop's `tiles_touched` computed from, so a |
| 103 | // feature reaching only into a neighbour's buffer still descends towards it. |
| 104 | let Some(range) = geom::tile_range(&box_, z, extent, buffer) else { return }; |
| 105 | |
| 106 | // The deepest cell holding the whole range is the one whose tile indices agree |
| 107 | // once the low bits are dropped. |
| 108 | let mut shift = 0u32; |
| 109 | while (range.x0 >> shift) != (range.x1 >> shift) || (range.y0 >> shift) != (range.y1 >> shift) { |
| 110 | shift += 1; |
| 111 | } |
| 112 | let level = z - shift as u8; |
| 113 | let (cx, cy) = (range.x0 >> shift, range.y0 >> shift); |
| 114 | |
| 115 | // The start cell already contains the geometry, so this clip inserts nothing |
| 116 | // unless the feature runs off the edge of the grid -- where the old loop's edge |
| 117 | // tile cut it at the same coordinate, because a cell on the grid's border shares |
| 118 | // that border with its leaves. |
| 119 | let clipped = clip_geometry(g, &cell_rect(level, cx, cy, z, extent, buffer)); |
| 120 | if is_empty(&clipped) { |
| 121 | return; |
| 122 | } |
| 123 | walk(&clipped, level, cx, cy, z, extent, buffer, emit); |
| 124 | } |
| 125 | |
| 126 | /// One quadtree cell's clip rect in world coordinates, grown by `buffer`. |
| 127 | /// |
| 128 | /// At `level == z` this is [`geom::tile_rect`] to the bit: `2^0` is 1, so the |
| 129 | /// arithmetic below is the same arithmetic. |
| 130 | fn cell_rect(level: u8, cx: u64, cy: u64, z: u8, extent: u32, buffer: f64) -> Rect { |
| 131 | let side = extent as f64 * (1u64 << (z - level)) as f64; |
| 132 | let (ox, oy) = (cx as f64 * side, cy as f64 * side); |
| 133 | Rect { |
| 134 | min_x: ox - buffer, |
| 135 | min_y: oy - buffer, |
| 136 | max_x: ox + side + buffer, |
| 137 | max_y: oy + side + buffer, |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | /// Descend from a cell whose clipped geometry is `g`, emitting at the leaves. |
| 142 | #[allow(clippy::too_many_arguments)] |
| 143 | fn walk<V, F>( |
| 144 | g: &Geometry<V>, |
| 145 | level: u8, |
| 146 | cx: u64, |
| 147 | cy: u64, |
| 148 | z: u8, |
| 149 | extent: u32, |
| 150 | buffer: f64, |
| 151 | emit: &mut F, |
| 152 | ) where |
| 153 | V: Vertex, |
| 154 | F: FnMut(u64, u64, &Geometry<V>), |
| 155 | { |
| 156 | if level == z { |
| 157 | emit(cx, cy, g); |
| 158 | return; |
| 159 | } |
| 160 | // One bbox for the four child clips below: each child whose rect misses |
| 161 | // the box clips to empty without walking a vertex, and a child |
| 162 | // containing the whole box clips to a copy of `g` (see `clip_child`). |
| 163 | // Concentrated geometries — the common case below the top levels — pay |
| 164 | // one walk plus one real clip per level instead of four full clips. |
| 165 | let box_ = geom::bounds(g); |
| 166 | for (dx, dy) in [(0u64, 0u64), (1, 0), (0, 1), (1, 1)] { |
| 167 | let (nx, ny) = (cx * 2 + dx, cy * 2 + dy); |
| 168 | let clipped = clip_child(g, box_.as_ref(), &cell_rect(level + 1, nx, ny, z, extent, buffer)); |
| 169 | if is_empty(&clipped) { |
| 170 | continue; |
| 171 | } |
| 172 | walk(&clipped, level + 1, nx, ny, z, extent, buffer, emit); |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | /// Whether `outer` contains `inner` wholly (boundary-inclusive, matching the |
| 177 | /// clipper's own `>=`/`<=` comparisons). |
| 178 | fn contains_rect(outer: &Rect, inner: &Rect) -> bool { |
| 179 | outer.min_x <= inner.min_x |
| 180 | && inner.max_x <= outer.max_x |
| 181 | && outer.min_y <= inner.min_y |
| 182 | && inner.max_y <= outer.max_y |
| 183 | } |
| 184 | |
| 185 | /// A vertex is finite iff both coordinates are. |
| 186 | fn finite_pt((x, y): Pt) -> bool { |
| 187 | x.is_finite() && y.is_finite() |
| 188 | } |
| 189 | |
| 190 | /// Clip `g` to one child cell, short-circuiting the two decided cases. |
| 191 | /// |
| 192 | /// `box_` is `g`'s bbox (computed once per level by the caller, not per |
| 193 | /// child): a child the box misses clips to empty, and a child containing the |
| 194 | /// whole box clips to a copy. Both are exact — see below — and both skip the |
| 195 | /// per-vertex clip walk. |
| 196 | /// |
| 197 | /// Exactness: `clip_geometry` invents vertices only at boundary crossings |
| 198 | /// (Liang-Barsky interpolates only moved endpoints; Sutherland-Hodgman pushes |
| 199 | /// only crossings plus surviving vertices), and drops only non-finite |
| 200 | /// vertices. With every vertex strictly inside the rect there are no |
| 201 | /// crossings to invent; with the box missing the rect there is nothing to |
| 202 | /// keep. The boundary-inclusive tests below (`contains_rect` uses `<=`, the |
| 203 | /// miss test negates `intersects`) match the clipper's own inclusive |
| 204 | /// comparisons (`inside` uses `>=`/`<=`, `clip_segment` keeps `q >= 0`), so |
| 205 | /// a vertex exactly on a child edge takes the general path — where the |
| 206 | /// crossing arithmetic (not the fast path) decides, exactly as before. |
| 207 | fn clip_child<V>(g: &Geometry<V>, box_: Option<&Rect>, rect: &Rect) -> Geometry<V> |
| 208 | where |
| 209 | V: Vertex, |
| 210 | { |
| 211 | match box_ { |
| 212 | // No finite vertex at all: every clip path drops everything. |
| 213 | // `clip_geometry` on points filters to empty; lines partition into |
| 214 | // nothing; rings fail the 3-vertex floor. Same empty, no walk. |
| 215 | None => empty_like(g), |
| 216 | Some(b) => { |
| 217 | if !b.intersects(rect) { |
| 218 | return empty_like(g); |
| 219 | } |
| 220 | if contains_rect(rect, b) { |
| 221 | // Every finite vertex strictly inside: clone. Non-finite |
| 222 | // vertices are NOT cloned along — `clip_geometry` drops them |
| 223 | // (`finite` filter in every path), so keeping them would |
| 224 | // invent vertices the clip removes. The filter walk is O(V) |
| 225 | // like the bbox was, but allocation-free for the common |
| 226 | // all-finite case... it still walks. Cheaper than the clip's |
| 227 | // interpolations + allocs, and correct where clone is not. |
| 228 | return clone_finite(g); |
| 229 | } |
| 230 | clip_geometry(g, rect) |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | /// An empty geometry of `g`'s variant: what `clip_geometry` returns when |
| 236 | /// nothing survives (empty vec, same variant — the drain tests part counts, |
| 237 | /// never the variant... it tests `is_empty`, which is variant-agnostic, but |
| 238 | /// matching the variant keeps the shape identical anyway). |
| 239 | fn empty_like<V>(g: &Geometry<V>) -> Geometry<V> |
| 240 | where |
| 241 | V: Vertex, |
| 242 | { |
| 243 | match g { |
| 244 | Geometry::Points(_) => Geometry::Points(Vec::new()), |
| 245 | Geometry::Lines(_) => Geometry::Lines(Vec::new()), |
| 246 | Geometry::Polygons(_) => Geometry::Polygons(Vec::new()), |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | /// `g` with non-finite vertices dropped, otherwise verbatim. |
| 251 | /// |
| 252 | /// What `clip_geometry` reduces to when every finite vertex sits inside the |
| 253 | /// rect: no crossings invented (nothing crosses a boundary it never meets), |
| 254 | /// nothing kept that the filter would drop. |
| 255 | /// |
| 256 | /// Per-variant because the clip's drop granularity differs per path: |
| 257 | /// - Points: the filter IS the clip (kept or dropped whole). Exact. |
| 258 | /// - Lines: an all-inside line survives whole — `clip_line` welds one |
| 259 | /// gapless run back into itself, and lines under 2 vertices never survive |
| 260 | /// its push gates. Replicated below, including the degenerate floors. |
| 261 | /// - Polygons: delegated to the real clip (see below). |
| 262 | /// |
| 263 | /// The all-finite check rides the same walk as the filter: one pass, no |
| 264 | /// second scan. When anything drops, lines still return the filtered form |
| 265 | /// directly (exact, per above); only polygons delegate. |
| 266 | fn clone_finite<V>(g: &Geometry<V>) -> Geometry<V> |
| 267 | where |
| 268 | V: Vertex, |
| 269 | { |
| 270 | match g { |
| 271 | Geometry::Points(pts) => { |
| 272 | // The filter is the whole clip for points: kept whole or dropped. |
| 273 | Geometry::Points(pts.iter().copied().filter(|p| finite_pt(p.xy())).collect()) |
| 274 | } |
| 275 | Geometry::Lines(lines) => { |
| 276 | let mut out = Vec::with_capacity(lines.len()); |
| 277 | for line in lines { |
| 278 | let kept: Vec<V> = |
| 279 | line.iter().copied().filter(|p| finite_pt(p.xy())).collect(); |
| 280 | // `clip_line`'s floors, replicated: a run under 2 vertices is |
| 281 | // never pushed (windows(2) yields nothing; the trailing push |
| 282 | // needs len > 1). An all-inside line is one gapless run, so |
| 283 | // the kept vec IS the clip output — no welding needed, since |
| 284 | // no gap ever opens. |
| 285 | if kept.len() >= 2 { |
| 286 | out.push(kept); |
| 287 | } |
| 288 | // 0 or 1 surviving vertices: dropped, exactly as the clip's |
| 289 | // `len() > 1` gates drop them (a lone vertex never forms a |
| 290 | // segment, and `current` never reaches pushable length). |
| 291 | } |
| 292 | Geometry::Lines(out) |
| 293 | } |
| 294 | Geometry::Polygons(polys) => { |
| 295 | // Rings need the clip's own normalisation (explicit-close |
| 296 | // handling and consecutive-duplicate dedup interact with |
| 297 | // filtering in ways a hand replica would get subtly wrong), and |
| 298 | // rings hold a minority of map vertices (lines dominate: |
| 299 | // boundaries, roads, rivers). So polygons always take the |
| 300 | // general path. (Revisit with measurements if rings dominate a |
| 301 | // profile: replicate `clip_ring`'s normalisation on filtered |
| 302 | // rings, pinned by the shape tests below.) |
| 303 | clip_geometry(g, &Rect { |
| 304 | min_x: f64::NEG_INFINITY, |
| 305 | min_y: f64::NEG_INFINITY, |
| 306 | max_x: f64::INFINITY, |
| 307 | max_y: f64::INFINITY, |
| 308 | }) |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | /// Whether a clip left anything at all. |
| 314 | /// |
| 315 | /// A part-count test is enough: [`clip_geometry`] already drops lines below two |
| 316 | /// vertices and rings below three, so a surviving part is a drawable part. |
| 317 | fn is_empty<V>(g: &Geometry<V>) -> bool { |
| 318 | match g { |
| 319 | Geometry::Points(pts) => pts.is_empty(), |
| 320 | Geometry::Lines(lines) => lines.is_empty(), |
| 321 | Geometry::Polygons(polys) => polys.is_empty(), |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | /// Bucket points into the tiles whose buffered rects hold them. |
| 326 | /// |
| 327 | /// Deliberately the padded box rather than just the tile the coordinate floors |
| 328 | /// into: a point three units from a tile edge belongs in the neighbour's buffer too, |
| 329 | /// which is what keeps a label from being clipped at a tile join. That is exactly |
| 330 | /// the set `tiles_touched` listed and `clip_geometry`'s `contains` test then kept. |
| 331 | /// |
| 332 | /// One `Vec` of `(tile, point)` pairs sorted into runs, rather than a map of tiles to |
| 333 | /// point lists. A `Points` feature is usually a single point, and this crate's |
| 334 | /// standard for a per-feature path is set by `bucket_feature` threading its record |
| 335 | /// buffer through from the caller -- a `HashMap` plus a `Vec` per tile per feature |
| 336 | /// would be three allocations to place one node. The sort is stable, so points keep |
| 337 | /// their input order within a tile. |
| 338 | fn bucket_points<V, F>(pts: &[V], z: u8, extent: u32, buffer: f64, emit: &mut F) |
| 339 | where |
| 340 | V: Vertex, |
| 341 | F: FnMut(u64, u64, &Geometry<V>), |
| 342 | { |
| 343 | let mut spread: Vec<((u64, u64), V)> = Vec::with_capacity(pts.len()); |
| 344 | for p in pts { |
| 345 | let (x, y) = p.xy(); |
| 346 | let box_ = Rect { min_x: x, min_y: y, max_x: x, max_y: y }; |
| 347 | let Some(range) = geom::tile_range(&box_, z, extent, buffer) else { continue }; |
| 348 | for tile in range.iter() { |
| 349 | spread.push((tile, *p)); |
| 350 | } |
| 351 | } |
| 352 | spread.sort_by_key(|&(tile, _)| tile); |
| 353 | // One `Geometry` reused across tiles, its inner `Vec` refilled rather than |
| 354 | // reallocated: `emit` takes a borrow, so handing over an owned vector per tile |
| 355 | // would give the allocation away and leave nothing to reuse. |
| 356 | let mut holder = Geometry::Points(Vec::new()); |
| 357 | let mut at = 0usize; |
| 358 | while at < spread.len() { |
| 359 | let tile = spread[at].0; |
| 360 | let end = at + spread[at..].partition_point(|&(t, _)| t == tile); |
| 361 | let Geometry::Points(one) = &mut holder else { unreachable!("built as points") }; |
| 362 | one.clear(); |
| 363 | one.extend(spread[at..end].iter().map(|&(_, p)| p)); |
| 364 | emit(tile.0, tile.1, &holder); |
| 365 | at = end; |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | #[cfg(test)] |
| 370 | mod tests { |
| 371 | include!("subdivide_part1.rs"); |
| 372 | include!("subdivide_part2.rs"); |
| 373 | include!("subdivide_part3.rs"); |
| 374 | } |