From 1e3fdcf571fe531279429407837916a19cde145b Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 18:56:42 -0600 Subject: [PATCH 1/4] fix(analysis): Clip keeps a valid mask's edges where they are, so neighbours leave no gap --- crates/analysis/src/tools.rs | 59 ++++++++++++++++--- .../overlay-regressions/clip-mask-seam.json | 1 - 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 2c3e9b55ef..3b54e3c721 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2352,9 +2352,13 @@ fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option, cache_bytes: Opti return Ok::<_, String>(ClipMask::NoPolygon); }; let ext = merc_extent(&m); - // Union even one polygon: collapsed rings have no filled area. Keep the original - // bounds too: rounding an edge must not hide a line the boolean overlay clips to it. - let mask = union_all(m.0.iter()); + // A valid mask's edges stay exactly where they are, so it meets its neighbours along those + // they share: a union would round each mask to a grid of its own. Any other is unioned, + // even one polygon: collapsed rings have no filled area. Keep the original bounds too: + // rounding an edge must not hide a line the boolean overlay clips to it. + let valid = geo::CoordsIter::coords_count(&m) <= KEEP_WHOLE_COORDS + && crate::validity::check(Some(&in_plane(&m)), crate::validity::MAX_WORK).problems.is_empty(); + let mask = if valid { m.orient(Direction::Default) } else { union_all(m.0.iter()) }; let ext = ext.union(&merc_extent(&mask)); Ok(if mask.0.is_empty() { ClipMask::NoArea } else { ClipMask::Mask(mask, ext) }) }, @@ -14500,12 +14504,16 @@ mod tests { .filter_map(|r| masks.features[*r].geometry.as_ref().and_then(to_multipolygon)) .collect(); let whole = union_all(polys.iter().flat_map(|m| m.0.iter())); + let as_they_are = MultiPolygon::new(polys.iter().flat_map(|m| m.0.clone()).collect()); let features = &inp.0.0["features"]; let expected: Vec<_> = rows(&inp, &p, "input", features) .into_iter() .filter_map(|r| { let f = &features.features[r]; - let g = part(&dissolved(f.geometry.as_ref()?), &whole, true)?; + let g = f.geometry.as_ref()?; + // A point on a mask's edge is in it, where the union's grid can move the edge off it. + let mask = if matches!(g, Geometry::Point(_) | Geometry::MultiPoint(_)) { &as_they_are } else { &whole }; + let g = part(&dissolved(g), mask, true)?; Some((f.attrs.clone(), g)) }) .collect(); @@ -14808,7 +14816,7 @@ mod tests { for y in [-1e-12, -0.01] { lines.push(Some(Geometry::Line(vec![vec![Coord::new(0.1, y), Coord::new(0.9, y)]])), vec![]); } - let whole = union_all(to_multipolygon(masks.features[0].geometry.as_ref().unwrap()).unwrap().0.iter()); + let whole = to_multipolygon(masks.features[0].geometry.as_ref().unwrap()).unwrap(); let expected: Vec<_> = lines.features.iter().filter_map(|f| part(f.geometry.as_ref().unwrap(), &whole, true)).collect(); // The integer overlay snaps the near line onto the edge, but leaves the far line out. assert_eq!(expected.len(), 1); @@ -16109,7 +16117,35 @@ mod tests { } } - /// A shared diagonal becomes a small positive-area overlap when the mask is normalized. + /// Masks that share an edge leave no gap along it: a triangle over one comes out in one part (#2573). + #[test] + fn clip_leaves_no_gap_between_masks_that_share_an_edge() { + let poly = |pts: &[(f64, f64)]| Geometry::Polygon(vec![vec![pts.iter().map(|&(x, y)| Coord::new(x, y)).collect()]]); + for (feature, one, other) in [ + ( + poly(&[(43.0, 72.28125), (43.2109375, 72.0), (43.0, 72.0), (43.0, 72.28125)]), + poly(&[(43.046875, 72.421875), (43.046875, 72.140625), (42.8359375, 72.140625), (43.046875, 72.421875)]), + poly(&[(42.8359375, 72.140625), (43.375, 72.140625), (42.8359375, 71.859375), (42.8359375, 72.140625)]), + ), + ( + poly(&[(-99.5, 33.5), (-99.0, 33.5), (-99.0, 34.0), (-99.5, 33.5)]), + poly(&[(-99.75, 33.71875), (-99.25, 33.71875), (-99.25, 34.21875), (-99.75, 33.71875)]), + poly(&[(-99.25, 34.21875), (-99.25, 33.28125), (-98.75, 34.21875), (-99.25, 34.21875)]), + ), + ] { + let mut input = Dataset::new("input", GeometryType::Polygon, vec![]); + input.push(Some(feature), vec![]); + let mut masks = Dataset::new("masks", GeometryType::Polygon, vec![]); + masks.push(Some(one), vec![]); + masks.push(Some(other), vec![]); + let m = Map(HashMap::from([("input".into(), input), ("masks".into(), masks)])); + let out = layer(crate::run("clip", &m, &serde_json::json!({"input": "input", "clip": "masks"})).unwrap()); + let Some(Geometry::Polygon(parts)) = &out.features[0].geometry else { panic!("a polygon") }; + assert_eq!(parts.len(), 1, "{parts:?}"); + } + } + + /// A sliver of an overlap along a diagonal is kept and said; a diagonal only shared is no overlap. /// Count kept features once, across workers, without changing their geometry; an ordinary /// partial clip needs no notice. #[test] @@ -16119,7 +16155,16 @@ mod tests { let (x, y, d) = (-89.7, 35.05, 0.01); let tract = poly(&[(x, y), (x + d, y + d), (x - d, y + d), (x, y)]); let town = poly(&[(x, y), (x + d, y + d), (x + 6.0 * d, y - 0.3 * d), (x, y)]); - let mask = union_all(to_multipolygon(&town).unwrap().0.iter()); + let mut touching = Dataset::new("touching", GeometryType::Polygon, vec![]); + touching.push(Some(tract.clone()), vec![]); + let mut beside = Dataset::new("beside", GeometryType::Polygon, vec![]); + beside.push(Some(town), vec![]); + let m = Map(HashMap::from([("touching".into(), touching), ("beside".into(), beside)])); + let r = clip_on(&m, &serde_json::json!({"input": "touching", "clip": "beside"}), Some(1), None).unwrap(); + assert_eq!(r.messages, ["Clip: 0 features kept"]); + let e = 2e-9; + let town = poly(&[(x - e, y), (x + d - e, y + d), (x + 6.0 * d, y - 0.3 * d), (x - e, y)]); + let mask = to_multipolygon(&town).unwrap().orient(Direction::Default); // The old part path keeps this sliver: exactly-zero checks miss it. Keep its coordinates // bit for bit, and count the two output features rather than dropped boundary contacts. let expected = part(&tract, &mask, true).unwrap(); diff --git a/crates/analysis/tests/reference/overlay-regressions/clip-mask-seam.json b/crates/analysis/tests/reference/overlay-regressions/clip-mask-seam.json index d47881ec71..8ab002af11 100644 --- a/crates/analysis/tests/reference/overlay-regressions/clip-mask-seam.json +++ b/crates/analysis/tests/reference/overlay-regressions/clip-mask-seam.json @@ -1,6 +1,5 @@ { "seed": "13714318419105429329", "index": 614, - "known": "gap between rounded clip masks", "case": {"a":[{"type":"Polygon","coordinates":[[[-25.01953125,42.0],[-25.0,41.9833984375],[-25.0,42.0],[-25.01953125,42.0]]]}],"b":[{"type":"Polygon","coordinates":[[[-25.029296875,41.9931640625],[-25.009765625,41.9931640625],[-25.009765625,42.009765625],[-25.029296875,41.9931640625]]]},{"type":"Polygon","coordinates":[[[-25.009765625,42.009765625],[-25.009765625,41.9736328125],[-24.990234375,42.009765625],[-25.009765625,42.009765625]]]}],"tools":["clip"]} } From 2e2e080470c6e6344b702f620b8dd0d02d0f7fe2 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 23:08:26 -0600 Subject: [PATCH 2/4] fix(analysis): Clip's threads allow for checking the masks --- crates/analysis/src/tools.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 3b54e3c721..11132d0dc4 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2312,10 +2312,10 @@ impl MaskCache { } /// [`clip`] on `threads` threads (by the number of items in each step, and the memory each -/// takes, when `None`): the masks are unioned, and each input feature clipped, on their own +/// takes, when `None`): the masks are checked, those that aren't valid unioned, and each input feature clipped, on their own /// (#1252), in batches of [`CLIP_BATCH`] features a thread, and the rows come back in input /// order, as on one thread. A thread's work in progress takes about twice the largest mask's -/// coordinates while the masks are unioned, then twice the largest input feature's, a list of +/// coordinates while the masks are unioned (and what checking one takes), then twice the largest input feature's, a list of /// the masks (or the index's references to them), and the larger of the largest mask and the /// largest size of the masks one feature meets, together (found for each batch first, standing /// for their union); as many threads run as fit, at that much work each, in half the scratch @@ -2340,20 +2340,22 @@ fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option, cache_bytes: Opti rows.iter().filter_map(|&r| ds.features.get(r)?.geometry.as_ref()).map(coord_bytes).max().unwrap_or(0) }; let largest_mask = largest(clip_ds, &mask_rows); - // Each mask is a union: Cancel is looked at, and progress counted, before each. A thread - // holds a mask's polygons and their union. + // Each mask is checked, and unioned unless it is valid: Cancel is looked at, and progress counted, + // before each. A thread holds a mask's polygons and their union, and for one small enough to be + // checked, a copy in the plane and about 100 bytes a coordinate ([`KEEP_WHOLE_COORDS`]). + let checked = largest_mask.min(KEEP_WHOLE_COORDS * std::mem::size_of::()).saturating_mul(8); crate::control::begin(mask_rows.len()); let made = crate::parallel::try_map_on( &mask_rows, - threads_for(mask_rows.len(), largest_mask.saturating_mul(2)), + threads_for(mask_rows.len(), largest_mask.saturating_mul(2).saturating_add(checked)), || (), |_, _, &r| { let Some(m) = clip_ds.features.get(r).and_then(|f| f.geometry.as_ref()).and_then(polygon_of) else { return Ok::<_, String>(ClipMask::NoPolygon); }; let ext = merc_extent(&m); - // A valid mask's edges stay exactly where they are, so it meets its neighbours along those - // they share: a union would round each mask to a grid of its own. Any other is unioned, + // A valid mask's edges stay exactly where they are, so masks that share one leave no gap along + // it: a union would round each to a grid of its own. Any other is unioned, // even one polygon: collapsed rings have no filled area. Keep the original bounds too: // rounding an edge must not hide a line the boolean overlay clips to it. let valid = geo::CoordsIter::coords_count(&m) <= KEEP_WHOLE_COORDS From 157ff242d9ad4d8497232010b7c0484610613555 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 00:17:41 -0600 Subject: [PATCH 3/4] fix(analysis): zones of several parts that are valid keep their edges too, so neighbours leave no gap --- crates/analysis/src/tools.rs | 81 ++++++++++++++++++++++++++++-------- 1 file changed, 63 insertions(+), 18 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 11132d0dc4..ba6ce8bd9d 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2312,10 +2312,11 @@ impl MaskCache { } /// [`clip`] on `threads` threads (by the number of items in each step, and the memory each -/// takes, when `None`): the masks are checked, those that aren't valid unioned, and each input feature clipped, on their own +/// takes, when `None`): the masks are made ready ([`keeps_its_edges`], or a union), and each input +/// feature clipped, on their own /// (#1252), in batches of [`CLIP_BATCH`] features a thread, and the rows come back in input /// order, as on one thread. A thread's work in progress takes about twice the largest mask's -/// coordinates while the masks are unioned (and what checking one takes), then twice the largest input feature's, a list of +/// coordinates while the masks are made ready, and what checking one takes, then twice the largest input feature's, a list of /// the masks (or the index's references to them), and the larger of the largest mask and the /// largest size of the masks one feature meets, together (found for each batch first, standing /// for their union); as many threads run as fit, at that much work each, in half the scratch @@ -2341,26 +2342,21 @@ fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option, cache_bytes: Opti }; let largest_mask = largest(clip_ds, &mask_rows); // Each mask is checked, and unioned unless it is valid: Cancel is looked at, and progress counted, - // before each. A thread holds a mask's polygons and their union, and for one small enough to be - // checked, a copy in the plane and about 100 bytes a coordinate ([`KEEP_WHOLE_COORDS`]). - let checked = largest_mask.min(KEEP_WHOLE_COORDS * std::mem::size_of::()).saturating_mul(8); + // before each. A thread holds a mask's polygons and their union, or what checking one takes. crate::control::begin(mask_rows.len()); let made = crate::parallel::try_map_on( &mask_rows, - threads_for(mask_rows.len(), largest_mask.saturating_mul(2).saturating_add(checked)), + threads_for(mask_rows.len(), largest_mask.saturating_mul(2).saturating_add(edges_check_bytes(largest_mask))), || (), |_, _, &r| { let Some(m) = clip_ds.features.get(r).and_then(|f| f.geometry.as_ref()).and_then(polygon_of) else { return Ok::<_, String>(ClipMask::NoPolygon); }; let ext = merc_extent(&m); - // A valid mask's edges stay exactly where they are, so masks that share one leave no gap along - // it: a union would round each to a grid of its own. Any other is unioned, - // even one polygon: collapsed rings have no filled area. Keep the original bounds too: - // rounding an edge must not hide a line the boolean overlay clips to it. - let valid = geo::CoordsIter::coords_count(&m) <= KEEP_WHOLE_COORDS - && crate::validity::check(Some(&in_plane(&m)), crate::validity::MAX_WORK).problems.is_empty(); - let mask = if valid { m.orient(Direction::Default) } else { union_all(m.0.iter()) }; + // A valid mask keeps its edges. Any other is unioned, even one polygon: collapsed rings have no + // filled area. Keep the original bounds too: rounding an edge must not hide a line the boolean + // overlay clips to it. + let mask = if keeps_its_edges(&m) { m.orient(Direction::Default) } else { union_all(m.0.iter()) }; let ext = ext.union(&merc_extent(&mask)); Ok(if mask.0.is_empty() { ClipMask::NoArea } else { ClipMask::Mask(mask, ext) }) }, @@ -2586,7 +2582,7 @@ fn outside_each( } /// An overlay polygon: its row in the overlay layer, its extent and its polygons in the analysis -/// plane, oriented for the overlay, its parts unioned when it has several (as Clip's mask is). +/// plane, oriented for the overlay, its parts unioned when it has several that aren't valid as they are. struct Zone { row: usize, ext: Extent, @@ -2594,10 +2590,23 @@ struct Zone { } /// A feature's polygons as a mask for the overlay: parts of one feature may overlap, which the -/// overlay can't take as they are, so several are unioned; one polygon is only oriented, so its -/// edges stay exactly where they are. +/// overlay can't take as they are, so several are unioned unless they are valid together; those, and +/// one polygon, are only oriented, so their edges stay exactly where they are. fn mask_of(poly: MultiPolygon) -> MultiPolygon { - if poly.0.len() > 1 { union_all(poly.0.iter()) } else { poly.orient(Direction::Default) } + if poly.0.len() > 1 && !keeps_its_edges(&poly) { union_all(poly.0.iter()) } else { poly.orient(Direction::Default) } +} + +/// Whether the overlay can take a mask's polygons as they are: valid, and few enough to look at +/// ([`KEEP_WHOLE_COORDS`]). A union would round them to a grid of its own, apart from a neighbour's, and +/// leave a gap along an edge they share. +fn keeps_its_edges(m: &MultiPolygon) -> bool { + m.coords_count() <= KEEP_WHOLE_COORDS && crate::validity::check(Some(&in_plane(m)), crate::validity::MAX_WORK).problems.is_empty() +} + +/// What [`keeps_its_edges`] holds at most while it looks at a feature of `largest` bytes of coordinates: +/// a copy in the plane (16 bytes a coordinate) and the check's state (about 100). +fn edges_check_bytes(largest: usize) -> usize { + largest.min(KEEP_WHOLE_COORDS * std::mem::size_of::()).saturating_mul(8) } /// How an overlay tool uses its overlay polygons, for [`overlay_zones_on`]. @@ -2645,7 +2654,10 @@ fn overlay_zones_on<'a>( return Err(format!("'{}' is not a polygon layer", ov.name)); } let zone_rows = each_once(rows(inp, p, k, ov)); - let threads = geometry_threads(zone_rows.len(), threads, || Ok(largest_geometry_bytes(ov, &zone_rows)?.saturating_mul(2)))?; + let threads = geometry_threads(zone_rows.len(), threads, || { + let largest = largest_geometry_bytes(ov, &zone_rows)?; + Ok(largest.saturating_mul(2).saturating_add(edges_check_bytes(largest))) + })?; let made = crate::parallel::try_map_on( &zone_rows, threads, @@ -16147,6 +16159,39 @@ mod tests { } } + /// Zones of several parts that share an edge leave no gap along it either: nothing of a feature + /// across it is left when both are erased (#2573). 644 of 3,000 such pairs left some when each was + /// unioned first. + #[test] + fn zones_of_several_parts_that_share_an_edge_leave_no_gap() { + let mut seed = 11_u64; + let mut rnd = |lo: f64, hi: f64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + lo + (hi - lo) * ((seed >> 11) as f64 / (1u64 << 53) as f64) + }; + for round in 0..100 { + let (x, y, dx, dy) = (rnd(-170.0, 170.0), rnd(-70.0, 70.0), rnd(0.01, 0.3), rnd(-0.1, 0.1)); + let (a, b) = (Coord::new(x, y), Coord::new(x + dx, y + dy)); + // Above the edge and below it, each with a part far from it. + let mut zone = |side: f64| { + let Geometry::Polygon(far) = sq(x + side * rnd(1.0, 3.0), y + side * rnd(1.0, 3.0), 0.1) else { panic!("a polygon") }; + let tip = Coord::new(x + rnd(0.0, dx), y + side * 0.5); + Geometry::Polygon([vec![vec![vec![a, b, tip, a]]], far].concat()) + }; + let mut zones = Dataset::new("zones", GeometryType::Polygon, vec![]); + zones.push(Some(zone(1.0)), vec![]); + zones.push(Some(zone(-1.0)), vec![]); + let w = dx.min(0.05) / 8.0; + let mut input = Dataset::new("input", GeometryType::Polygon, vec![]); + input.push(Some(sq(x + dx / 2.0 - w / 2.0, y + dy / 2.0 - w / 2.0, w)), vec![]); + let m = Map(HashMap::from([("input".into(), input), ("zones".into(), zones)])); + let out = layer(crate::run("erase", &m, &serde_json::json!({"input": "input", "erase": "zones"})).unwrap()); + assert_eq!(out.features.len(), 0, "round {round}: {:?}", out.features.geometry(0)); + } + } + /// A sliver of an overlap along a diagonal is kept and said; a diagonal only shared is no overlap. /// Count kept features once, across workers, without changing their geometry; an ordinary /// partial clip needs no notice. From 1ea4b6827e2c824dfd0a775b566e54ff09f0f41f Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 01:06:47 -0600 Subject: [PATCH 4/4] fix(analysis): only a feature's own polygons keep their edges, not several features' gathered --- crates/analysis/src/tools.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index ba6ce8bd9d..760a4020fe 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2589,11 +2589,16 @@ struct Zone { poly: MultiPolygon, } -/// A feature's polygons as a mask for the overlay: parts of one feature may overlap, which the -/// overlay can't take as they are, so several are unioned unless they are valid together; those, and -/// one polygon, are only oriented, so their edges stay exactly where they are. +/// Polygons as a mask for the overlay: they may overlap, which the overlay can't take as they are, so +/// several are unioned; one polygon is only oriented, so its edges stay exactly where they are. fn mask_of(poly: MultiPolygon) -> MultiPolygon { - if poly.0.len() > 1 && !keeps_its_edges(&poly) { union_all(poly.0.iter()) } else { poly.orient(Direction::Default) } + if poly.0.len() > 1 { union_all(poly.0.iter()) } else { poly.orient(Direction::Default) } +} + +/// One feature's polygons as a zone: as [`mask_of`] gives them, but for several that are valid together, +/// which keep their edges too ([`keeps_its_edges`]). +fn zone_of(poly: MultiPolygon) -> MultiPolygon { + if poly.0.len() > 1 && keeps_its_edges(&poly) { poly.orient(Direction::Default) } else { mask_of(poly) } } /// Whether the overlay can take a mask's polygons as they are: valid, and few enough to look at @@ -2666,7 +2671,7 @@ fn overlay_zones_on<'a>( let Some((g, poly)) = ov.features.get(row).and_then(|f| f.geometry.as_ref()).and_then(|g| Some((g, polygon_of(g)?))) else { return Ok::<_, String>(ZoneMade::NoPolygon); }; - let poly = mask_of(poly); + let poly = zone_of(poly); if poly.0.is_empty() && use_ != ZoneUse::AsIs { return Ok(ZoneMade::NoArea); }