maps: carry vertex significance through the clip, so tiles agree
- Commit
7712a4a0b29c22e333cdf0fa6d4463b3c5fec7ec- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 23:04 UTC (3 months ago)
- Parents
cb5e85c
Diff
scripts/maps/tile_build/src/clip.rs
diff --git a/scripts/maps/tile_build/src/clip.rs b/scripts/maps/tile_build/src/clip.rsindex c947c75403..90df5181fa 100644--- a/scripts/maps/tile_build/src/clip.rs+++ b/scripts/maps/tile_build/src/clip.rs@@ -17,10 +17,22 @@ //! It clips against each of the four half-planes in turn, and it is exact for a //! convex polygon. For a **concave** polygon whose clipped result is two or more //! disjoint pieces, it returns a single ring joined by a degenerate sliver running-//! along the boundary: zero area, so it renders correctly, but it is one ring-//! where a strict result would be two. Splitting them requires a general polygon-//! clipper (Vatti or Greiner-Hormann), which is a large piece of work for a defect-//! that is invisible at render time. Documented here rather than pretended away.+//! along the boundary. That sliver has zero area, so a scanline rasteriser fills+//! the right pixels, but it is one ring where a strict result would be two, and+//! that is not free: earcut cannot triangulate a self-touching ring reliably (see+//! `library/map/src/main/rust/src/tess/fill.rs`), so the renderer is left doing+//! the repair. Splitting them requires a general polygon clipper (Vatti or+//! Greiner-Hormann), which is a large piece of work. Documented here rather than+//! pretended away.+//!+//! ## Clip-introduced vertices are never removed+//!+//! A crossing this module interpolates is not in the source, so no annotation pass+//! measured it: it comes out of [`crate::geom::Vertex::boundary`] with significance+//! [`crate::geom::ALWAYS`]. That is what holds an exterior and a hole that both+//! reach the same tile edge to the same vertices along it. Thinning those two+//! coincident edges independently is what used to push a hole out through its own+//! exterior. //! //! ## The `NaN` question //!@@ -31,18 +43,21 @@ //! so they should not arise, but the clipper is the last place that can still tell //! the difference between "outside" and "unknown". -use crate::geom::{Geometry, Pt, Rect};+use crate::geom::{Geometry, Pt, Rect, Vertex}; /// Clip a geometry to `rect`, in the same coordinate space as the input. /// /// Points are kept or dropped whole; lines are partitioned; polygon rings are /// clipped into new rings. Parts that vanish entirely are removed, so an empty /// result means the geometry does not touch the rect at all.-pub fn clip_geometry(g: &Geometry, rect: &Rect) -> Geometry {+pub fn clip_geometry<V: Vertex>(g: &Geometry<V>, rect: &Rect) -> Geometry<V> { match g {- Geometry::Points(pts) => {- Geometry::Points(pts.iter().copied().filter(|p| finite(*p) && rect.contains(*p)).collect())- }+ Geometry::Points(pts) => Geometry::Points(+ pts.iter()+ .copied()+ .filter(|p| finite(*p) && rect.contains(p.xy()))+ .collect(),+ ), Geometry::Lines(lines) => { let mut out = Vec::new(); for line in lines {@@ -63,7 +78,8 @@ pub fn clip_geometry(g: &Geometry, rect: &Rect) -> Geometry { } } -fn finite((x, y): Pt) -> bool {+fn finite<V: Vertex>(v: V) -> bool {+ let (x, y) = v.xy(); x.is_finite() && y.is_finite() } @@ -72,9 +88,9 @@ fn finite((x, y): Pt) -> bool { /// Consecutive segments that survive the clip and still meet are welded back into /// one output line; a gap starts a new one. That is what makes the result a /// partition of the original rather than a bag of segments.-pub fn clip_line(line: &[Pt], rect: &Rect) -> Vec<Vec<Pt>> {- let mut out: Vec<Vec<Pt>> = Vec::new();- let mut current: Vec<Pt> = Vec::new();+pub fn clip_line<V: Vertex>(line: &[V], rect: &Rect) -> Vec<Vec<V>> {+ let mut out: Vec<Vec<V>> = Vec::new();+ let mut current: Vec<V> = Vec::new(); for w in line.windows(2) { let (a, b) = (w[0], w[1]);@@ -96,7 +112,10 @@ pub fn clip_line(line: &[Pt], rect: &Rect) -> Vec<Vec<Pt>> { } } Some((ca, cb)) => {- if current.last() == Some(&ca) {+ // By position, not by vertex: the near end of this segment and the+ // far end of the last are the same place but need not be the same+ // vertex -- one may be a source vertex and the other a crossing.+ if current.last().map(|v| v.xy()) == Some(ca.xy()) { current.push(cb); } else { if current.len() > 1 {@@ -123,23 +142,28 @@ pub fn clip_line(line: &[Pt], rect: &Rect) -> Vec<Vec<Pt>> { /// each of the four boundaries; the segment is outside as soon as the interval /// closes. ///+/// An endpoint the interval did not move is returned as itself, significance and+/// all; an endpoint it did move is a new vertex on the boundary.+/// /// A non-finite endpoint is `None`. Every comparison below would be false for a /// `NaN`, so it would fall through as "inside" and emit a `NaN` intersection.-pub fn clip_segment(a: Pt, b: Pt, rect: &Rect) -> Option<(Pt, Pt)> {+pub fn clip_segment<V: Vertex>(a: V, b: V, rect: &Rect) -> Option<(V, V)> { if !finite(a) || !finite(b) { return None; }- let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let (ax, ay) = a.xy();+ let (bx, by) = b.xy();+ let (dx, dy) = (bx - ax, by - ay); let mut t0 = 0.0f64; let mut t1 = 1.0f64; // Each boundary is `p * t <= q`, where p is the direction component and q the // distance to the boundary. for &(p, q) in &[- (-dx, a.0 - rect.min_x),- (dx, rect.max_x - a.0),- (-dy, a.1 - rect.min_y),- (dy, rect.max_y - a.1),+ (-dx, ax - rect.min_x),+ (dx, rect.max_x - ax),+ (-dy, ay - rect.min_y),+ (dy, rect.max_y - ay), ] { if p == 0.0 { // Parallel to this boundary: inside iff already on the right side.@@ -167,9 +191,10 @@ pub fn clip_segment(a: Pt, b: Pt, rect: &Rect) -> Option<(Pt, Pt)> { } } }+ let at = |t: f64| (ax + t * dx, ay + t * dy); Some((- (a.0 + t0 * dx, a.1 + t0 * dy),- (a.0 + t1 * dx, a.1 + t1 * dy),+ if t0 == 0.0 { a } else { V::boundary(at(t0)) },+ if t1 == 1.0 { b } else { V::boundary(at(t1)) }, )) } @@ -179,8 +204,8 @@ pub fn clip_segment(a: Pt, b: Pt, rect: &Rect) -> Option<(Pt, Pt)> { /// disappears the whole polygon does, holes included: a hole with no surrounding /// area is not a shape, and emitting one would render as a solid patch of the /// wrong colour.-pub fn clip_polygon(rings: &[Vec<Pt>], rect: &Rect) -> Vec<Vec<Pt>> {- let mut out: Vec<Vec<Pt>> = Vec::new();+pub fn clip_polygon<V: Vertex>(rings: &[Vec<V>], rect: &Rect) -> Vec<Vec<V>> {+ let mut out: Vec<Vec<V>> = Vec::new(); for (i, ring) in rings.iter().enumerate() { let clipped = clip_ring(ring, rect); if clipped.len() < 3 {@@ -197,12 +222,14 @@ pub fn clip_polygon(rings: &[Vec<Pt>], rect: &Rect) -> Vec<Vec<Pt>> { /// Sutherland-Hodgman: clip one ring against the four boundaries in turn. /// /// The caller's closure convention is preserved: an explicitly closed ring-/// (first == last) is normalised on the way in and re-closed on the way out, and-/// an unclosed one stays unclosed. Fewer than three distinct vertices out means-/// the ring did not survive.-pub fn clip_ring(ring: &[Pt], rect: &Rect) -> Vec<Pt> {- let was_closed = ring.len() > 1 && ring.first() == ring.last();- let open: Vec<Pt> = ring[..ring.len() - usize::from(was_closed)]+/// (first == last) is normalised on the way in and re-closed on the way out with a+/// **copy of the surviving first vertex**, so the two carry the same significance+/// and no later filter can open the ring by keeping one and dropping the other. An+/// unclosed ring stays unclosed. Fewer than three distinct vertices out means the+/// ring did not survive.+pub fn clip_ring<V: Vertex>(ring: &[V], rect: &Rect) -> Vec<V> {+ let was_closed = ring.len() > 1 && ring.first().map(|v| v.xy()) == ring.last().map(|v| v.xy());+ let open: Vec<V> = ring[..ring.len() - usize::from(was_closed)] .iter() .copied() .filter(|p| finite(*p))@@ -221,28 +248,28 @@ pub fn clip_ring(ring: &[Pt], rect: &Rect) -> Vec<Pt> { if current.len() < 3 { return Vec::new(); }- let mut next: Vec<Pt> = Vec::with_capacity(current.len() + 4);+ let mut next: Vec<V> = Vec::with_capacity(current.len() + 4); for i in 0..current.len() { let a = current[(i + current.len() - 1) % current.len()]; let b = current[i];- let (a_in, b_in) = (edge.inside(a), edge.inside(b));+ let (a_in, b_in) = (edge.inside(a.xy()), edge.inside(b.xy())); if b_in { // Entering: the crossing comes first, then the vertex itself. if !a_in {- next.push(edge.intersect(a, b));+ next.push(V::boundary(edge.intersect(a.xy(), b.xy()))); } next.push(b); } else if a_in { // Leaving: only the crossing.- next.push(edge.intersect(a, b));+ next.push(V::boundary(edge.intersect(a.xy(), b.xy()))); } } current = next; } // The clip can put two crossings on the same boundary point.- current.dedup();- if current.len() > 1 && current.first() == current.last() {+ current.dedup_by(|a, b| a.xy() == b.xy());+ if current.len() > 1 && current.first().map(|v| v.xy()) == current.last().map(|v| v.xy()) { current.pop(); } if current.len() < 3 {@@ -459,7 +486,7 @@ mod tests { #[test] fn a_single_vertex_line_yields_nothing() { assert!(clip_line(&[(5.0, 5.0)], &r()).is_empty());- assert!(clip_line(&[], &r()).is_empty());+ assert!(clip_line::<Pt>(&[], &r()).is_empty()); } // --- polygons ----------------------------------------------------------@@ -520,7 +547,7 @@ mod tests { #[test] fn a_degenerate_ring_disappears() {- assert!(clip_ring(&[], &r()).is_empty());+ assert!(clip_ring::<Pt>(&[], &r()).is_empty()); assert!(clip_ring(&[(1.0, 1.0), (2.0, 2.0)], &r()).is_empty()); // A closed ring of two distinct vertices is a line, not an area. assert!(clip_ring(&[(1.0, 1.0), (2.0, 2.0), (1.0, 1.0)], &r()).is_empty());@@ -617,4 +644,53 @@ mod tests { let out = clip_line(&line, &rect); assert!(close(out[0][1], (4096.0 + DEFAULT_BUFFER, 100.0)), "{out:?}"); }++ // --- significance ------------------------------------------------------++ /// Every vertex the clip interpolates is marked as one no threshold may drop,+ /// and every vertex that merely passes through keeps whatever it arrived with.+ /// That is the contract [`crate::simplify::filter`] relies on to keep two rings+ /// sharing a boundary edge on the same vertices.+ #[test]+ fn a_crossing_is_marked_unremovable_and_a_pass_through_keeps_its_significance() {+ use crate::geom::{SigPt, ALWAYS};++ let at = |x: f64, y: f64, sig: f64| SigPt { x, y, sig };+ // In from the west, out to the east: both ends are crossings, the middle+ // vertex is the source's own and keeps its score.+ let line = [at(-5.0, 5.0, 7.0), at(5.0, 5.0, 3.0), at(15.0, 5.0, 9.0)];+ let out = clip_line(&line, &r());+ assert_eq!(out.len(), 1, "{out:?}");+ let piece = &out[0];+ assert_eq!(piece.len(), 3);+ assert_eq!(piece[0], at(0.0, 5.0, ALWAYS), "the western crossing");+ assert_eq!(piece[1], at(5.0, 5.0, 3.0), "untouched, score and all");+ assert_eq!(piece[2], at(10.0, 5.0, ALWAYS), "the eastern crossing");++ // A segment entirely inside is handed back as the very same vertices, not+ // as recomputed ones: `a + 1.0 * (b - a)` is not always `b`.+ let inside = [at(2.0, 2.0, 4.0), at(8.0, 7.0, 6.0)];+ assert_eq!(clip_line(&inside, &r())[0], inside.to_vec());+ }++ /// A ring re-closed after clipping must close on a **copy** of its first+ /// surviving vertex. Two ends with different significance is how a filter opens+ /// a ring: it keeps one and drops the other.+ #[test]+ fn a_re_closed_ring_closes_on_a_copy_of_its_first_vertex() {+ use crate::geom::SigPt;++ let at = |x: f64, y: f64, sig: f64| SigPt { x, y, sig };+ // Half in, half out, so the ring is genuinely rebuilt by the clip.+ let ring = [+ at(5.0, 2.0, 1.0),+ at(15.0, 2.0, 2.0),+ at(15.0, 8.0, 3.0),+ at(5.0, 8.0, 4.0),+ at(5.0, 2.0, 1.0),+ ];+ let out = clip_ring(&ring, &r());+ assert!(out.len() > 3, "{out:?}");+ assert_eq!(out.first(), out.last(), "closed, on the same vertex exactly");+ } }
scripts/maps/tile_build/src/geom.rs
diff --git a/scripts/maps/tile_build/src/geom.rs b/scripts/maps/tile_build/src/geom.rsindex e794f1e4ee..ccf3ff8759 100644--- a/scripts/maps/tile_build/src/geom.rs+++ b/scripts/maps/tile_build/src/geom.rs@@ -5,10 +5,11 @@ //! //! ```text //! lon/lat --project_geometry--> world (tile units x extent, per zoom)+//! world --simplify::annotate-> world (per-vertex significance, in place) //! world --clip::clip_geometry-> world (against one tile's buffered rect)+//! world --simplify::filter----> world (fewer vertices) //! world --translate-----------> tile (origin at the tile's corner) //! tile --quantize------------> integer tile coordinates-//! integer --simplify::simplify--> integer (fewer vertices) //! integer --mvt::encode_*-------> command stream //! ``` //!@@ -38,6 +39,84 @@ pub type Pt = (f64, f64); /// A vertex on the integer tile grid, ready to encode. pub type IPt = (i32, i32); +/// A world-space vertex carrying how much shape it is responsible for.+///+/// `sig` is the squared distance the vertex deviates from the chord+/// [`crate::simplify::annotate`] measured it against, in the same world units as+/// `x` and `y`. It is the whole point of this type: significance is computed+/// **once** on the unclipped source ring and then compared against a per-zoom+/// threshold, so a vertex is kept or dropped identically in every ring and every+/// tile it appears in. Simplifying each clipped ring on its own is what let a+/// hole and the exterior it shared a tile-boundary edge with thin differently and+/// drift apart.+///+/// A named struct rather than a three-wide tuple so the compiler names every site+/// that has to think about the extra field.+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct SigPt {+ pub x: f64,+ pub y: f64,+ pub sig: f64,+}++/// The significance of a vertex no threshold may remove: a path's own endpoints,+/// and every vertex the clipper invents on a tile boundary.+pub const ALWAYS: f64 = f64::INFINITY;++impl SigPt {+ /// A vertex whose significance is not yet known. [`crate::simplify::annotate`]+ /// overwrites this; a vertex it never chooses is genuinely worth nothing and+ /// zero is the right answer.+ pub fn new(x: f64, y: f64) -> SigPt {+ SigPt { x, y, sig: 0.0 }+ }+}++/// A vertex the geometry pipeline can carry: enough to be clipped, translated and+/// quantised without knowing whether it also carries significance.+///+/// [`Pt`] and [`SigPt`] both implement it, which is what lets [`clip`] and the+/// coordinate-only parts of this module be written once and tested on plain pairs.+///+/// [`clip`]: crate::clip+pub trait Vertex: Copy {+ fn xy(self) -> Pt;++ /// The same vertex moved to `to`, keeping everything else about it.+ fn moved(self, to: Pt) -> Self;++ /// A vertex invented at `at`, where an edge crosses a clip boundary.+ ///+ /// It is not in the source, so no annotation pass ever measured it, and+ /// nothing downstream may remove it: it is the only thing holding two rings+ /// that share a boundary edge to the same vertex set.+ fn boundary(at: Pt) -> Self;+}++impl Vertex for Pt {+ fn xy(self) -> Pt {+ self+ }+ fn moved(self, to: Pt) -> Pt {+ to+ }+ fn boundary(at: Pt) -> Pt {+ at+ }+}++impl Vertex for SigPt {+ fn xy(self) -> Pt {+ (self.x, self.y)+ }+ fn moved(self, (x, y): Pt) -> SigPt {+ SigPt { x, y, sig: self.sig }+ }+ fn boundary((x, y): Pt) -> SigPt {+ SigPt { x, y, sig: ALWAYS }+ }+}+ /// Tile-boundary overspill, in extent units at [`DEFAULT_EXTENT`]. /// /// Geometry is clipped to the tile rect grown by this much, so a line crossing a@@ -60,14 +139,18 @@ pub fn buffer_for(extent: u32) -> f64 { /// singular cases removes a whole layer of branching from the clipper and the /// encoders, and MVT itself draws no distinction -- geometry type is per feature, /// not per part.+///+/// `V` is the vertex type: [`Pt`] in lon/lat, which is what a source and a spill+/// record hold, and [`SigPt`] from [`project_geometry`] onwards, where the+/// pipeline needs each vertex's significance. #[derive(Debug, Clone, PartialEq)]-pub enum Geometry {- Points(Vec<Pt>),- Lines(Vec<Vec<Pt>>),+pub enum Geometry<V = Pt> {+ Points(Vec<V>),+ Lines(Vec<Vec<V>>), /// Each polygon is `[exterior, hole, hole, ...]`. Ring orientation is *not* /// significant here; [`crate::mvt::encode_polygons`] derives it from the /// signed area rather than trusting the input.- Polygons(Vec<Vec<Vec<Pt>>>),+ Polygons(Vec<Vec<Vec<V>>>), } /// The integer counterpart of [`Geometry`], always in one tile's coordinates.@@ -138,8 +221,14 @@ pub fn project_scaled(lon: f64, lat: f64, z: u8, extent: u32) -> Pt { } /// Project a whole lon/lat geometry into world coordinates for one zoom.-pub fn project_geometry(g: &Geometry, z: u8, extent: u32) -> Geometry {- let p = |&(lon, lat): &Pt| project_scaled(lon, lat, z, extent);+///+/// The result's vertices carry no significance yet; [`crate::simplify::annotate`]+/// is what fills that in, and it is the next step in the pipeline.+pub fn project_geometry(g: &Geometry, z: u8, extent: u32) -> Geometry<SigPt> {+ let p = |&(lon, lat): &Pt| {+ let (x, y) = project_scaled(lon, lat, z, extent);+ SigPt::new(x, y)+ }; match g { Geometry::Points(pts) => Geometry::Points(pts.iter().map(p).collect()), Geometry::Lines(lines) => {@@ -159,7 +248,7 @@ pub fn project_geometry(g: &Geometry, z: u8, extent: u32) -> Geometry { /// Non-finite vertices are skipped. They should not exist -- [`project`] clamps -- /// but a `NaN` reaching [`tile_range`] would silently produce an empty range, /// and dropping it here at least keeps the rest of the geometry.-pub fn bounds(g: &Geometry) -> Option<Rect> {+pub fn bounds<V: Vertex>(g: &Geometry<V>) -> Option<Rect> { let mut r: Option<Rect> = None; let mut add = |(x, y): Pt| { if !x.is_finite() || !y.is_finite() {@@ -176,9 +265,9 @@ pub fn bounds(g: &Geometry) -> Option<Rect> { }); }; match g {- Geometry::Points(pts) => pts.iter().for_each(|p| add(*p)),- Geometry::Lines(lines) => lines.iter().flatten().for_each(|p| add(*p)),- Geometry::Polygons(polys) => polys.iter().flatten().flatten().for_each(|p| add(*p)),+ Geometry::Points(pts) => pts.iter().for_each(|p| add(p.xy())),+ Geometry::Lines(lines) => lines.iter().flatten().for_each(|p| add(p.xy())),+ Geometry::Polygons(polys) => polys.iter().flatten().flatten().for_each(|p| add(p.xy())), } r }@@ -252,12 +341,19 @@ impl TileRange { /// /// Polygons keep whole-ring boxes: a polygon legitimately covers its interior tiles, /// and per-segment boxes would drop every tile strictly inside the ring.-pub fn tiles_touched(g: &Geometry, z: u8, extent: u32, pad: f64, out: &mut Vec<(u64, u64)>) {+pub fn tiles_touched<V: Vertex>(+ g: &Geometry<V>,+ z: u8,+ extent: u32,+ pad: f64,+ out: &mut Vec<(u64, u64)>,+) { out.clear(); match g { // A point's box is a point; one range call each is already tight. Geometry::Points(pts) => {- for &(x, y) in pts {+ for p in pts {+ let (x, y) = p.xy(); push_box(out, x, y, x, y, z, extent, pad); } }@@ -266,10 +362,13 @@ pub fn tiles_touched(g: &Geometry, z: u8, extent: u32, pad: f64, out: &mut Vec<( match line.as_slice() { [] => {} // A degenerate one-point "line" still occupies a tile.- [(x, y)] => push_box(out, *x, *y, *x, *y, z, extent, pad),+ [p] => {+ let (x, y) = p.xy();+ push_box(out, x, y, x, y, z, extent, pad)+ } _ => { for seg in line.windows(2) {- push_segment(out, seg[0], seg[1], z, extent, pad, 0);+ push_segment(out, seg[0].xy(), seg[1].xy(), z, extent, pad, 0); } } }@@ -282,7 +381,8 @@ pub fn tiles_touched(g: &Geometry, z: u8, extent: u32, pad: f64, out: &mut Vec<( let Some(ext) = rings.first() else { continue }; let mut min = (f64::INFINITY, f64::INFINITY); let mut max = (f64::NEG_INFINITY, f64::NEG_INFINITY);- for &(x, y) in ext {+ for p in ext {+ let (x, y) = p.xy(); if !x.is_finite() || !y.is_finite() { continue; }@@ -414,8 +514,11 @@ pub fn tile_rect(tx: u64, ty: u64, extent: u32, buffer: f64) -> Rect { /// Shift a geometry by `(dx, dy)`. Applied after the clip, with the tile's world /// origin negated, to put the geometry in tile coordinates.-pub fn translate(g: &Geometry, dx: f64, dy: f64) -> Geometry {- let t = |&(x, y): &Pt| (x + dx, y + dy);+pub fn translate<V: Vertex>(g: &Geometry<V>, dx: f64, dy: f64) -> Geometry<V> {+ let t = |v: &V| {+ let (x, y) = v.xy();+ v.moved((x + dx, y + dy))+ }; match g { Geometry::Points(pts) => Geometry::Points(pts.iter().map(t).collect()), Geometry::Lines(lines) => {@@ -432,7 +535,7 @@ pub fn translate(g: &Geometry, dx: f64, dy: f64) -> Geometry { /// Convenience for the two steps that always follow a clip: translate into the /// tile, then round onto the integer grid.-pub fn to_tile(g: &Geometry, tx: u64, ty: u64, extent: u32) -> IntGeometry {+pub fn to_tile<V: Vertex>(g: &Geometry<V>, tx: u64, ty: u64, extent: u32) -> IntGeometry { let e = extent as f64; quantize(&translate(g, -(tx as f64 * e), -(ty as f64 * e))) }@@ -444,7 +547,7 @@ pub fn to_tile(g: &Geometry, tx: u64, ty: u64, extent: u32) -> IntGeometry { /// wasted three bytes that some renderers treat as a degenerate segment. Rings /// keep their explicit closing vertex here; [`crate::mvt::encode_polygons`] /// strips it, since `ClosePath` implies it.-pub fn quantize(g: &Geometry) -> IntGeometry {+pub fn quantize<V: Vertex>(g: &Geometry<V>) -> IntGeometry { match g { Geometry::Points(pts) => IntGeometry::Points(pts.iter().map(round_pt).collect()), Geometry::Lines(lines) => {@@ -459,7 +562,8 @@ pub fn quantize(g: &Geometry) -> IntGeometry { } } -fn round_pt(&(x, y): &Pt) -> IPt {+fn round_pt<V: Vertex>(v: &V) -> IPt {+ let (x, y) = v.xy(); (round_i32(x), round_i32(y)) } @@ -539,7 +643,7 @@ mod tests { bounds(&g), Some(Rect { min_x: -3.0, min_y: 0.0, max_x: 10.0, max_y: 20.0 }) );- assert_eq!(bounds(&Geometry::Points(vec![])), None);+ assert_eq!(bounds(&Geometry::<Pt>::Points(vec![])), None); // A NaN vertex is skipped rather than poisoning the whole box. let g = Geometry::Points(vec![(1.0, 2.0), (f64::NAN, 0.0), (3.0, 4.0)]);
scripts/maps/tile_build/src/lib.rs
diff --git a/scripts/maps/tile_build/src/lib.rs b/scripts/maps/tile_build/src/lib.rsindex 5d6159217a..6d7d5df9b4 100644--- a/scripts/maps/tile_build/src/lib.rs+++ b/scripts/maps/tile_build/src/lib.rs@@ -23,7 +23,8 @@ //! integer tile coordinates out. //! * [`clip`] — Liang-Barsky for lines, Sutherland-Hodgman for polygons, against //! a tile's buffered rect.-//! * [`simplify`] — Douglas-Peucker in integer tile coordinates.+//! * [`simplify`] — Douglas-Peucker once per feature to score every vertex, then+//! a per-zoom threshold on those scores. //! * [`pyramid`] — the tile pyramid driver and the drop policy. //! * [`par`] — the thread budget (`--threads`, `MAPS_THREADS`) and the pool the //! tilers run on. Parallelism never changes an output byte.
scripts/maps/tile_build/src/pyramid.rs
diff --git a/scripts/maps/tile_build/src/pyramid.rs b/scripts/maps/tile_build/src/pyramid.rsindex 837b39633a..ed1de20945 100644--- a/scripts/maps/tile_build/src/pyramid.rs+++ b/scripts/maps/tile_build/src/pyramid.rs@@ -3,8 +3,8 @@ //! Turns a list of lon/lat features into a PMTiles archive: //! //! ```text-//! per zoom, per feature: bounds -> tile range-//! per tile: clip -> to_tile -> simplify -> encode -> drop policy+//! per zoom, per feature: project -> annotate -> tile range+//! per tile: clip -> filter -> to_tile -> encode -> drop policy //! -> gzip -> pmtiles::Builder //! ``` //!@@ -35,11 +35,14 @@ //! push an archive past its own `--maximum-zoom`, so an archive's advertised zoom //! range stops being a fact about its contents. Here `--maxzoom` is exactly the //! deepest zoom present.-//! * **`--detect-shared-borders` is not implemented.** Adjacent admin polygons are-//! simplified independently, so two countries sharing a border can end up with-//! slightly different vertex sets along it. At low zoom that shows as a hairline-//! gap or a hairline overlap. Reproducing it needs a shared topology pass across-//! features, which is a project of its own.+//! * **`--detect-shared-borders` is not implemented.** Two *different* admin+//! polygons that share a border are simplified independently, so at low zoom the+//! border can show as a hairline gap or a hairline overlap. Reproducing that needs+//! a shared topology pass across features, which is a project of its own. The+//! intra-feature case — a hole and the exterior it shares a clipped tile edge with+//! — is not affected: [`crate::simplify`] annotates each vertex once on the+//! unclipped source and filters per zoom, so both rings keep the same vertices+//! along the edge. use crate::clip::clip_geometry; use crate::geom::{self, Geometry, IntGeometry};@@ -234,8 +237,11 @@ fn bucket_feature( ) -> Result<BucketedFeature> { let t0 = std::time::Instant::now(); // Project once per feature per zoom, not once per tile: a coastline can cross- // thousands of tiles and the projection is the expensive part.- let projected = geom::project_geometry(geometry, z, opts.extent);+ // thousands of tiles and the projection is the expensive part. Annotating here+ // for the same reason, and because it has to see the ring UNCLIPPED -- see+ // `simplify`'s module docs.+ let mut projected = geom::project_geometry(geometry, z, opts.extent);+ simplify::annotate(&mut projected); geom::tiles_touched(&projected, z, opts.extent, buffer, touched); let mut out = BucketedFeature { blob: Vec::new(),@@ -244,17 +250,17 @@ fn bucket_feature( for &(tx, ty) in touched.iter() { let rect = geom::tile_rect(tx, ty, opts.extent, buffer); let clipped = clip_geometry(&projected, &rect);- let local = geom::to_tile(&clipped, tx, ty, opts.extent);- let simplified = simplify::simplify(&local, tolerance);- if simplified.is_empty() {+ let filtered = simplify::filter(&clipped, tolerance);+ let local = geom::to_tile(&filtered, tx, ty, opts.extent);+ if local.is_empty() { continue; } rec.clear(); spill::encode_record( pmtiles::tile_id(z, tx, ty), seq,- extent_of(&simplified),- &simplified,+ extent_of(&local),+ &local, props, rec, )?;@@ -301,12 +307,22 @@ pub fn build_archive(features: &[Feature], opts: &Options) -> Result<(Vec<u8>, V let tolerance = simplify::tolerance_for(z, opts.max_zoom, opts.simplification); // Project once per zoom, not once per tile: a coastline can cross thousands- // of tiles and the projection is the expensive part. Per-feature pure, so it- // maps across the pool; `collect` into a Vec keeps it in input order.- let projected: Vec<Option<Geometry>> = par::install(|| {+ // of tiles and the projection is the expensive part. Annotate here too, both+ // for that reason and because significance has to be measured on the+ // UNCLIPPED ring. Per-feature pure, so it maps across the pool; `collect`+ // into a Vec keeps it in input order.+ //+ // Identical to `bucket_feature`'s prologue on purpose: the byte-identity+ // tests compare the two producers, so a step added to one and not the other+ // is a test failure rather than a silent divergence.+ let projected: Vec<Option<Geometry<geom::SigPt>>> = par::install(|| { features .par_iter()- .map(|f| Some(geom::project_geometry(&f.geometry, z, opts.extent)))+ .map(|f| {+ let mut p = geom::project_geometry(&f.geometry, z, opts.extent);+ simplify::annotate(&mut p);+ Some(p)+ }) .collect() }); @@ -348,7 +364,7 @@ pub fn build_archive(features: &[Feature], opts: &Options) -> Result<(Vec<u8>, V let indices = &by_tile[&(tx, ty)]; let rect = geom::tile_rect(tx, ty, opts.extent, buffer); - // Clip, move into the tile, simplify. Anything that vanishes+ // Clip, thin, move into the tile. Anything that vanishes // here never reached the tile in the first place, so it is not // a "drop". let mut placed: Vec<(usize, i64, IntGeometry)> =@@ -356,12 +372,12 @@ pub fn build_archive(features: &[Feature], opts: &Options) -> Result<(Vec<u8>, V for &i in indices { let p = projected[i].as_ref().expect("filtered above"); let clipped = clip_geometry(p, &rect);- let local = geom::to_tile(&clipped, tx, ty, opts.extent);- let simplified = simplify::simplify(&local, tolerance);- if simplified.is_empty() {+ let filtered = simplify::filter(&clipped, tolerance);+ let local = geom::to_tile(&filtered, tx, ty, opts.extent);+ if local.is_empty() { continue; }- placed.push((i, extent_of(&simplified), simplified));+ placed.push((i, extent_of(&local), local)); } if placed.is_empty() { return Ok(None);@@ -1788,6 +1804,173 @@ mod tests { assert!(mvt::signed_area(&rings[0][1]) < 0, "interior negative"); } + /// A z6 tile spans `360/64 = 5.625` degrees of longitude, so `-123.75` is+ /// exactly the edge between tile x 9 and tile x 10. Everything below is built+ /// around that so a fixture can be made to straddle a real tile boundary+ /// without having to invert the projection.+ const Z6_TILE_EDGE_LON: f64 = -123.75;++ /// A polygon whose exterior **and** hole both cross [`Z6_TILE_EDGE_LON`], with+ /// enough sub-tolerance jitter along every edge that filtering has something to+ /// remove on both sides of the boundary.+ ///+ /// One z6 extent unit is `5.625 / 4096` degrees, about `0.00137`, so the jitter+ /// below is a third of a unit: under the 1-unit tolerance, and therefore exactly+ /// the detail a coarse zoom is supposed to drop.+ fn straddling_polygon() -> Feature {+ let jitter = |i: usize| (i % 5) as f64 * 0.0005;+ let ring = |west: f64, east: f64, south: f64, north: f64| {+ let mut r: Vec<(f64, f64)> = Vec::new();+ let (w, h) = (east - west, north - south);+ for i in 0..=200 {+ let t = i as f64 / 200.0;+ r.push((west + w * t, south + jitter(i)));+ }+ for i in 0..=20 {+ let t = i as f64 / 20.0;+ r.push((east - jitter(i), south + h * t));+ }+ for i in 0..=200 {+ let t = i as f64 / 200.0;+ r.push((east - w * t, north - jitter(i)));+ }+ for i in 0..=20 {+ let t = i as f64 / 20.0;+ r.push((west + jitter(i), north - h * t));+ }+ r.push(r[0]);+ r+ };+ let e = Z6_TILE_EDGE_LON;+ Feature {+ geometry: Geometry::Polygons(vec![vec![+ ring(e - 2.25, e + 2.75, 36.0, 40.0),+ ring(e - 1.25, e + 1.75, 37.0, 39.0),+ ]]),+ props: vec![("name".to_string(), Value::String("straddler".into()))],+ }+ }++ /// Crossing-number point-in-ring, with a point on the ring counting as inside.+ ///+ /// Integer throughout, and `i64` for the cross products: two `i32` spans+ /// multiply to 62 bits, so containment is decided exactly rather than nearly.+ fn in_ring(ring: &[(i32, i32)], p: (i32, i32)) -> bool {+ let n = ring.len();+ let mut inside = false;+ for i in 0..n {+ let (ax, ay) = ring[i];+ let (bx, by) = ring[(i + 1) % n];+ let cross = (bx as i64 - ax as i64) * (p.1 as i64 - ay as i64)+ - (by as i64 - ay as i64) * (p.0 as i64 - ax as i64);+ if cross == 0+ && p.0 >= ax.min(bx)+ && p.0 <= ax.max(bx)+ && p.1 >= ay.min(by)+ && p.1 <= ay.max(by)+ {+ return true;+ }+ if (ay > p.1) != (by > p.1) {+ let d = by as i64 - ay as i64;+ let u = d * (p.0 as i64 - ax as i64);+ let t = (p.1 as i64 - ay as i64) * (bx as i64 - ax as i64);+ if (d > 0) == (u < t) {+ inside = !inside;+ }+ }+ }+ inside+ }++ /// The invariant the whole annotate-then-filter design exists to hold: a hole+ /// that crossed a tile boundary is still inside its exterior once the tile has+ /// been built.+ ///+ /// A hole straddling its exterior is not something earcut can express, so the+ /// renderer has to drop it (`library/map/src/main/rust/src/tess/fill.rs`) and the+ /// island or lake fills in solid. Simplifying each clipped ring on its own is+ /// what used to produce them, so this asserts on the built archive rather than+ /// on any one stage.+ #[test]+ fn a_hole_crossing_a_tile_boundary_stays_inside_its_exterior() {+ // maxzoom above the zoom under test, so z6 is genuinely being thinned:+ // `tolerance_for` spares only the deepest zoom.+ let (bytes, _) =+ build_archive(&[straddling_polygon()], &Options::new("land", 6, 7)).unwrap();+ let a = Archive::parse(&bytes).unwrap();++ let mut checked = 0;+ for (id, raw) in a.iter_tiles().unwrap() {+ let (z, _, _) = pmtiles::tile_zxy(id);+ let tile = Tile::decode(&crate::gz::decompress(raw).unwrap()).unwrap();+ let f = &tile.layer("land").unwrap().features[0];+ for rings in mvt::decode_polygons(&f.geometry).expect("polygon geometry") {+ let (exterior, holes) = rings.split_first().expect("an exterior");+ for hole in holes {+ for &p in hole {+ assert!(+ in_ring(exterior, p),+ "z{z} tile {id}: hole vertex {p:?} escaped its exterior"+ );+ }+ checked += 1;+ }+ }+ }+ assert!(checked > 0, "the fixture produced no holes to check");+ }++ /// Two tiles that overlap must agree, vertex for vertex, on the geometry inside+ /// the overlap. They clip the same annotated source and threshold it the same+ /// way, so the only thing that can make them disagree is thinning a clipped ring+ /// against its own endpoints -- which is what a seam at a tile join looks like.+ ///+ /// The comparison is over the band strictly inside BOTH buffered rects: the+ /// crossings each tile's own clip introduced sit exactly on the edge of that+ /// band and belong to one tile only.+ #[test]+ fn two_adjacent_tiles_agree_on_the_geometry_they_share() {+ let (bytes, _) =+ build_archive(&[straddling_polygon()], &Options::new("land", 6, 7)).unwrap();+ let a = Archive::parse(&bytes).unwrap();++ let extent = DEFAULT_EXTENT;+ let buffer = geom::buffer_for(extent);+ let (edge_tile_x, _) = geom::project(Z6_TILE_EDGE_LON, 0.0, 6);+ let edge = edge_tile_x * extent as f64;+ let east_tx = edge_tile_x as u64;+ // The straddling polygon covers lat 36..40, which at z6 is one tile row.+ let ty = geom::project(0.0, 38.0, 6).1.floor() as u64;++ // Every vertex of the feature, in WORLD coordinates, that lies strictly+ // inside both tiles' buffered rects.+ let shared = |tx: u64| -> Vec<(i64, i64)> {+ let tile = a+ .tile(6, tx, ty)+ .unwrap()+ .map(|b| Tile::decode(&b).unwrap())+ .unwrap_or_else(|| panic!("a tile at z6/{tx}/{ty}"));+ let f = &tile.layer("land").unwrap().features[0];+ let ox = tx as i64 * extent as i64;+ let mut out: Vec<(i64, i64)> = mvt::decode_polygons(&f.geometry)+ .expect("polygon geometry")+ .into_iter()+ .flatten()+ .flatten()+ .map(|(x, y)| (x as i64 + ox, y as i64))+ .filter(|&(x, _)| ((x as f64) - edge).abs() < buffer)+ .collect();+ out.sort_unstable();+ out+ };++ let west = shared(east_tx - 1);+ let east = shared(east_tx);+ assert!(!west.is_empty(), "the fixture reaches neither side of the edge");+ assert_eq!(west, east, "the two tiles disagree inside their overlap");+ }+ #[test] fn a_feature_spanning_several_tiles_appears_in_each_of_them() { // A line across most of California at z6 lands in more than one tile.
scripts/maps/tile_build/src/simplify.rs
diff --git a/scripts/maps/tile_build/src/simplify.rs b/scripts/maps/tile_build/src/simplify.rsindex 7fcf89129d..08ce6d4978 100644--- a/scripts/maps/tile_build/src/simplify.rs+++ b/scripts/maps/tile_build/src/simplify.rs@@ -1,30 +1,52 @@-//! Douglas-Peucker simplification, in integer tile coordinates.+//! Simplification, in two halves: annotate once, then filter per zoom. //!-//! Runs **after** the clip, so it only ever sees vertices already inside a tile's-//! buffered rect. That ordering matters: simplifying first and clipping second-//! would let a removed vertex change where an edge crosses the tile boundary, and-//! two adjacent tiles would disagree about the crossing point.+//! [`annotate`] runs Douglas-Peucker **once** over each unclipped source ring or+//! line and records, on every vertex, how much shape that vertex is responsible+//! for. [`filter`] then keeps a vertex when its significance clears the zoom's+//! threshold. This is geojson-vt's design, and it is here for one reason: //!-//! ## Why integers+//! ## Why not Douglas-Peucker per tile //!-//! The output is going straight into an MVT command stream, which is integer. Any-//! precision the algorithm preserves below one unit is discarded moments later, so-//! working in floats would only add rounding differences between runs. Distances-//! are compared **squared**, in `i128`, so there is no square root and no overflow:-//! a buffered coordinate fits in `i32`, and the cross product of two such spans-//! needs 64 bits before it is squared.+//! [`crate::clip::clip_polygon`] clips each ring of a polygon on its own, so a hole+//! that crossed a tile edge ends up sharing an edge **exactly** with the clipped+//! exterior along the tile boundary. Running Douglas-Peucker on each ring+//! afterwards anchors each at its own first and last vertex -- positions that have+//! nothing to do with each other between two rings -- so those two coincident+//! edges get thinned differently and move apart by up to a unit. The hole then+//! straddles or escapes its exterior, earcut cannot express that, and the renderer+//! has no choice but to drop the hole: every affected island and lake fills in+//! solid.+//!+//! Annotating first fixes it by construction. A vertex's significance is a property+//! of the vertex, not of the ring it is being simplified inside, so it is kept or+//! dropped consistently in every ring and every tile it appears in. Vertices the+//! clipper invents on the boundary carry [`crate::geom::ALWAYS`], so a clipped ring+//! is never re-simplified along the edge it was cut at.+//!+//! ## Why annotating once is enough+//!+//! [`crate::geom::project`] is a pure scale by `2^z`, so every perpendicular+//! distance at one zoom is the same constant multiple of the distance at another:+//! significance is scale-invariant, and the zoom only picks the threshold. That is+//! also why the annotation pass uses the tolerance at `max_zoom`, which+//! [`tolerance_for`] defines as zero -- full recursion, so every vertex receives+//! its true significance rather than only those above some floor.+//!+//! It is also cheaper than what it replaces: once per feature per zoom instead of+//! once per feature per **tile**. //! //! ## Rings have two extra rules //!-//! * **Closure is preserved.** The first and last vertex of a closed ring are both-//! anchors, so the ring cannot be opened by simplification.+//! * **Closure is preserved.** A closed ring is filtered without its explicit+//! closing vertex and re-closed with a copy of whichever vertex survived first,+//! so the two can never disagree. //! * **A ring never drops below four vertices**, i.e. three distinct corners plus //! the repeated close. Fewer than that encloses no area, and an MVT polygon with //! a two-vertex ring is a renderer's problem rather than a small one. When-//! simplification would go that far the **ring is dropped instead**, and if that-//! ring was the exterior the whole polygon goes with it. Keeping a collapsed-//! sliver would paint a hairline in the layer's fill colour, which is worse than-//! the feature being absent at that zoom.+//! filtering would go that far the **ring is dropped instead**, and if that ring+//! was the exterior the whole polygon goes with it. Keeping a collapsed sliver+//! would paint a hairline in the layer's fill colour, which is worse than the+//! feature being absent at that zoom. //! //! ## The tolerance policy is ours, not tippecanoe's //!@@ -36,7 +58,7 @@ //! documented policy rather than a reproduction of `--simplification`, and the //! tests assert the policy's own invariants -- never equality with tippecanoe. -use crate::geom::{IPt, IntGeometry};+use crate::geom::{Geometry, SigPt, Vertex, ALWAYS}; /// Simplification tolerance at [`crate::mvt::DEFAULT_EXTENT`], in extent units. ///@@ -60,30 +82,50 @@ pub fn tolerance_for(z: u8, max_zoom: u8, multiplier: f64) -> f64 { } } -/// Simplify every part of a geometry.+/// Record every vertex's significance, in place, on an unclipped geometry.+///+/// Must run **before** the clip: the whole point is that a vertex is measured+/// against its neighbours in the source, not against wherever a tile boundary+/// happened to cut the ring.+///+/// Points are left alone. There is nothing in a point to remove, and thinning a+/// point layer is the drop policy's job.+pub fn annotate(g: &mut Geometry<SigPt>) {+ match g {+ Geometry::Points(_) => {}+ Geometry::Lines(lines) => lines.iter_mut().for_each(|l| annotate_path(l)),+ Geometry::Polygons(polys) => polys+ .iter_mut()+ .flatten()+ .for_each(|ring| annotate_path(ring)),+ }+}++/// Keep the vertices whose significance clears `tolerance`. ///-/// Points pass through: there is nothing in a point to remove, and dropping one-/// would silently thin a layer that the drop policy is supposed to own.-pub fn simplify(g: &IntGeometry, tolerance: f64) -> IntGeometry {+/// A pure filter: no vertex is measured, moved or invented here, which is what+/// makes two rings that share an edge agree along it.+pub fn filter(g: &Geometry<SigPt>, tolerance: f64) -> Geometry<SigPt> { if tolerance <= 0.0 { return g.clone(); }+ let tol_sq = tolerance * tolerance; match g {- IntGeometry::Points(_) => g.clone(),- IntGeometry::Lines(lines) => IntGeometry::Lines(+ Geometry::Points(_) => g.clone(),+ Geometry::Lines(lines) => Geometry::Lines( lines .iter()- .map(|l| simplify_line(l, tolerance))+ .map(|l| filter_line(l, tol_sq)) .filter(|l| l.len() >= 2) .collect(), ),- IntGeometry::Polygons(polys) => IntGeometry::Polygons(+ Geometry::Polygons(polys) => Geometry::Polygons( polys .iter() .filter_map(|rings| {- let mut out: Vec<Vec<IPt>> = Vec::with_capacity(rings.len());+ let mut out: Vec<Vec<SigPt>> = Vec::with_capacity(rings.len()); for (i, ring) in rings.iter().enumerate() {- match simplify_ring(ring, tolerance) {+ match filter_ring(ring, tol_sq) { Some(r) => out.push(r), // The exterior collapsing takes the holes with it. None if i == 0 => return None,@@ -97,118 +139,157 @@ pub fn simplify(g: &IntGeometry, tolerance: f64) -> IntGeometry { } } -/// Douglas-Peucker on an open polyline. The endpoints are always kept.-pub fn simplify_line(line: &[IPt], tolerance: f64) -> Vec<IPt> {- if line.len() < 3 || tolerance <= 0.0 {- return line.to_vec();- }- let tol_sq = (tolerance * tolerance) as i128;- let mut keep = vec![false; line.len()];- keep[0] = true;- keep[line.len() - 1] = true;- mark(line, 0, line.len() - 1, tol_sq, &mut keep);- line.iter()- .zip(&keep)- .filter(|(_, k)| **k)- .map(|(p, _)| *p)- .collect()+/// Filter an open polyline. Its endpoints carry [`ALWAYS`] -- either from+/// [`annotate`], or from the clipper having put them on a tile boundary -- so they+/// survive without a special case for them.+pub fn filter_line(line: &[SigPt], tol_sq: f64) -> Vec<SigPt> {+ line.iter().copied().filter(|v| v.sig > tol_sq).collect() } -/// Douglas-Peucker on a ring, or `None` when the result would enclose no area.+/// Filter a ring, or `None` when the result would enclose no area. ///-/// A closed ring (first == last) stays closed. An unclosed one stays unclosed, and+/// A closed ring (first == last) stays closed; an unclosed one stays unclosed, and /// its floor is one lower since it has no repeated vertex.-pub fn simplify_ring(ring: &[IPt], tolerance: f64) -> Option<Vec<IPt>> {- let closed = ring.len() > 1 && ring.first() == ring.last();+pub fn filter_ring(ring: &[SigPt], tol_sq: f64) -> Option<Vec<SigPt>> {+ let closed = ring.len() > 1 && ring.first().map(|v| v.xy()) == ring.last().map(|v| v.xy()); let floor = if closed { MIN_RING_VERTICES } else { MIN_RING_VERTICES - 1 }; if ring.len() < floor { return None; }- if tolerance <= 0.0 {- return Some(ring.to_vec());- }-- // Running Douglas-Peucker over the closed ring works because the chord from- // the first vertex to the last is degenerate, so `perp_dist_sq` falls back to- // point-to-point distance and picks the vertex furthest from the start. That- // splits the ring into two arcs, each of which then simplifies normally.- let simplified = simplify_line(ring, tolerance);- if simplified.len() < floor {+ // The closing vertex is not filtered on its own: re-closing with a copy of the+ // surviving first vertex is what makes it impossible to open the ring.+ let open = &ring[..ring.len() - usize::from(closed)];+ let mut out: Vec<SigPt> = open.iter().copied().filter(|v| v.sig > tol_sq).collect();+ if out.len() + usize::from(closed) < floor { return None; }- // Belt and braces: closure is what `keep[len-1] = true` guarantees, but a- // polygon that silently opened would be a rendering bug nothing else catches.- if closed && simplified.first() != simplified.last() {- return None;+ if closed {+ out.push(out[0]); }- Some(simplified)+ Some(out) } -/// Mark the vertices Douglas-Peucker keeps between two anchors.+/// Run Douglas-Peucker to exhaustion over one path, writing each vertex's+/// significance as it goes.+///+/// The path's own two ends are [`ALWAYS`]: a line must keep its endpoints, and for+/// a closed ring the two ends are the same place, so anchoring both is what keeps+/// the ring closed.+fn annotate_path(pts: &mut [SigPt]) {+ let Some(last) = pts.len().checked_sub(1) else { return };+ pts[0].sig = ALWAYS;+ pts[last].sig = ALWAYS;+ if pts.len() < 3 {+ return;+ }+ mark(pts, 0, last);+}++/// Measure every vertex between two anchors and recurse into both halves. /// /// Iterative rather than recursive: a coastline ring can be hundreds of thousands /// of vertices, and the recursion depth is only bounded by the data.-fn mark(pts: &[IPt], first: usize, last: usize, tol_sq: i128, keep: &mut [bool]) {+///+/// There is no tolerance here -- recursion continues while any vertex is off the+/// chord at all, which is [`tolerance_for`] at `max_zoom` and is what gives every+/// vertex its true significance rather than a lower bound on it. A vertex that is+/// exactly on every chord it is ever measured against keeps significance zero and+/// is dropped by any non-zero threshold, which is correct: it carries no shape.+fn mark(pts: &mut [SigPt], first: usize, last: usize) { let mut stack = vec![(first, last)]; while let Some((a, b)) = stack.pop() { if b <= a + 1 { continue; }- let mut worst = 0i128;+ let mut worst = 0.0f64; let mut worst_i = a; for i in (a + 1)..b {- let d = perp_dist_sq(pts[i], pts[a], pts[b]);+ let d = seg_dist_sq(pts[i], pts[a], pts[b]); if d > worst { worst = d; worst_i = i; } }- if worst > tol_sq {- keep[worst_i] = true;+ if worst > 0.0 {+ pts[worst_i].sig = worst; stack.push((a, worst_i)); stack.push((worst_i, b)); } } } -/// Squared distance from `p` to the segment `a -> b`.+/// Squared distance from `p` to the **segment** `a -> b`. ///-/// A zero-length chord degrades to point-to-point distance, which is what makes-/// the closed-ring case work.-fn perp_dist_sq(p: IPt, a: IPt, b: IPt) -> i128 {- let (dx, dy) = ((b.0 - a.0) as i128, (b.1 - a.1) as i128);- let (px, py) = ((p.0 - a.0) as i128, (p.1 - a.1) as i128);+/// The segment, not the infinite line it lies on. The two agree wherever the foot+/// of the perpendicular is between the endpoints, which is the only case an open+/// polyline's first pass produces -- but a closed ring's first chord is degenerate+/// (`a == b`), and past that the chords are arbitrary, so a vertex beyond an+/// endpoint would otherwise be scored by a perpendicular that misses the segment+/// entirely. This is geojson-vt's `getSqSegDist`.+fn seg_dist_sq(p: SigPt, a: SigPt, b: SigPt) -> f64 {+ let (mut x, mut y) = (a.x, a.y);+ let (dx, dy) = (b.x - x, b.y - y); let len_sq = dx * dx + dy * dy;- if len_sq == 0 {- return px * px + py * py;- }- // Distance from the infinite line, not the segment: Douglas-Peucker measures- // deviation from the chord, and both endpoints are anchors anyway.- let cross = px * dy - py * dx;- // cross^2 / len_sq, kept as an integer division. Truncating biases the- // comparison very slightly towards dropping a vertex, which is the safe- // direction: it can never keep a vertex that is genuinely below tolerance.- (cross * cross) / len_sq+ if len_sq > 0.0 {+ let t = ((p.x - x) * dx + (p.y - y) * dy) / len_sq;+ if t > 1.0 {+ x = b.x;+ y = b.y;+ } else if t > 0.0 {+ x += dx * t;+ y += dy * t;+ }+ }+ let (dx, dy) = (p.x - x, p.y - y);+ dx * dx + dy * dy } #[cfg(test)] mod tests { use super::*;+ use crate::geom::Pt;++ /// Annotate a path and hand back the vertices a tolerance keeps, as plain pairs.+ fn thin(pts: &[Pt], tolerance: f64) -> Vec<Pt> {+ let mut g = line_of(pts);+ annotate(&mut g);+ let Geometry::Lines(out) = filter(&g, tolerance) else { panic!() };+ match out.first() {+ Some(l) => l.iter().map(|v| v.xy()).collect(),+ None => Vec::new(),+ }+ }++ fn line_of(pts: &[Pt]) -> Geometry<SigPt> {+ Geometry::Lines(vec![pts.iter().map(|&(x, y)| SigPt::new(x, y)).collect()])+ }++ fn ring_of(pts: &[Pt]) -> Vec<SigPt> {+ pts.iter().map(|&(x, y)| SigPt::new(x, y)).collect()+ }++ /// Annotate one ring on its own and filter it, as the polygon path would.+ fn thin_ring(pts: &[Pt], tolerance: f64) -> Option<Vec<Pt>> {+ let mut ring = ring_of(pts);+ annotate_path(&mut ring);+ filter_ring(&ring, tolerance * tolerance)+ .map(|r| r.iter().map(|v| v.xy()).collect())+ } #[test] fn a_collinear_run_collapses_to_its_endpoints() {- let line = vec![(0, 0), (10, 0), (20, 0), (30, 0), (40, 0)];- assert_eq!(simplify_line(&line, 1.0), vec![(0, 0), (40, 0)]);+ let line = [(0.0, 0.0), (10.0, 0.0), (20.0, 0.0), (30.0, 0.0), (40.0, 0.0)];+ assert_eq!(thin(&line, 1.0), vec![(0.0, 0.0), (40.0, 0.0)]); } #[test] fn a_deviation_above_tolerance_is_kept_and_below_is_dropped() { // The middle vertex sits 5 units off the chord.- let line = vec![(0, 0), (50, 5), (100, 0)];- assert_eq!(simplify_line(&line, 1.0), line, "5 > 1, so it stays");+ let line = [(0.0, 0.0), (50.0, 5.0), (100.0, 0.0)];+ assert_eq!(thin(&line, 1.0), line.to_vec(), "5 > 1, so it stays"); assert_eq!(- simplify_line(&line, 10.0),- vec![(0, 0), (100, 0)],+ thin(&line, 10.0),+ vec![(0.0, 0.0), (100.0, 0.0)], "5 < 10, so it goes" ); }@@ -216,23 +297,26 @@ mod tests { #[test] fn endpoints_are_never_removed() { // Even a line whose interior is entirely within tolerance keeps its ends.- let line = vec![(0, 0), (1, 0), (2, 0), (100, 0)];- let out = simplify_line(&line, 50.0);- assert_eq!(out.first(), Some(&(0, 0)));- assert_eq!(out.last(), Some(&(100, 0)));- assert!(out.len() >= 2);+ let line = [(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (100.0, 0.0)];+ let out = thin(&line, 50.0);+ assert_eq!(out.first(), Some(&(0.0, 0.0)));+ assert_eq!(out.last(), Some(&(100.0, 0.0)));+ assert_eq!(out.len(), 2); } #[test]- fn simplification_is_monotonic_in_the_tolerance() {+ fn thinning_is_monotonic_in_the_tolerance() { // A zigzag of decreasing amplitude: a larger tolerance must never keep more // vertices than a smaller one.- let line: Vec<IPt> = (0..40)- .map(|i| (i * 10, if i % 2 == 0 { 40 - i } else { -(40 - i) }))+ let line: Vec<Pt> = (0..40)+ .map(|i| {+ let a = (40 - i) as f64;+ ((i * 10) as f64, if i % 2 == 0 { a } else { -a })+ }) .collect(); let mut prev = usize::MAX; for tol in [0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0] {- let n = simplify_line(&line, tol).len();+ let n = thin(&line, tol).len(); assert!( n <= prev, "tolerance {tol} kept {n} vertices, more than the {prev} before it"@@ -240,15 +324,15 @@ mod tests { prev = n; } // And the extremes behave.- assert_eq!(simplify_line(&line, 0.0), line, "no tolerance, no change");- assert_eq!(simplify_line(&line, 1e9).len(), 2, "everything but the ends");+ assert_eq!(thin(&line, 0.0), line, "no tolerance, no change");+ assert_eq!(thin(&line, 1e9).len(), 2, "everything but the ends"); } #[test]- fn simplification_never_adds_a_vertex_or_reorders_them() {- let line: Vec<IPt> = (0..50).map(|i| (i * 7, (i * i) % 23)).collect();+ fn thinning_never_adds_a_vertex_or_reorders_them() {+ let line: Vec<Pt> = (0..50).map(|i| ((i * 7) as f64, ((i * i) % 23) as f64)).collect(); for tol in [1.0, 3.0, 9.0] {- let out = simplify_line(&line, tol);+ let out = thin(&line, tol); assert!(out.len() <= line.len()); // The output is a subsequence of the input. let mut it = line.iter();@@ -258,92 +342,174 @@ mod tests { } } + /// The property the whole design exists for. Two rings that share an edge --+ /// which is what a clip against a tile boundary produces -- must agree on it+ /// vertex for vertex after filtering, whatever else happens to either ring.+ #[test]+ fn a_vertex_shared_between_two_rings_is_kept_or_dropped_in_both() {+ use crate::clip::clip_polygon;+ use crate::geom::Rect;++ let rect = Rect { min_x: 0.0, min_y: 0.0, max_x: 100.0, max_y: 100.0 };+ // An exterior and a hole that both hang out over the eastern boundary, so+ // the clip gives them a shared run of vertices along x = 100.+ let exterior: Vec<Pt> = vec![+ (10.0, 10.0),+ (150.0, 10.0),+ (150.0, 90.0),+ (10.0, 90.0),+ (10.0, 10.0),+ ];+ let hole: Vec<Pt> = vec![+ (40.0, 30.0),+ (150.0, 30.0),+ (150.0, 70.0),+ (40.0, 70.0),+ (40.0, 30.0),+ ];+ let mut g = Geometry::Polygons(vec![vec![ring_of(&exterior), ring_of(&hole)]]);+ annotate(&mut g);+ let Geometry::Polygons(polys) = &g else { panic!() };+ let clipped = clip_polygon(&polys[0], &rect);+ assert_eq!(clipped.len(), 2, "exterior and hole both survive the clip");++ // Every vertex the clip put on the eastern boundary appears in both rings.+ let on_edge = |rings: &Vec<Vec<SigPt>>| -> Vec<Pt> {+ rings+ .iter()+ .flatten()+ .map(|v| v.xy())+ .filter(|(x, _)| *x == 100.0)+ .collect()+ };+ for tol in [0.5, 1.0, 8.0, 64.0] {+ let g = Geometry::Polygons(vec![clipped.clone()]);+ let Geometry::Polygons(out) = filter(&g, tol) else { panic!() };+ let kept = on_edge(&out[0]);+ let before = on_edge(&vec![clipped[0].clone(), clipped[1].clone()]);+ assert_eq!(+ kept, before,+ "tolerance {tol} moved a boundary vertex: {kept:?} vs {before:?}"+ );+ }+ }++ /// Clip-introduced vertices carry `ALWAYS`, so no tolerance can remove them --+ /// which is the only thing holding two clipped rings to the same boundary edge.+ #[test]+ fn boundary_vertices_survive_the_coarsest_tolerance() {+ use crate::clip::clip_ring;+ use crate::geom::Rect;++ let rect = Rect { min_x: 0.0, min_y: 0.0, max_x: 10.0, max_y: 10.0 };+ let mut ring = ring_of(&[(-5.0, -5.0), (15.0, -5.0), (15.0, 15.0), (-5.0, 15.0), (-5.0, -5.0)]);+ annotate_path(&mut ring);+ let clipped = clip_ring(&ring, &rect);+ // Every surviving vertex is a crossing the clipper invented.+ assert!(clipped.iter().all(|v| v.sig == ALWAYS), "{clipped:?}");+ let out = filter_ring(&clipped, 1e18).expect("nothing to drop");+ assert_eq!(out.len(), clipped.len());+ }+ #[test] fn a_closed_ring_stays_closed() { // A square with a redundant midpoint on each side.- let ring = vec![- (0, 0),- (50, 0),- (100, 0),- (100, 50),- (100, 100),- (50, 100),- (0, 100),- (0, 50),- (0, 0),+ let ring = [+ (0.0, 0.0),+ (50.0, 0.0),+ (100.0, 0.0),+ (100.0, 50.0),+ (100.0, 100.0),+ (50.0, 100.0),+ (0.0, 100.0),+ (0.0, 50.0),+ (0.0, 0.0), ];- let out = simplify_ring(&ring, 1.0).expect("a square survives");+ let out = thin_ring(&ring, 1.0).expect("a square survives"); assert_eq!(out.first(), out.last(), "closure preserved"); assert_eq!(out.len(), 5, "four corners plus the close: {out:?}"); } #[test] fn an_unclosed_ring_stays_unclosed() {- let ring = vec![(0, 0), (50, 0), (100, 0), (100, 100), (0, 100)];- let out = simplify_ring(&ring, 1.0).unwrap();+ let ring = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];+ let out = thin_ring(&ring, 1.0).unwrap(); assert_ne!(out.first(), out.last()); assert_eq!(out.len(), 4, "the collinear midpoint goes: {out:?}"); } #[test] fn a_ring_is_dropped_rather_than_collapsed_below_four_vertices() {- // A very thin sliver: at a large tolerance every interior vertex is within- // tolerance of the chord, so Douglas-Peucker would leave 2 vertices. That- // encloses no area, so the ring must be dropped instead.- let ring = vec![(0, 0), (500, 1), (1000, 0), (500, -1), (0, 0)];- assert_eq!(simplify_ring(&ring, 1000.0), None, "a collapsed ring is dropped");+ // A very thin sliver: at a large tolerance every vertex but the two ends is+ // sub-tolerance, which leaves 2 and encloses no area. Drop it instead.+ let ring = [(0.0, 0.0), (500.0, 1.0), (1000.0, 0.0), (500.0, -1.0), (0.0, 0.0)];+ assert_eq!(thin_ring(&ring, 1000.0), None, "a collapsed ring is dropped"); // At a tolerance it can actually survive, it does.- assert!(simplify_ring(&ring, 0.5).is_some());+ assert!(thin_ring(&ring, 0.5).is_some()); } #[test] fn a_ring_that_is_already_too_small_is_rejected() {- assert_eq!(simplify_ring(&[], 1.0), None);- assert_eq!(simplify_ring(&[(0, 0)], 1.0), None);- assert_eq!(simplify_ring(&[(0, 0), (1, 1)], 1.0), None);+ assert_eq!(thin_ring(&[], 1.0), None);+ assert_eq!(thin_ring(&[(0.0, 0.0)], 1.0), None);+ assert_eq!(thin_ring(&[(0.0, 0.0), (1.0, 1.0)], 1.0), None); // Closed, but only two distinct vertices.- assert_eq!(simplify_ring(&[(0, 0), (1, 1), (0, 0)], 1.0), None);+ assert_eq!(thin_ring(&[(0.0, 0.0), (1.0, 1.0), (0.0, 0.0)], 1.0), None); // The minimum viable closed ring, at zero tolerance.- assert!(simplify_ring(&[(0, 0), (10, 0), (0, 10), (0, 0)], 0.0).is_some());+ let tri = [(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (0.0, 0.0)];+ assert!(thin_ring(&tri, 0.0).is_some()); } #[test] fn a_ring_at_the_floor_is_dropped_only_when_it_is_below_tolerance() {- // Four vertices is the floor, but Douglas-Peucker can still remove the two- // interior ones -- the ring is a line from ring[0] back to ring[0], so both- // corners are measured against a degenerate chord. Whether it survives is- // therefore a question about its size, not its vertex count.- let ring = vec![(0, 0), (1000, 0), (0, 1000), (0, 0)];- assert_eq!(simplify_ring(&ring, 1.0), Some(ring.clone()), "1000 units across, 1 unit tolerance");- assert_eq!(simplify_ring(&ring, 1e9), None, "sub-tolerance, so dropped not collapsed");+ // Four vertices is the floor, but filtering can still remove the two+ // interior ones: whether the ring survives is a question about its size,+ // not its vertex count.+ let ring = [(0.0, 0.0), (1000.0, 0.0), (0.0, 1000.0), (0.0, 0.0)];+ assert_eq!(+ thin_ring(&ring, 1.0),+ Some(ring.to_vec()),+ "1000 units across, 1 unit tolerance"+ );+ assert_eq!(thin_ring(&ring, 1e9), None, "sub-tolerance, so dropped not collapsed"); } #[test] fn the_geometry_entry_point_drops_lines_that_fall_below_two_vertices() {- // simplify_line always keeps both ends, so a 2-vertex line survives; the- // filter exists for a degenerate 1-vertex input.- let g = IntGeometry::Lines(vec![- vec![(0, 0), (10, 0), (20, 0)],- vec![(5, 5)],+ let mut g = Geometry::Lines(vec![+ ring_of(&[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0)]),+ ring_of(&[(5.0, 5.0)]), ]);- let IntGeometry::Lines(out) = simplify(&g, 1.0) else { panic!() };+ annotate(&mut g);+ let Geometry::Lines(out) = filter(&g, 1.0) else { panic!() }; assert_eq!(out.len(), 1);- assert_eq!(out[0], vec![(0, 0), (20, 0)]);+ assert_eq!(+ out[0].iter().map(|v| v.xy()).collect::<Vec<_>>(),+ vec![(0.0, 0.0), (20.0, 0.0)]+ ); } #[test] fn losing_the_exterior_ring_drops_the_whole_polygon() { // A 1000x2 sliver and a 100000-unit square, at a 1000-unit tolerance: the // sliver is entirely sub-tolerance and the square is nowhere near it.- let sliver = vec![(0, 0), (500, 1), (1000, 0), (500, -1), (0, 0)];- let fat = vec![(0, 0), (100_000, 0), (100_000, 100_000), (0, 100_000), (0, 0)];+ let sliver = [(0.0, 0.0), (500.0, 1.0), (1000.0, 0.0), (500.0, -1.0), (0.0, 0.0)];+ let fat = [+ (0.0, 0.0),+ (100_000.0, 0.0),+ (100_000.0, 100_000.0),+ (0.0, 100_000.0),+ (0.0, 0.0),+ ]; // Exterior collapses: the polygon goes, hole and all.- let g = IntGeometry::Polygons(vec![vec![sliver.clone(), fat.clone()]]);- let IntGeometry::Polygons(out) = simplify(&g, 1000.0) else { panic!() };+ let mut g = Geometry::Polygons(vec![vec![ring_of(&sliver), ring_of(&fat)]]);+ annotate(&mut g);+ let Geometry::Polygons(out) = filter(&g, 1000.0) else { panic!() }; assert!(out.is_empty(), "{out:?}"); // A hole collapsing leaves the exterior intact.- let g = IntGeometry::Polygons(vec![vec![fat, sliver]]);- let IntGeometry::Polygons(out) = simplify(&g, 1000.0) else { panic!() };+ let mut g = Geometry::Polygons(vec![vec![ring_of(&fat), ring_of(&sliver)]]);+ annotate(&mut g);+ let Geometry::Polygons(out) = filter(&g, 1000.0) else { panic!() }; assert_eq!(out.len(), 1); assert_eq!(out[0].len(), 1, "the hole was dropped, the exterior kept"); }@@ -351,15 +517,17 @@ mod tests { #[test] fn points_pass_through_untouched() { // Thinning points is the drop policy's job, not simplification's.- let g = IntGeometry::Points(vec![(0, 0), (1, 1), (2, 2), (3, 3)]);- assert_eq!(simplify(&g, 1e9), g);+ let mut g = Geometry::Points(ring_of(&[(0.0, 0.0), (1.0, 1.0), (2.0, 2.0)]));+ annotate(&mut g);+ assert_eq!(filter(&g, 1e9), g); } #[test] fn a_zero_tolerance_is_the_identity() {- let g = IntGeometry::Lines(vec![vec![(0, 0), (1, 0), (2, 0), (3, 0)]]);- assert_eq!(simplify(&g, 0.0), g);- assert_eq!(simplify(&g, -1.0), g, "a negative tolerance is not a licence");+ let mut g = line_of(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0)]);+ annotate(&mut g);+ assert_eq!(filter(&g, 0.0), g);+ assert_eq!(filter(&g, -1.0), g, "a negative tolerance is not a licence"); } #[test]@@ -371,13 +539,53 @@ mod tests { } #[test]- fn the_distance_maths_does_not_overflow_at_the_coordinate_extremes() {- // A span of the full i32 range, squared, needs more than 64 bits. If this- // panics in debug or wraps in release, the comparison is meaningless.- let big = i32::MAX / 2;- let d = perp_dist_sq((0, big), (-big, 0), (big, 0));- assert!(d > 0, "{d}");- assert_eq!(perp_dist_sq((5, 5), (0, 0), (0, 0)), 50, "degenerate chord");- assert_eq!(perp_dist_sq((5, 0), (0, 0), (10, 0)), 0, "on the chord");+ fn the_distance_is_to_the_segment_not_the_line_it_lies_on() {+ let p = |x: f64, y: f64| SigPt::new(x, y);+ // Beyond `b`: the perpendicular to the infinite line would say 0.+ assert_eq!(seg_dist_sq(p(20.0, 0.0), p(0.0, 0.0), p(10.0, 0.0)), 100.0);+ assert_eq!(seg_dist_sq(p(-5.0, 0.0), p(0.0, 0.0), p(10.0, 0.0)), 25.0);+ // Between them, it is the perpendicular.+ assert_eq!(seg_dist_sq(p(5.0, 3.0), p(0.0, 0.0), p(10.0, 0.0)), 9.0);+ assert_eq!(seg_dist_sq(p(5.0, 0.0), p(0.0, 0.0), p(10.0, 0.0)), 0.0);+ // A degenerate chord, which is what a closed ring's first pass measures+ // against, is point-to-point.+ assert_eq!(seg_dist_sq(p(5.0, 5.0), p(0.0, 0.0), p(0.0, 0.0)), 50.0);+ }++ #[test]+ fn significance_is_scale_invariant() {+ // The same shape at two scales must rank its vertices the same way, which is+ // what lets one annotation pass serve every zoom.+ let shape: Vec<Pt> = vec![+ (0.0, 0.0),+ (10.0, 3.0),+ (20.0, 1.0),+ (30.0, 12.0),+ (40.0, 2.0),+ (50.0, 0.0),+ ];+ let mut small = line_of(&shape);+ let mut big = line_of(&shape.iter().map(|(x, y)| (x * 8.0, y * 8.0)).collect::<Vec<_>>());+ annotate(&mut small);+ annotate(&mut big);+ let sig = |g: &Geometry<SigPt>| -> Vec<f64> {+ let Geometry::Lines(l) = g else { panic!() };+ l[0].iter().map(|v| v.sig).collect()+ };+ for (a, b) in sig(&small).iter().zip(sig(&big)) {+ if a.is_finite() {+ assert!((b - a * 64.0).abs() < 1e-9, "{a} scaled to {b}, not {}", a * 64.0);+ } else {+ assert!(b.is_infinite());+ }+ }+ // And a threshold scaled with them keeps the same vertices.+ let kept = |g: &Geometry<SigPt>, tol: f64| -> usize {+ let Geometry::Lines(l) = filter(g, tol) else { panic!() };+ l[0].len()+ };+ for tol in [0.5, 1.0, 2.0, 4.0] {+ assert_eq!(kept(&small, tol), kept(&big, tol * 8.0), "at tolerance {tol}");+ } } }