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

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

pyramid_part5.rs458 lines · 20.0 KiBRaw
1 use super::*;
2 use crate::mvt::Tile;
3 use crate::pmtiles::Archive;
4
5 fn line(coords: &[(f64, f64)], props: Vec<(&str, Value)>) -> Feature {
6 Feature {
7 geometry: Geometry::Lines(vec![coords.to_vec()]),
8 props: props.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
9 }
10 }
11
12 fn square(min_lon: f64, min_lat: f64, size: f64, name: &str) -> Feature {
13 Feature {
14 geometry: Geometry::Polygons(vec![vec![vec![
15 (min_lon, min_lat),
16 (min_lon + size, min_lat),
17 (min_lon + size, min_lat + size),
18 (min_lon, min_lat + size),
19 (min_lon, min_lat),
20 ]]]),
21 props: vec![("name".to_string(), Value::String(name.into()))],
22 }
23 }
24
25 fn tile_at(archive: &Archive, z: u8, lon: f64, lat: f64) -> Option<Tile> {
26 let (fx, fy) = geom::project(lon, lat, z);
27 archive
28 .tile(z, fx.floor() as u64, fy.floor() as u64)
29 .unwrap()
30 .map(|b| Tile::decode(&b).unwrap())
31 }
32
33 #[test]
34 fn a_line_archive_round_trips_through_the_reader() {
35 let features = vec![line(
36 &[(-122.42, 37.77), (-122.40, 37.79), (-122.38, 37.78)],
37 vec![("maxspeed", Value::String("25 mph".into()))],
38 )];
39 let (bytes, report) = build_archive(&features, &Options::new("maxspeed", 10, 12)).unwrap();
40 let a = Archive::parse(&bytes).unwrap();
41 assert_eq!((a.header.min_zoom, a.header.max_zoom), (10, 12));
42 assert!(String::from_utf8_lossy(&a.metadata).contains("maxspeed"));
43 assert_eq!(report.len(), 3);
44
45 for z in 10..=12u8 {
46 let tile = tile_at(&a, z, -122.42, 37.77).unwrap_or_else(|| panic!("a tile at z{z}"));
47 let l = tile.layer("maxspeed").unwrap();
48 assert_eq!(l.features.len(), 1, "z{z}");
49 assert_eq!(l.features[0].geom_type, GeomType::LineString);
50 assert_eq!(
51 l.features[0].get("maxspeed"),
52 Some(&Value::String("25 mph".into()))
53 );
54 // And the geometry decodes as a line.
55 assert!(mvt::decode_lines(&l.features[0].geometry).is_some());
56 }
57 }
58
59 #[test]
60 fn a_polygon_archive_keeps_its_winding_and_its_hole() {
61 let with_hole = Feature {
62 geometry: Geometry::Polygons(vec![vec![
63 vec![(-122.5, 37.7), (-122.3, 37.7), (-122.3, 37.9), (-122.5, 37.9), (-122.5, 37.7)],
64 vec![(-122.45, 37.75), (-122.35, 37.75), (-122.35, 37.85), (-122.45, 37.85), (-122.45, 37.75)],
65 ]]),
66 props: vec![("name".to_string(), Value::String("Oakland".into()))],
67 };
68 let (bytes, _) = build_archive(&[with_hole], &Options::new("admin_city", 9, 10)).unwrap();
69 let a = Archive::parse(&bytes).unwrap();
70 let tile = tile_at(&a, 10, -122.4, 37.8).expect("a tile");
71 let f = &tile.layer("admin_city").unwrap().features[0];
72 assert_eq!(f.geom_type, GeomType::Polygon);
73 let rings = mvt::decode_polygons(&f.geometry).expect("polygon geometry");
74 assert_eq!(rings.len(), 1);
75 assert_eq!(rings[0].len(), 2, "exterior plus its hole: {rings:?}");
76 assert!(mvt::signed_area(&rings[0][0]) > 0, "exterior positive");
77 assert!(mvt::signed_area(&rings[0][1]) < 0, "interior negative");
78 }
79
80 /// A z6 tile spans `360/64 = 5.625` degrees of longitude, so `-123.75` is
81 /// exactly the edge between tile x 9 and tile x 10. Everything below is built
82 /// around that so a fixture can be made to straddle a real tile boundary
83 /// without having to invert the projection.
84 const Z6_TILE_EDGE_LON: f64 = -123.75;
85
86 /// A polygon whose exterior **and** hole both cross [`Z6_TILE_EDGE_LON`], with
87 /// enough sub-tolerance jitter along every edge that filtering has something to
88 /// remove on both sides of the boundary.
89 ///
90 /// One z6 extent unit is `5.625 / 4096` degrees, about `0.00137`, so the jitter
91 /// below is a third of a unit: under the 1-unit tolerance, and therefore exactly
92 /// the detail a coarse zoom is supposed to drop.
93 fn straddling_polygon() -> Feature {
94 let jitter = |i: usize| (i % 5) as f64 * 0.0005;
95 let ring = |west: f64, east: f64, south: f64, north: f64| {
96 let mut r: Vec<(f64, f64)> = Vec::new();
97 let (w, h) = (east - west, north - south);
98 for i in 0..=200 {
99 let t = i as f64 / 200.0;
100 r.push((west + w * t, south + jitter(i)));
101 }
102 for i in 0..=20 {
103 let t = i as f64 / 20.0;
104 r.push((east - jitter(i), south + h * t));
105 }
106 for i in 0..=200 {
107 let t = i as f64 / 200.0;
108 r.push((east - w * t, north - jitter(i)));
109 }
110 for i in 0..=20 {
111 let t = i as f64 / 20.0;
112 r.push((west + jitter(i), north - h * t));
113 }
114 r.push(r[0]);
115 r
116 };
117 let e = Z6_TILE_EDGE_LON;
118 Feature {
119 geometry: Geometry::Polygons(vec![vec![
120 ring(e - 2.25, e + 2.75, 36.0, 40.0),
121 ring(e - 1.25, e + 1.75, 37.0, 39.0),
122 ]]),
123 props: vec![("name".to_string(), Value::String("straddler".into()))],
124 }
125 }
126
127 /// The same fixture, moved to straddle longitude 0.
128 ///
129 /// At z6, lon 0 projects to world x exactly 32, so this crosses the edge between
130 /// tile 31 and tile 32 -- and `31 >> 5` is 0 where `32 >> 5` is 1, so those two
131 /// tiles' quadtree ancestries diverge at the ROOT. That is the worst case for
132 /// [`crate::subdivide`]: the geometry each tile sees has been clipped down two
133 /// completely separate chains of six cells, rather than sharing a parent.
134 fn root_straddling_polygon() -> Feature {
135 let Feature { geometry, props } = straddling_polygon();
136 let shift = -Z6_TILE_EDGE_LON;
137 let Geometry::Polygons(polys) = geometry else { panic!("a polygon fixture") };
138 Feature {
139 geometry: Geometry::Polygons(
140 polys
141 .into_iter()
142 .map(|rings| {
143 rings
144 .into_iter()
145 .map(|r| r.into_iter().map(|(lon, lat)| (lon + shift, lat)).collect())
146 .collect()
147 })
148 .collect(),
149 ),
150 props,
151 }
152 }
153
154 /// Crossing-number point-in-ring, with a point on the ring counting as inside.
155 ///
156 /// Integer throughout, and `i64` for the cross products: two `i32` spans
157 /// multiply to 62 bits, so containment is decided exactly rather than nearly.
158 fn in_ring(ring: &[(i32, i32)], p: (i32, i32)) -> bool {
159 let n = ring.len();
160 let mut inside = false;
161 for i in 0..n {
162 let (ax, ay) = ring[i];
163 let (bx, by) = ring[(i + 1) % n];
164 let cross = (bx as i64 - ax as i64) * (p.1 as i64 - ay as i64)
165 - (by as i64 - ay as i64) * (p.0 as i64 - ax as i64);
166 if cross == 0
167 && p.0 >= ax.min(bx)
168 && p.0 <= ax.max(bx)
169 && p.1 >= ay.min(by)
170 && p.1 <= ay.max(by)
171 {
172 return true;
173 }
174 if (ay > p.1) != (by > p.1) {
175 let d = by as i64 - ay as i64;
176 let u = d * (p.0 as i64 - ax as i64);
177 let t = (p.1 as i64 - ay as i64) * (bx as i64 - ax as i64);
178 if (d > 0) == (u < t) {
179 inside = !inside;
180 }
181 }
182 }
183 inside
184 }
185
186 /// The invariant the whole annotate-then-filter design exists to hold: a hole
187 /// that crossed a tile boundary is still inside its exterior once the tile has
188 /// been built.
189 ///
190 /// A hole straddling its exterior is not something earcut can express, so the
191 /// renderer has to drop it (`library/map/src/main/rust/src/tess/fill.rs`) and the
192 /// island or lake fills in solid. Simplifying each clipped ring on its own is
193 /// what used to produce them, so this asserts on the built archive rather than
194 /// on any one stage.
195 #[test]
196 fn a_hole_crossing_a_tile_boundary_stays_inside_its_exterior() {
197 // maxzoom above the zoom under test, so z6 is genuinely being thinned:
198 // `tolerance_for` spares only the deepest zoom.
199 let (bytes, _) =
200 build_archive(&[straddling_polygon()], &Options::new("land", 6, 7)).unwrap();
201 let a = Archive::parse(&bytes).unwrap();
202
203 let mut checked = 0;
204 for (id, raw) in a.iter_tiles().unwrap() {
205 let (z, _, _) = pmtiles::tile_zxy(id);
206 let tile = Tile::decode(&crate::gz::decompress(raw).unwrap()).unwrap();
207 let f = &tile.layer("land").unwrap().features[0];
208 for rings in mvt::decode_polygons(&f.geometry).expect("polygon geometry") {
209 let (exterior, holes) = rings.split_first().expect("an exterior");
210 for hole in holes {
211 for &p in hole {
212 assert!(
213 in_ring(exterior, p),
214 "z{z} tile {id}: hole vertex {p:?} escaped its exterior"
215 );
216 }
217 checked += 1;
218 }
219 }
220 }
221 assert!(checked > 0, "the fixture produced no holes to check");
222 }
223
224 /// Two tiles that overlap must agree, vertex for vertex, on the geometry inside
225 /// the overlap. They clip the same annotated source and threshold it the same
226 /// way, so the only thing that can make them disagree is thinning a clipped ring
227 /// against its own endpoints -- which is what a seam at a tile join looks like.
228 ///
229 /// The comparison is over the band strictly inside BOTH buffered rects: the
230 /// crossings each tile's own clip introduced sit exactly on the edge of that
231 /// band and belong to one tile only.
232 ///
233 /// Held **exact**, and that is a claim worth stating since [`crate::subdivide`]
234 /// arrived. A leaf's geometry is now clipped down a chain of ancestor cells, and
235 /// two adjacent leaves can have different chains -- so it would have been
236 /// reasonable to expect the shared band to need a shape comparison rather than a
237 /// vertex one. It does not, because an ancestor boundary line either coincides
238 /// with the leaf's own line on that side or lies outside the leaf entirely, so no
239 /// ancestor ever puts a vertex *inside* a leaf that the leaf's own clip would not
240 /// have put there. `subdivide`'s tests measure that directly; this measures the
241 /// consequence at the seam, which is the thing a reader actually cares about.
242 #[test]
243 fn two_adjacent_tiles_agree_on_the_geometry_they_share() {
244 assert_adjacent_tiles_agree(straddling_polygon(), Z6_TILE_EDGE_LON);
245 }
246
247 /// The same seam, at the one edge where the two tiles share no quadtree ancestor
248 /// at all: tile 31 and tile 32 at z6 diverge at the root, so each side's geometry
249 /// has been clipped down six cells that have nothing in common but the world.
250 ///
251 /// If a descent could open a seam, it would open it here.
252 #[test]
253 fn two_tiles_under_different_quadtree_roots_still_agree_on_their_seam() {
254 assert_adjacent_tiles_agree(root_straddling_polygon(), 0.0);
255 }
256
257 /// Build one feature at z6 and compare the two tiles either side of `edge_lon`
258 /// over the band their buffers share.
259 fn assert_adjacent_tiles_agree(feature: Feature, edge_lon: f64) {
260 // maxzoom above the zoom under test, so z6 is genuinely being thinned:
261 // `tolerance_for` spares only the deepest zoom.
262 let (bytes, _) = build_archive(&[feature], &Options::new("land", 6, 7)).unwrap();
263 let a = Archive::parse(&bytes).unwrap();
264
265 let extent = DEFAULT_EXTENT;
266 let buffer = geom::buffer_for(extent);
267 let (edge_tile_x, _) = geom::project(edge_lon, 0.0, 6);
268 let edge = edge_tile_x * extent as f64;
269 let east_tx = edge_tile_x as u64;
270 // The straddling polygon covers lat 36..40, which at z6 is one tile row.
271 let ty = geom::project(0.0, 38.0, 6).1.floor() as u64;
272
273 // Every vertex of the feature, in WORLD coordinates, that lies strictly
274 // inside both tiles' buffered rects.
275 let shared = |tx: u64| -> Vec<(i64, i64)> {
276 let tile = a
277 .tile(6, tx, ty)
278 .unwrap()
279 .map(|b| Tile::decode(&b).unwrap())
280 .unwrap_or_else(|| panic!("a tile at z6/{tx}/{ty}"));
281 let f = &tile.layer("land").unwrap().features[0];
282 let ox = tx as i64 * extent as i64;
283 let mut out: Vec<(i64, i64)> = mvt::decode_polygons(&f.geometry)
284 .expect("polygon geometry")
285 .into_iter()
286 .flatten()
287 .flatten()
288 .map(|(x, y)| (x as i64 + ox, y as i64))
289 .filter(|&(x, _)| ((x as f64) - edge).abs() < buffer)
290 .collect();
291 out.sort_unstable();
292 out
293 };
294
295 let west = shared(east_tx - 1);
296 let east = shared(east_tx);
297 assert!(!west.is_empty(), "the fixture reaches neither side of the edge");
298 assert_eq!(west, east, "the two tiles disagree inside their overlap");
299 }
300
301 #[test]
302 fn a_feature_spanning_several_tiles_appears_in_each_of_them() {
303 // A line across most of California at z6 lands in more than one tile.
304 let features = vec![line(&[(-124.0, 40.0), (-116.0, 33.0)], vec![])];
305 let (bytes, report) = build_archive(&features, &Options::new("l", 6, 6)).unwrap();
306 let a = Archive::parse(&bytes).unwrap();
307 assert!(report[0].tiles > 1, "{:?}", report[0]);
308 assert!(a.header.addressed_tiles > 1);
309 // Every tile it reaches actually carries geometry.
310 for (_, raw) in a.iter_tiles().unwrap() {
311 let tile = Tile::decode(&crate::gz::decompress(raw).unwrap()).unwrap();
312 let l = tile.layer("l").unwrap();
313 assert_eq!(l.features.len(), 1);
314 assert!(!l.features[0].geometry.is_empty());
315 }
316 }
317
318 /// The failure mode of walking segments instead of filling the bounding box is
319 /// UNDER-inclusion: a tile the line crosses but which no segment box happens to
320 /// name would leave a hole in the middle of a drawn line.
321 ///
322 /// A long diagonal at z10 is the sharpest test of that. Every column of tiles
323 /// between its two ends must hold at least one tile -- a missing column is a
324 /// visible break in the line.
325 #[test]
326 fn a_long_diagonal_leaves_no_gap_in_the_tiles_it_covers() {
327 let (west, east) = ((-124.0, 42.0), (-114.0, 33.0));
328 let features = vec![line(&[west, east], vec![])];
329 let (bytes, report) = build_archive(&features, &Options::new("l", 10, 10)).unwrap();
330 let a = Archive::parse(&bytes).unwrap();
331 assert!(report[0].tiles > 50, "a real spread of tiles: {:?}", report[0]);
332
333 let (wx, wy) = geom::project(west.0, west.1, 10);
334 let (ex, ey) = geom::project(east.0, east.1, 10);
335 let (x0, x1) = (wx.floor() as u64, ex.floor() as u64);
336 let (ylo, yhi) = (wy.floor() as u64, ey.floor() as u64);
337
338 // Probe every column the line spans; each must carry at least one tile
339 // somewhere in the y band the line occupies.
340 for x in x0..=x1 {
341 let mut found = false;
342 for y in ylo..=yhi {
343 if a.tile(10, x, y).unwrap().is_some() {
344 found = true;
345 break;
346 }
347 }
348 assert!(found, "column x={x} has no tile: the line has a gap there");
349 }
350
351 // And every archived tile really carries geometry, so none is a stray.
352 for (_, raw) in a.iter_tiles().unwrap() {
353 let tile = Tile::decode(&crate::gz::decompress(raw).unwrap()).unwrap();
354 let l = tile.layer("l").unwrap();
355 assert!(!l.features[0].geometry.is_empty());
356 }
357 }
358
359 #[test]
360 fn tiles_a_feature_does_not_reach_are_not_created() {
361 let features = vec![line(&[(-122.42, 37.77), (-122.41, 37.78)], vec![])];
362 let (bytes, _) = build_archive(&features, &Options::new("l", 12, 12)).unwrap();
363 let a = Archive::parse(&bytes).unwrap();
364 // A small line at z12 covers a handful of tiles, not the whole grid.
365 assert!(a.header.addressed_tiles < 10, "{}", a.header.addressed_tiles);
366 assert!(tile_at(&a, 12, -74.0, 40.7).is_none(), "nothing in New York");
367 }
368
369 #[test]
370 fn two_runs_are_byte_identical() {
371 let features = vec![
372 line(&[(-122.42, 37.77), (-122.40, 37.79)], vec![("a", Value::Uint(1))]),
373 square(-122.5, 37.7, 0.1, "A"),
374 ];
375 let opts = Options::new("l", 10, 12);
376 let (a, ra) = build_archive(&features, &opts).unwrap();
377 let (b, rb) = build_archive(&features, &opts).unwrap();
378 assert_eq!(a, b, "determinism is a regression surface here");
379 assert_eq!(ra, rb);
380 }
381
382 // --- the drop policy ---------------------------------------------------
383
384 #[test]
385 fn nothing_is_dropped_when_the_tile_fits() {
386 let features: Vec<Feature> = (0..50)
387 .map(|i| {
388 let d = i as f64 * 0.0001;
389 line(&[(-122.42 + d, 37.77), (-122.41 + d, 37.78)], vec![])
390 })
391 .collect();
392 let (_, report) = build_archive(&features, &Options::new("l", 12, 12)).unwrap();
393 assert_eq!(report[0].dropped, 0, "{:?}", report[0]);
394 assert_eq!(report[0].over_budget, 0);
395 assert!(report[0].kept >= 50);
396 }
397
398 #[test]
399 fn a_tight_budget_drops_the_least_important_features_first() {
400 // One long line and many short ones in the same tile, with a budget only a
401 // few features wide. Importance is bbox span, so the long one must survive.
402 let mut features = vec![line(
403 &[(-122.45, 37.75), (-122.35, 37.85)],
404 vec![("id", Value::String("long".into()))],
405 )];
406 for i in 0..200 {
407 let d = i as f64 * 0.00005;
408 features.push(line(
409 &[(-122.40 + d, 37.80), (-122.3999 + d, 37.8001)],
410 vec![("id", Value::String(format!("short{i}")))],
411 ));
412 }
413 let mut opts = Options::new("l", 11, 11);
414 opts.max_tile_bytes = 400;
415 let (bytes, report) = build_archive(&features, &opts).unwrap();
416 assert!(report[0].dropped > 0, "the budget must have bitten: {:?}", report[0]);
417
418 let a = Archive::parse(&bytes).unwrap();
419 let tile = tile_at(&a, 11, -122.40, 37.80).expect("a tile");
420 let ids: Vec<String> = tile
421 .layer("l")
422 .unwrap()
423 .features
424 .iter()
425 .filter_map(|f| match f.get("id") {
426 Some(Value::String(s)) => Some(s.clone()),
427 _ => None,
428 })
429 .collect();
430 assert!(ids.contains(&"long".to_string()), "the long line survives: {ids:?}");
431 }
432
433 #[test]
434 fn a_dropping_tile_stays_within_its_budget() {
435 let features: Vec<Feature> = (0..400)
436 .map(|i| {
437 let d = i as f64 * 0.00002;
438 line(
439 &[(-122.40 + d, 37.80), (-122.399 + d, 37.801)],
440 vec![("name", Value::String(format!("street number {i}")))],
441 )
442 })
443 .collect();
444 let mut opts = Options::new("l", 11, 11);
445 opts.max_tile_bytes = 600;
446 let (bytes, report) = build_archive(&features, &opts).unwrap();
447 assert!(report[0].dropped > 0);
448 assert!(
449 report[0].largest_tile_bytes <= 600,
450 "largest tile {} exceeds the 600-byte budget",
451 report[0].largest_tile_bytes
452 );
453 // The archive still reads, which is the thing a bad drop breaks.
454 let a = Archive::parse(&bytes).unwrap();
455 for (_, raw) in a.iter_tiles().unwrap() {
456 assert!(Tile::decode(&crate::gz::decompress(raw).unwrap()).is_ok());
457 }
458 }