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

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

tiler_part2.rs578 lines · 27.4 KiBRaw
1fn read_chunks(
2 store: &Store,
3 z: u8,
4 send: std::sync::mpsc::SyncSender<(usize, Vec<Feature>)>,
5) -> Result<()> {
6 // Ordered parallel producer: dedicated decode threads (never the rayon pool)
7 // pull contiguous spill chunks, resequenced by file index before batching.
8 // ZoomReader already parallelises decode on dedicated spill lanes; here we
9 // add an outer sequencer that decodes in parallel batches and reorders.
10 let total_wanted = store.wanted_len_for_zoom(z);
11 if total_wanted == 0 {
12 return Ok(());
13 }
14 // For small zooms the serial path is faster than threading overhead.
15 if total_wanted < 256 {
16 let mut reader =
17 store.reader_for_zoom(z).map_err(|e| tile_build::proto::Error(e.to_string()))?;
18 let want = chunk_vertices();
19 let mut chunk: Vec<Feature> = Vec::new();
20 let mut vertices = 0usize;
21 let mut index = 0usize;
22 let (_, total) = reader.chunks();
23 let mut bar = Progress::new(format!("Map z{z}"), total, "chunk(s)", true);
24 let mut ticked = 0usize;
25 loop {
26 let next = reader.next().map_err(|e| tile_build::proto::Error(e.to_string()))?;
27 let (done, _) = reader.chunks();
28 while ticked < done {
29 bar.tick("chunk(s)");
30 ticked += 1;
31 }
32 let Some(feature) = next else { break };
33 vertices += vertex_count(&feature.geometry);
34 chunk.push(feature);
35 if vertices >= want {
36 if send.send((index, std::mem::take(&mut chunk))).is_err() {
37 return Ok(());
38 }
39 index += 1;
40 vertices = 0;
41 }
42 }
43 if !chunk.is_empty() {
44 let _ = send.send((index, chunk));
45 }
46 bar.finish("chunk(s)");
47 return Ok(());
48 }
49 // Bounded k-way merge: 4 dedicated decode lanes stream per-feature in
50 // file order with backpressure; peak ~ O(lanes × CHUNK_VERTICES) not O(zoom).
51 // Each lane's channel is bounded (depth 2), so decodes block rather than
52 // buffering the whole zoom. We k-way merge by feature position via sequential
53 // lane draining in round-robin file order, emitting CHUNK_VERTICES batches
54 // incrementally and dropping features after send.
55 let want = chunk_vertices();
56 let lanes = 4usize.min(total_wanted.div_ceil(64));
57 let wanted_per_lane = total_wanted.div_ceil(lanes.max(1));
58 let wanted = store.wanted_chunks_for_zoom(z);
59 let mut lane_wanted: Vec<Vec<usize>> = vec![Vec::new(); lanes];
60 for (i, &c) in wanted.iter().enumerate() {
61 let lane = (i / wanted_per_lane).min(lanes - 1);
62 lane_wanted[lane].push(c);
63 }
64 let store_path = store.path().to_path_buf();
65 let store_chunks = store.raw_chunks().to_vec();
66 let store_mins = store.chunk_mins_cloned();
67 let store_anon = store.anon_store();
68 // Bounded per-lane channels: each lane streams its features in order.
69 // Cap 12 blocks (×64 feats) per lane keeps decode threads fed without
70 // buffering the whole zoom; peak O(lanes×cap×block) is MB-scale.
71 const LANE_CAP_BLOCKS: usize = 12;
72 let lane_channels: Vec<(
73 std::sync::mpsc::SyncSender<Option<Vec<Feature>>>,
74 std::sync::mpsc::Receiver<Option<Vec<Feature>>>,
75 )> = (0..lanes)
76 .map(|_| std::sync::mpsc::sync_channel::<Option<Vec<Feature>>>(LANE_CAP_BLOCKS))
77 .collect();
78 let (sends, recvs): (Vec<_>, Vec<_>) = lane_channels.into_iter().unzip();
79 let first_err: Mutex<Option<String>> = Mutex::new(None);
80 let block_features: usize = 64; // one spill chunk worth
81 std::thread::scope(|scope| {
82 let mut handles = Vec::new();
83 for (lane, w) in lane_wanted.into_iter().enumerate() {
84 let path = store_path.clone();
85 let chunks = store_chunks.clone();
86 let chunk_mins = store_mins.clone();
87 let anon = store_anon.clone();
88 let first_err = &first_err;
89 let send_lane = sends[lane].clone();
90 let h = std::thread::Builder::new()
91 .name(format!("mamaps-decode-{lane}"))
92 .spawn_scoped(scope, move || {
93 let store_view =
94 crate::store::Store::view_over(path, chunks, chunk_mins, anon);
95 let mut r = match store_view.reader_for_wanted(w, z) {
96 Ok(r) => r,
97 Err(e) => {
98 let mut g = first_err.lock().unwrap();
99 if g.is_none() {
100 *g = Some(e.to_string());
101 }
102 let _ = send_lane.send(None);
103 return;
104 }
105 };
106 let mut block: Vec<Feature> = Vec::with_capacity(block_features);
107 loop {
108 match r.next() {
109 Ok(Some(f)) => {
110 block.push(f);
111 if block.len() >= block_features {
112 if send_lane.send(Some(std::mem::take(&mut block))).is_err() {
113 return;
114 }
115 block = Vec::with_capacity(block_features);
116 }
117 }
118 Ok(None) => break,
119 Err(e) => {
120 let mut g = first_err.lock().unwrap();
121 if g.is_none() {
122 *g = Some(e.to_string());
123 }
124 break;
125 }
126 }
127 }
128 if !block.is_empty() {
129 let _ = send_lane.send(Some(block));
130 }
131 let _ = send_lane.send(None);
132 });
133 match h {
134 Ok(handle) => handles.push(handle),
135 Err(e) => {
136 let mut g = first_err.lock().unwrap();
137 if g.is_none() {
138 *g = Some(format!("cannot start decode lane {lane}: {e}"));
139 }
140 }
141 }
142 }
143 // Drop sends so lanes see close on early abort.
144 drop(sends);
145 // Bounded k-way merge: lanes emit contiguous spill blocks in ascending
146 // file-index order; we drain them round-robin in that same order, but
147 // with bounded channels the merge holds at most one block per lane.
148 // Because partitioning is contiguous, iterating lanes 0..N and for each
149 // lane draining its next block in order yields exact file order without
150 // a heap: lane 0's first blocks are globally first, then lane 1, etc.
151 // Backpressure comes from bounded per-lane channels + downstream send
152 // bounded (workers*2) — decode threads block when we don't drain.
153 let mut bar = Progress::new(format!("Map z{z}"), total_wanted, "chunk(s)", true);
154 let mut tiler_chunk: Vec<Feature> = Vec::new();
155 let mut vertices = 0usize;
156 let mut index = 0usize;
157 let mut ticked = 0usize;
158 // Estimate ticks from spill chunks; exact ticks come from progress model.
159 // We tick total_wanted once upfront to match baseline progress semantics.
160 while ticked < total_wanted {
161 bar.tick("chunk(s)");
162 ticked += 1;
163 if ticked >= total_wanted {
164 break;
165 }
166 }
167 let mut lane_done = vec![false; lanes];
168 let mut lane_buffers: Vec<std::collections::VecDeque<Feature>> =
169 (0..lanes).map(|_| std::collections::VecDeque::new()).collect();
170 let mut active_lanes = lanes;
171 // Streaming merge: hold one block per lane, emit in file order lane-by-lane.
172 // Because lanes are contiguous partitions, merge is simply lane 0 fully, then 1, ...
173 // But to keep peak bounded we rotate: fill one block per lane, emit it, loop.
174 // Simpler correct-by-construction: drain lane 0 completely (streaming), then lane 1, etc.
175 // Each lane's stream is already file-ordered; concatenation of drained lanes in lane
176 // index order == global file order. Bounded because we pull one block at a time per lane.
177 'outer: for lane in 0..lanes {
178 loop {
179 let block = recvs[lane].recv();
180 let block = match block {
181 Ok(Some(b)) => b,
182 Ok(None) => {
183 lane_done[lane] = true;
184 active_lanes -= 1;
185 break;
186 }
187 Err(_) => {
188 lane_done[lane] = true;
189 active_lanes -= 1;
190 break;
191 }
192 };
193 for feature in block {
194 vertices += vertex_count(&feature.geometry);
195 tiler_chunk.push(feature);
196 if vertices >= want {
197 if send.send((index, std::mem::take(&mut tiler_chunk))).is_err() {
198 // Unblock lanes by draining
199 for (li, done) in lane_done.iter().enumerate() {
200 if !*done {
201 drop(recvs[li].try_recv());
202 }
203 }
204 return Ok(());
205 }
206 index += 1;
207 vertices = 0;
208 }
209 }
210 // Bounded: after emitting one block's worth, loop pulls next block for this lane.
211 // Other lanes' bounded channels (cap 2) block their decodes until we cycle to them,
212 // but since partitions are contiguous lane 0's blocks are globally first, we must
213 // finish lane 0 before lane 1's blocks are in order — so lane 1 correctly blocks.
214 }
215 if active_lanes == 0 {
216 break 'outer;
217 }
218 let _ = &mut lane_buffers; // suppress unused warning
219 }
220 for h in handles {
221 let _ = h.join();
222 }
223 if !tiler_chunk.is_empty() {
224 let _ = send.send((index, tiler_chunk));
225 }
226 bar.finish("chunk(s)");
227 if let Some(e) = first_err.lock().unwrap().take() {
228 // Surface decode errors after draining so downstream sees failure rather than short archive.
229 // Error already logged; return Err to fail this zoom rather than publish short archive.
230 return Err(tile_build::proto::Error(e));
231 }
232 Ok(())
233 })
234}
235
236/// Take chunks until the reader is finished, tiling each into a map of its own and spilling it.
237///
238/// A panic inside one chunk is **caught and recorded** rather than allowed to unwind, and the loop
239/// keeps draining. That is not defensiveness about a bug that should not happen, it is about the
240/// shape of the failure: a worker that dies with a bounded channel full behind it leaves the reader
241/// blocked on a send nobody will ever take, and at one worker there is nobody else to drain it. So
242/// the bug's symptom would be a 64-core box sitting at 0% forever in the middle of a five-minute
243/// stage, instead of an error naming the zoom. `map_zoom` fails the build on the flag.
244///
245/// The spill write is deliberately **outside** the `catch_unwind`, which wraps [`tile_chunk`] alone.
246/// A failed write records the flag and keeps draining for exactly the same reason a panic does.
247fn tile_chunks(
248 receive: &Mutex<std::sync::mpsc::Receiver<(usize, Vec<Feature>)>>,
249 done: &Mutex<Vec<(usize, ChunkRef, Tally)>>,
250 failed: &std::sync::atomic::AtomicBool,
251 spill: &ChunkSpill,
252 z: u8,
253 tolerance: f64,
254 buffer: f64,
255 country_zooms: &std::collections::HashMap<u64, u8>,
256) {
257 loop {
258 // Held to take a chunk and never while tiling one: the lock covers a pointer move, and the
259 // work either side of it is milliseconds.
260 let next = receive.lock().expect("the chunk queue").recv();
261 let Ok((index, features)) = next else { return };
262 // `AssertUnwindSafe` because everything the closure touches is a local: the chunk map it
263 // builds is thrown away on a panic.
264 let tiled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
265 tile_chunk(&features, z, tolerance, buffer, country_zooms)
266 }));
267 match tiled {
268 Ok((chunk, tally)) => match spill.write_chunk(chunk) {
269 Ok(at) => done.lock().expect("the chunk list").push((index, at, tally)),
270 Err(e) => {
271 eprintln!("ERROR: cannot spill chunk {index} of z{z}: {e}");
272 failed.store(true, Ordering::Relaxed);
273 }
274 },
275 Err(_) => {
276 eprintln!("ERROR: chunk {index} of z{z} panicked while being tiled");
277 failed.store(true, Ordering::Relaxed);
278 }
279 }
280 }
281}
282
283/// Project, simplify and clip one chunk of features into a tile map of its own.
284///
285/// Verbatim the loop this module used to run on the main thread over the whole store, with the
286/// destination private to the caller. Nothing here reads shared state, and that is why the chunk
287/// boundaries cannot change a result: a feature's fate depends on the feature, the zoom and the
288/// tolerance, and on nothing else in the chunk it happens to be in.
289///
290/// The tile loop is a quadtree descent ([`subdivide::subdivide`]), not a pass over every tile the
291/// feature touches. A boundary relation spanning three states used to be clipped in full against
292/// each of its hundreds of thousands of z13 tiles; now it is clipped once per zoom level. Filtering
293/// stays where it was, **before** the descent: significance is measured on the whole geometry, so a
294/// vertex's fate must not depend on which tile it lands in.
295///
296/// `country_zooms` (place id → label start zoom, probe-only) drops a `country` label
297/// below its start zoom before any geometry work: the label is a point, so nothing
298/// downstream would remove it, and carrying it would defeat the gating.
299/// Whether the z14 wash cap is active for this build.
300///
301/// Unconditional: the renderer overzooms wash from z13 (shipped together with
302/// this gate), so gated archives are always safe to publish. (Previously
303/// opt-in via `MAMAPS_WASH_CAP=1` during the renderer-first rollout; the flag
304/// is retired now that both halves ship.)
305///
306/// `pub(crate)` so tests asserting flag-dependent behavior (e.g. the rings
307/// lake test) can branch rather than baking one flag state in.
308pub(crate) fn wash_cap_enabled() -> bool {
309 true
310}
311
312/// Whether a feature is wash dropped at this zoom: z14 landtype areas whose
313/// class is carried at shallower zooms (`min_zoom != max`) are redundant with
314/// the z13 parent tile, which the renderer overzooms. Detail areas
315/// (`min_zoom == 14`: pools, pitches, playgrounds — kinds absent at z13 so
316/// overzoom cannot recover them) and all lines (cheap, high-salience relief
317/// and hydrography cues) survive.
318///
319/// Pure function of (kind, zoom, geometry-type): no geometry work, no shared
320/// state, so chunk/thread boundaries cannot change the answer — the property
321/// `tile_chunk`'s doc comment defends.
322fn is_wash_dropped(feature: &Feature, z: u8) -> bool {
323 wash_cap_enabled() && wash_drops_kind(feature.class.layer, feature.class.area, feature.class.min_zoom, z)
324}
325
326/// The wash-cap predicate without the env gate, so unit tests can pin the
327/// rule without touching process-global state (the `OnceLock` in
328/// `wash_cap_enabled` is set once per test process).
329fn wash_drops_kind(layer: u8, area: bool, min_zoom: u8, z: u8) -> bool {
330 use tilecodec::mamaps::dict;
331 z == crate::DEFAULT_MAX_ZOOM
332 && layer == dict::LAYER_LANDTYPE
333 && area
334 && min_zoom != crate::DEFAULT_MAX_ZOOM
335}
336
337fn tile_chunk(
338 features: &[Feature],
339 z: u8,
340 tolerance: f64,
341 buffer: f64,
342 country_zooms: &std::collections::HashMap<u64, u8>,
343) -> (Chunk, Tally) {
344 let mut tiles: Chunk = BTreeMap::new();
345 let mut tally = Tally::default();
346 // TEMP-PROFILE: per-stage walls inside the map phase. Thread-local (each
347 // worker runs its own `tile_chunk`), summed into the process log at
348 // `map_zoom` end. Removed once the hotspot is measured (CA run).
349 let mut t_project = std::time::Duration::ZERO;
350 let mut t_annotate = std::time::Duration::ZERO;
351 let mut t_filter = std::time::Duration::ZERO;
352 let mut t_subdiv = std::time::Duration::ZERO;
353 for feature in features {
354 // Country label gating: the score (footprint × headcount) decided in stage A
355 // (see `extract_fallback::country_zoom`); this is where it is enforced. A
356 // missing score keeps the schema floor — a missing map entry must never hide
357 // a country. Probe-only (`get`), never iterated, so the archive stays
358 // deterministic; counted as dropped so the report stays honest.
359 if feature.class.layer == tilecodec::mamaps::dict::LAYER_PLACES {
360 if let Some(&start) = country_zooms.get(&feature.id) {
361 if z < start {
362 tally.dropped += 1;
363 continue;
364 }
365 }
366 }
367 // z14 wash cap: wash areas are redundant with the z13 parent (see
368 // `is_wash_dropped`). Before any geometry work, like the gate above.
369 if is_wash_dropped(feature, z) {
370 tally.dropped += 1;
371 continue;
372 }
373 let t = std::time::Instant::now();
374 let mut projected = geom::project_geometry(&feature.geometry, z, EXTENT);
375 t_project += t.elapsed();
376 // Significance first, then filter: computed on the whole geometry so a vertex's fate
377 // does not depend on which tile it lands in.
378 let t = std::time::Instant::now();
379 simplify::annotate(&mut projected);
380 t_annotate += t.elapsed();
381 // Buildings live only at z14, where the policy tolerance is 0.0; the floor below
382 // keeps only collinear midpoints and sub-pixel jaggies — see `tolerance_for_layer`.
383 // Roads take the per-feature floor at z14 (washable classes only).
384 let layer_tolerance = tolerance_for_feature(feature, z, tolerance);
385 let t = std::time::Instant::now();
386 let thinned = simplify::filter(&projected, layer_tolerance);
387 t_filter += t.elapsed();
388 // Near-rectangles digitised by hand gain a cheap varint delta when their edges snap
389 // exactly axis-aligned — see `snap_building_rings`. Survivors only, so the measured
390 // significance above is never stale; a pure function of the feature, so the archive
391 // stays independent of thread count and chunk boundaries. Gated to the one layer that
392 // pays for it, so every other layer's filtered geometry moves without another copy.
393 let thinned = if feature.class.layer == tilecodec::mamaps::dict::LAYER_BUILDINGS {
394 snap_building_rings(&thinned, feature.class.layer)
395 } else {
396 thinned
397 };
398 if is_empty(&thinned) {
399 tally.dropped += 1;
400 continue;
401 }
402 let t = std::time::Instant::now();
403 subdivide::subdivide(&thinned, z, EXTENT, buffer, &mut |tx, ty, clipped| {
404 // The descent prunes on a part surviving at all; this is the stricter test that
405 // decides whether a tile is worth writing, and it stays exactly where it was.
406 if is_empty(clipped) {
407 return;
408 }
409 let local = geom::to_tile(clipped, tx, ty, EXTENT);
410 let layer = tiles
411 .entry((tile_id(z, tx, ty), feature.class.layer))
412 .or_insert_with(|| ChunkEntry::new(feature.class.layer));
413 let added = push(layer, feature, &local);
414 tally.features += added.0;
415 tally.points += added.1;
416 });
417 t_subdiv += t.elapsed();
418 }
419 // TEMP-PROFILE: summed per worker; see `map_zoom` for the fold.
420 // Removed with the probes.
421 tally.profile_add(t_project, t_annotate, t_filter, t_subdiv);
422 (tiles, tally)
423}
424
425/// The tolerance to simplify a layer at: the per-zoom policy, with a floor for buildings
426/// and a multiplier for the boundary wash.
427///
428/// Buildings live only at z14 and up, where [`simplify::tolerance_for`] returns 0.0 — full
429/// detail. Half an extent unit there is ~0.3 m on the ground, sub-pixel on any screen the style
430/// draws at, and only drops what is invisible anyway: exactly-collinear midpoints, whose
431/// significance is 0 and which any non-zero threshold already removes, plus sub-pixel jaggies.
432/// Every other layer keeps the policy tolerance untouched. A coarser global tolerance still wins
433/// (`max`, not replace), and a zero/negative policy for a non-building layer is unchanged.
434///
435/// `boundaries` alone keeps the [`WASH_SIMPLIFICATION`] multiplier: a low-zoom line backdrop.
436/// `landtype` simplifies at 1.5x: natural boundaries (forest edges, shorelines,
437/// farmland) are washes, not navigation geometry — same reasoning as
438/// boundaries, smaller factor because parks and lakes are looked at closer.
439/// Roads and transit curves take the wash below z14: at z13 a 1.5x tolerance
440/// drops sub-10m wiggles (a 2x grid stretch could straighten them) while z14
441/// stays at policy 0.0 — full detail where carriageway/lane alignment lives.
442/// Buildings and the point layers keep 1.0 — navigation geometry and
443/// labels, not a wash.
444///
445/// The prototype at `analysis/mamaps_building_savings.py` estimates this plus the snap below at
446/// ~2% + ~4% of building-tile bytes; buildings are z14-only, 9.76M features, ~20% of the archive.
447fn tolerance_for_layer(layer: u8, z: u8, tolerance: f64) -> f64 {
448 use tilecodec::mamaps::dict;
449 if layer == dict::LAYER_BUILDINGS
450 && z >= crate::schema::buildings::MIN_ZOOM
451 {
452 tolerance.max(BUILDING_TOLERANCE)
453 } else if layer == dict::LAYER_BOUNDARIES {
454 tolerance * WASH_SIMPLIFICATION
455 } else if layer == dict::LAYER_LANDTYPE {
456 // z13 tiles span ~5 km: triple the wash there, keep 1.5x at z14
457 // where parks sit under streets.
458 if z == 13 {
459 tolerance * LANDTYPE_Z13_SIMPLIFICATION
460 } else {
461 tolerance * LANDTYPE_SIMPLIFICATION
462 }
463 } else if z < crate::DEFAULT_MAX_ZOOM
464 && (layer == dict::LAYER_ROADS || layer == dict::LAYER_TRANSIT)
465 {
466 // Below the archive max the policy tolerance is non-zero, so the wash
467 // bites; at z14 policy is 0.0 and 1.5x of zero is zero — crisp.
468 tolerance * WASH_SIMPLIFICATION
469 } else {
470 tolerance
471 }
472}
473
474/// The tolerance for one feature: the layer policy, plus the z14 roads
475/// floor. Washable roads (not arterial, no lanes/split — see `needs_crisp`)
476/// take [`ROAD_DETAIL_FLOOR`] at the archive max, where the layer policy is
477/// 0.0; everything else keeps the layer value untouched.
478fn tolerance_for_feature(feature: &crate::extract::Feature, z: u8, tolerance: f64) -> f64 {
479 use tilecodec::mamaps::dict;
480 let base = tolerance_for_layer(feature.class.layer, z, tolerance);
481 if z == crate::DEFAULT_MAX_ZOOM
482 && feature.class.layer == dict::LAYER_ROADS
483 && !needs_crisp(feature)
484 {
485 base.max(ROAD_DETAIL_FLOOR)
486 } else {
487 base
488 }
489}
490
491/// Snap a building geometry's near-axis-aligned edges to exactly axis-aligned.
492///
493/// Hand-digitised footprints are near-rectangles: edges within [`BUILDING_SNAP`] of horizontal
494/// or vertical snap flat, turning an 8-delta wobble into a repeated constant the varint arena
495/// encodes cheaply. Runs on `SigPt` survivors **after** [`simplify::filter`], via
496/// [`Vertex::moved`] so significance rides along untouched — nothing downstream re-measures.
497/// Only ever called for the buildings layer (the caller gates it); strictly per-edge — never
498/// a corner merge, never a vertex invented or removed — so winding, closure and hole
499/// containment are exactly what the filter left.
500///
501/// Deterministic by construction: a pure function of the ring's coordinates, so two runs tile
502/// identically however features are chunked or threaded — the property
503/// `the_archive_is_identical_however_the_features_are_chunked` defends.
504fn snap_building_rings(geometry: &Geometry<SigPt>, layer: u8) -> Geometry<SigPt> {
505 debug_assert_eq!(layer, tilecodec::mamaps::dict::LAYER_BUILDINGS);
506 match geometry {
507 Geometry::Points(_) | Geometry::Lines(_) => geometry.clone(),
508 Geometry::Polygons(polygons) => Geometry::Polygons(
509 polygons
510 .iter()
511 .map(|rings| rings.iter().map(|ring| snap_building_ring(ring)).collect())
512 .collect(),
513 ),
514 }
515}
516
517/// Snap one ring's near-axis-aligned edges flat, preserving length, order, closure and winding.
518fn snap_building_ring(ring: &[SigPt]) -> Vec<SigPt> {
519 if ring.len() < 2 {
520 return ring.to_vec();
521 }
522 // The explicit close duplicates the first vertex; snapping the closing edge in the same
523 // pass as the rest would compare the duplicate against its twin and average the corner
524 // away. Snap the distinct vertices, then re-close with the surviving first.
525 let closed = ring.len() > 1 && ring.first().map(|v| v.xy()) == ring.last().map(|v| v.xy());
526 let open_len = ring.len() - usize::from(closed);
527 if open_len < 2 {
528 return ring.to_vec();
529 }
530 let open = &ring[..open_len];
531 let mut snapped: Vec<(f64, f64)> = open.iter().map(|v| v.xy()).collect();
532 // Forward pass: each edge votes its dominant direction; a near-horizontal edge levels both
533 // endpoints to their mean y, a near-vertical one to their mean x. Means, not first-wins, so
534 // a shared corner snapped from either side lands identically — the seam property the
535 // annotate-then-filter design exists for.
536 for i in 0..open_len {
537 let j = (i + 1) % open_len;
538 let ((x0, y0), (x1, y1)) = (snapped[i], snapped[j]);
539 let (dx, dy) = ((x1 - x0).abs(), (y1 - y0).abs());
540 if dx <= BUILDING_SNAP && dy > BUILDING_SNAP {
541 // Near-vertical: level x.
542 let x = (x0 + x1) / 2.0;
543 snapped[i].0 = x;
544 snapped[j].0 = x;
545 } else if dy <= BUILDING_SNAP && dx > BUILDING_SNAP {
546 // Near-horizontal: level y.
547 let y = (y0 + y1) / 2.0;
548 snapped[i].1 = y;
549 snapped[j].1 = y;
550 }
551 }
552 let mut out: Vec<SigPt> = open
553 .iter()
554 .zip(snapped)
555 .map(|(v, (x, y))| {
556 // Round onto the building grid: hand jitter (±1 unit) collapses
557 // into repeated constants. Runs here — after the filter, on
558 // survivors only — so measured significance is never stale.
559 let gx = (x / crate::tiler::BUILDING_GRID).round() * crate::tiler::BUILDING_GRID;
560 let gy = (y / crate::tiler::BUILDING_GRID).round() * crate::tiler::BUILDING_GRID;
561 v.moved((gx, gy))
562 })
563 .collect();
564 if closed {
565 out.push(out[0]);
566 }
567 out
568}
569
570/// Input vertices in a geometry, for chunking. Counted rather than estimated, because it is the
571/// number that decides how long a chunk takes.
572fn vertex_count(geometry: &Geometry) -> usize {
573 match geometry {
574 Geometry::Points(points) => points.len(),
575 Geometry::Lines(lines) => lines.iter().map(Vec::len).sum(),
576 Geometry::Polygons(polygons) => polygons.iter().flatten().map(Vec::len).sum(),
577 }
578}