From 362743ca091ceb53bf617d106046eb6c005688fd Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 09:31:38 -0600 Subject: [PATCH 1/6] fix(analysis): Dissolve finishes on polygons that trapped the overlay library --- ATTRIBUTION.md | 1 + Cargo.lock | 55 +++++++- crates/analysis/Cargo.toml | 1 + crates/analysis/src/tools.rs | 123 +++++++++++++++--- .../analysis/testdata/dissolve-contours.json | 5 + 5 files changed, 163 insertions(+), 22 deletions(-) create mode 100644 crates/analysis/testdata/dissolve-contours.json diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 75055baee5..3dfbe5f7ad 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -34,6 +34,7 @@ of use. | CityGML test mesh (`crates/data/tests/data/rocking-chair.gml`), read only by tests | 97 faces of the rocking chair in OGC's CityGML 3.0 sample `Building_LOD3-EPSG25832.gml` ([CityGML-3.0Encodings](https://github.com/opengeospatial/CityGML-3.0Encodings/blob/master/Moved_to_CITYGML-3.0Encoding_CityGML/Examples/Examples-from-CityGML-2.0/building/CityGMLv3/Building_LOD3-EPSG25832.gml)), copyright (c) 2013 3DXScape, copied on 2026-11-12 and rewritten as a CityGML 2.0 object, coordinates unchanged | MIT | | Datum grid test files (`crates/data/tests/data/grids/us_noaa_conus.tif`, `us_noaa_ethpgn.tif`), read only by the datum grid tests | NOAA's NADCON and HARN grids as converted by [PROJ-data](https://github.com/OSGeo/PROJ-data) (`us_noaa`), copied unchanged from [cdn.proj.org](https://cdn.proj.org) | Public domain | | LERC GeoTIFF test files (`crates/data/tests/data/lerc/*.tif`), read only by the LERC tests | Written for the RustGIS project by `make_lerc.py` there with [GDAL](https://gdal.org) 3.9.3 through [rasterio](https://rasterio.readthedocs.io) 1.4.3, run only to write them; the values are made up | Apache-2.0 | +| Dissolve contour regression (`crates/analysis/testdata/dissolve-contours.json`), read only by tests | Three polygons reduced to ten vertices from the U.S. Census Bureau's [2024 TIGER/Line Census Blocks for Oregon](https://www2.census.gov/geo/tiger/TIGER2024/TABBLOCK20/tl_2024_41_tabblock20.zip) | Public domain | | Analysis reference corpus (`crates/analysis/tests/reference/`: layers and expected results) | Written for the RustGIS project from `generate.py` there: the layers are made up; the expected results were computed by [GEOS](https://libgeos.org) 3.13.1 through [Shapely](https://shapely.readthedocs.io) 2.1.2, and distances, buffers, areas and lengths by GeographicLib in [PROJ](https://proj.org) 9.5.1 through [pyproj](https://pyproj4.github.io/pyproj/) 3.7.2, run only to write them (GEOS is LGPL-2.1, Shapely BSD-3-Clause, PROJ and pyproj MIT; none is included in or linked into RustGIS) | Apache-2.0 | Coordinate systems are looked up by EPSG and ESRI code in the catalog of diff --git a/Cargo.lock b/Cargo.lock index 6764cffdeb..005124c500 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2209,7 +2209,7 @@ dependencies = [ "float_next_after 2.0.0", "geo-types", "geographiclib-rs", - "i_overlay", + "i_overlay 4.5.2", "log", "num-traits", "rand 0.10.3", @@ -2768,6 +2768,15 @@ dependencies = [ "libm", ] +[[package]] +name = "i_float" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ecaff1ce29bcacd72cdf581ba6fce636ef4c4e0b2da7e7846dd0137d98141e2" +dependencies = [ + "libm", +] + [[package]] name = "i_key_sort" version = "0.10.3" @@ -2777,26 +2786,53 @@ dependencies = [ "rayon", ] +[[package]] +name = "i_key_sort" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14269ee362009550495e20650ff3c2bca14a8147fe251e216760381ffed90b6f" + [[package]] name = "i_overlay" version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8dd314b4668e2b3a12508f2e125558c82a6c0a8636fa5107a900f79ce414e450" dependencies = [ - "i_float", - "i_key_sort", - "i_shape", - "i_tree", + "i_float 1.16.0", + "i_key_sort 0.10.3", + "i_shape 1.18.0", + "i_tree 0.18.0", "rayon", ] +[[package]] +name = "i_overlay" +version = "9.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c72f9301c5ab9d2c207a4bdfefbc0b22b7a9750816e49585d4e44904b76390c9" +dependencies = [ + "i_float 5.0.0", + "i_key_sort 0.12.0", + "i_shape 5.0.0", + "i_tree 0.20.0", +] + [[package]] name = "i_shape" version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa9eac533d7509a8ab87672b60ac610c17240f9ea4851d26227689fdfe349c8" dependencies = [ - "i_float", + "i_float 1.16.0", +] + +[[package]] +name = "i_shape" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa1878f91ef7921feaf1b2346253ebc5e661878b22d5715195c1d5dcf0f20ae5" +dependencies = [ + "i_float 5.0.0", ] [[package]] @@ -2805,6 +2841,12 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4804bdc1dc124eb7e1aa9e144ecc04096bcf787a10a15fa44af682b51f0f6cce" +[[package]] +name = "i_tree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048af31de955890c62a8506fec511335a5089e91e1c516537add16f96c507d84" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -5179,6 +5221,7 @@ dependencies = [ "a5", "geo", "h3o", + "i_overlay 9.2.1", "log", "proptest", "rustgis-data", diff --git a/crates/analysis/Cargo.toml b/crates/analysis/Cargo.toml index e5d7b8c064..40c3abae66 100644 --- a/crates/analysis/Cargo.toml +++ b/crates/analysis/Cargo.toml @@ -12,6 +12,7 @@ workspace = true rustgis-geom = { workspace = true } rustgis-data = { workspace = true } geo = { workspace = true } +i_overlay9 = { package = "i_overlay", version = "9.2" } a5 = { workspace = true } h3o = { workspace = true } s2 = { workspace = true } diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index b35730f4ae..ead1eef5bd 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1603,13 +1603,69 @@ pub fn find_field_case_insensitive(ds: &Dataset, name: &str) -> Result(polys: impl IntoIterator>) -> MultiPolygon { +/// Geo's polygon union, with consistent ring orientation so the fill rule follows the first ring. +fn geo_union_all<'a>(polys: impl IntoIterator>) -> MultiPolygon { let oriented: Vec> = polys.into_iter().map(|p| p.orient(Direction::Default)).collect(); geo::unary_union(oriented.iter()) } +/// Union a Dissolve group using consistently oriented rings and OGC extraction. +/// Overlay masks use Geo's union to keep its rounding on shared boundaries. +fn union_all<'a, P>(polys: P) -> MultiPolygon +where + P: IntoIterator>, + P::IntoIter: Clone, +{ + use geo::{Winding, winding_order::WindingOrder}; + use i_overlay9::core::{fill_rule::FillRule, overlay_rule::OverlayRule}; + use i_overlay9::float::overlay::{FloatOverlay, OverlayOptions}; + use i_overlay9::i_float::float::compatible::FloatPointCompatible; + + // i_overlay 4.5 can loop forever during contour extraction. Restore geo::unary_union + // and remove the direct dependency once geo ships with i_overlay 9. + let polys = polys.into_iter(); + let mut winding = None; + let mut supported = true; + let mut subject = Vec::new(); + for poly in polys.clone() { + let (exterior, interiors) = poly.orient(Direction::Default).into_inner(); + for ring in std::iter::once(exterior).chain(interiors) { + if winding.is_none() { + winding = ring.winding_order(); + } + // Overlay closes paths implicitly. Polygon::new closes them again on output. + if let Some((_, open)) = ring.0.split_last() { + subject.push( + open.iter() + .map(|c| { + let point = [c.x, c.y]; + supported &= point.is_in_safe_range(); + point + }) + .collect::>(), + ); + } + } + } + // The new adapter panics outside its coordinate range. Keep geo's existing behavior there. + if !supported { + drop(subject); + return geo_union_all(polys); + } + let fill = if winding == Some(WindingOrder::CounterClockwise) { FillRule::Positive } else { FillRule::Negative }; + let shapes = + FloatOverlay::with_subj_custom(&subject, OverlayOptions::::ogc(), Default::default()).overlay(OverlayRule::Subject, fill); + MultiPolygon::new( + shapes + .into_iter() + .map(|shape| { + let mut rings = shape.into_iter().map(|path| path.into_iter().map(|[x, y]| (x, y)).collect()); + geo::Polygon::new(rings.next().unwrap_or_else(geo::LineString::empty), rings.collect()) + }) + .collect(), + ) +} + // --------------------------------------------------------------------------------------------- // tools @@ -1778,7 +1834,7 @@ fn buffer_with_limits(inp: &dyn Inputs, p: &Json, limit: usize, bytes: usize) -> crate::control::check()?; // The union isn't counted: the buffers' count ends here rather than stand at its end. crate::control::begin(0); - let u = union_all(all.iter().flat_map(|m| m.0.iter())); + let u = geo_union_all(all.iter().flat_map(|m| m.0.iter())); if u.coords_count() > limit { return Err(VERTEX_BUDGET_ERROR.into()); } @@ -1818,7 +1874,7 @@ fn buffer_with_limits(inp: &dyn Inputs, p: &Json, limit: usize, bytes: usize) -> fn dissolved(g: &Geometry) -> std::borrow::Cow<'_, Geometry> { match g { Geometry::Polygon(polys) if polys.len() > 1 => to_multipolygon(g) - .and_then(|m| from_multipolygon(&union_all(m.0.iter()))) + .and_then(|m| from_multipolygon(&geo_union_all(m.0.iter()))) .map_or(std::borrow::Cow::Borrowed(g), std::borrow::Cow::Owned), _ => std::borrow::Cow::Borrowed(g), } @@ -2151,7 +2207,7 @@ impl MaskCache { /// The union of the masks `near` names, from the cache, or made and kept there. fn union_of(&mut self, near: &[usize], masks: &[(MultiPolygon, Extent)]) -> Cow<'_, MultiPolygon> { - let make = || union_all(near.iter().filter_map(|i| masks.get(*i)).flat_map(|(m, _)| m.0.iter())); + let make = || geo_union_all(near.iter().filter_map(|i| masks.get(*i)).flat_map(|(m, _)| m.0.iter())); if self.big.as_ref().is_some_and(|(ids, _)| ids.as_slice() == near) { return match &self.big { Some((_, mask)) => Cow::Borrowed(mask), @@ -2231,7 +2287,7 @@ fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option, cache_bytes: Opti 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()); + let mask = geo_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) }) }, @@ -2462,7 +2518,7 @@ struct Zone { /// 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 { union_all(poly.0.iter()) } else { poly.orient(Direction::Default) } + if poly.0.len() > 1 { geo_union_all(poly.0.iter()) } else { poly.orient(Direction::Default) } } /// How an overlay tool uses its overlay polygons, for [`overlay_zones_on`]. @@ -2655,7 +2711,7 @@ fn rest_outside(g: &Geometry, whole: &Geometry, hit: &[&Zone]) -> Option Some(g.clone()), [only] => part(whole, &only.poly, false), - _ => part(whole, &union_all(hit.iter().flat_map(|z| z.poly.0.iter())), false), + _ => part(whole, &geo_union_all(hit.iter().flat_map(|z| z.poly.0.iter())), false), } } @@ -3274,7 +3330,7 @@ fn split_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result(match polys.as_slice() { [only] => std::borrow::Cow::Borrowed(&only.poly), - _ => std::borrow::Cow::Owned(union_all(polys.iter().flat_map(|z| z.poly.0.iter()))), + _ => std::borrow::Cow::Owned(geo_union_all(polys.iter().flat_map(|z| z.poly.0.iter()))), }) }, )?; @@ -7229,7 +7285,7 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result Result one, parts => { let polys: Vec> = parts.iter().filter_map(to_multipolygon).collect(); - let Some(g) = from_multipolygon(&union_all(polys.iter().flat_map(|m| m.0.iter()))) else { + let Some(g) = from_multipolygon(&geo_union_all(polys.iter().flat_map(|m| m.0.iter()))) else { let key: Vec = zone.key.iter().map(ToString::to_string).collect(); return Err(format!( "Tabulate Intersection: the parts of a class in the zone '{}' could not be combined", @@ -9801,6 +9857,41 @@ mod tests { } } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn dissolve_union_finishes_extracting_contours() { + use geo::Validation; + + let paths: Vec> = serde_json::from_str(include_str!("../testdata/dissolve-contours.json")).unwrap(); + let mut polys: Vec<_> = paths.into_iter().map(|path| geo::Polygon::new(path.into(), vec![])).collect(); + + // The old overlay only hits this dead end with enough segments for its fragmented + // solver. A disjoint rectangle covers the grid, so the small squares add no union area. + let (x, y, width, height) = (-123.796, 42.736, 0.013, 0.004); + let rectangle = |x, y, w, h| geo::Polygon::new(vec![(x, y), (x + w, y), (x + w, y + h), (x, y + h)].into(), vec![]); + let (dx, dy) = (width / 64.0, height / 64.0); + for row in 0..64 { + for col in 0..64 { + polys.push(rectangle(x + f64::from(col) * dx + dx / 4.0, y + f64::from(row) * dy + dy / 4.0, dx / 2.0, dy / 2.0)); + } + } + polys.push(rectangle(x, y, width, height)); + + let (done, result) = std::sync::mpsc::channel(); + let worker = std::thread::Builder::new().spawn(move || done.send(union_all(&polys)).unwrap()).unwrap(); + // test-wait: bound the wait so a contour loop fails the test instead of hanging CI. + let union = result.recv_timeout(std::time::Duration::from_secs(15)).expect("polygon union did not finish"); + worker.join().unwrap(); + assert!(union.is_valid()); + let mut areas: Vec<_> = union.0.iter().map(geo::Area::unsigned_area).collect(); + areas.sort_by(f64::total_cmp); + assert_eq!(areas.len(), 2); + // Areas of the merged Census polygons and the separate rectangle, computed with GEOS. + for (area, expected) in areas.into_iter().zip([1.575_209_1e-5, 5.2e-5]) { + assert!((area - expected).abs() < 1e-10, "area {area}, expected {expected}"); + } + } + /// Dissolve says how many features it left out for having no polygon: a point and a line in a /// polygon layer (as Minimum Bounding Geometry's flat hulls are), an empty polygon and a /// feature without geometry. Those in a group add nothing to its count or statistics. A layer @@ -13815,7 +13906,7 @@ mod tests { .iter() .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 whole = geo_union_all(polys.iter().flat_map(|m| m.0.iter())); let features = &inp.0.0["features"]; let expected: Vec<_> = rows(&inp, &p, "input", features) .into_iter() @@ -13962,7 +14053,7 @@ mod tests { /// no area or a coordinate that isn't finite, whatever the mask. #[test] fn a_feature_is_placed_without_an_overlay_only_clear_of_the_mask_edges() { - let mask = union_all(to_multipolygon(&sq(0.0, 0.0, 1.0)).unwrap().0.iter()); + let mask = geo_union_all(to_multipolygon(&sq(0.0, 0.0, 1.0)).unwrap().0.iter()); let edges = MaskEdges::new(&mask); let place = |g: &Geometry| { let whole = to_multipolygon(g).unwrap(); @@ -14124,7 +14215,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 = geo_union_all(to_multipolygon(masks.features[0].geometry.as_ref().unwrap()).unwrap().0.iter()); 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); @@ -15323,7 +15414,7 @@ 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 mask = geo_union_all(to_multipolygon(&town).unwrap().0.iter()); // 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/testdata/dissolve-contours.json b/crates/analysis/testdata/dissolve-contours.json new file mode 100644 index 0000000000..b5a9bfe6ca --- /dev/null +++ b/crates/analysis/testdata/dissolve-contours.json @@ -0,0 +1,5 @@ +[ + [[-123.532095, 42.829254], [-123.532042, 42.822733], [-123.536802, 42.822733], [-123.53683, 42.822779]], + [[-123.53683, 42.822779], [-123.536802, 42.822733], [-123.538032, 42.822733]], + [[-123.540574, 42.822733], [-123.532042, 42.822733], [-123.531443, 42.822732]] +] From ab7d73d917102aebc7adf60ad735eee921d4ddde Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 14:20:59 -0600 Subject: [PATCH 2/6] fix(analysis): preserve valid Dissolve shells after a collapsed ring --- crates/analysis/src/tools.rs | 63 ++++++++++++++++++++++++------------ 1 file changed, 43 insertions(+), 20 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index ead1eef5bd..5cb404aca1 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1609,14 +1609,16 @@ fn geo_union_all<'a>(polys: impl IntoIterator>) -> geo::unary_union(oriented.iter()) } -/// Union a Dissolve group using consistently oriented rings and OGC extraction. -/// Overlay masks use Geo's union to keep its rounding on shared boundaries. -fn union_all<'a, P>(polys: P) -> MultiPolygon +/// Union a Dissolve group using consistently oriented rings and OGC extraction. A group uses +/// Geo's union if any coordinate is outside the finite range ±2^500 (about ±3.27e150). +/// The i_overlay 9 stopgap uses its serial build on desktop and in the browser. Its optional +/// parallel build would require integrating the sort and split workers with RustGIS's thread +/// setting. The union is one step with no Cancel check inside it. +fn dissolve_union<'a, P>(polys: P) -> MultiPolygon where P: IntoIterator>, P::IntoIter: Clone, { - use geo::{Winding, winding_order::WindingOrder}; use i_overlay9::core::{fill_rule::FillRule, overlay_rule::OverlayRule}; use i_overlay9::float::overlay::{FloatOverlay, OverlayOptions}; use i_overlay9::i_float::float::compatible::FloatPointCompatible; @@ -1624,15 +1626,11 @@ where // i_overlay 4.5 can loop forever during contour extraction. Restore geo::unary_union // and remove the direct dependency once geo ships with i_overlay 9. let polys = polys.into_iter(); - let mut winding = None; let mut supported = true; let mut subject = Vec::new(); for poly in polys.clone() { let (exterior, interiors) = poly.orient(Direction::Default).into_inner(); for ring in std::iter::once(exterior).chain(interiors) { - if winding.is_none() { - winding = ring.winding_order(); - } // Overlay closes paths implicitly. Polygon::new closes them again on output. if let Some((_, open)) = ring.0.split_last() { subject.push( @@ -1647,14 +1645,15 @@ where } } } - // The new adapter panics outside its coordinate range. Keep geo's existing behavior there. + // Out-of-range groups still use Geo's contour extraction, which can hang. if !supported { drop(subject); return geo_union_all(polys); } - let fill = if winding == Some(WindingOrder::CounterClockwise) { FillRule::Positive } else { FillRule::Negative }; - let shapes = - FloatOverlay::with_subj_custom(&subject, OverlayOptions::::ogc(), Default::default()).overlay(OverlayRule::Subject, fill); + // The exteriors are counterclockwise and the holes clockwise. A collapsed exterior can + // leave a hole as the first wound ring, but the group still needs positive fill. + let shapes = FloatOverlay::with_subj_custom(&subject, OverlayOptions::::ogc(), Default::default()) + .overlay(OverlayRule::Subject, FillRule::Positive); MultiPolygon::new( shapes .into_iter() @@ -1884,7 +1883,7 @@ fn dissolved(g: &Geometry) -> std::borrow::Cow<'_, Geometry> { /// overlap with it, a line's stretches in it, the points in it or on its edge; outside, the rest. /// `None` when nothing is left, or only a shared edge or corner. /// -/// The mask's polygons are in the run's plane ([`crate::convert::plane`]), oriented as `union_all` +/// The mask's polygons are in the run's plane ([`crate::convert::plane`]), oriented as `geo_union_all` /// leaves them. The feature's may wind either way (the reference corpus has a clockwise parcel), /// but must not overlap each other: pass a feature of several polygons through [`dissolved`] first, /// once for all its masks. @@ -3456,7 +3455,7 @@ fn dissolve(inp: &dyn Inputs, p: &Json) -> Result { crate::control::check()?; crate::control::reached(done); let n = parts.len() as i64; - let u = union_all(parts.iter().flat_map(|m| m.0.iter())); + let u = dissolve_union(parts.iter().flat_map(|m| m.0.iter())); let mut attrs = if fi.is_some() { vec![key, Value::Int(n)] } else { vec![Value::Int(n)] }; if !requests.is_empty() { record_order(&mut records); @@ -9865,20 +9864,21 @@ mod tests { let paths: Vec> = serde_json::from_str(include_str!("../testdata/dissolve-contours.json")).unwrap(); let mut polys: Vec<_> = paths.into_iter().map(|path| geo::Polygon::new(path.into(), vec![])).collect(); - // The old overlay only hits this dead end with enough segments for its fragmented - // solver. A disjoint rectangle covers the grid, so the small squares add no union area. + // The grid must exceed both fragment solver thresholds (16,000 segments in i_overlay + // 4.5.2 and 32,000 in 9.2.1). A separate rectangle covers it, so the squares add no area. let (x, y, width, height) = (-123.796, 42.736, 0.013, 0.004); let rectangle = |x, y, w, h| geo::Polygon::new(vec![(x, y), (x + w, y), (x + w, y + h), (x, y + h)].into(), vec![]); - let (dx, dy) = (width / 64.0, height / 64.0); - for row in 0..64 { - for col in 0..64 { + const SIDE: i32 = 128; + let (dx, dy) = (width / f64::from(SIDE), height / f64::from(SIDE)); + for row in 0..SIDE { + for col in 0..SIDE { polys.push(rectangle(x + f64::from(col) * dx + dx / 4.0, y + f64::from(row) * dy + dy / 4.0, dx / 2.0, dy / 2.0)); } } polys.push(rectangle(x, y, width, height)); let (done, result) = std::sync::mpsc::channel(); - let worker = std::thread::Builder::new().spawn(move || done.send(union_all(&polys)).unwrap()).unwrap(); + let worker = std::thread::Builder::new().spawn(move || done.send(dissolve_union(&polys)).unwrap()).unwrap(); // test-wait: bound the wait so a contour loop fails the test instead of hanging CI. let union = result.recv_timeout(std::time::Duration::from_secs(15)).expect("polygon union did not finish"); worker.join().unwrap(); @@ -9892,6 +9892,29 @@ mod tests { } } + #[test] + fn dissolve_union_keeps_shells_after_a_collapsed_exterior() { + let hole = geo::Rect::new((0.0, 0.0), (2.0, 2.0)).to_polygon(); + let collapsed = geo::Polygon::new(vec![(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)].into(), vec![hole.exterior().clone()]); + let a = geo::Rect::new((3.0, 0.0), (4.0, 1.0)).to_polygon(); + let b = geo::Rect::new((5.0, 0.0), (6.0, 1.0)).to_polygon(); + + let union = dissolve_union([&collapsed, &a, &b]); + assert_eq!(union.0.len(), 2); + assert!((geo::Area::unsigned_area(&union) - 2.0).abs() < 1e-9); + } + + #[test] + fn dissolve_union_falls_back_for_out_of_range_exteriors_and_holes() { + let wide = geo::LineString::from(vec![(0.0, 0.0), (1e160, 1.0), (1.0, 1.0), (0.0, 1.0)]); + let shell = geo::Rect::new((-1.0, -1.0), (2.0, 2.0)).to_polygon(); + let wide_shell = geo::Polygon::new(wide.clone(), vec![]); + let wide_hole = geo::Polygon::new(shell.exterior().clone(), vec![wide]); + for poly in [&wide_shell, &wide_hole] { + assert_eq!(dissolve_union([poly]), geo_union_all([poly])); + } + } + /// Dissolve says how many features it left out for having no polygon: a point and a line in a /// polygon layer (as Minimum Bounding Geometry's flat hulls are), an empty polygon and a /// feature without geometry. Those in a group add nothing to its count or statistics. A layer From 9bf0114483463a78c556f50f0fd77278670c6d7b Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 16:18:31 -0600 Subject: [PATCH 3/6] fix(analysis): keep spiked rings in Dissolve and count groups left without geometry --- crates/analysis/src/tools.rs | 118 +++++++++++++++++++++++++++++++++-- 1 file changed, 113 insertions(+), 5 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 5cb404aca1..695b913f22 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1609,7 +1609,10 @@ fn geo_union_all<'a>(polys: impl IntoIterator>) -> geo::unary_union(oriented.iter()) } -/// Union a Dissolve group using consistently oriented rings and OGC extraction. A group uses +/// Union a Dissolve group using consistently oriented rings and OGC extraction. A ring whose +/// winding can't be read at its least vertex, as with a spike there, is oriented by its signed +/// area; at exactly zero (a collapsed ring, or lobes that cancel out) it keeps the direction it +/// has, and the positive fill keeps only what it goes around counterclockwise. A group uses /// Geo's union if any coordinate is outside the finite range ±2^500 (about ±3.27e150). /// The i_overlay 9 stopgap uses its serial build on desktop and in the browser. Its optional /// parallel build would require integrating the sort and split workers with RustGIS's thread @@ -1619,6 +1622,7 @@ where P: IntoIterator>, P::IntoIter: Clone, { + use geo::{Area, Winding}; use i_overlay9::core::{fill_rule::FillRule, overlay_rule::OverlayRule}; use i_overlay9::float::overlay::{FloatOverlay, OverlayOptions}; use i_overlay9::i_float::float::compatible::FloatPointCompatible; @@ -1630,7 +1634,15 @@ where let mut subject = Vec::new(); for poly in polys.clone() { let (exterior, interiors) = poly.orient(Direction::Default).into_inner(); - for ring in std::iter::once(exterior).chain(interiors) { + for (hole, mut ring) in std::iter::once((false, exterior)).chain(interiors.into_iter().map(|r| (true, r))) { + if ring.winding_order().is_none() { + // Taken from the ring's first vertex, so large coordinates don't cancel out. + let area = geo::Polygon::new(ring.clone(), vec![]).signed_area(); + let backwards = if hole { area > 0.0 } else { area < 0.0 }; + if backwards { + ring.0.reverse(); + } + } // Overlay closes paths implicitly. Polygon::new closes them again on output. if let Some((_, open)) = ring.0.split_last() { subject.push( @@ -1650,8 +1662,9 @@ where drop(subject); return geo_union_all(polys); } - // The exteriors are counterclockwise and the holes clockwise. A collapsed exterior can - // leave a hole as the first wound ring, but the group still needs positive fill. + // Exteriors run counterclockwise and holes clockwise, except rings of zero area and ones that + // touch or cross themselves so that their least vertex turns against most of their area. The + // fill is positive whichever ring comes first: after a collapsed exterior, that is a hole. let shapes = FloatOverlay::with_subj_custom(&subject, OverlayOptions::::ogc(), Default::default()) .overlay(OverlayRule::Subject, FillRule::Positive); MultiPolygon::new( @@ -3449,6 +3462,8 @@ fn dissolve(inp: &dyn Inputs, p: &Json) -> Result { fields.extend(added); let mut out = Dataset::new(out_name(p, format!("{}_Dissolve", ds.name)), GeometryType::Polygon, fields); let mut rounded = Rounded::new(requests.len()); + // Groups written without a geometry, as their union is empty. + let mut no_shape = 0usize; // The unions are the work: counted, and Cancel looked at, group by group. crate::control::begin(groups.len()); for (done, (key, parts, mut records)) in groups.into_iter().enumerate() { @@ -3463,7 +3478,9 @@ fn dissolve(inp: &dyn Inputs, p: &Json) -> Result { rounded.count_texts(ds, &records, &requests, false)?; attrs.extend(statistic_values(ds, &records, &requests, false, separator, &mut rounded)?); } - out.push(from_multipolygon(&u), attrs); + let shape = from_multipolygon(&u); + no_shape += usize::from(shape.is_none()); + out.push(shape, attrs); } let n = out.features.len(); // Features read, none with a polygon: an unusable result, so an error saying why. @@ -3479,6 +3496,11 @@ fn dissolve(inp: &dyn Inputs, p: &Json) -> Result { "Dissolve: {not_polygons} feature(s) left out, with their values: no geometry, an empty polygon, or a point or line rather than a polygon" ) }); } + if no_shape > 0 { + losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedGeometry, text: format!( + "Dissolve: {no_shape} feature(s) written without geometry: merging their polygons left no area (none to begin with, too small or thin beside the group's extent, or coordinates too large to merge)" + ) }); + } let (said, rounded) = rounded_notice(&rounded, out.fields.get(first_added..).unwrap_or_default()); messages.extend(said); losses.extend(rounded); @@ -9904,6 +9926,48 @@ mod tests { assert!((geo::Area::unsigned_area(&union) - 2.0).abs() < 1e-9); } + /// A ring with a spike at its lexicographically least vertex has no winding there, and keeps + /// its area whichever way it goes around: alone, beside other polygons, as a hole, with a + /// hole, and millimetres across at projected coordinates, where products of them would + /// swallow its area. + #[test] + fn dissolve_union_keeps_rings_with_a_spike_at_their_least_vertex() { + use geo::{Area, MapCoords, Winding}; + type Ring = geo::LineString; + + let clockwise: Ring = + vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (30.0, 10.0), (30.0, -10.0), (10.0, -10.0), (10.0, 0.0), (0.0, 0.0)].into(); + let reversed = |r: &Ring| Ring::new(r.0.iter().rev().copied().collect()); + let rect = |x, y, w, h| geo::Rect::new((x, y), (x + w, y + h)).to_polygon(); + let solid = |r: &Ring| geo::Polygon::new(r.clone(), vec![]); + let square = rect(50.0, 0.0, 1.0, 1.0); + let window = rect(15.0, -5.0, 5.0, 10.0).exterior().clone(); + for ring in [clockwise.clone(), reversed(&clockwise)] { + assert_eq!(ring.winding_order(), None); + let spiked = solid(&ring); + let away = Ring::new(clockwise.0.iter().map(|c| geo::Coord { x: c.x + 100.0, y: c.y }).collect()); + let mut groups = vec![ + (vec![spiked.clone()], 400.0), + (vec![spiked.clone(), square.clone()], 401.0), + (vec![square.clone(), spiked.clone()], 401.0), + (vec![spiked.clone(), solid(&away)], 800.0), + (vec![spiked.clone(), solid(&reversed(&away))], 800.0), + (vec![geo::Polygon::new(rect(-5.0, -20.0, 45.0, 40.0).exterior().clone(), vec![ring.clone()])], 1400.0), + ]; + for hole in [window.clone(), reversed(&window)] { + groups.push((vec![geo::Polygon::new(ring.clone(), vec![hole])], 350.0)); + } + for (polys, expected) in groups { + for (scale, x, y) in [(1.0, 0.0, 0.0), (0.001, 500_000.0, 5_000_000.0)] { + let placed: Vec<_> = + polys.iter().map(|p| p.map_coords(|c| geo::Coord { x: x + c.x * scale, y: y + c.y * scale })).collect(); + let area = dissolve_union(&placed).unsigned_area() / (scale * scale); + assert!((area - expected).abs() < 0.01, "area {area}, expected {expected}: {placed:?}"); + } + } + } + } + #[test] fn dissolve_union_falls_back_for_out_of_range_exteriors_and_holes() { let wide = geo::LineString::from(vec![(0.0, 0.0), (1e160, 1.0), (1.0, 1.0), (0.0, 1.0)]); @@ -10116,6 +10180,50 @@ mod tests { ); } + /// Dissolve counts the groups whose polygons merge to nothing, and still writes their feature + /// with its count and statistics: coordinates out of range, every vertex in one place, and a + /// unit square that the overlay's grid has no room for beside a triangle 1e12° wide. A layer + /// whose groups all have an area says nothing. + #[test] + fn dissolve_counts_groups_left_without_geometry() { + let triangle = |far: f64| { + let at = |x, y| Coord::new(x, y); + Geometry::Polygon(vec![vec![vec![at(0.0, 0.0), at(far, 1.0), at(1.0, 1.0), at(0.0, 1.0), at(0.0, 0.0)]]]) + }; + let empty = [vec![triangle(1e160)], vec![sq(3.0, 3.0, 0.0)], vec![sq(2.0, 0.0, 1.0), triangle(1e12)]]; + let run = |groups: &[Vec]| { + let fields = vec![Field::new("k", FieldType::Integer), Field::new("v", FieldType::Double)]; + let mut polys = Dataset::new("polys", GeometryType::Polygon, fields); + for (k, group) in groups.iter().enumerate() { + for g in group { + polys.push(Some(g.clone()), vec![Value::Int(k as i64), Value::Float(2.0)]); + } + } + let m = Map(HashMap::from([("polys".to_string(), polys)])); + let params = serde_json::json!({"input": "polys", "field": "k", "statistics": [{"field": "v", "statistic": "SUM"}]}); + let res = crate::run("dissolve", &m, ¶ms).unwrap(); + let note = said(&res).into_iter().find(|m| m.contains("without geometry")); + let out = layer(res); + let rows: Vec<_> = (0..out.features.len()) + .map(|r| (out.features.row(r).unwrap().geometry().is_some(), out.value(r, 1).as_f64(), out.value(r, 2).as_f64())) + .collect(); + (rows, note) + }; + let notice = |n: usize| { + format!( + "DroppedGeometry: Dissolve: {n} feature(s) written without geometry: merging their polygons left no area (none to begin with, too small or thin beside the group's extent, or coordinates too large to merge)" + ) + }; + let clean = vec![sq(0.0, 0.0, 1.0), sq(1.0, 0.0, 1.0)]; + let row = |geometry: bool, group: &[Geometry]| (geometry, Some(group.len() as f64), Some(2.0 * group.len() as f64)); + for group in &empty { + assert_eq!(run(&[clean.clone(), group.clone()]), (vec![row(true, &clean), row(false, group)], Some(notice(1)))); + } + let rows = empty.iter().map(|g| row(false, g)).collect(); + assert_eq!(run(&empty), (rows, Some(notice(3)))); + assert_eq!(run(std::slice::from_ref(&clean)), (vec![row(true, &clean)], None)); + } + /// Dissolve's groups, found by their keys' hash: in the order first met, −0 with 0, each NaN /// on its own (it equals no value), and a number apart from the same text and a whole number /// apart from the same fraction. From ed586bade55234d259031a94e51f74252bc07c3f Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 18:11:03 -0600 Subject: [PATCH 4/6] fix(analysis): orient rings that revisit their least vertex by area in Dissolve Leave out the holes of an exterior that encloses nothing. --- crates/analysis/src/tools.rs | 117 +++++++++++++++++++++++++---------- 1 file changed, 83 insertions(+), 34 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 695b913f22..5ddc4525a7 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1609,20 +1609,27 @@ fn geo_union_all<'a>(polys: impl IntoIterator>) -> geo::unary_union(oriented.iter()) } +/// Whether `ring`'s winding can't be read from the turn at its least vertex, as geo reads it: it +/// has no turn there (a spike), or several, as the ring comes back through it. +fn winding_unsure(ring: &geo::LineString) -> bool { + let least = ring.0.iter().copied().reduce(|a, b| if (b.x, b.y) < (a.x, a.y) { b } else { a }); + geo::Winding::winding_order(ring).is_none() || ring.0.iter().skip(1).filter(|c| Some(**c) == least).count() > 1 +} + /// Union a Dissolve group using consistently oriented rings and OGC extraction. A ring whose -/// winding can't be read at its least vertex, as with a spike there, is oriented by its signed -/// area; at exactly zero (a collapsed ring, or lobes that cancel out) it keeps the direction it -/// has, and the positive fill keeps only what it goes around counterclockwise. A group uses -/// Geo's union if any coordinate is outside the finite range ±2^500 (about ±3.27e150). -/// The i_overlay 9 stopgap uses its serial build on desktop and in the browser. Its optional -/// parallel build would require integrating the sort and split workers with RustGIS's thread -/// setting. The union is one step with no Cancel check inside it. +/// winding is unsure ([`winding_unsure`]) is oriented by its signed area; at exactly zero (a +/// collapsed ring, or lobes that cancel out) it keeps the direction it has, and the positive fill +/// keeps only what it goes around counterclockwise. Such an exterior that encloses nothing is +/// taken without its holes. A group uses Geo's union if any coordinate is outside the finite range +/// ±2^500 (about ±3.27e150). The i_overlay 9 stopgap uses its serial build on desktop and in the +/// browser. Its optional parallel build would require integrating the sort and split workers with +/// RustGIS's thread setting. The union is one step with no Cancel check inside it. fn dissolve_union<'a, P>(polys: P) -> MultiPolygon where P: IntoIterator>, P::IntoIter: Clone, { - use geo::{Area, Winding}; + use geo::Area; use i_overlay9::core::{fill_rule::FillRule, overlay_rule::OverlayRule}; use i_overlay9::float::overlay::{FloatOverlay, OverlayOptions}; use i_overlay9::i_float::float::compatible::FloatPointCompatible; @@ -1635,7 +1642,8 @@ where for poly in polys.clone() { let (exterior, interiors) = poly.orient(Direction::Default).into_inner(); for (hole, mut ring) in std::iter::once((false, exterior)).chain(interiors.into_iter().map(|r| (true, r))) { - if ring.winding_order().is_none() { + let unsure = winding_unsure(&ring); + if unsure { // Taken from the ring's first vertex, so large coordinates don't cancel out. let area = geo::Polygon::new(ring.clone(), vec![]).signed_area(); let backwards = if hole { area > 0.0 } else { area < 0.0 }; @@ -1645,15 +1653,26 @@ where } // Overlay closes paths implicitly. Polygon::new closes them again on output. if let Some((_, open)) = ring.0.split_last() { - subject.push( - open.iter() - .map(|c| { - let point = [c.x, c.y]; - supported &= point.is_in_safe_range(); - point - }) - .collect::>(), - ); + let path: Vec<_> = open + .iter() + .map(|c| { + let point = [c.x, c.y]; + supported &= point.is_in_safe_range(); + point + }) + .collect(); + // The holes of an exterior that encloses nothing would cut its neighbors. + let nothing = !hole + && unsure + && supported + && !poly.interiors().is_empty() + && FloatOverlay::with_subj_custom(&path, OverlayOptions::::ogc(), Default::default()) + .overlay(OverlayRule::Subject, FillRule::NonZero) + .is_empty(); + subject.push(path); + if nothing { + break; + } } } } @@ -1663,8 +1682,8 @@ where return geo_union_all(polys); } // Exteriors run counterclockwise and holes clockwise, except rings of zero area and ones that - // touch or cross themselves so that their least vertex turns against most of their area. The - // fill is positive whichever ring comes first: after a collapsed exterior, that is a hole. + // cross themselves so that their least vertex turns against most of their area. The fill is + // positive whichever ring comes first. let shapes = FloatOverlay::with_subj_custom(&subject, OverlayOptions::::ogc(), Default::default()) .overlay(OverlayRule::Subject, FillRule::Positive); MultiPolygon::new( @@ -9878,6 +9897,17 @@ mod tests { } } + /// What `union` returns, failing the test after 15 s: a contour loop would hang CI. + #[cfg(not(target_arch = "wasm32"))] + fn finishes(union: impl FnOnce() -> T + Send + 'static) -> T { + let (send, received) = std::sync::mpsc::channel(); + let worker = std::thread::Builder::new().spawn(move || send.send(union()).unwrap()).unwrap(); + // test-wait: bound the wait so a contour loop fails the test instead of hanging CI. + let result = received.recv_timeout(std::time::Duration::from_secs(15)).expect("polygon union did not finish"); + worker.join().unwrap(); + result + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn dissolve_union_finishes_extracting_contours() { @@ -9899,11 +9929,7 @@ mod tests { } polys.push(rectangle(x, y, width, height)); - let (done, result) = std::sync::mpsc::channel(); - let worker = std::thread::Builder::new().spawn(move || done.send(dissolve_union(&polys)).unwrap()).unwrap(); - // test-wait: bound the wait so a contour loop fails the test instead of hanging CI. - let union = result.recv_timeout(std::time::Duration::from_secs(15)).expect("polygon union did not finish"); - worker.join().unwrap(); + let union = finishes(move || dissolve_union(&polys)); assert!(union.is_valid()); let mut areas: Vec<_> = union.0.iter().map(geo::Area::unsigned_area).collect(); areas.sort_by(f64::total_cmp); @@ -9926,10 +9952,27 @@ mod tests { assert!((geo::Area::unsigned_area(&union) - 2.0).abs() < 1e-9); } - /// A ring with a spike at its lexicographically least vertex has no winding there, and keeps - /// its area whichever way it goes around: alone, beside other polygons, as a hole, with a - /// hole, and millimetres across at projected coordinates, where products of them would - /// swallow its area. + /// An exterior that encloses nothing doesn't cut the polygons its hole covers, whether its + /// vertices lie on one line or it goes out and back along two, and whichever comes first. + #[test] + fn dissolve_union_leaves_a_collapsed_exteriors_holes_out() { + let hole = geo::Rect::new((0.0, 0.0), (2.0, 2.0)).to_polygon().exterior().clone(); + let square = geo::Rect::new((0.5, 0.5), (1.5, 1.5)).to_polygon(); + // The second one's area rounds to -1.1e-16, not zero. + let there_and_back = vec![(0.1, 0.1), (0.5, 0.7), (2.2, 1.4), (2.8, 0.8), (2.2, 1.4), (0.5, 0.7)]; + for flat in [vec![(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)], there_and_back] { + let collapsed = geo::Polygon::new(flat.into(), vec![hole.clone()]); + for group in [[&collapsed, &square], [&square, &collapsed]] { + let union = dissolve_union(group); + assert!((geo::Area::unsigned_area(&union) - 1.0).abs() < 1e-9, "{union:?}"); + } + } + } + + /// A ring with a spike at its lexicographically least vertex has no winding there, and one + /// that comes back through that vertex can have the wrong one. Both keep their area whichever + /// way they go around: alone, beside other polygons, as a hole, with a hole, and millimetres + /// across at projected coordinates, where products of them would swallow their area. #[test] fn dissolve_union_keeps_rings_with_a_spike_at_their_least_vertex() { use geo::{Area, MapCoords, Winding}; @@ -9942,8 +9985,11 @@ mod tests { let solid = |r: &Ring| geo::Polygon::new(r.clone(), vec![]); let square = rect(50.0, 0.0, 1.0, 1.0); let window = rect(15.0, -5.0, 5.0, 10.0).exterior().clone(); - for ring in [clockwise.clone(), reversed(&clockwise)] { - assert_eq!(ring.winding_order(), None); + assert_eq!(clockwise.winding_order(), None); + // Closed through a point on either side, so it passes its least vertex twice. + let through = |y| Ring::new([(2.0, y).into()].into_iter().chain(clockwise.0.iter().copied()).chain([(2.0, y).into()]).collect()); + let rings = [clockwise.clone(), through(-3.0), through(3.0)]; + for ring in rings.iter().flat_map(|r| [r.clone(), reversed(r)]) { let spiked = solid(&ring); let away = Ring::new(clockwise.0.iter().map(|c| geo::Coord { x: c.x + 100.0, y: c.y }).collect()); let mut groups = vec![ @@ -9968,15 +10014,18 @@ mod tests { } } + #[cfg(not(target_arch = "wasm32"))] #[test] fn dissolve_union_falls_back_for_out_of_range_exteriors_and_holes() { let wide = geo::LineString::from(vec![(0.0, 0.0), (1e160, 1.0), (1.0, 1.0), (0.0, 1.0)]); let shell = geo::Rect::new((-1.0, -1.0), (2.0, 2.0)).to_polygon(); let wide_shell = geo::Polygon::new(wide.clone(), vec![]); let wide_hole = geo::Polygon::new(shell.exterior().clone(), vec![wide]); - for poly in [&wide_shell, &wide_hole] { - assert_eq!(dissolve_union([poly]), geo_union_all([poly])); - } + finishes(move || { + for poly in [&wide_shell, &wide_hole] { + assert_eq!(dissolve_union([poly]), geo_union_all([poly])); + } + }); } /// Dissolve says how many features it left out for having no polygon: a point and a line in a From 2a30f810f800313d8b9aa944ee875c7fd904e6d5 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 18:59:26 -0600 Subject: [PATCH 5/6] fix(analysis): leave out the holes of an empty exterior in Dissolve --- crates/analysis/src/tools.rs | 263 ++++++++++++++++++----------------- 1 file changed, 139 insertions(+), 124 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 5ddc4525a7..739853fdc8 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1652,27 +1652,28 @@ where } } // Overlay closes paths implicitly. Polygon::new closes them again on output. - if let Some((_, open)) = ring.0.split_last() { - let path: Vec<_> = open - .iter() - .map(|c| { - let point = [c.x, c.y]; - supported &= point.is_in_safe_range(); - point - }) - .collect(); - // The holes of an exterior that encloses nothing would cut its neighbors. - let nothing = !hole - && unsure - && supported - && !poly.interiors().is_empty() - && FloatOverlay::with_subj_custom(&path, OverlayOptions::::ogc(), Default::default()) - .overlay(OverlayRule::Subject, FillRule::NonZero) - .is_empty(); - subject.push(path); - if nothing { - break; - } + let path: Vec<_> = ring + .0 + .split_last() + .map_or(&[][..], |(_, open)| open) + .iter() + .map(|c| { + let point = [c.x, c.y]; + supported &= point.is_in_safe_range(); + point + }) + .collect(); + // The holes of an exterior that encloses nothing would cut its neighbors. + let nothing = !hole + && unsure + && supported + && !poly.interiors().is_empty() + && FloatOverlay::with_subj_custom(&path, OverlayOptions::::ogc(), Default::default()) + .overlay(OverlayRule::Subject, FillRule::NonZero) + .is_empty(); + subject.push(path); + if nothing { + break; } } } @@ -9898,14 +9899,14 @@ mod tests { } /// What `union` returns, failing the test after 15 s: a contour loop would hang CI. - #[cfg(not(target_arch = "wasm32"))] fn finishes(union: impl FnOnce() -> T + Send + 'static) -> T { let (send, received) = std::sync::mpsc::channel(); let worker = std::thread::Builder::new().spawn(move || send.send(union()).unwrap()).unwrap(); // test-wait: bound the wait so a contour loop fails the test instead of hanging CI. - let result = received.recv_timeout(std::time::Duration::from_secs(15)).expect("polygon union did not finish"); - worker.join().unwrap(); - result + let result = received.recv_timeout(std::time::Duration::from_secs(15)); + assert_ne!(result.as_ref().err(), Some(&std::sync::mpsc::RecvTimeoutError::Timeout), "polygon union did not finish"); + worker.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic)); + result.unwrap() } #[cfg(not(target_arch = "wasm32"))] @@ -9942,31 +9943,35 @@ mod tests { #[test] fn dissolve_union_keeps_shells_after_a_collapsed_exterior() { - let hole = geo::Rect::new((0.0, 0.0), (2.0, 2.0)).to_polygon(); - let collapsed = geo::Polygon::new(vec![(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)].into(), vec![hole.exterior().clone()]); - let a = geo::Rect::new((3.0, 0.0), (4.0, 1.0)).to_polygon(); - let b = geo::Rect::new((5.0, 0.0), (6.0, 1.0)).to_polygon(); - - let union = dissolve_union([&collapsed, &a, &b]); - assert_eq!(union.0.len(), 2); - assert!((geo::Area::unsigned_area(&union) - 2.0).abs() < 1e-9); + finishes(|| { + let hole = geo::Rect::new((0.0, 0.0), (2.0, 2.0)).to_polygon(); + let collapsed = geo::Polygon::new(vec![(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)].into(), vec![hole.exterior().clone()]); + let a = geo::Rect::new((3.0, 0.0), (4.0, 1.0)).to_polygon(); + let b = geo::Rect::new((5.0, 0.0), (6.0, 1.0)).to_polygon(); + + let union = dissolve_union([&collapsed, &a, &b]); + assert_eq!(union.0.len(), 2); + assert!((geo::Area::unsigned_area(&union) - 2.0).abs() < 1e-9); + }); } - /// An exterior that encloses nothing doesn't cut the polygons its hole covers, whether its - /// vertices lie on one line or it goes out and back along two, and whichever comes first. + /// An exterior that encloses nothing doesn't cut the polygons its hole covers: it has no + /// vertices, they lie on one line, or it goes out and back along two, whichever comes first. #[test] fn dissolve_union_leaves_a_collapsed_exteriors_holes_out() { - let hole = geo::Rect::new((0.0, 0.0), (2.0, 2.0)).to_polygon().exterior().clone(); - let square = geo::Rect::new((0.5, 0.5), (1.5, 1.5)).to_polygon(); - // The second one's area rounds to -1.1e-16, not zero. - let there_and_back = vec![(0.1, 0.1), (0.5, 0.7), (2.2, 1.4), (2.8, 0.8), (2.2, 1.4), (0.5, 0.7)]; - for flat in [vec![(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)], there_and_back] { - let collapsed = geo::Polygon::new(flat.into(), vec![hole.clone()]); - for group in [[&collapsed, &square], [&square, &collapsed]] { - let union = dissolve_union(group); - assert!((geo::Area::unsigned_area(&union) - 1.0).abs() < 1e-9, "{union:?}"); + finishes(|| { + let hole = geo::Rect::new((0.0, 0.0), (2.0, 2.0)).to_polygon().exterior().clone(); + let square = geo::Rect::new((0.5, 0.5), (1.5, 1.5)).to_polygon(); + // Its area rounds to -1.1e-16, not zero. + let there_and_back = vec![(0.1, 0.1), (0.5, 0.7), (2.2, 1.4), (2.8, 0.8), (2.2, 1.4), (0.5, 0.7)]; + for flat in [vec![], vec![(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)], there_and_back] { + let collapsed = geo::Polygon::new(flat.into(), vec![hole.clone()]); + for group in [[&collapsed, &square], [&square, &collapsed]] { + let union = dissolve_union(group); + assert!((geo::Area::unsigned_area(&union) - 1.0).abs() < 1e-9, "{union:?}"); + } } - } + }); } /// A ring with a spike at its lexicographically least vertex has no winding there, and one @@ -9975,55 +9980,63 @@ mod tests { /// across at projected coordinates, where products of them would swallow their area. #[test] fn dissolve_union_keeps_rings_with_a_spike_at_their_least_vertex() { - use geo::{Area, MapCoords, Winding}; - type Ring = geo::LineString; - - let clockwise: Ring = - vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (30.0, 10.0), (30.0, -10.0), (10.0, -10.0), (10.0, 0.0), (0.0, 0.0)].into(); - let reversed = |r: &Ring| Ring::new(r.0.iter().rev().copied().collect()); - let rect = |x, y, w, h| geo::Rect::new((x, y), (x + w, y + h)).to_polygon(); - let solid = |r: &Ring| geo::Polygon::new(r.clone(), vec![]); - let square = rect(50.0, 0.0, 1.0, 1.0); - let window = rect(15.0, -5.0, 5.0, 10.0).exterior().clone(); - assert_eq!(clockwise.winding_order(), None); - // Closed through a point on either side, so it passes its least vertex twice. - let through = |y| Ring::new([(2.0, y).into()].into_iter().chain(clockwise.0.iter().copied()).chain([(2.0, y).into()]).collect()); - let rings = [clockwise.clone(), through(-3.0), through(3.0)]; - for ring in rings.iter().flat_map(|r| [r.clone(), reversed(r)]) { - let spiked = solid(&ring); - let away = Ring::new(clockwise.0.iter().map(|c| geo::Coord { x: c.x + 100.0, y: c.y }).collect()); - let mut groups = vec![ - (vec![spiked.clone()], 400.0), - (vec![spiked.clone(), square.clone()], 401.0), - (vec![square.clone(), spiked.clone()], 401.0), - (vec![spiked.clone(), solid(&away)], 800.0), - (vec![spiked.clone(), solid(&reversed(&away))], 800.0), - (vec![geo::Polygon::new(rect(-5.0, -20.0, 45.0, 40.0).exterior().clone(), vec![ring.clone()])], 1400.0), - ]; - for hole in [window.clone(), reversed(&window)] { - groups.push((vec![geo::Polygon::new(ring.clone(), vec![hole])], 350.0)); - } - for (polys, expected) in groups { - for (scale, x, y) in [(1.0, 0.0, 0.0), (0.001, 500_000.0, 5_000_000.0)] { - let placed: Vec<_> = - polys.iter().map(|p| p.map_coords(|c| geo::Coord { x: x + c.x * scale, y: y + c.y * scale })).collect(); - let area = dissolve_union(&placed).unsigned_area() / (scale * scale); - assert!((area - expected).abs() < 0.01, "area {area}, expected {expected}: {placed:?}"); + finishes(|| { + use geo::{Area, MapCoords, Winding}; + type Ring = geo::LineString; + + let clockwise: Ring = + vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (30.0, 10.0), (30.0, -10.0), (10.0, -10.0), (10.0, 0.0), (0.0, 0.0)].into(); + let reversed = |r: &Ring| Ring::new(r.0.iter().rev().copied().collect()); + let rect = |x, y, w, h| geo::Rect::new((x, y), (x + w, y + h)).to_polygon(); + let solid = |r: &Ring| geo::Polygon::new(r.clone(), vec![]); + let square = rect(50.0, 0.0, 1.0, 1.0); + let window = rect(15.0, -5.0, 5.0, 10.0).exterior().clone(); + assert_eq!(clockwise.winding_order(), None); + // Closed through a point on either side, so it passes its least vertex twice. + let through = + |y| Ring::new([(2.0, y).into()].into_iter().chain(clockwise.0.iter().copied()).chain([(2.0, y).into()]).collect()); + let rings = [clockwise.clone(), through(-3.0), through(3.0)]; + for ring in rings.iter().flat_map(|r| [r.clone(), reversed(r)]) { + let spiked = solid(&ring); + let away = Ring::new(clockwise.0.iter().map(|c| geo::Coord { x: c.x + 100.0, y: c.y }).collect()); + let mut groups = vec![ + (vec![spiked.clone()], 400.0), + (vec![spiked.clone(), square.clone()], 401.0), + (vec![square.clone(), spiked.clone()], 401.0), + (vec![spiked.clone(), solid(&away)], 800.0), + (vec![spiked.clone(), solid(&reversed(&away))], 800.0), + (vec![geo::Polygon::new(rect(-5.0, -20.0, 45.0, 40.0).exterior().clone(), vec![ring.clone()])], 1400.0), + ]; + for hole in [window.clone(), reversed(&window)] { + groups.push((vec![geo::Polygon::new(ring.clone(), vec![hole])], 350.0)); + } + for (polys, expected) in groups { + for (scale, x, y) in [(1.0, 0.0, 0.0), (0.001, 500_000.0, 5_000_000.0)] { + let placed: Vec<_> = + polys.iter().map(|p| p.map_coords(|c| geo::Coord { x: x + c.x * scale, y: y + c.y * scale })).collect(); + let area = dissolve_union(&placed).unsigned_area() / (scale * scale); + assert!((area - expected).abs() < 0.01, "area {area}, expected {expected}: {placed:?}"); + } } } - } + }); } - #[cfg(not(target_arch = "wasm32"))] #[test] fn dissolve_union_falls_back_for_out_of_range_exteriors_and_holes() { - let wide = geo::LineString::from(vec![(0.0, 0.0), (1e160, 1.0), (1.0, 1.0), (0.0, 1.0)]); - let shell = geo::Rect::new((-1.0, -1.0), (2.0, 2.0)).to_polygon(); - let wide_shell = geo::Polygon::new(wide.clone(), vec![]); - let wide_hole = geo::Polygon::new(shell.exterior().clone(), vec![wide]); - finishes(move || { - for poly in [&wide_shell, &wide_hole] { - assert_eq!(dissolve_union([poly]), geo_union_all([poly])); + finishes(|| { + let shell = geo::Rect::new((-1.0, -1.0), (2.0, 2.0)).to_polygon(); + let window = geo::Rect::new((15.0, -5.0), (20.0, 5.0)).to_polygon(); + for x in [1e160, f64::INFINITY] { + let wide = geo::LineString::from(vec![(0.0, 0.0), (x, 1.0), (1.0, 1.0), (0.0, 1.0)]); + let wide_shell = geo::Polygon::new(wide.clone(), vec![]); + let wide_hole = geo::Polygon::new(shell.exterior().clone(), vec![wide]); + let spiked = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (x, 10.0), (30.0, -10.0), (10.0, -10.0), (10.0, 0.0)]; + let unsure = geo::Polygon::new(spiked.into(), vec![window.exterior().clone()]); + assert!(winding_unsure(unsure.exterior())); + for poly in [&wide_shell, &wide_hole, &unsure] { + assert_eq!(dissolve_union([poly]), geo_union_all([poly])); + } } }); } @@ -10048,7 +10061,7 @@ mod tests { } let m = Map(HashMap::from([("polys".to_string(), polys)])); let params = serde_json::json!({"input": "polys", "field": "k", "statistics": [{"field": "v", "statistic": "SUM"}]}); - let res = crate::run("dissolve", &m, ¶ms).unwrap(); + let res = finishes(move || crate::run("dissolve", &m, ¶ms).unwrap()); let note = said(&res).into_iter().find(|m| m.contains("left out")); let out = layer(res); (out.features.len(), out.value(0, 1).as_f64(), out.value(0, 2).as_f64(), note) @@ -10235,42 +10248,44 @@ mod tests { /// whose groups all have an area says nothing. #[test] fn dissolve_counts_groups_left_without_geometry() { - let triangle = |far: f64| { - let at = |x, y| Coord::new(x, y); - Geometry::Polygon(vec![vec![vec![at(0.0, 0.0), at(far, 1.0), at(1.0, 1.0), at(0.0, 1.0), at(0.0, 0.0)]]]) - }; - let empty = [vec![triangle(1e160)], vec![sq(3.0, 3.0, 0.0)], vec![sq(2.0, 0.0, 1.0), triangle(1e12)]]; - let run = |groups: &[Vec]| { - let fields = vec![Field::new("k", FieldType::Integer), Field::new("v", FieldType::Double)]; - let mut polys = Dataset::new("polys", GeometryType::Polygon, fields); - for (k, group) in groups.iter().enumerate() { - for g in group { - polys.push(Some(g.clone()), vec![Value::Int(k as i64), Value::Float(2.0)]); + finishes(|| { + let triangle = |far: f64| { + let at = |x, y| Coord::new(x, y); + Geometry::Polygon(vec![vec![vec![at(0.0, 0.0), at(far, 1.0), at(1.0, 1.0), at(0.0, 1.0), at(0.0, 0.0)]]]) + }; + let empty = [vec![triangle(1e160)], vec![sq(3.0, 3.0, 0.0)], vec![sq(2.0, 0.0, 1.0), triangle(1e12)]]; + let run = |groups: &[Vec]| { + let fields = vec![Field::new("k", FieldType::Integer), Field::new("v", FieldType::Double)]; + let mut polys = Dataset::new("polys", GeometryType::Polygon, fields); + for (k, group) in groups.iter().enumerate() { + for g in group { + polys.push(Some(g.clone()), vec![Value::Int(k as i64), Value::Float(2.0)]); + } } + let m = Map(HashMap::from([("polys".to_string(), polys)])); + let params = serde_json::json!({"input": "polys", "field": "k", "statistics": [{"field": "v", "statistic": "SUM"}]}); + let res = crate::run("dissolve", &m, ¶ms).unwrap(); + let note = said(&res).into_iter().find(|m| m.contains("without geometry")); + let out = layer(res); + let rows: Vec<_> = (0..out.features.len()) + .map(|r| (out.features.row(r).unwrap().geometry().is_some(), out.value(r, 1).as_f64(), out.value(r, 2).as_f64())) + .collect(); + (rows, note) + }; + let notice = |n: usize| { + format!( + "DroppedGeometry: Dissolve: {n} feature(s) written without geometry: merging their polygons left no area (none to begin with, too small or thin beside the group's extent, or coordinates too large to merge)" + ) + }; + let clean = vec![sq(0.0, 0.0, 1.0), sq(1.0, 0.0, 1.0)]; + let row = |geometry: bool, group: &[Geometry]| (geometry, Some(group.len() as f64), Some(2.0 * group.len() as f64)); + for group in &empty { + assert_eq!(run(&[clean.clone(), group.clone()]), (vec![row(true, &clean), row(false, group)], Some(notice(1)))); } - let m = Map(HashMap::from([("polys".to_string(), polys)])); - let params = serde_json::json!({"input": "polys", "field": "k", "statistics": [{"field": "v", "statistic": "SUM"}]}); - let res = crate::run("dissolve", &m, ¶ms).unwrap(); - let note = said(&res).into_iter().find(|m| m.contains("without geometry")); - let out = layer(res); - let rows: Vec<_> = (0..out.features.len()) - .map(|r| (out.features.row(r).unwrap().geometry().is_some(), out.value(r, 1).as_f64(), out.value(r, 2).as_f64())) - .collect(); - (rows, note) - }; - let notice = |n: usize| { - format!( - "DroppedGeometry: Dissolve: {n} feature(s) written without geometry: merging their polygons left no area (none to begin with, too small or thin beside the group's extent, or coordinates too large to merge)" - ) - }; - let clean = vec![sq(0.0, 0.0, 1.0), sq(1.0, 0.0, 1.0)]; - let row = |geometry: bool, group: &[Geometry]| (geometry, Some(group.len() as f64), Some(2.0 * group.len() as f64)); - for group in &empty { - assert_eq!(run(&[clean.clone(), group.clone()]), (vec![row(true, &clean), row(false, group)], Some(notice(1)))); - } - let rows = empty.iter().map(|g| row(false, g)).collect(); - assert_eq!(run(&empty), (rows, Some(notice(3)))); - assert_eq!(run(std::slice::from_ref(&clean)), (vec![row(true, &clean)], None)); + let rows = empty.iter().map(|g| row(false, g)).collect(); + assert_eq!(run(&empty), (rows, Some(notice(3)))); + assert_eq!(run(std::slice::from_ref(&clean)), (vec![row(true, &clean)], None)); + }); } /// Dissolve's groups, found by their keys' hash: in the order first met, −0 with 0, each NaN @@ -10296,7 +10311,7 @@ mod tests { polys.push(Some(sq(i as f64 * 3.0, 0.0, 1.0)), vec![k]); } let m = Map(HashMap::from([("polys".to_string(), polys)])); - let d = layer(crate::run("dissolve", &m, &serde_json::json!({"input": "polys", "field": "k"})).unwrap()); + let d = layer(finishes(move || crate::run("dissolve", &m, &serde_json::json!({"input": "polys", "field": "k"})).unwrap())); let got: Vec = (0..d.features.len()).map(|r| format!("{:?}×{:?}", d.value(r, 0), d.value(r, 1))).collect(); assert_eq!( got, From 1105e933282e5913d008f010e253e2ce9911baa5 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 23:17:43 -0600 Subject: [PATCH 6/6] fix(analysis): orient every ring by its signed area in Dissolve Geo reads a ring's winding from the turn at its least vertex. Nearly coincident vertices there made a tiny lobe decide it, and the whole polygon was lost. Pin i_overlay to 9.2.1 or later. --- crates/analysis/Cargo.toml | 4 ++- crates/analysis/src/tools.rs | 69 +++++++++++++++++++----------------- 2 files changed, 39 insertions(+), 34 deletions(-) diff --git a/crates/analysis/Cargo.toml b/crates/analysis/Cargo.toml index 40c3abae66..d4d33413e7 100644 --- a/crates/analysis/Cargo.toml +++ b/crates/analysis/Cargo.toml @@ -12,7 +12,9 @@ workspace = true rustgis-geom = { workspace = true } rustgis-data = { workspace = true } geo = { workspace = true } -i_overlay9 = { package = "i_overlay", version = "9.2" } +# Not 9.2.0: of 8,674 random groups it wrote invalid polygons for 5 (one of valid input), and 9.2.1 +# for none. +i_overlay9 = { package = "i_overlay", version = "9.2.1" } a5 = { workspace = true } h3o = { workspace = true } s2 = { workspace = true } diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 739853fdc8..6d6c997e2c 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1609,21 +1609,15 @@ fn geo_union_all<'a>(polys: impl IntoIterator>) -> geo::unary_union(oriented.iter()) } -/// Whether `ring`'s winding can't be read from the turn at its least vertex, as geo reads it: it -/// has no turn there (a spike), or several, as the ring comes back through it. -fn winding_unsure(ring: &geo::LineString) -> bool { - let least = ring.0.iter().copied().reduce(|a, b| if (b.x, b.y) < (a.x, a.y) { b } else { a }); - geo::Winding::winding_order(ring).is_none() || ring.0.iter().skip(1).filter(|c| Some(**c) == least).count() > 1 -} - -/// Union a Dissolve group using consistently oriented rings and OGC extraction. A ring whose -/// winding is unsure ([`winding_unsure`]) is oriented by its signed area; at exactly zero (a -/// collapsed ring, or lobes that cancel out) it keeps the direction it has, and the positive fill -/// keeps only what it goes around counterclockwise. Such an exterior that encloses nothing is -/// taken without its holes. A group uses Geo's union if any coordinate is outside the finite range -/// ±2^500 (about ±3.27e150). The i_overlay 9 stopgap uses its serial build on desktop and in the -/// browser. Its optional parallel build would require integrating the sort and split workers with -/// RustGIS's thread setting. The union is one step with no Cancel check inside it. +/// Union a Dissolve group using consistently oriented rings and OGC extraction. Each ring is +/// oriented by its signed area: geo reads the turn at its least vertex, which a spike there leaves +/// missing and nearly coincident vertices there can leave wrong. At exactly zero (a collapsed +/// ring, or lobes that cancel out) it keeps geo's direction, and the positive fill keeps only what +/// it goes around counterclockwise. An exterior that encloses nothing is taken without its holes. +/// A group uses Geo's union if any coordinate is outside the finite range ±2^500 (about +/// ±3.27e150). The i_overlay 9 stopgap uses its serial build on desktop and in the browser. Its +/// optional parallel build would require integrating the sort and split workers with RustGIS's +/// thread setting. The union is one step with no Cancel check inside it. fn dissolve_union<'a, P>(polys: P) -> MultiPolygon where P: IntoIterator>, @@ -1634,22 +1628,20 @@ where use i_overlay9::float::overlay::{FloatOverlay, OverlayOptions}; use i_overlay9::i_float::float::compatible::FloatPointCompatible; - // i_overlay 4.5 can loop forever during contour extraction. Restore geo::unary_union - // and remove the direct dependency once geo ships with i_overlay 9. + // i_overlay 4.5 can loop forever during contour extraction. Once geo ships with i_overlay 9, + // drop the direct dependency, but keep the orientation and the positive fill: geo's own main + // still picks the fill from the first ring with a winding, which loses other polygons. let polys = polys.into_iter(); let mut supported = true; let mut subject = Vec::new(); for poly in polys.clone() { let (exterior, interiors) = poly.orient(Direction::Default).into_inner(); for (hole, mut ring) in std::iter::once((false, exterior)).chain(interiors.into_iter().map(|r| (true, r))) { - let unsure = winding_unsure(&ring); - if unsure { - // Taken from the ring's first vertex, so large coordinates don't cancel out. - let area = geo::Polygon::new(ring.clone(), vec![]).signed_area(); - let backwards = if hole { area > 0.0 } else { area < 0.0 }; - if backwards { - ring.0.reverse(); - } + // Taken from the ring's first vertex, so large coordinates don't cancel out. + let area = geo::Polygon::new(ring.clone(), vec![]).signed_area(); + let backwards = if hole { area > 0.0 } else { area < 0.0 }; + if backwards { + ring.0.reverse(); } // Overlay closes paths implicitly. Polygon::new closes them again on output. let path: Vec<_> = ring @@ -1665,7 +1657,6 @@ where .collect(); // The holes of an exterior that encloses nothing would cut its neighbors. let nothing = !hole - && unsure && supported && !poly.interiors().is_empty() && FloatOverlay::with_subj_custom(&path, OverlayOptions::::ogc(), Default::default()) @@ -1682,9 +1673,8 @@ where drop(subject); return geo_union_all(polys); } - // Exteriors run counterclockwise and holes clockwise, except rings of zero area and ones that - // cross themselves so that their least vertex turns against most of their area. The fill is - // positive whichever ring comes first. + // Exteriors run counterclockwise and holes clockwise, by area, except rings of zero area. The + // fill is positive whichever ring comes first. let shapes = FloatOverlay::with_subj_custom(&subject, OverlayOptions::::ogc(), Default::default()) .overlay(OverlayRule::Subject, FillRule::Positive); MultiPolygon::new( @@ -9909,7 +9899,6 @@ mod tests { result.unwrap() } - #[cfg(not(target_arch = "wasm32"))] #[test] fn dissolve_union_finishes_extracting_contours() { use geo::Validation; @@ -10022,6 +10011,21 @@ mod tests { }); } + /// A 100 m parcel whose westmost corner has three vertices within four micrometres, where + /// its edges cross: the turn at its least vertex says the wrong way around. + #[test] + fn dissolve_union_keeps_a_ring_that_crosses_itself_at_near_duplicate_vertices() { + finishes(|| { + let (e, n) = (500_000.0, 5_000_000.0); + let mut ring = vec![(e + 100.0, n), (e + 100.0, n + 100.0), (e, n + 50.0 - 2e-6), (e - 1e-6, n + 50.0), (e, n + 50.0 + 2e-6)]; + for _ in 0..2 { + let area = geo::Area::unsigned_area(&dissolve_union([&geo::Polygon::new(ring.clone().into(), vec![])])); + assert!((area - 5000.0).abs() < 0.01, "area {area}"); + ring.reverse(); + } + }); + } + #[test] fn dissolve_union_falls_back_for_out_of_range_exteriors_and_holes() { finishes(|| { @@ -10032,9 +10036,8 @@ mod tests { let wide_shell = geo::Polygon::new(wide.clone(), vec![]); let wide_hole = geo::Polygon::new(shell.exterior().clone(), vec![wide]); let spiked = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (x, 10.0), (30.0, -10.0), (10.0, -10.0), (10.0, 0.0)]; - let unsure = geo::Polygon::new(spiked.into(), vec![window.exterior().clone()]); - assert!(winding_unsure(unsure.exterior())); - for poly in [&wide_shell, &wide_hole, &unsure] { + let spiked = geo::Polygon::new(spiked.into(), vec![window.exterior().clone()]); + for poly in [&wide_shell, &wide_hole, &spiked] { assert_eq!(dissolve_union([poly]), geo_union_all([poly])); } }