Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / subdivide_part2.rs
subdivide_part2.rs423 lines · 19.0 KiBRaw
| 1 | |
| 2 | /// **The gate.** The descent's answer for a tile must be the same shape as |
| 3 | /// clipping the source straight to that tile -- same tiles, same parts, same |
| 4 | /// rings, same vertices, same areas, same lengths. |
| 5 | /// |
| 6 | /// It is not the same BYTES, and the reason is not the one the plan expected. |
| 7 | /// The worry was that clipping to an ancestor cell inserts vertices on that |
| 8 | /// ancestor's boundary which nothing downstream removes. That does not happen: a |
| 9 | /// child cell is a subset of its parent and both are grown by the *same* buffer, |
| 10 | /// so a parent boundary line either coincides with the child's line on that side |
| 11 | /// -- when the child sits on that border -- or lies strictly outside the child, |
| 12 | /// where the next clip removes it. Coincident lines produce coincident crossings. |
| 13 | /// So no ancestor vertex survives that the leaf would not have invented itself, |
| 14 | /// and [`the_descent_invents_no_vertices`] measures that directly. |
| 15 | /// |
| 16 | /// What differs instead is [`Divergence::rotated`]: ring rotation, and last-bit |
| 17 | /// drift on interpolated line crossings. Neither moves a shape, and both are |
| 18 | /// below the quantisation grid or invisible to it. A collinear-reduction pass |
| 19 | /// would not address either, so there is none. |
| 20 | #[test] |
| 21 | fn the_descent_is_the_same_shape_as_a_direct_clip() { |
| 22 | let mut bad = Vec::new(); |
| 23 | for (name, g, z) in corpus() { |
| 24 | let d = compare(&g, z); |
| 25 | assert!(d.tiles > 0, "{name}: nothing was tiled at all"); |
| 26 | if !d.missing.is_empty() { |
| 27 | bad.push(format!( |
| 28 | "{name} at z{z}: {} of {} tiles are in one and not the other: {:?}", |
| 29 | d.missing.len(), |
| 30 | d.tiles, |
| 31 | &d.missing[..d.missing.len().min(6)] |
| 32 | )); |
| 33 | } |
| 34 | if !d.wrong.is_empty() { |
| 35 | bad.push(format!( |
| 36 | "{name} at z{z}: {} of {} tiles changed shape: {:?}", |
| 37 | d.wrong.len(), |
| 38 | d.tiles, |
| 39 | &d.wrong[..d.wrong.len().min(3)] |
| 40 | )); |
| 41 | } |
| 42 | } |
| 43 | assert!(bad.is_empty(), "{}", bad.join("\n")); |
| 44 | } |
| 45 | |
| 46 | /// The archive-growth question, measured. Boundary vertices on internal cell |
| 47 | /// edges would cost bytes at every zoom, and that was the main argument for a |
| 48 | /// collinear pass. The descent emits no more vertices than a direct clip -- fewer, |
| 49 | /// in fact, because a concave ring's zero-area sliver comes out shorter when the |
| 50 | /// clip happens in stages. |
| 51 | #[test] |
| 52 | fn the_descent_invents_no_vertices() { |
| 53 | let (mut mine, mut theirs) = (0usize, 0usize); |
| 54 | for (_, g, z) in corpus() { |
| 55 | let d = compare(&g, z); |
| 56 | mine += d.descent_vertices; |
| 57 | theirs += d.direct_vertices; |
| 58 | } |
| 59 | assert!(theirs > 0); |
| 60 | assert!( |
| 61 | mine <= theirs, |
| 62 | "the descent would grow the archive: {mine} vertices vs {theirs}" |
| 63 | ); |
| 64 | } |
| 65 | |
| 66 | /// A ring of `n` vertices around `(cx, cy)`, radius varying with `wobble`. |
| 67 | /// |
| 68 | /// Deliberately not star-convex when `wobble` is large: a convex-ish blob never |
| 69 | /// makes Sutherland-Hodgman produce the self-touching output that composing a clip |
| 70 | /// has to survive. |
| 71 | fn wobbly_ring(cx: f64, cy: f64, radius: f64, n: usize, wobble: &mut impl FnMut() -> f64) -> Vec<Pt> { |
| 72 | let mut r: Vec<Pt> = (0..n) |
| 73 | .map(|i| { |
| 74 | let a = i as f64 * std::f64::consts::TAU / n as f64; |
| 75 | let d = radius * (0.25 + 1.5 * wobble()); |
| 76 | (w(cx + d * a.cos()), w(cy + d * a.sin())) |
| 77 | }) |
| 78 | .collect(); |
| 79 | r.push(r[0]); |
| 80 | r |
| 81 | } |
| 82 | |
| 83 | /// **A hole must not vanish.** Found by `test/diff_mamaps.py` on a real us-west z13 |
| 84 | /// archive: one `landcover` feature came back with 13 rings where a direct clip gave |
| 85 | /// 14, and the missing one was a hole carrying a quarter of the feature's net area. |
| 86 | /// A hole that disappears renders as a lake filled in solid. |
| 87 | /// |
| 88 | /// The corpus above missed it because every hole in it is an axis-aligned square. A |
| 89 | /// hole only triggers this when it is concave enough that clipping it to an ancestor |
| 90 | /// cell leaves a self-touching ring, and positioned so that the next clip down has |
| 91 | /// to cut that ring again. |
| 92 | /// |
| 93 | /// Ring COUNT and NET signed area, not vertex lists: what matters is that the hole is |
| 94 | /// still there and still subtracts the same ground. |
| 95 | #[test] |
| 96 | fn a_hole_survives_the_descent_that_a_direct_clip_keeps() { |
| 97 | let mut seed = 0x9E37_79B9_7F4A_7C15u64; |
| 98 | let mut next = move || { |
| 99 | seed ^= seed << 13; |
| 100 | seed ^= seed >> 7; |
| 101 | seed ^= seed << 17; |
| 102 | (seed >> 11) as f64 / (1u64 << 53) as f64 |
| 103 | }; |
| 104 | |
| 105 | let mut checked = 0usize; |
| 106 | let mut bad: Vec<String> = Vec::new(); |
| 107 | |
| 108 | // A comb-shaped hole is the sharpest case, and the reason is the gap in the |
| 109 | // descent's soundness argument. Composing clips is exact for a CONVEX ring: |
| 110 | // `clip(clip(g,P),L) == clip(g,L)` because both are set intersections. For a |
| 111 | // concave ring Sutherland-Hodgman does not return the intersection as a simple |
| 112 | // polygon -- it returns one SELF-TOUCHING ring joined by zero-width slivers -- |
| 113 | // and re-clipping that is not covered by the argument. A comb straddling a cell |
| 114 | // boundary produces exactly that, many times over. |
| 115 | let comb_hole = { |
| 116 | let mut r: Vec<Pt> = vec![(w(2.0), w(4.0))]; |
| 117 | for i in 0..11 { |
| 118 | let y0 = 4.0 + i as f64 * 0.7; |
| 119 | let y1 = y0 + 0.35; |
| 120 | r.push((w(12.5), w(y0))); |
| 121 | r.push((w(12.5), w(y1))); |
| 122 | r.push((w(2.0), w(y1))); |
| 123 | r.push((w(2.0), w(y0 + 0.7))); |
| 124 | } |
| 125 | r.push((w(2.0), w(12.0))); |
| 126 | r.push((w(2.0), w(4.0))); |
| 127 | r |
| 128 | }; |
| 129 | let ext = square(0.5, 15.5); |
| 130 | let g = polygon(&[&ext, &comb_hole]); |
| 131 | for z in [4u8, 5, 6] { |
| 132 | let mine: std::collections::HashMap<_, _> = descend(&g, z).into_iter().collect(); |
| 133 | for (tile, expect) in direct(&g, z) { |
| 134 | let Some(got) = mine.get(&tile) else { |
| 135 | bad.push(format!("comb hole z{z} tile {tile:?}: the descent lost the tile")); |
| 136 | continue; |
| 137 | }; |
| 138 | let (Geometry::Polygons(a), Geometry::Polygons(b)) = (got, &expect) else { continue }; |
| 139 | if a.len() != b.len() { |
| 140 | bad.push(format!("comb hole z{z} tile {tile:?}: {} polygons vs {}", a.len(), b.len())); |
| 141 | continue; |
| 142 | } |
| 143 | for (i, (ra, rb)) in a.iter().zip(b).enumerate() { |
| 144 | checked += 1; |
| 145 | if ra.len() != rb.len() { |
| 146 | bad.push(format!( |
| 147 | "comb hole z{z} tile {tile:?} polygon {i}: {} rings vs {}", |
| 148 | ra.len(), |
| 149 | rb.len() |
| 150 | )); |
| 151 | continue; |
| 152 | } |
| 153 | let net = |rings: &Vec<Vec<SigPt>>| -> f64 { |
| 154 | rings.iter().map(|r| signed_area(r)).sum() |
| 155 | }; |
| 156 | let (na, nb) = (net(ra), net(rb)); |
| 157 | if (na - nb).abs() > SLOP * (1.0 + nb.abs()) { |
| 158 | bad.push(format!( |
| 159 | "comb hole z{z} tile {tile:?} polygon {i}: net area {na} vs {nb}" |
| 160 | )); |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | for case in 0..120 { |
| 167 | // A big wobbly exterior with two wobbly holes inside it, at a zoom deep |
| 168 | // enough that the descent runs several levels. |
| 169 | let ext = wobbly_ring(8.0, 8.0, 5.0, 40, &mut next); |
| 170 | let holes: Vec<Vec<Pt>> = (0..2) |
| 171 | .map(|k| { |
| 172 | let (ox, oy) = (6.0 + 4.0 * k as f64, 6.0 + 3.0 * next()); |
| 173 | wobbly_ring(ox, oy, 1.6, 24, &mut next) |
| 174 | }) |
| 175 | .collect(); |
| 176 | let mut rings: Vec<&[Pt]> = vec![&ext]; |
| 177 | rings.extend(holes.iter().map(|h| h.as_slice())); |
| 178 | let g = polygon(&rings); |
| 179 | |
| 180 | let mine: std::collections::HashMap<_, _> = descend(&g, 5).into_iter().collect(); |
| 181 | for (tile, expect) in direct(&g, 5) { |
| 182 | let Some(got) = mine.get(&tile) else { |
| 183 | bad.push(format!("case {case} tile {tile:?}: the descent lost the tile")); |
| 184 | continue; |
| 185 | }; |
| 186 | let (Geometry::Polygons(a), Geometry::Polygons(b)) = (got, &expect) else { |
| 187 | continue; |
| 188 | }; |
| 189 | for (i, (ra, rb)) in a.iter().zip(b).enumerate() { |
| 190 | checked += 1; |
| 191 | if ra.len() != rb.len() { |
| 192 | bad.push(format!( |
| 193 | "case {case} tile {tile:?} polygon {i}: {} rings vs {}", |
| 194 | ra.len(), |
| 195 | rb.len() |
| 196 | )); |
| 197 | continue; |
| 198 | } |
| 199 | let net = |rings: &Vec<Vec<SigPt>>| -> f64 { |
| 200 | rings.iter().map(|r| signed_area(r)).sum() |
| 201 | }; |
| 202 | let (na, nb) = (net(ra), net(rb)); |
| 203 | if (na - nb).abs() > SLOP * (1.0 + nb.abs()) { |
| 204 | bad.push(format!( |
| 205 | "case {case} tile {tile:?} polygon {i}: net area {na} vs {nb}" |
| 206 | )); |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | assert!(checked > 0, "the fixture produced no polygons to check"); |
| 212 | assert!(bad.is_empty(), "{} of {checked}:\n{}", bad.len(), bad[..bad.len().min(8)].join("\n")); |
| 213 | } |
| 214 | |
| 215 | /// **The composition property, tested directly.** Nothing in [`crate::clip`] asserts |
| 216 | /// `clip(clip(g, A), B) == clip(g, B)` for `B` inside `A`, and the whole descent is |
| 217 | /// that identity applied `z - level` times. This searches for a counterexample over |
| 218 | /// random rings, random holes and random nested rect pairs. |
| 219 | /// |
| 220 | /// Ring COUNT and NET signed area, because those are what a failure costs: a lost |
| 221 | /// ring is a lost hole, and a hole that vanishes renders as a lake filled in solid. |
| 222 | #[test] |
| 223 | fn clipping_twice_is_clipping_once_for_a_nested_rect() { |
| 224 | let mut seed = 0x1234_5678_9ABC_DEF1u64; |
| 225 | let mut next = move || { |
| 226 | seed ^= seed << 13; |
| 227 | seed ^= seed >> 7; |
| 228 | seed ^= seed << 17; |
| 229 | (seed >> 11) as f64 / (1u64 << 53) as f64 |
| 230 | }; |
| 231 | |
| 232 | let mut bad: Vec<String> = Vec::new(); |
| 233 | let mut checked = 0usize; |
| 234 | for case in 0..4000 { |
| 235 | // A wobbly exterior, and half the time a wobbly hole inside it. Wobble is |
| 236 | // wide enough that the rings are genuinely concave, which is the only case |
| 237 | // composition is in doubt for. |
| 238 | let ext = wobbly_ring(4.0, 4.0, 3.0, 6 + (next() * 24.0) as usize, &mut next); |
| 239 | let mut rings: Vec<Vec<Pt>> = vec![ext]; |
| 240 | if next() < 0.5 { |
| 241 | rings.push(wobbly_ring( |
| 242 | 3.5 + next(), |
| 243 | 3.5 + next(), |
| 244 | 0.6 + next(), |
| 245 | 6 + (next() * 18.0) as usize, |
| 246 | &mut next, |
| 247 | )); |
| 248 | } |
| 249 | let refs: Vec<&[Pt]> = rings.iter().map(|r| r.as_slice()).collect(); |
| 250 | let g = polygon(&refs); |
| 251 | |
| 252 | // Outer rect A, and inner rect B strictly inside it -- the relationship a |
| 253 | // parent cell and a descendant cell always have. |
| 254 | let (ax0, ay0) = (next() * 3.0, next() * 3.0); |
| 255 | let (aw, ah) = (1.0 + next() * 6.0, 1.0 + next() * 6.0); |
| 256 | let a = Rect { |
| 257 | min_x: w(ax0), |
| 258 | min_y: w(ay0), |
| 259 | max_x: w(ax0 + aw), |
| 260 | max_y: w(ay0 + ah), |
| 261 | }; |
| 262 | let (bx0, by0) = (ax0 + next() * aw * 0.5, ay0 + next() * ah * 0.5); |
| 263 | let b = Rect { |
| 264 | min_x: w(bx0), |
| 265 | min_y: w(by0), |
| 266 | max_x: w(bx0 + next() * (ax0 + aw - bx0)), |
| 267 | max_y: w(by0 + next() * (ay0 + ah - by0)), |
| 268 | }; |
| 269 | |
| 270 | let once = clip_geometry(&g, &b); |
| 271 | let twice = clip_geometry(&clip_geometry(&g, &a), &b); |
| 272 | checked += 1; |
| 273 | |
| 274 | let (Geometry::Polygons(p1), Geometry::Polygons(p2)) = (&once, &twice) else { |
| 275 | continue; |
| 276 | }; |
| 277 | if p1.len() != p2.len() { |
| 278 | bad.push(format!("case {case}: {} polygons once vs {} twice", p1.len(), p2.len())); |
| 279 | continue; |
| 280 | } |
| 281 | for (i, (r1, r2)) in p1.iter().zip(p2).enumerate() { |
| 282 | if r1.len() != r2.len() { |
| 283 | bad.push(format!( |
| 284 | "case {case} polygon {i}: {} rings once vs {} twice (A {a:?} B {b:?})", |
| 285 | r1.len(), |
| 286 | r2.len() |
| 287 | )); |
| 288 | continue; |
| 289 | } |
| 290 | let net = |rings: &Vec<Vec<SigPt>>| -> f64 { |
| 291 | rings.iter().map(|r| signed_area(r)).sum() |
| 292 | }; |
| 293 | let (n1, n2) = (net(r1), net(r2)); |
| 294 | if (n1 - n2).abs() > SLOP * (1.0 + n1.abs()) { |
| 295 | bad.push(format!( |
| 296 | "case {case} polygon {i}: net area {n1} once vs {n2} twice" |
| 297 | )); |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | assert!(checked > 0); |
| 302 | assert!( |
| 303 | bad.is_empty(), |
| 304 | "{} of {checked} nested clips disagree:\n{}", |
| 305 | bad.len(), |
| 306 | bad[..bad.len().min(6)].join("\n") |
| 307 | ); |
| 308 | } |
| 309 | |
| 310 | /// **Byte-identity is genuinely gone.** Recorded as a test so nobody later reads |
| 311 | /// the shape test above as a byte guarantee and builds on it. |
| 312 | /// |
| 313 | /// Three differences, in descending order of how many tiles they touch, none of |
| 314 | /// them a shape: |
| 315 | /// |
| 316 | /// 1. **A ring's starting vertex.** The largest share by far. Sutherland-Hodgman |
| 317 | /// keeps its input's rotation and the descent's input is its parent's answer. |
| 318 | /// 2. **Fewer collinear spurs.** A concave ring's zero-area run along a clip |
| 319 | /// boundary comes out shorter when the clip happens in stages, so the descent |
| 320 | /// emits fewer vertices than a direct clip, never more. |
| 321 | /// 3. **Last-bit drift on a line crossing.** Liang-Barsky interpolates both |
| 322 | /// coordinates, so a crossing computed off an already-interpolated vertex can |
| 323 | /// land an ULP away -- 1e-12 world units against a quantisation grid of 1. |
| 324 | /// |
| 325 | /// What is NOT in that list is the thing the plan expected to dominate: surviving |
| 326 | /// vertices on internal cell boundaries. [`the_descent_invents_no_vertices`] is |
| 327 | /// where that is measured, and it is why there is no collinear-reduction pass. |
| 328 | #[test] |
| 329 | fn the_descent_is_not_byte_identical_and_this_is_where_that_is_written_down() { |
| 330 | let (mut differing, mut total) = (0usize, 0usize); |
| 331 | for (_, g, z) in corpus() { |
| 332 | let d = compare(&g, z); |
| 333 | differing += d.rotated; |
| 334 | total += d.tiles; |
| 335 | } |
| 336 | assert!( |
| 337 | differing > 0, |
| 338 | "if no tile's bytes differed, byte-identity is back and this test is a lie" |
| 339 | ); |
| 340 | assert!(differing < total, "some tiles must still match exactly"); |
| 341 | } |
| 342 | |
| 343 | /// A feature small enough for one tile must not recurse at all |
| 344 | /// the leaf, and the leaf clip is the only clip. This is the overwhelmingly common |
| 345 | /// case -- a building, a shop, a street -- and it has to stay exactly as cheap as |
| 346 | /// it was. |
| 347 | #[test] |
| 348 | fn a_feature_inside_one_tile_is_clipped_once() { |
| 349 | let g = polygon(&[&square(0.2, 0.8)]); |
| 350 | let mut clips = 0usize; |
| 351 | let mut tiles = Vec::new(); |
| 352 | subdivide(&g, 6, EXTENT, BUFFER, &mut |tx, ty, _| { |
| 353 | clips += 1; |
| 354 | tiles.push((tx, ty)); |
| 355 | }); |
| 356 | assert_eq!(tiles, vec![(0, 0)]); |
| 357 | assert_eq!(clips, 1); |
| 358 | } |
| 359 | |
| 360 | /// The start cell is chosen from the PADDED range, so a feature that only reaches |
| 361 | /// into a neighbour's buffer still descends towards that neighbour. Picking the |
| 362 | /// cell from the unpadded box would leave a seam at the join. |
| 363 | #[test] |
| 364 | fn a_feature_reaching_only_into_a_neighbours_buffer_still_lands_there() { |
| 365 | // Two units inside tile 1's western edge, well within the 5-unit buffer. |
| 366 | let x = w(1.0) + 2.0; |
| 367 | let g = line(&[(x, w(1.2)), (x, w(1.8))]); |
| 368 | let mut tiles: Vec<(u64, u64)> = Vec::new(); |
| 369 | subdivide(&g, 4, EXTENT, BUFFER, &mut |tx, ty, _| tiles.push((tx, ty))); |
| 370 | tiles.sort_unstable(); |
| 371 | assert_eq!(tiles, vec![(0, 1), (1, 1)], "tile 0's buffer holds it too"); |
| 372 | } |
| 373 | |
| 374 | /// A leaf's cell rect must be the tile rect the old loop clipped against, to the |
| 375 | /// bit -- not merely close to it. A single unit of drift would move every |
| 376 | /// crossing on every tile boundary in the archive. |
| 377 | #[test] |
| 378 | fn a_leaf_cell_is_exactly_the_tile_rect() { |
| 379 | for (tx, ty, z) in [(0u64, 0u64, 0u8), (1, 1, 4), (13, 6, 4), (827, 1391, 14)] { |
| 380 | assert_eq!( |
| 381 | cell_rect(z, tx, ty, z, EXTENT, BUFFER), |
| 382 | geom::tile_rect(tx, ty, EXTENT, BUFFER), |
| 383 | "leaf ({tx},{ty}) at z{z}" |
| 384 | ); |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | /// A cell contains its four children, buffer and all. This is the monotonicity the |
| 389 | /// whole descent rests on: if it failed, an ancestor clip could remove geometry a |
| 390 | /// leaf clip would have kept, and features would vanish from tiles. |
| 391 | #[test] |
| 392 | fn a_cells_buffered_rect_contains_its_childrens() { |
| 393 | let z = 5u8; |
| 394 | for level in 0..z { |
| 395 | for (cx, cy) in [(0u64, 0u64), (1, 0), (1, 2)] { |
| 396 | let parent = cell_rect(level, cx, cy, z, EXTENT, BUFFER); |
| 397 | for (dx, dy) in [(0u64, 0u64), (1, 0), (0, 1), (1, 1)] { |
| 398 | let child = cell_rect(level + 1, cx * 2 + dx, cy * 2 + dy, z, EXTENT, BUFFER); |
| 399 | assert!( |
| 400 | parent.min_x <= child.min_x |
| 401 | && parent.min_y <= child.min_y |
| 402 | && child.max_x <= parent.max_x |
| 403 | && child.max_y <= parent.max_y, |
| 404 | "level {level} cell ({cx},{cy}) does not contain child (+{dx},+{dy}): \ |
| 405 | {parent:?} vs {child:?}" |
| 406 | ); |
| 407 | } |
| 408 | } |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | /// Emptiness prunes, so a feature must not be handed tiles it does not reach. |
| 413 | #[test] |
| 414 | fn tiles_a_feature_does_not_reach_are_not_visited() { |
| 415 | // A diagonal across a 8x8 tile block: the far corners are empty. |
| 416 | let g = line(&[(w(0.5), w(0.5)), (w(7.5), w(7.5))]); |
| 417 | let mut tiles: Vec<(u64, u64)> = Vec::new(); |
| 418 | subdivide(&g, 4, EXTENT, BUFFER, &mut |tx, ty, _| tiles.push((tx, ty))); |
| 419 | assert!(tiles.contains(&(0, 0)) && tiles.contains(&(7, 7))); |
| 420 | assert!(!tiles.contains(&(0, 7)), "the line never goes there"); |
| 421 | assert!(!tiles.contains(&(7, 0)), "nor there"); |
| 422 | assert!(tiles.len() < 24, "walked {} tiles of the 64-tile box", tiles.len()); |
| 423 | } |