Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / scripts / maps / tile_build / src / subdivide_part1.rs

subdivide_part1.rs470 lines · 19.0 KiBRaw
1 use super::*;
2 use crate::geom::{Pt, SigPt};
3 use crate::mvt::DEFAULT_EXTENT;
4
5 const EXTENT: u32 = DEFAULT_EXTENT;
6 const BUFFER: f64 = geom::DEFAULT_BUFFER;
7
8 /// A world coordinate `t` tiles along an axis.
9 fn w(t: f64) -> f64 {
10 t * EXTENT as f64
11 }
12
13 fn sig(pts: &[Pt]) -> Vec<SigPt> {
14 pts.iter().map(|&(x, y)| SigPt::new(x, y)).collect()
15 }
16
17 fn line(pts: &[Pt]) -> Geometry<SigPt> {
18 let mut g = Geometry::Lines(vec![sig(pts)]);
19 crate::simplify::annotate(&mut g);
20 g
21 }
22
23 fn polygon(rings: &[&[Pt]]) -> Geometry<SigPt> {
24 let mut g = Geometry::Polygons(vec![rings.iter().map(|r| sig(r)).collect()]);
25 crate::simplify::annotate(&mut g);
26 g
27 }
28
29 /// A closed axis-aligned ring, in tile units.
30 fn square(min: f64, max: f64) -> Vec<Pt> {
31 vec![
32 (w(min), w(min)),
33 (w(max), w(min)),
34 (w(max), w(max)),
35 (w(min), w(max)),
36 (w(min), w(min)),
37 ]
38 }
39
40 /// A comb: `teeth` prongs pointing east off a spine on the west.
41 ///
42 /// The shape Sutherland-Hodgman is worst at. A clip that cuts the prongs off from
43 /// the spine leaves several disjoint pieces, which S-H returns as ONE
44 /// self-touching ring joined by zero-width slivers along the clip boundary. A
45 /// two-prong U reaches that case once; a comb reaches it many times over, with
46 /// slivers stacked on the same boundary line -- and clipping *that* again is the
47 /// thing the descent does and a single clip never did.
48 fn comb(teeth: usize, min: f64, max: f64) -> Geometry<SigPt> {
49 let span = max - min;
50 let spine = min + span * 0.15;
51 let mut r: Vec<Pt> = vec![(w(min), w(min))];
52 for i in 0..teeth {
53 // Two bands per tooth: out along the top of the tooth, back along the
54 // bottom of the gap above it.
55 let y0 = min + span * (i as f64 * 2.0 + 0.4) / (teeth as f64 * 2.0);
56 let y1 = min + span * (i as f64 * 2.0 + 1.4) / (teeth as f64 * 2.0);
57 r.push((w(spine), w(y0)));
58 r.push((w(max), w(y0)));
59 r.push((w(max), w(y1)));
60 r.push((w(spine), w(y1)));
61 }
62 r.push((w(spine), w(max)));
63 r.push((w(min), w(max)));
64 r.push((w(min), w(min)));
65 let mut g = Geometry::Polygons(vec![vec![sig(&r)]]);
66 crate::simplify::annotate(&mut g);
67 g
68 }
69
70 /// Collect the descent's answer per tile.
71 fn descend(g: &Geometry<SigPt>, z: u8) -> Vec<((u64, u64), Geometry<SigPt>)> {
72 let mut out = Vec::new();
73 subdivide(g, z, EXTENT, BUFFER, &mut |tx, ty, clipped| {
74 out.push(((tx, ty), clipped.clone()))
75 });
76 out
77 }
78
79 /// What the old loop produced: `tiles_touched`, then a clip of the whole
80 /// geometry against each tile, skipping the ones that came back empty.
81 fn direct(g: &Geometry<SigPt>, z: u8) -> Vec<((u64, u64), Geometry<SigPt>)> {
82 let mut touched = Vec::new();
83 geom::tiles_touched(g, z, EXTENT, BUFFER, &mut touched);
84 let mut out = Vec::new();
85 for (tx, ty) in touched {
86 let clipped = clip_geometry(g, &geom::tile_rect(tx, ty, EXTENT, BUFFER));
87 if is_empty(&clipped) {
88 continue;
89 }
90 out.push(((tx, ty), clipped));
91 }
92 out
93 }
94
95 fn vertices(g: &Geometry<SigPt>) -> usize {
96 match g {
97 Geometry::Points(p) => p.len(),
98 Geometry::Lines(l) => l.iter().map(Vec::len).sum(),
99 Geometry::Polygons(p) => p.iter().flatten().map(Vec::len).sum(),
100 }
101 }
102
103 /// How far apart two world coordinates may be and still be the same vertex.
104 ///
105 /// One world unit is 1/4096 of a tile and [`geom::quantize`] rounds to the nearest
106 /// one, so anything below half a unit is invisible in the output. This is seven
107 /// orders of magnitude tighter than that: the drift the descent introduces is
108 /// last-bit drift from interpolating a crossing off an already-interpolated
109 /// vertex, not a shape moving.
110 const SLOP: f64 = 1e-6;
111
112 fn near(a: SigPt, b: SigPt) -> bool {
113 (a.x - b.x).abs() <= SLOP
114 && (a.y - b.y).abs() <= SLOP
115 // Equality first, so two unremovable vertices match: `inf - inf` is `NaN`.
116 && (a.sig == b.sig || (a.sig - b.sig).abs() <= SLOP)
117 }
118
119 /// Whether two rings are the same ring, allowing for a different starting vertex
120 /// and for Sutherland-Hodgman's zero-area bookkeeping.
121 ///
122 /// Two things are forgiven, and both are things the algorithm does to itself:
123 ///
124 /// * **Rotation.** S-H's output order follows its input's, and clipping in stages
125 /// changes the intermediate order -- so the descent's rings start at a different
126 /// vertex. A rotation is the same polygon: same edges, same winding, same area,
127 /// and MVT re-states the start vertex as a `MoveTo` either way.
128 /// * **Collinear spurs.** Clipping a concave ring leaves degenerate runs along the
129 /// clip boundary, and how many vertices a run costs depends on how many passes
130 /// built it. Measured over the corpus, the direct clip carries MORE of them than
131 /// the descent does, so this forgives the descent nothing it needs.
132 ///
133 /// What is not forgiven is a vertex that carries shape. Reducing both rings to
134 /// their corners and then demanding a rotation is what makes that distinction, and
135 /// the signed-area check beside it is the independent witness.
136 fn same_ring(a: &[SigPt], b: &[SigPt]) -> bool {
137 let (a, b) = (corners(a), corners(b));
138 let n = a.len();
139 n == b.len() && (n == 0 || (0..n).any(|k| (0..n).all(|i| near(a[i], b[(i + k) % n]))))
140 }
141
142 /// A ring's corners: opened, and with every vertex that turns no corner removed.
143 ///
144 /// Removing one vertex can leave its neighbours collinear with each other, so this
145 /// runs to a fixed point rather than in one pass.
146 fn corners(ring: &[SigPt]) -> Vec<SigPt> {
147 let closed = ring.len() > 1 && ring.first().map(|v| v.xy()) == ring.last().map(|v| v.xy());
148 let mut out: Vec<SigPt> = ring[..ring.len() - usize::from(closed)].to_vec();
149 loop {
150 let n = out.len();
151 if n < 3 {
152 return out;
153 }
154 let Some(at) = (0..n).find(|&i| straight(out[(i + n - 1) % n], out[i], out[(i + 1) % n]))
155 else {
156 return out;
157 };
158 out.remove(at);
159 }
160 }
161
162 /// Whether `b` sits on the line through `a` and `c`, turning no corner.
163 ///
164 /// The cross product scaled by the two edge lengths, so this is a bound on the
165 /// sine of the turn rather than on an area -- an area threshold would call a long
166 /// gentle bend straight and a short sharp one bent.
167 fn straight(a: SigPt, b: SigPt, c: SigPt) -> bool {
168 let ((ax, ay), (bx, by), (cx, cy)) = (a.xy(), b.xy(), c.xy());
169 let (ux, uy) = (bx - ax, by - ay);
170 let (vx, vy) = (cx - bx, cy - by);
171 let scale = (ux * ux + uy * uy).sqrt() * (vx * vx + vy * vy).sqrt();
172 (ux * vy - uy * vx).abs() <= SLOP * (scale + 1.0)
173 }
174
175 fn signed_area(ring: &[SigPt]) -> f64 {
176 let n = ring.len();
177 let mut a = 0.0;
178 for i in 0..n {
179 let (x1, y1) = ring[i].xy();
180 let (x2, y2) = ring[(i + 1) % n].xy();
181 a += x1 * y2 - x2 * y1;
182 }
183 a / 2.0
184 }
185
186 fn length(line: &[SigPt]) -> f64 {
187 line.windows(2)
188 .map(|w| {
189 let ((x1, y1), (x2, y2)) = (w[0].xy(), w[1].xy());
190 ((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt()
191 })
192 .sum()
193 }
194
195 /// Whether two clips of the same feature into the same tile are the same shape.
196 ///
197 /// `None` when they are; otherwise why not. Rings are compared up to rotation and
198 /// last-bit drift, everything else exactly: part counts, ring counts, vertex
199 /// counts, and -- as an independent witness that a rotation really is a rotation
200 /// -- signed area per ring and total length per line.
201 fn same_shape(a: &Geometry<SigPt>, b: &Geometry<SigPt>) -> Option<String> {
202 match (a, b) {
203 (Geometry::Points(x), Geometry::Points(y)) => (x != y).then(|| "points differ".into()),
204 (Geometry::Lines(x), Geometry::Lines(y)) => {
205 if x.len() != y.len() {
206 return Some(format!("{} line parts vs {}", x.len(), y.len()));
207 }
208 for (i, (p, q)) in x.iter().zip(y).enumerate() {
209 if p.len() != q.len() {
210 return Some(format!("part {i}: {} vertices vs {}", p.len(), q.len()));
211 }
212 if !p.iter().zip(q).all(|(u, v)| near(*u, *v)) {
213 return Some(format!("part {i}: vertices moved"));
214 }
215 let (lp, lq) = (length(p), length(q));
216 if (lp - lq).abs() > SLOP * (1.0 + lq.abs()) {
217 return Some(format!("part {i}: length {lp} vs {lq}"));
218 }
219 }
220 None
221 }
222 (Geometry::Polygons(x), Geometry::Polygons(y)) => {
223 if x.len() != y.len() {
224 return Some(format!("{} polygons vs {}", x.len(), y.len()));
225 }
226 for (i, (rp, rq)) in x.iter().zip(y).enumerate() {
227 if rp.len() != rq.len() {
228 return Some(format!("polygon {i}: {} rings vs {}", rp.len(), rq.len()));
229 }
230 for (j, (p, q)) in rp.iter().zip(rq).enumerate() {
231 if !same_ring(p, q) {
232 return Some(format!(
233 "polygon {i} ring {j}: not a rotation ({} corners vs {})",
234 corners(p).len(),
235 corners(q).len()
236 ));
237 }
238 let (ap, aq) = (signed_area(p), signed_area(q));
239 if (ap - aq).abs() > SLOP * (1.0 + aq.abs()) {
240 return Some(format!("polygon {i} ring {j}: area {ap} vs {aq}"));
241 }
242 }
243 }
244 None
245 }
246 _ => Some("geometry kind changed".into()),
247 }
248 }
249
250 /// What one shape's descent cost against a direct clip, over every tile it
251 /// reaches.
252 struct Divergence {
253 tiles: usize,
254 /// Tiles one produced and the other did not, either way round.
255 missing: Vec<(u64, u64)>,
256 /// Tiles whose shapes are not the same shape, with the reason.
257 wrong: Vec<((u64, u64), String)>,
258 /// Tiles whose bytes differ although the shape does not -- a ring rotation, or
259 /// a crossing that moved by its last bit. Measured, not asserted away.
260 rotated: usize,
261 descent_vertices: usize,
262 direct_vertices: usize,
263 }
264
265 fn compare(g: &Geometry<SigPt>, z: u8) -> Divergence {
266 let mine = descend(g, z);
267 let mut want: std::collections::HashMap<(u64, u64), Geometry<SigPt>> =
268 direct(g, z).into_iter().collect();
269 let mut d = Divergence {
270 tiles: 0,
271 missing: Vec::new(),
272 wrong: Vec::new(),
273 rotated: 0,
274 descent_vertices: 0,
275 direct_vertices: 0,
276 };
277 for (tile, got) in &mine {
278 d.tiles += 1;
279 d.descent_vertices += vertices(got);
280 // A tile the descent claims and the direct clip never reached is
281 // over-inclusion; a tile it lost is a seam. Both are `missing`.
282 let Some(expect) = want.remove(tile) else {
283 d.missing.push(*tile);
284 continue;
285 };
286 d.direct_vertices += vertices(&expect);
287 match same_shape(got, &expect) {
288 Some(why) => d.wrong.push((*tile, why)),
289 None if *got != expect => d.rotated += 1,
290 None => {}
291 }
292 }
293 for (tile, expect) in want {
294 d.tiles += 1;
295 d.direct_vertices += vertices(&expect);
296 d.missing.push(tile);
297 }
298 d.missing.sort_unstable();
299 d
300 }
301
302 /// A deterministic corpus of shapes that cross a tile grid, each with the zoom to
303 /// tile it at. Named so a failure says which shape broke.
304 fn corpus() -> Vec<(&'static str, Geometry<SigPt>, u8)> {
305 let mut out: Vec<(&'static str, Geometry<SigPt>, u8)> = vec![
306 // A comb: many prongs, so one clip leaves Sutherland-Hodgman joining
307 // several disjoint pieces into one self-touching ring. Clipping that
308 // result again is the case a two-prong U does not reach.
309 ("a comb of 9 teeth", comb(9, 0.5, 6.5), 4),
310 ("a comb of 25 teeth", comb(25, 0.5, 6.5), 4),
311 ("a comb on exact tile lines", comb(8, 1.0, 5.0), 4),
312 ("a comb over many z7 tiles", comb(40, 2.5, 40.5), 7),
313 // --- the no-recursion case: one tile, so the leaf clip is the only clip ---
314 ("a ring inside one tile", polygon(&[&square(0.2, 0.8)]), 4),
315 (
316 "a line inside one tile",
317 line(&[(w(0.2), w(0.2)), (w(0.5), w(0.7)), (w(0.8), w(0.3))]),
318 4,
319 ),
320 // --- polygons spanning many tiles, which is the case this exists for ---
321 ("a ring over 6x6 tiles", polygon(&[&square(0.5, 6.5)]), 4),
322 ("a ring on exact tile corners", polygon(&[&square(1.0, 5.0)]), 4),
323 (
324 "a ring with a hole crossing tiles",
325 polygon(&[&square(0.5, 6.5), &square(2.25, 4.75)]),
326 4,
327 ),
328 (
329 "a hole sharing a tile edge with its exterior",
330 polygon(&[&square(1.0, 5.0), &square(2.0, 4.0)]),
331 4,
332 ),
333 // A U straddling tile boundaries: Sutherland-Hodgman returns one ring with
334 // a zero-area sliver here, which is the structure most at risk from
335 // composing clips.
336 (
337 "a concave U over several tiles",
338 polygon(&[&[
339 (w(0.5), w(0.5)),
340 (w(5.5), w(0.5)),
341 (w(5.5), w(2.5)),
342 (w(2.5), w(2.5)),
343 (w(2.5), w(4.5)),
344 (w(5.5), w(4.5)),
345 (w(5.5), w(6.5)),
346 (w(0.5), w(6.5)),
347 (w(0.5), w(0.5)),
348 ]]),
349 4,
350 ),
351 ];
352
353 // A star, so edges cross tile lines at angles that are not nice fractions.
354 let mut star: Vec<Pt> = (0..24)
355 .map(|i| {
356 let a = i as f64 * std::f64::consts::TAU / 24.0;
357 let r = if i % 2 == 0 { 3.3 } else { 1.7 };
358 (w(4.0 + r * a.cos()), w(4.0 + r * a.sin()))
359 })
360 .collect();
361 star.push(star[0]);
362 out.push(("a 12-point star", polygon(&[&star]), 4));
363
364 // --- lines, which the plan calls the fragile case -------------------
365 out.push((
366 "a long diagonal",
367 line(&[(w(0.3), w(0.3)), (w(7.7), w(6.1))]),
368 4,
369 ));
370 out.push((
371 "a diagonal through exact tile corners",
372 line(&[(w(0.0), w(0.0)), (w(8.0), w(8.0))]),
373 4,
374 ));
375 out.push((
376 "a staircase, one vertex per tile corner",
377 line(&(0..=8).map(|i| (w(i as f64), w(i as f64))).collect::<Vec<_>>()),
378 4,
379 ));
380 // Leaves and re-enters repeatedly, so the weld is exercised at every level.
381 out.push((
382 "a zigzag crossing one tile line many times",
383 line(
384 &(0..40)
385 .map(|i| {
386 let t = i as f64 / 39.0;
387 (w(2.0 + 0.6 * ((i % 2) as f64 * 2.0 - 1.0)), w(0.5 + 6.0 * t))
388 })
389 .collect::<Vec<_>>(),
390 ),
391 4,
392 ));
393 // A vertex sitting exactly on a tile line, which is where an inclusive
394 // `inside` test and an interpolated crossing can disagree.
395 out.push((
396 "a line with a vertex exactly on a tile line",
397 line(&[(w(0.5), w(1.5)), (w(2.0), w(2.0)), (w(3.5), w(1.5))]),
398 4,
399 ));
400 // A spiral, for edges at many angles and lengths at once.
401 out.push((
402 "a spiral over the grid",
403 line(
404 &(0..200)
405 .map(|i| {
406 let t = i as f64 / 199.0;
407 let a = t * std::f64::consts::TAU * 3.0;
408 let r = 0.2 + 3.5 * t;
409 (w(4.0 + r * a.cos()), w(4.0 + r * a.sin()))
410 })
411 .collect::<Vec<_>>(),
412 ),
413 4,
414 ));
415
416 // --- pseudo-random walks, deterministically seeded ------------------
417 let mut seed = 0x2545_F491_4F6C_DD1Du64;
418 let mut next = move || {
419 seed ^= seed << 13;
420 seed ^= seed >> 7;
421 seed ^= seed << 17;
422 (seed >> 11) as f64 / (1u64 << 53) as f64
423 };
424 for _ in 0..8 {
425 let pts: Vec<Pt> = (0..60)
426 .map(|_| (w(next() * 8.0), w(next() * 8.0)))
427 .collect();
428 out.push(("a random walk", line(&pts), 4));
429 }
430 for _ in 0..8 {
431 // A convex-ish blob: random radii around a circle, so the ring does not
432 // self-intersect but its edges still cross tile lines arbitrarily.
433 let mut ring: Vec<Pt> = (0..20)
434 .map(|i| {
435 let a = i as f64 * std::f64::consts::TAU / 20.0;
436 let r = 1.0 + 2.5 * next();
437 (w(4.0 + r * a.cos()), w(4.0 + r * a.sin()))
438 })
439 .collect();
440 ring.push(ring[0]);
441 out.push(("a random blob", polygon(&[&ring]), 4));
442 }
443
444 // --- deeper zooms, so the descent runs more levels ------------------
445 out.push(("a ring over many z7 tiles", polygon(&[&square(3.5, 60.5)]), 7));
446 out.push((
447 "a long diagonal over many z7 tiles",
448 line(&[(w(1.3), w(2.3)), (w(90.7), w(70.1))]),
449 7,
450 ));
451 // --- off the edge of the grid --------------------------------------
452 out.push(("a ring hanging off the grid", polygon(&[&square(-2.0, 3.0)]), 4));
453 out.push((
454 "a line hanging off the grid",
455 line(&[(w(-3.0), w(-1.0)), (w(4.0), w(5.0))]),
456 4,
457 ));
458
459 // --- points --------------------------------------------------------
460 let mut pts = Geometry::Points(sig(&[
461 (w(0.5), w(0.5)),
462 (w(1.0), w(1.0)),
463 (w(2.9999), w(3.0001)),
464 (w(5.5), w(2.5)),
465 ]));
466 crate::simplify::annotate(&mut pts);
467 out.push(("a handful of points", pts, 4));
468
469 out
470 }