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

Modern-Apps.git / scripts / maps / mamaps_build / src / tiler_part7.rs

tiler_part7.rs414 lines · 20.0 KiBRaw
1#[cfg(test)]
2mod tests {
3 use super::*;
4
5 /// The tests hold features in memory and the tiler reads them from a file, so they spill
6 /// first. Keeps a test about tiling from reading like a test about plumbing.
7 pub(super) fn spilled(features: &[Feature]) -> crate::store::Store {
8 crate::store::Store::of(features).expect("spill")
9 }
10
11 use crate::schema::Class;
12
13 use tilecodec::mamaps::dict;
14
15 pub(super) fn square(lon: f64, lat: f64, size: f64) -> Geometry {
16 Geometry::Polygons(vec![vec![vec![
17 (lon, lat),
18 (lon + size, lat),
19 (lon + size, lat + size),
20 (lon, lat + size),
21 (lon, lat),
22 ]]])
23 }
24
25 pub(super) fn lake(lon: f64, lat: f64, size: f64, min_zoom: u8) -> Feature {
26 Feature {
27 class: Class::area(dict::LAYER_LANDTYPE, crate::schema::kind("lake"), min_zoom),
28 geometry: square(lon, lat, size),
29 name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0,
30 turn_fwd: Vec::new(),
31 turn_bwd: Vec::new(),
32 building: None,
33 carriageway: tilecodec::mamaps::body::Carriageway::default(),
34 }
35 }
36
37 pub(super) fn shed(lon: f64, lat: f64, size: f64) -> Feature {
38 Feature {
39 class: Class {
40 min_area_px: crate::schema::buildings::MIN_AREA_PX,
41 ..Class::area(dict::LAYER_BUILDINGS, crate::schema::kind("building"), 14)
42 },
43 geometry: square(lon, lat, size),
44 name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0,
45 turn_fwd: Vec::new(),
46 turn_bwd: Vec::new(),
47 building: None,
48 carriageway: tilecodec::mamaps::body::Carriageway::default(),
49 }
50 }
51
52 pub(super) fn buildings_in_archive(bytes: &[u8]) -> usize {
53 tilecodec::mamaps::read::read_all(bytes)
54 .expect("read")
55 .iter()
56 .map(|(_, _, body)| {
57 Body::parse(body)
58 .expect("parse")
59 .layer(dict::LAYER_BUILDINGS)
60 .map(|layer| layer.features.len())
61 .unwrap_or(0)
62 })
63 .sum()
64 }
65
66 pub(super) fn settings(min_zoom: u8, max_zoom: u8) -> Settings {
67 // `min_zoom`/`max_zoom` are kept as arguments so call sites read unchanged;
68 // the tiler builds z0-14 regardless.
69 let _ = (min_zoom, max_zoom);
70 Settings {
71 build_id: 7,
72 scratch: scratch(),
73 force_chunk_spill_file: false,
74 dem: crate::dem::Dem::from_grids(14, 17, Vec::new()),
75 region_links: std::collections::HashMap::new(),
76 country_zooms: std::collections::HashMap::new(),
77 }
78 }
79
80 /// A scratch path of this test's own. The tiler truncates and removes it per zoom, so two tests
81 /// sharing one would tile each other's chunks.
82 pub(super) fn scratch() -> PathBuf {
83 static NEXT: AtomicUsize = AtomicUsize::new(0);
84 std::env::temp_dir().join(format!(
85 "mamaps_test_{}_{}.tilechunks",
86 std::process::id(),
87 NEXT.fetch_add(1, Ordering::Relaxed),
88 ))
89 }
90
91 /// The thread budget and the chunk size are process-wide, and `cargo test` runs these tests in
92 /// one process on several threads. The tests that set either take this lock against each other —
93 /// not for safety, an `AtomicUsize` is safe, but so that a test asserting "this is what one
94 /// thread produces" really is running on one thread when it says so.
95 ///
96 /// A poisoned lock is taken anyway: poisoning means another test panicked, and *its* failure is
97 /// the one worth reading rather than a cascade of lock errors on top of it.
98 pub(super) static BUDGET: Mutex<()> = Mutex::new(());
99
100 pub(super) fn budget() -> std::sync::MutexGuard<'static, ()> {
101 let guard = BUDGET.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
102 // Trip the once-only environment adoption here, *before* the test sets its own count. Left
103 // to `build`, the first call would run it after `set_threads(1)` and could quietly put
104 // `RAYON_NUM_THREADS` back — leaving a test that says "one thread" asserting nothing.
105 adopt_thread_budget();
106 guard
107 }
108
109 /// `par::clear_threads` is `#[cfg(test)]` *inside* `tile_build`, so it does not exist from here.
110 /// Putting the box's own count back is the same thing for a test process.
111 pub(super) fn release_threads() {
112 par::set_threads(std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4));
113 }
114
115 /// Enough features, spread over enough tiles, that every zoom has several chunks to merge and
116 /// several tiles per chunk. A single-tile fixture would pass any merge, correct or not.
117 pub(super) fn a_crowd() -> Vec<Feature> {
118 let mut features = Vec::new();
119 for i in 0..60 {
120 let (row, column) = (i / 10, i % 10);
121 let (lon, lat) = (-120.0 + column as f64 * 0.03, 35.0 + row as f64 * 0.03);
122 features.push(lake(lon, lat, 0.02, 0));
123 features.push(Feature {
124 class: Class::area(dict::LAYER_BUILDINGS, crate::schema::kind("building"), 0),
125 geometry: square(lon + 0.004, lat + 0.004, 0.004),
126 name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0,
127 turn_fwd: Vec::new(),
128 turn_bwd: Vec::new(),
129 building: None,
130 carriageway: tilecodec::mamaps::body::Carriageway::default(),
131 });
132 // A line as well, so the merge has to rebase a `GEOM_LINE` feature's parts too, and a
133 // long one so it crosses tiles rather than sitting inside one.
134 features.push(Feature {
135 class: Class::line(dict::LAYER_LANDTYPE, crate::schema::kind("river"), 0),
136 geometry: Geometry::Lines(vec![(0..40)
137 .map(|k| (lon + k as f64 * 0.002, lat + (k % 5) as f64 * 0.001))
138 .collect()]),
139 name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0,
140 turn_fwd: Vec::new(),
141 turn_bwd: Vec::new(),
142 building: None,
143 carriageway: tilecodec::mamaps::body::Carriageway::default(),
144 });
145 }
146 features
147 }
148
149 /// **The sub-2px drop.** A footprint under two display pixels at z14 is a speck, not detail:
150 /// dropped by the `min_area_px` floor, while a house-sized one on the same build survives.
151 #[test]
152 fn a_speck_sized_footprint_is_dropped_but_a_house_survives() {
153 // A degree at z14 is ~186k extent units at this latitude, so 0.00005 deg is ~9
154 // units a side (area ~85 < the 512-unit floor) and 0.0005 deg is ~93 units a side
155 // (area ~8700, well above it). Both sit inside one 0.022-deg tile; one build, because
156 // a speck alone would leave zero tiles and the writer refuses an empty archive.
157 let speck = shed(-120.001, 35.001, 0.00005);
158 let house = shed(-120.01, 35.01, 0.0005);
159 let (bytes, stats) = build(&spilled(&[speck, house]), &settings(14, 14)).expect("build");
160 assert_eq!(buildings_in_archive(&bytes), 1, "the house survives, the speck does not");
161 assert_eq!(stats.iter().find(|s| s.zoom == 14).expect("z14").features, 1);
162 }
163
164 /// **The z14 tolerance floor.** A wobble under half an extent unit (~0.3 m) is sub-pixel: the
165 /// midpoint goes on the buildings layer, while the same geometry on a non-building layer
166 /// keeps every vertex at a zero tolerance.
167 #[test]
168 fn sub_pixel_jaggies_simplify_on_buildings_only() {
169 // A 100x10-unit wall with a 0.4-unit bump: under BUILDING_TOLERANCE, over zero.
170 let ring: Vec<SigPt> =
171 [(0.0, 0.0), (50.0, 0.4), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0), (0.0, 0.0)]
172 .iter()
173 .map(|&(x, y)| SigPt::new(x, y))
174 .collect();
175 let mut g = Geometry::Polygons(vec![vec![ring]]);
176 simplify::annotate(&mut g);
177 let tol = tolerance_for_layer(dict::LAYER_BUILDINGS, 14, 0.0);
178 assert_eq!(tol, BUILDING_TOLERANCE);
179 let Geometry::Polygons(out) = simplify::filter(&g, tol) else { panic!() };
180 assert_eq!(out[0][0].len(), 5, "the 0.4-unit bump goes: {out:?}");
181 // The same shape on landtype at a zero tolerance keeps it.
182 let landtype_tol = tolerance_for_layer(dict::LAYER_LANDTYPE, 14, 0.0);
183 assert_eq!(landtype_tol, 0.0, "the wash scales the policy, and 1.5x of zero is zero");
184 let Geometry::Polygons(kept) = simplify::filter(&g, landtype_tol) else { panic!() };
185 assert_eq!(kept[0][0].len(), 6, "at zero tolerance nothing moves");
186 // A coarser global tolerance still wins over the floor.
187 assert_eq!(tolerance_for_layer(dict::LAYER_BUILDINGS, 14, 2.0), 2.0);
188 // And below the buildings floor the policy stands: z13 keeps 1.0, not 0.5.
189 assert_eq!(tolerance_for_layer(dict::LAYER_BUILDINGS, 13, 1.0), 1.0);
190 assert_eq!(tolerance_for_layer(dict::LAYER_LANDTYPE, 13, 1.0), 3.0, "z13 landtype triples the wash");
191 // Roads take the wash below the archive max (z13 1.5x); at z14 policy
192 // is 0.0 and the wash is a no-op — crisp where lanes align.
193 assert_eq!(tolerance_for_layer(dict::LAYER_ROADS, 13, 1.0), 1.5, "roads wash below max zoom");
194 assert_eq!(tolerance_for_layer(dict::LAYER_ROADS, 14, 0.0), 0.0, "roads crisp at max zoom");
195 assert_eq!(tolerance_for_layer(dict::LAYER_TRANSIT, 13, 1.0), 1.5, "transit curves wash below max zoom");
196 assert_eq!(tolerance_for_layer(dict::LAYER_BOUNDARIES, 10, 2.0), 3.0, "the boundary wash scales the policy");
197 }
198
199 /// **The orthogonal snap.** A hand-digitised near-rectangle snaps exactly axis-aligned;
200 /// anything further off stays where it was, and closure, order and count are untouched.
201 #[test]
202 fn near_rectangles_snap_flat_and_true_shapes_do_not_move() {
203 let ring_of = |pts: &[(f64, f64)]| -> Vec<SigPt> {
204 pts.iter().map(|&(x, y)| SigPt::new(x, y)).collect()
205 };
206 // A 100x50 rectangle with a 0.3-unit wobble on each side.
207 let wonky = ring_of(&[
208 (0.0, 0.2),
209 (100.3, 0.0),
210 (100.0, 50.1),
211 (49.8, 50.0),
212 (0.0, 50.0),
213 (0.0, 0.2),
214 ]);
215 let snapped = snap_building_ring(&wonky);
216 assert_eq!(snapped.len(), wonky.len(), "no vertex added or removed");
217 assert_eq!(snapped.first().map(|v| v.xy()), snapped.last().map(|v| v.xy()), "still closed");
218 let pts: Vec<(f64, f64)> = snapped.iter().map(|v| v.xy()).collect();
219 // Long edges are exactly flat now: y constant along the bottom, x along the sides.
220 assert!((pts[0].1 - pts[1].1).abs() == 0.0, "bottom edge flat: {pts:?}");
221 assert!((pts[1].0 - pts[2].0).abs() == 0.0, "right edge flat: {pts:?}");
222 // A genuinely diagonal edge is out of snap range and untouched.
223 let diag = ring_of(&[(0.0, 0.0), (100.0, 40.0), (100.0, 100.0), (0.0, 100.0), (0.0, 0.0)]);
224 assert_eq!(
225 snap_building_ring(&diag).iter().map(|v| v.xy()).collect::<Vec<_>>(),
226 diag.iter().map(|v| v.xy()).collect::<Vec<_>>(),
227 "a 40-unit lean is not a wobble",
228 );
229 // Significance rides along: the snap moves coordinates, never re-measures them.
230 let mut g = Geometry::Polygons(vec![vec![wonky.clone()]]);
231 simplify::annotate(&mut g);
232 let Geometry::Polygons(annotated) = &g else { panic!() };
233 let before: Vec<f64> = annotated[0][0].iter().map(|v| v.sig).collect();
234 let Geometry::Polygons(after) = snap_building_rings(&g, dict::LAYER_BUILDINGS) else {
235 panic!()
236 };
237 let kept: Vec<f64> = after[0][0].iter().map(|v| v.sig).collect();
238 assert_eq!(before, kept, "snapping must not touch significance");
239 }
240
241 /// **The end of the id path.** A `poi` node's OSM id survives classification, the spill, the
242 /// tiler's chunk merge and the body encoder, and comes back out of the archive attached to
243 /// the same feature. Every other layer's id table stays absent, which is the whole reason the
244 /// table is a side table.
245 #[test]
246 fn a_poi_carries_its_osm_id_into_the_archive() {
247 let osm = crate::extract::tagged_id(240_109_189, crate::extract::ELEMENT_NODE);
248 let poi = Feature {
249 class: Class::line(dict::LAYER_POI, crate::schema::kind("cafe"), 0),
250 geometry: Geometry::Points(vec![(-120.0, 35.0)]),
251 name: Some("Blue Bottle".to_string()),
252 id: osm,
253 transit_color: 0,
254 transit_ordinal: 0,
255 transit_lanes: 0,
256 transit_taper: 0,
257 lane_count: 0,
258 turn_fwd: Vec::new(),
259 turn_bwd: Vec::new(),
260 building: None,
261 carriageway: tilecodec::mamaps::body::Carriageway::default(),
262 };
263 let features = vec![poi, lake(-120.0, 35.0, 0.01, 0)];
264 let (bytes, _) = build(&spilled(&features), &settings(14, 14)).expect("build");
265 let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read");
266 let mut seen = false;
267 for (_, _, body) in &entries {
268 let body = Body::parse(body).expect("parse");
269 let Some(layer) = body.layer(dict::LAYER_POI) else { continue };
270 for (index, feature) in layer.features.iter().enumerate() {
271 assert_eq!(body.feature_id(dict::LAYER_POI, index), Some(osm));
272 assert_eq!(feature.name(&body), Some("Blue Bottle"));
273 seen = true;
274 }
275 assert_eq!(
276 body.feature_id(dict::LAYER_LANDTYPE, 0),
277 None,
278 "the lake's layer carries no id table",
279 );
280 }
281 assert!(seen, "the poi should reach at least one tile");
282 }
283
284 /// **The lane path, end to end.** A multi-lane road's `lane_count` survives classification,
285 /// the way spill, the tiler's chunk merge and the body encoder, and comes back out of a v5
286 /// archive on the same feature — which is what the renderer's lane fan reads. Also pins that
287 /// the archive is written at the writer's own format version.
288 #[test]
289 fn a_multi_lane_road_carries_its_lane_count_into_the_archive() {
290 let road = Feature {
291 class: Class::line(dict::LAYER_ROADS, crate::schema::kind("major_road"), 12),
292 geometry: Geometry::Lines(vec![vec![(-120.0, 35.0), (-119.99, 35.001)]]),
293 name: None,
294 id: tilecodec::mamaps::body::ID_NONE,
295 transit_color: 0,
296 transit_ordinal: 0,
297 transit_lanes: 0,
298 transit_taper: 0,
299 lane_count: 4,
300 turn_fwd: Vec::new(),
301 turn_bwd: Vec::new(),
302 building: None,
303 carriageway: tilecodec::mamaps::body::Carriageway::default(),
304 };
305 let (bytes, _) = build(&spilled(&[road]), &settings(14, 14)).expect("build");
306 // The writer's own version byte, so an older reader rejects the archive cleanly.
307 // v9: leaves compress by default, which the v8 byte cannot name.
308 assert_eq!(
309 bytes[7],
310 tilecodec::mamaps::header::FORMAT_VERSION_V9,
311 "the archive header carries the writer's own format version",
312 );
313 let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read");
314 let mut seen = false;
315 for (_, _, body) in &entries {
316 let body = Body::parse(body).expect("parse");
317 let Some(layer) = body.layer(dict::LAYER_ROADS) else { continue };
318 for feature in &layer.features {
319 assert_eq!(feature.lane_count, 4, "the road's four lanes survive the archive");
320 seen = true;
321 }
322 }
323 assert!(seen, "the road should reach at least one tile");
324 }
325
326 /// **The S3DB building path, end to end.** A building's height, roof and colours survive the
327 /// spill, the tiler's chunk merge and stage C, and come back out of a v6 archive on the same
328 /// feature via the body's building side table — which is what the renderer reads to extrude it.
329 #[test]
330 fn a_buildings_s3db_attrs_reach_the_archive() {
331 use tilecodec::mamaps::body::{BuildingAttrs, ROOF_GABLED, ROOF_ORIENT_ACROSS};
332 let attrs = BuildingAttrs {
333 height: 420,
334 min_height: 30,
335 roof_height: 90,
336 roof_shape: ROOF_GABLED,
337 roof_direction: 64,
338 roof_orientation: ROOF_ORIENT_ACROSS,
339 building_colour: 0xFF_C8_A0_78,
340 roof_colour: 0xFF_80_20_20,
341 };
342 let building = Feature {
343 class: Class::area(dict::LAYER_BUILDINGS, crate::schema::kind("building"), 14),
344 geometry: square(-120.001, 35.001, 0.0008),
345 name: None,
346 id: tilecodec::mamaps::body::ID_NONE,
347 transit_color: 0,
348 transit_ordinal: 0,
349 transit_lanes: 0,
350 transit_taper: 0,
351 lane_count: 0,
352 turn_fwd: Vec::new(),
353 turn_bwd: Vec::new(),
354 building: Some(attrs),
355 carriageway: tilecodec::mamaps::body::Carriageway::default(),
356 };
357 let (bytes, _) = build(&spilled(&[building]), &settings(14, 14)).expect("build");
358 // v9: leaves compress by default, which the v8 byte cannot name.
359 assert_eq!(
360 bytes[7],
361 tilecodec::mamaps::header::FORMAT_VERSION_V9,
362 "the archive header carries the writer's own format version",
363 );
364 let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read");
365 let mut seen = false;
366 for (_, _, body) in &entries {
367 let body = Body::parse(body).expect("parse");
368 let Some(layer) = body.layer(dict::LAYER_BUILDINGS) else { continue };
369 for index in 0..layer.features.len() {
370 let got = body
371 .building_attrs(dict::LAYER_BUILDINGS, index)
372 .expect("the buildings layer must carry a building table");
373 assert_eq!(got, attrs, "the S3DB attributes survive the archive");
374 seen = true;
375 }
376 }
377 assert!(seen, "the building should reach at least one tile");
378 }
379
380 /// A building with no S3DB tags carries a default record, and a tile where *every* building is
381 /// default carries no building table at all — the renderer falls back to its own height. This
382 /// pins that the table is paid for only where 3D data exists.
383 #[test]
384 fn a_plain_building_tile_carries_no_building_table() {
385 use tilecodec::mamaps::body::BuildingAttrs;
386 let building = Feature {
387 class: Class::area(dict::LAYER_BUILDINGS, crate::schema::kind("building"), 14),
388 geometry: square(-120.001, 35.001, 0.0008),
389 name: None,
390 id: tilecodec::mamaps::body::ID_NONE,
391 transit_color: 0,
392 transit_ordinal: 0,
393 transit_lanes: 0,
394 transit_taper: 0,
395 lane_count: 0,
396 turn_fwd: Vec::new(),
397 turn_bwd: Vec::new(),
398 building: Some(BuildingAttrs::default()),
399 carriageway: tilecodec::mamaps::body::Carriageway::default(),
400 };
401 let (bytes, _) = build(&spilled(&[building]), &settings(14, 14)).expect("build");
402 for (_, _, body) in &tilecodec::mamaps::read::read_all(&bytes).expect("read") {
403 let body = Body::parse(body).expect("parse");
404 if body.layer(dict::LAYER_BUILDINGS).is_some() {
405 assert!(
406 body.buildings.is_empty(),
407 "an all-default building tile must not carry a building table",
408 );
409 }
410 }
411 }
412
413 include!("tiler_part7_s1.rs");
414}