Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / rings.rs
rings.rs452 lines · 19.0 KiBRaw
| 1 | //! Stage C: normalise ring winding and hole containment, once, at build time. |
| 2 | //! |
| 3 | //! # Why this is worth a module |
| 4 | //! |
| 5 | //! The published z0 ocean tile is one polygon with **105 holes**, of which 40 overlap each other, 6 |
| 6 | //! straddle the exterior, 4 are entirely outside it and 13 are lakes nested inside other holes. |
| 7 | //! `tess::fill` on device repairs all of that every time the tile is tessellated, under a frame |
| 8 | //! budget, in `i32`. Doing it here instead costs nothing anyone waits for, runs in `f64`, and turns |
| 9 | //! a per-frame repair into a one-time fact — which is what |
| 10 | //! [`FLAG_RINGS_VALIDATED`](tilecodec::mamaps::header::FLAG_RINGS_VALIDATED) tells the renderer. |
| 11 | //! |
| 12 | //! # What "valid" means here |
| 13 | //! |
| 14 | //! Per part group, after this runs: |
| 15 | //! |
| 16 | //! 1. exactly one exterior, wound counter-clockwise; |
| 17 | //! 2. every hole wound clockwise; |
| 18 | //! 3. every hole strictly inside its exterior; |
| 19 | //! 4. no two holes overlapping; |
| 20 | //! 5. no zero-area ring. |
| 21 | //! |
| 22 | //! Those five are what `tess::fill` assumes and what the batch check in this module's tests asserts |
| 23 | //! over every tile of a real build. |
| 24 | //! |
| 25 | //! # What it does not do |
| 26 | //! |
| 27 | //! It does not clip a straddling hole to its exterior or subtract one overlapping hole from another. |
| 28 | //! Both need a real boolean operation, and getting one subtly wrong is worse than dropping the hole: |
| 29 | //! a dropped hole paints a lake as land, which is visible and wrong; a botched intersection paints a |
| 30 | //! wedge across a continent, which is visible and inexplicable. So a hole that cannot be placed |
| 31 | //! cleanly is **dropped and counted**, and the count is in the build report. |
| 32 | |
| 33 | use tilecodec::mamaps::body::{BuildingAttrs, LaneTurns, Layer, Part, WINDING_HOLE, WINDING_OUTER}; |
| 34 | |
| 35 | /// What normalising a build cost, for the report. |
| 36 | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] |
| 37 | pub struct Stats { |
| 38 | /// Rings whose winding disagreed with their stated role and was corrected. |
| 39 | pub rewound: u64, |
| 40 | /// Rings that enclosed no area at all. |
| 41 | pub zero_area: u64, |
| 42 | /// Holes dropped for being outside their exterior, straddling it, or overlapping another hole. |
| 43 | pub holes_dropped: u64, |
| 44 | pub groups: u64, |
| 45 | } |
| 46 | |
| 47 | impl Stats { |
| 48 | pub fn add(&mut self, other: Stats) { |
| 49 | self.rewound += other.rewound; |
| 50 | self.zero_area += other.zero_area; |
| 51 | self.holes_dropped += other.holes_dropped; |
| 52 | self.groups += other.groups; |
| 53 | } |
| 54 | |
| 55 | /// Did anything have to be corrected? |
| 56 | #[cfg_attr(not(test), allow(dead_code))] |
| 57 | pub fn clean(&self) -> bool { |
| 58 | self.rewound == 0 && self.zero_area == 0 && self.holes_dropped == 0 |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | /// Normalise every polygon feature of a layer in place. |
| 63 | /// |
| 64 | /// Rebuilds the parts table and the coordinate arena, because dropping a ring changes both and the |
| 65 | /// encoder requires the parts to tile the arena exactly. |
| 66 | pub fn normalise(layer: &mut Layer) -> Stats { |
| 67 | normalise_with_ids(layer, None, None, None) |
| 68 | } |
| 69 | |
| 70 | /// As [`normalise`], but also drops the id and turn-lane records of any feature it drops. |
| 71 | /// |
| 72 | /// The side tables are indexed by feature position, so the retain at the end has to happen to all |
| 73 | /// of them or every entry after the first casualty describes the wrong feature. This only started |
| 74 | /// mattering when `boundaries` gained a table: `places` and `poi` are points, and a point never |
| 75 | /// loses its single part, so the retain was a no-op for every layer that carried ids. A road's |
| 76 | /// turn table rides along for the same discipline, though a road is a line and a line is never |
| 77 | /// dropped here. |
| 78 | pub fn normalise_with_ids( |
| 79 | layer: &mut Layer, |
| 80 | ids: Option<&mut Vec<u64>>, |
| 81 | turns: Option<&mut Vec<LaneTurns>>, |
| 82 | buildings: Option<&mut Vec<BuildingAttrs>>, |
| 83 | ) -> Stats { |
| 84 | let mut stats = Stats::default(); |
| 85 | let mut parts: Vec<Part> = Vec::with_capacity(layer.parts.len()); |
| 86 | let mut coords: Vec<(i16, i16)> = Vec::with_capacity(layer.coords.len()); |
| 87 | |
| 88 | for feature in &mut layer.features { |
| 89 | if feature.geom_type != tilecodec::mamaps::body::GEOM_POLYGON { |
| 90 | // A line's parts pass through untouched: winding means nothing on an open path. |
| 91 | let start = parts.len() as u32; |
| 92 | for part in layer.parts[feature.parts_offset as usize..] |
| 93 | .iter() |
| 94 | .take(feature.part_count as usize) |
| 95 | { |
| 96 | let points = ring_points(&layer.coords, part); |
| 97 | parts.push(Part { |
| 98 | coord_start: coords.len() as u32, |
| 99 | point_count: points.len() as u32, |
| 100 | winding: part.winding, |
| 101 | }); |
| 102 | coords.extend_from_slice(points); |
| 103 | } |
| 104 | feature.parts_offset = start; |
| 105 | continue; |
| 106 | } |
| 107 | stats.groups += 1; |
| 108 | let group: Vec<(&Part, &[(i16, i16)])> = layer.parts |
| 109 | [feature.parts_offset as usize..] |
| 110 | .iter() |
| 111 | .take(feature.part_count as usize) |
| 112 | .map(|part| (part, ring_points(&layer.coords, part))) |
| 113 | .collect(); |
| 114 | |
| 115 | // The exterior is the first part, by the format's own convention. |
| 116 | let Some((_, exterior)) = group.first().copied() else { |
| 117 | feature.part_count = 0; |
| 118 | continue; |
| 119 | }; |
| 120 | let exterior_area = signed_area(exterior); |
| 121 | if exterior_area == 0.0 { |
| 122 | // A zero-area exterior takes its holes with it: there is nothing for them to be in. |
| 123 | stats.zero_area += 1; |
| 124 | feature.part_count = 0; |
| 125 | continue; |
| 126 | } |
| 127 | |
| 128 | let start = parts.len() as u32; |
| 129 | let mut count = 0u32; |
| 130 | // An exterior is counter-clockwise. Reversed rather than re-labelled, because the winding |
| 131 | // field states a fact about the coordinates and the two must agree. |
| 132 | // `(ring, box)`, because every containment test below needs the box and computing it per |
| 133 | // comparison would put back the quadratic cost the boxes exist to remove. |
| 134 | let mut kept: Vec<(Vec<(i16, i16)>, (i16, i16, i16, i16))> = |
| 135 | Vec::with_capacity(group.len()); |
| 136 | let mut exterior_ring = exterior.to_vec(); |
| 137 | if exterior_area < 0.0 { |
| 138 | exterior_ring.reverse(); |
| 139 | stats.rewound += 1; |
| 140 | } |
| 141 | push_ring(&mut parts, &mut coords, &exterior_ring, WINDING_OUTER); |
| 142 | count += 1; |
| 143 | let exterior_box = bounds(&exterior_ring); |
| 144 | kept.push((exterior_ring, exterior_box)); |
| 145 | |
| 146 | for (_, hole) in group.iter().skip(1) { |
| 147 | let area = signed_area(hole); |
| 148 | if area == 0.0 { |
| 149 | stats.zero_area += 1; |
| 150 | continue; |
| 151 | } |
| 152 | let hole_box = bounds(hole); |
| 153 | // Strictly inside its exterior. A straddling or outside hole is dropped rather than |
| 154 | // clipped: a dropped hole paints a lake as land, which is visible and explicable, and a |
| 155 | // botched clip paints a wedge across a continent, which is neither. |
| 156 | if !strictly_inside(hole, hole_box, &kept[0].0, exterior_box) { |
| 157 | stats.holes_dropped += 1; |
| 158 | continue; |
| 159 | } |
| 160 | // And not overlapping a hole already kept. Same reasoning: no boolean operations. |
| 161 | if kept |
| 162 | .iter() |
| 163 | .skip(1) |
| 164 | .any(|(other, other_box)| rings_overlap(hole, hole_box, other, *other_box)) |
| 165 | { |
| 166 | stats.holes_dropped += 1; |
| 167 | continue; |
| 168 | } |
| 169 | let mut ring = hole.to_vec(); |
| 170 | // A hole is clockwise, which is the opposite sign to its exterior. |
| 171 | if area > 0.0 { |
| 172 | ring.reverse(); |
| 173 | stats.rewound += 1; |
| 174 | } |
| 175 | push_ring(&mut parts, &mut coords, &ring, WINDING_HOLE); |
| 176 | count += 1; |
| 177 | // Reversing a ring does not move it, so the box is still the one just computed. |
| 178 | kept.push((ring, hole_box)); |
| 179 | } |
| 180 | feature.parts_offset = start; |
| 181 | feature.part_count = count; |
| 182 | } |
| 183 | |
| 184 | // A feature whose exterior went takes no parts, so it draws nothing. Removed outright rather |
| 185 | // than left as an empty group, which the encoder refuses. The id table is indexed by feature |
| 186 | // position, so it is filtered by the same predicate, in the same order, first. |
| 187 | if let Some(ids) = ids { |
| 188 | if ids.len() == layer.features.len() { |
| 189 | let mut at = 0; |
| 190 | ids.retain(|_| { |
| 191 | let keep = layer.features[at].part_count > 0; |
| 192 | at += 1; |
| 193 | keep |
| 194 | }); |
| 195 | } |
| 196 | } |
| 197 | if let Some(turns) = turns { |
| 198 | if turns.len() == layer.features.len() { |
| 199 | let mut at = 0; |
| 200 | turns.retain(|_| { |
| 201 | let keep = layer.features[at].part_count > 0; |
| 202 | at += 1; |
| 203 | keep |
| 204 | }); |
| 205 | } |
| 206 | } |
| 207 | // The building side table is indexed by feature position too, so a dropped degenerate building |
| 208 | // must drop its attrs with it, in the same order and by the same predicate. |
| 209 | if let Some(buildings) = buildings { |
| 210 | if buildings.len() == layer.features.len() { |
| 211 | let mut at = 0; |
| 212 | buildings.retain(|_| { |
| 213 | let keep = layer.features[at].part_count > 0; |
| 214 | at += 1; |
| 215 | keep |
| 216 | }); |
| 217 | } |
| 218 | } |
| 219 | layer.features.retain(|feature| feature.part_count > 0); |
| 220 | layer.parts = parts; |
| 221 | layer.coords = coords; |
| 222 | stats |
| 223 | } |
| 224 | |
| 225 | fn ring_points<'a>(coords: &'a [(i16, i16)], part: &Part) -> &'a [(i16, i16)] { |
| 226 | let start = part.coord_start as usize; |
| 227 | &coords[start..start + part.point_count as usize] |
| 228 | } |
| 229 | |
| 230 | fn push_ring( |
| 231 | parts: &mut Vec<Part>, |
| 232 | coords: &mut Vec<(i16, i16)>, |
| 233 | ring: &[(i16, i16)], |
| 234 | winding: u16, |
| 235 | ) { |
| 236 | parts.push(Part { |
| 237 | coord_start: coords.len() as u32, |
| 238 | point_count: ring.len() as u32, |
| 239 | winding, |
| 240 | }); |
| 241 | coords.extend_from_slice(ring); |
| 242 | } |
| 243 | |
| 244 | /// A ring's signed area by the shoelace formula: positive counter-clockwise. |
| 245 | /// |
| 246 | /// `f64` from `i64` terms. This is the whole reason the work belongs at build time: on device the |
| 247 | /// same computation is done in `i32` under a frame budget, where a long ring's cross products |
| 248 | /// overflow and a near-degenerate one rounds to the wrong sign. |
| 249 | pub fn signed_area(ring: &[(i16, i16)]) -> f64 { |
| 250 | let mut twice = 0i64; |
| 251 | for pair in ring.windows(2) { |
| 252 | let ((x0, y0), (x1, y1)) = (pair[0], pair[1]); |
| 253 | twice += x0 as i64 * y1 as i64 - x1 as i64 * y0 as i64; |
| 254 | } |
| 255 | // An unclosed ring: close it implicitly rather than reporting a wrong area. |
| 256 | if let (Some(first), Some(last)) = (ring.first(), ring.last()) { |
| 257 | if first != last { |
| 258 | twice += last.0 as i64 * first.1 as i64 - first.0 as i64 * last.1 as i64; |
| 259 | } |
| 260 | } |
| 261 | twice as f64 / 2.0 |
| 262 | } |
| 263 | |
| 264 | /// Is every vertex of `inner` inside `outer`? |
| 265 | /// |
| 266 | /// Vertex containment rather than a full geometric test. It is what distinguishes the three cases |
| 267 | /// that matter — wholly inside, wholly outside, straddling — and it cannot be fooled by anything a |
| 268 | /// clipped tile actually contains, because a hole that crosses its exterior has vertices on both |
| 269 | /// sides by construction. |
| 270 | /// A ring's bounding box as `(min_x, min_y, max_x, max_y)`. |
| 271 | /// |
| 272 | /// Computed once per ring and threaded into the containment tests, because those are the whole cost |
| 273 | /// of stage C. Measured on a California build with a coastline, `encode` — which is stage C plus |
| 274 | /// serialise plus DEFLATE — was 432.7 s against 94.7 s without one. `earth` lands in ~529 k |
| 275 | /// tile-layers and its polygons carry many holes, and both tests below are quadratic without a cheap |
| 276 | /// way to say "these two are nowhere near each other". |
| 277 | /// |
| 278 | /// Every use is **conservative**: a box test only ever rejects a case the exact test would also have |
| 279 | /// rejected, so the answers are unchanged and the archive stays byte-identical. |
| 280 | fn bounds(ring: &[(i16, i16)]) -> (i16, i16, i16, i16) { |
| 281 | let mut b = (i16::MAX, i16::MAX, i16::MIN, i16::MIN); |
| 282 | for &(x, y) in ring { |
| 283 | b.0 = b.0.min(x); |
| 284 | b.1 = b.1.min(y); |
| 285 | b.2 = b.2.max(x); |
| 286 | b.3 = b.3.max(y); |
| 287 | } |
| 288 | b |
| 289 | } |
| 290 | |
| 291 | /// Is `inner`'s box entirely within `outer`'s? |
| 292 | fn box_within(inner: (i16, i16, i16, i16), outer: (i16, i16, i16, i16)) -> bool { |
| 293 | inner.0 >= outer.0 && inner.1 >= outer.1 && inner.2 <= outer.2 && inner.3 <= outer.3 |
| 294 | } |
| 295 | |
| 296 | /// Do two boxes share any area? |
| 297 | fn boxes_meet(a: (i16, i16, i16, i16), b: (i16, i16, i16, i16)) -> bool { |
| 298 | !(a.2 < b.0 || a.0 > b.2 || a.3 < b.1 || a.1 > b.3) |
| 299 | } |
| 300 | |
| 301 | /// Is every vertex of `inner` inside `outer`? |
| 302 | /// |
| 303 | /// Vertex containment rather than a full geometric test. It is what distinguishes the three cases |
| 304 | /// that matter — wholly inside, wholly outside, straddling — and it cannot be fooled by anything a |
| 305 | /// clipped tile actually contains, because a hole that crosses its exterior has vertices on both |
| 306 | /// sides by construction. |
| 307 | fn strictly_inside( |
| 308 | inner: &[(i16, i16)], |
| 309 | inner_box: (i16, i16, i16, i16), |
| 310 | outer: &[(i16, i16)], |
| 311 | outer_box: (i16, i16, i16, i16), |
| 312 | ) -> bool { |
| 313 | // If any of `inner` lies outside `outer`'s box then that vertex is outside `outer` itself, so the |
| 314 | // exact test would say no too. This is what makes a hole belonging to a different part of the |
| 315 | // world cost four comparisons instead of a scan of the exterior. |
| 316 | if !box_within(inner_box, outer_box) { |
| 317 | return false; |
| 318 | } |
| 319 | inner.iter().all(|&point| point_in_ring(point, outer, outer_box)) |
| 320 | } |
| 321 | |
| 322 | /// Do two rings overlap? Approximated by mutual vertex containment. |
| 323 | /// |
| 324 | /// One ring having a vertex inside the other is the signature of every overlap a clipped tile |
| 325 | /// produces. Two rings that merely touch at a vertex are not overlapping, and are left alone — |
| 326 | /// `tess::fill` already handles a hole that touches its exterior. |
| 327 | fn rings_overlap( |
| 328 | a: &[(i16, i16)], |
| 329 | a_box: (i16, i16, i16, i16), |
| 330 | b: &[(i16, i16)], |
| 331 | b_box: (i16, i16, i16, i16), |
| 332 | ) -> bool { |
| 333 | // Disjoint boxes cannot overlap, and most pairs of holes in a real polygon are disjoint. This is |
| 334 | // the test that takes the pairwise scan from quadratic-in-vertices to quadratic-in-holes. |
| 335 | if !boxes_meet(a_box, b_box) { |
| 336 | return false; |
| 337 | } |
| 338 | a.iter().filter(|&&p| point_in_ring(p, b, b_box)).count() > 1 |
| 339 | || b.iter().filter(|&&p| point_in_ring(p, a, a_box)).count() > 1 |
| 340 | } |
| 341 | |
| 342 | /// Even-odd ray cast, with the boundary counting as inside. |
| 343 | /// |
| 344 | /// That last clause is what keeps clipped islands: the tile clipper emits exterior and hole |
| 345 | /// vertices onto the same tile-edge lines, so a hole clipped onto the tile edge touches its |
| 346 | /// exterior there. Reading those vertices as outside dropped the hole — an island filled in |
| 347 | /// solid on the fine tile while the coarse tile (hole fully inside) stayed pixel-perfect. |
| 348 | /// The renderer's `tess::fill::geom::point_within_ring` already counts the boundary as inside |
| 349 | /// for exactly this reason; stage C runs first and bakes its drops into the archive, so it |
| 350 | /// has to agree with it — a stricter rule here deletes islands the renderer would otherwise |
| 351 | /// have kept. |
| 352 | /// |
| 353 | /// The leniency admits exactly coincident edges — a vertex ON the exterior — never a vertex |
| 354 | /// genuinely outside it: those still fail every edge test and the hole still goes. And it is |
| 355 | /// safe in this direction only: a hole the tiler keeps but the renderer drops costs one |
| 356 | /// island, while a hole the tiler drops is gone for every reader. |
| 357 | fn point_in_ring((x, y): (i16, i16), ring: &[(i16, i16)], ring_box: (i16, i16, i16, i16)) -> bool { |
| 358 | // A point outside the box is outside the ring, for the cost of four comparisons rather than a |
| 359 | // walk of every edge. |
| 360 | if x < ring_box.0 || x > ring_box.2 || y < ring_box.1 || y > ring_box.3 { |
| 361 | return false; |
| 362 | } |
| 363 | let (x, y) = (x as f64, y as f64); |
| 364 | let mut inside = false; |
| 365 | for pair in ring.windows(2) { |
| 366 | let ((x0, y0), (x1, y1)) = (pair[0], pair[1]); |
| 367 | let (x0, y0, x1, y1) = (x0 as f64, y0 as f64, x1 as f64, y1 as f64); |
| 368 | if (y0 > y) != (y1 > y) { |
| 369 | let t = (y - y0) / (y1 - y0); |
| 370 | if x < x0 + t * (x1 - x0) { |
| 371 | inside = !inside; |
| 372 | } |
| 373 | } |
| 374 | } |
| 375 | inside || on_boundary((x, y), ring) |
| 376 | } |
| 377 | |
| 378 | /// Is the point exactly on one of the ring's edges? |
| 379 | /// |
| 380 | /// The tile clipper emits exterior and hole vertices onto the same tile-edge lines, quantised |
| 381 | /// to the same `i16` grid — a hole clipped onto the tile edge shares exact coordinates with |
| 382 | /// the exterior's clipped edge there. An exact integer cross product (no division, so no |
| 383 | /// truncation putting the two sides of one edge in disagreement), mirroring the renderer's |
| 384 | /// `tess::fill::geom::on_boundary`. |
| 385 | fn on_boundary((x, y): (f64, f64), ring: &[(i16, i16)]) -> bool { |
| 386 | for pair in ring.windows(2) { |
| 387 | let ((x0, y0), (x1, y1)) = (pair[0], pair[1]); |
| 388 | let (x0, y0, x1, y1) = (x0 as f64, y0 as f64, x1 as f64, y1 as f64); |
| 389 | let cross = (x - x0) * (y1 - y0) - (y - y0) * (x1 - x0); |
| 390 | if cross == 0.0 |
| 391 | && x >= x0.min(x1) |
| 392 | && x <= x0.max(x1) |
| 393 | && y >= y0.min(y1) |
| 394 | && y <= y0.max(y1) |
| 395 | { |
| 396 | return true; |
| 397 | } |
| 398 | } |
| 399 | false |
| 400 | } |
| 401 | |
| 402 | /// **Verification item 6 of the plan's list.** Every ring of a layer must satisfy all five |
| 403 | /// invariants. |
| 404 | /// |
| 405 | /// Returned as a list of complaints rather than a bool, so a failing build says which polygon and |
| 406 | /// why. Used by the generator's own tests over every tile of a real build. |
| 407 | #[cfg_attr(not(test), allow(dead_code))] |
| 408 | pub fn check(layer: &Layer) -> Vec<String> { |
| 409 | let mut problems = Vec::new(); |
| 410 | for (index, feature) in layer.features.iter().enumerate() { |
| 411 | if feature.geom_type != tilecodec::mamaps::body::GEOM_POLYGON { |
| 412 | continue; |
| 413 | } |
| 414 | let parts = layer.parts_of(feature); |
| 415 | let Some(exterior) = parts.first() else { |
| 416 | problems.push(format!("feature {index} has no parts")); |
| 417 | continue; |
| 418 | }; |
| 419 | if exterior.winding != WINDING_OUTER { |
| 420 | problems.push(format!("feature {index}'s first part is a hole")); |
| 421 | } |
| 422 | let exterior_points = layer.points(exterior); |
| 423 | let area = signed_area(exterior_points); |
| 424 | if area <= 0.0 { |
| 425 | problems.push(format!("feature {index}'s exterior is not counter-clockwise ({area})")); |
| 426 | } |
| 427 | let holes: Vec<&Part> = parts[1..].iter().collect(); |
| 428 | if holes.iter().any(|part| part.winding != WINDING_HOLE) { |
| 429 | problems.push(format!("feature {index} has a second exterior")); |
| 430 | } |
| 431 | for (i, hole) in holes.iter().enumerate() { |
| 432 | let points = layer.points(hole); |
| 433 | let area = signed_area(points); |
| 434 | if area >= 0.0 { |
| 435 | problems.push(format!("feature {index}'s hole {i} is not clockwise ({area})")); |
| 436 | } |
| 437 | if !strictly_inside(points, bounds(points), exterior_points, bounds(exterior_points)) |
| 438 | { |
| 439 | problems.push(format!("feature {index}'s hole {i} is not inside its exterior")); |
| 440 | } |
| 441 | for (j, other) in holes.iter().enumerate().skip(i + 1) { |
| 442 | let other_points = layer.points(other); |
| 443 | if rings_overlap(points, bounds(points), other_points, bounds(other_points)) { |
| 444 | problems.push(format!("feature {index}'s holes {i} and {j} overlap")); |
| 445 | } |
| 446 | } |
| 447 | } |
| 448 | } |
| 449 | problems |
| 450 | } |
| 451 | |
| 452 | include!("rings_part1.rs"); |