From 3725a4efed264313e2ea4bb7f84a713bf607a4f0 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 21:24:30 -0600 Subject: [PATCH 01/12] fix(analysis): overlay tools finish on polygons that trapped the overlay library --- Cargo.lock | 2 +- clippy.toml | 16 + crates/analysis/Cargo.toml | 3 - crates/analysis/src/geodesic.rs | 6 +- crates/analysis/src/repair.rs | 47 +- crates/analysis/src/selection.rs | 4 +- crates/analysis/src/sketch_edit.rs | 3 +- crates/analysis/src/tools.rs | 348 ++++++++------ crates/analysis/src/tools/repair_geometry.rs | 8 +- crates/analysis/src/topology.rs | 66 ++- .../tests/integration/repair_geometry.rs | 4 +- crates/analysis/tests/reference.rs | 2 + crates/data/Cargo.toml | 3 + crates/data/src/footprint.rs | 2 +- crates/data/src/lib.rs | 1 + crates/data/src/overlay.rs | 426 ++++++++++++++++++ crates/engine/src/cmd/design.rs | 2 +- crates/engine/src/tests.rs | 3 +- crates/tiles/src/stac/area.rs | 7 +- crates/tiles/src/vector_export.rs | 3 +- docs/user-guide/analysis.md | 2 +- 21 files changed, 743 insertions(+), 215 deletions(-) create mode 100644 crates/data/src/overlay.rs diff --git a/Cargo.lock b/Cargo.lock index c5ec1fd29d..b7161019bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5244,7 +5244,6 @@ dependencies = [ "a5", "geo", "h3o", - "i_overlay 9.2.1", "log", "proptest", "rustfft", @@ -5301,6 +5300,7 @@ dependencies = [ "geo", "geozero", "hayro", + "i_overlay 9.2.1", "image", "laz", "lerc-core", diff --git a/clippy.toml b/clippy.toml index f179907011..9d751aef91 100644 --- a/clippy.toml +++ b/clippy.toml @@ -12,7 +12,23 @@ allow-panic-in-tests = true # A thread count follows the user's setting (`rustgis_data::threads`), and a thread the system # refuses costs speed or ends one job with an error, never the app: `std::thread::spawn` panics # then, so use `std::thread::Builder` and handle its error (AGENTS.md › Use the threads). +# +# Geo's boolean operations run on an overlay engine that can loop forever on valid polygons: +# `rustgis_data::overlay` has the same operations without it. disallowed-methods = [ + { path = "geo::algorithm::bool_ops::unary_union", reason = "it can hang on valid polygons: `rustgis_data::overlay::union_all`" }, + { path = "geo::algorithm::bool_ops::BooleanOps::boolean_op", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" }, + { path = "geo::algorithm::bool_ops::BooleanOps::boolean_op_with_fill_rule", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" }, + { path = "geo::algorithm::bool_ops::BooleanOps::intersection", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" }, + { path = "geo::algorithm::bool_ops::BooleanOps::intersection_with_fill_rule", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" }, + { path = "geo::algorithm::bool_ops::BooleanOps::union", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" }, + { path = "geo::algorithm::bool_ops::BooleanOps::union_with_fill_rule", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" }, + { path = "geo::algorithm::bool_ops::BooleanOps::difference", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" }, + { path = "geo::algorithm::bool_ops::BooleanOps::difference_with_fill_rule", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" }, + { path = "geo::algorithm::bool_ops::BooleanOps::xor", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" }, + { path = "geo::algorithm::bool_ops::BooleanOps::xor_with_fill_rule", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" }, + { path = "geo::algorithm::bool_ops::BooleanOps::clip", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" }, + { path = "geo::algorithm::bool_ops::BooleanOps::clip_with_fill_rule", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" }, { path = "rustgis_geom::haversine_m", reason = "the sphere; the Earth measures with `wgs84_distance_m`" }, { path = "rustgis_geom::geodesic_length_m", reason = "the sphere; the Earth measures with `wgs84_length_m`" }, { path = "rustgis_geom::geodesic_ring_perimeter_m", reason = "the sphere; the Earth measures with `wgs84_ring_perimeter_area_m2`" }, diff --git a/crates/analysis/Cargo.toml b/crates/analysis/Cargo.toml index 0402b3e33f..bb5d8ab575 100644 --- a/crates/analysis/Cargo.toml +++ b/crates/analysis/Cargo.toml @@ -12,9 +12,6 @@ workspace = true rustgis-geom = { workspace = true } rustgis-data = { workspace = true } geo = { workspace = true } -# 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" } # FFTs for texture shading (#3146): pure Rust, MIT or Apache-2.0, builds for wasm32. rustfft = "6.4" a5 = { workspace = true } diff --git a/crates/analysis/src/geodesic.rs b/crates/analysis/src/geodesic.rs index ac0048954f..cc59180765 100644 --- a/crates/analysis/src/geodesic.rs +++ b/crates/analysis/src/geodesic.rs @@ -28,10 +28,11 @@ //! ([`crate::convert::own_length`]), as distances are in a projected system. use geo::{ - BooleanOps, Buffer, Contains, Coord as GC, CoordsIter, LineString, MultiLineString, MultiPolygon, Orient, Point, Polygon, + Buffer, Contains, Coord as GC, CoordsIter, LineString, MultiLineString, MultiPolygon, Orient, Point, Polygon, algorithm::buffer::{BufferStyle, LineCap, LineJoin}, orient::Direction, }; +use rustgis_data::overlay::Overlay as _; use rustgis_data::{Coord, Geometry}; use rustgis_geom::{Aeqd, geodesic_interpolate, haversine_m, lonlat_to_plane, plane_to_lonlat, spherical_centre}; @@ -567,8 +568,7 @@ fn union(pieces: Vec>) -> MultiPolygon { if pieces.len() == 1 { return pieces.into_iter().next().unwrap_or_else(|| MultiPolygon::new(vec![])); } - let oriented: Vec> = pieces.iter().flat_map(|m| m.0.iter()).map(|p| p.orient(Direction::Default)).collect(); - geo::unary_union(oriented.iter()) + rustgis_data::overlay::union_all(pieces.iter().flat_map(|m| m.0.iter())) } fn to_geometry(mp: &MultiPolygon) -> Option { diff --git a/crates/analysis/src/repair.rs b/crates/analysis/src/repair.rs index 3bd90addc1..606b83ab8c 100644 --- a/crates/analysis/src/repair.rs +++ b/crates/analysis/src/repair.rs @@ -11,7 +11,7 @@ //! around (non-zero winding: both lobes of a bowtie count, and the direction a ring is wound in //! doesn't matter); a part is its exterior ring's area less the union of its holes' areas, so a //! hole outside its exterior ring disappears and holes that overlap merge; and the feature is -//! the union of its parts, so parts that overlap merge. geo's boolean overlay (i_overlay) does +//! the union of its parts, so parts that overlap merge. the boolean overlay does //! the arithmetic on an integer grid, which moves coordinates a little ([`grid_step`], //! [`GRID_STEPS_MOVED`]), and writes each piece of a split interior as a part of its own. A hole //! or part narrower than a step of that grid in any direction (up to √2 steps across a diagonal, @@ -29,9 +29,10 @@ //! of the browser before it runs. Natively a panic is caught, and the feature is left as it was. use crate::validity::{self, At, Checked, Code, Limit, Problem, Room}; -use geo::algorithm::bool_ops::{BooleanOps, FillRule, OpType}; use geo::orient::{Direction, Orient}; use geo::{Area, Euclidean, Length}; +pub(crate) use rustgis_data::overlay::grid_step; +use rustgis_data::overlay::{FillRule, OpType, Overlay}; use rustgis_data::{Coord, Geometry}; /// Work per vertex the overlay takes in or makes, against the same bound as a check @@ -426,24 +427,6 @@ fn polygon( ) } -/// The step of the integer grid i_overlay rounds the points `pts` to: it takes half the larger -/// side of their extent, `h`, to about 2^29 grid units (2^(29 - round(log2 h)) units a unit of -/// the coordinates). `None` when there is no such grid: an extent that is empty, not finite, or -/// so large or so small that the scale or the step isn't a finite number. -pub(crate) fn grid_step(pts: impl Iterator) -> Option { - let (mut lo_x, mut lo_y, mut hi_x, mut hi_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); - for (x, y) in pts { - (lo_x, lo_y, hi_x, hi_y) = (lo_x.min(x), lo_y.min(y), hi_x.max(x), hi_y.max(y)); - } - let half = (hi_x - lo_x).max(hi_y - lo_y) * 0.5; - if !(half.is_finite() && half > 0.0) { - return None; - } - let e = 29.0 - half.log2().round(); - let (scale, step) = (e.exp2(), (-e).exp2()); - (scale.is_normal() && step.is_normal()).then_some(step) -} - /// The step of the grid the overlay rounds `rings` to ([`grid_step`]); an error when there is /// none, and the overlay can't run on them. fn on_grid<'a>(rings: impl Iterator>) -> Result { @@ -613,8 +596,7 @@ fn ring_area(ring: &[Coord], at: (usize, usize), crossing: &[(usize, usize)], ro // A simple ring: its area as it is, wound as the overlay expects. return Ok(geo::MultiPolygon::new(vec![poly.orient(Direction::Default)])); } - on_grid(std::iter::once(poly.exterior()))?; - Ok(poly.boolean_op_with_fill_rule(&geo::MultiPolygon::new(vec![]), OpType::Union, FillRule::NonZero)) + combine(&poly, &geo::MultiPolygon::new(vec![]), OpType::Union, FillRule::NonZero) } /// The rebuild under [`Rule::EvenOdd`] of `parts` (closed rings, each with 3 distinct points or @@ -686,7 +668,7 @@ fn by_parity(parts: &[Vec>], crossing: &[(usize, usize)], room: Room) let mut pieces: Vec> = room.vec(shell.0.len().saturating_add(cut.0.len())).map_err(kept_for)?; pieces.extend(shell.0); pieces.extend(cut.0); - geo::MultiPolygon::new(pieces).boolean_op_with_fill_rule(&empty, OpType::Union, FillRule::EvenOdd) + combine(&geo::MultiPolygon::new(pieces), &empty, OpType::Union, FillRule::EvenOdd)? }; if part.0.is_empty() { no_area += 1; @@ -712,7 +694,7 @@ fn by_parity(parts: &[Vec>], crossing: &[(usize, usize)], room: Room) let given = all.len(); let each: f64 = all.iter().map(Area::unsigned_area).sum(); let length: f64 = rings_of(&all).map(|r| Euclidean.length(r)).sum(); - let combined = geo::MultiPolygon::new(all).boolean_op_with_fill_rule(&empty, OpType::Union, FillRule::EvenOdd); + let combined = combine(&geo::MultiPolygon::new(all), &empty, OpType::Union, FillRule::EvenOdd)?; if combined.0.len() < given || each - combined.unsigned_area() > length * step { found.push(Code::PartsOverlap); } @@ -723,19 +705,26 @@ fn by_parity(parts: &[Vec>], crossing: &[(usize, usize)], room: Room) Ok(Rebuilt { polys: polygons(&combined, room).map_err(kept_for)?, no_area, narrow, found, duplicates }) } +/// `op` of `a` and `b`; an error when there is no grid ([`grid_step`]) for their coordinates, since a +/// panic in the overlay can't be caught in the browser. +fn combine(a: &impl Overlay, b: &impl Overlay, op: OpType, fill: FillRule) -> Result, Kept> { + on_grid(rings_of(a.polygons()).chain(rings_of(b.polygons())))?; + Ok(a.boolean_op_with_fill_rule(b, op, fill)) +} + /// What the checks don't tell of the holes of a part with a ring crossing itself, which they /// can't relate to the rest: [`Code::HoleOutsideShell`] when some of `cut`, its holes' areas, lies /// outside `shell`, its exterior ring's, and [`Code::RingsIntersect`] when holes overlap or touch /// along a line, which their union tells by making fewer polygons than it was given. fn unrelated_hole_codes(shell: &geo::MultiPolygon, cut: &geo::MultiPolygon, found: &mut Found) { - if !found.contains(&Code::HoleOutsideShell) && !cut.boolean_op_with_fill_rule(shell, OpType::Difference, FillRule::NonZero).0.is_empty() + if !found.contains(&Code::HoleOutsideShell) + && combine(cut, shell, OpType::Difference, FillRule::NonZero).is_ok_and(|outside| !outside.0.is_empty()) { found.push(Code::HoleOutsideShell); } if cut.0.len() > 1 && !found.contains(&Code::RingsIntersect) - && on_grid(rings_of(&cut.0)).is_ok() - && cut.boolean_op_with_fill_rule(&geo::MultiPolygon::new(vec![]), OpType::Union, FillRule::NonZero).0.len() < cut.0.len() + && combine(cut, &geo::MultiPolygon::new(vec![]), OpType::Union, FillRule::NonZero).is_ok_and(|merged| merged.0.len() < cut.0.len()) { found.push(Code::RingsIntersect); } @@ -1031,7 +1020,7 @@ fn by_area(parts: &[Vec>], crossing: &[(usize, usize)], room: Room) - if !related { unrelated_hole_codes(&shell, &cut, &mut found); } - shell.boolean_op_with_fill_rule(&cut, OpType::Difference, FillRule::NonZero) + combine(&shell, &cut, OpType::Difference, FillRule::NonZero)? }; if part.0.is_empty() { no_area += 1; @@ -1048,7 +1037,7 @@ fn by_area(parts: &[Vec>], crossing: &[(usize, usize)], room: Room) - } let all = geo::MultiPolygon::new(all); let merged = if parts.len() > 1 && all.0.len() > 1 { - let merged = all.boolean_op_with_fill_rule(&empty, OpType::Union, FillRule::NonZero); + let merged = combine(&all, &empty, OpType::Union, FillRule::NonZero)?; if merged.0.len() < all.0.len() { found.push(Code::PartsOverlap); } diff --git a/crates/analysis/src/selection.rs b/crates/analysis/src/selection.rs index bd9a66e970..fc98db19c3 100644 --- a/crates/analysis/src/selection.rs +++ b/crates/analysis/src/selection.rs @@ -3,9 +3,9 @@ //! Only the selection outline is normalized. Candidate geometries are borrowed, and their //! non-finite separators are treated as breaks rather than passed to `geo`. -use geo::algorithm::bool_ops::{BooleanOps, FillRule}; use geo::line_intersection::line_intersection; use geo::{Coord as GeoCoord, Intersects, Line, LineString, MultiPolygon, Point, Polygon}; +use rustgis_data::overlay::{FillRule, OpType, Overlay as _}; use rustgis_data::{Geometry, geometry::ring_contains}; use rustgis_geom::{Coord, Extent}; @@ -88,7 +88,7 @@ impl PolygonMask { } boundary.truncate(write); let raw = Polygon::new(LineString::new(local_ring), vec![]); - let filled = raw.union_with_fill_rule(&MultiPolygon::::new(vec![]), FillRule::EvenOdd); + let filled = raw.boolean_op_with_fill_rule(&MultiPolygon::::new(vec![]), OpType::Union, FillRule::EvenOdd); if filled.0.is_empty() { return Err("Selection outline has no filled area.".into()); } diff --git a/crates/analysis/src/sketch_edit.rs b/crates/analysis/src/sketch_edit.rs index 7fa49f26a7..438c5d6ff8 100644 --- a/crates/analysis/src/sketch_edit.rs +++ b/crates/analysis/src/sketch_edit.rs @@ -487,7 +487,8 @@ fn geo_polygon(rings: &[Vec]) -> Option> { /// The area two polygons share, in square metres (0 when their boxes don't meet). fn shared_area(a: &geo::Polygon, b: &geo::Polygon) -> f64 { - use geo::{Area, BooleanOps, BoundingRect, Intersects}; + use geo::{Area, BoundingRect, Intersects}; + use rustgis_data::overlay::Overlay as _; match (a.bounding_rect(), b.bounding_rect()) { (Some(x), Some(y)) if x.intersects(&y) => a.intersection(b).unsigned_area(), _ => 0.0, diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index f187aaa6b2..51e6cf9630 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -9,7 +9,8 @@ mod repair_geometry; mod tabulate_area; mod texture_shading; -use geo::{BooleanOps, Contains, ConvexHull, CoordsIter, InteriorPoint, Intersects, MultiPolygon, Orient, Relate, orient::Direction}; +use geo::{Contains, ConvexHull, CoordsIter, InteriorPoint, Intersects, MultiPolygon, Orient, Relate, orient::Direction}; +use rustgis_data::overlay::{Overlay as _, union_all}; use rustgis_data::raster::{Crs, Transformer}; use rustgis_data::{Coord, Dataset, Feature, Field, FieldType, Geometry, GeometryType, Measure, Value}; use rustgis_geom::Extent; @@ -1632,10 +1633,29 @@ fn result(ds: Dataset, msg: String) -> Result { Ok(ToolResult { losses: Vec::new(), output: Output::Layer(ds), messages: vec![msg] }) } -/// A geometry's polygons, or none when it has no polygon to give: an empty polygon, or a point -/// or line, which a polygon layer can hold (Minimum Bounding Geometry writes its flat hulls so). +/// A geometry's polygons, or none when it has no polygon to give: an empty polygon, one with a +/// coordinate that isn't finite, or a point or line, which a polygon layer can hold (Minimum Bounding +/// Geometry writes its flat hulls so). fn polygon_of(g: &Geometry) -> Option> { - to_multipolygon(g).filter(|mp| mp.0.iter().any(|p| !p.exterior().0.is_empty())) + to_multipolygon(g).filter(|_| !unusable(g)).filter(|mp| mp.0.iter().any(|p| !p.exterior().0.is_empty())) +} + +/// Whether a geometry is a polygon with a coordinate that isn't finite, which no overlay can cut. +fn unusable(g: &Geometry) -> bool { + to_multipolygon(g).is_some_and(|mp| mp.coords_iter().any(|c| !(c.x.is_finite() && c.y.is_finite()))) +} + +/// Says which input features `tool` can't cut ([`unusable`]), when there are any: those kept as they +/// are in a message, as nothing of them is lost, those left out as a loss. +fn say_uncut(r: &mut ToolResult, tool: &str, ds: &Dataset, rows: &[usize], kept: bool) { + let n = rows.iter().filter(|&&r| ds.features.get(r).and_then(|f| f.geometry.as_ref()).is_some_and(unusable)).count(); + let what = if kept { "kept as they are, not cut" } else { "left out" }; + let text = format!("{tool}: {n} feature(s) of '{}' {what}: they have a coordinate that isn't a number", ds.name); + match (n, kept) { + (0, _) => {} + (_, true) => r.messages.push(text), + (_, false) => r.losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedFeature, text }), + } } /// The error when `tool`, whose output would be empty, left out every feature of `layer` it was @@ -1651,7 +1671,7 @@ fn nothing_covered(tool: &str, layer: &str, left: LeftOut) -> String { /// What a feature [`overlay_zones_on`] leaves out holds: no geometry, or a geometry [`polygon_of`] /// gives nothing for. -const NO_POLYGON: &str = "no geometry, a point or line, or an empty polygon"; +const NO_POLYGON: &str = "no geometry, a point or line, an empty polygon, or one with a coordinate that isn't a number"; /// What a feature whose polygons, unioned, come to nothing holds: Clip leaves out such a mask, and /// the overlay tools such a feature of several parts (see [`ZoneUse`]). @@ -1716,91 +1736,6 @@ pub fn find_field_case_insensitive(ds: &Dataset, name: &str) -> Result(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. 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>, - P::IntoIter: Clone, -{ - 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; - - // 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))) { - // 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 - .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 - && 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; - } - } - } - // Out-of-range groups still use Geo's contour extraction, which can hang. - if !supported { - drop(subject); - return geo_union_all(polys); - } - // 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( - 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 @@ -1969,7 +1904,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 = geo_union_all(all.iter().flat_map(|m| m.0.iter())); + let u = union_all(all.iter().flat_map(|m| m.0.iter())); if u.coords_count() > limit { return Err(VERTEX_BUDGET_ERROR.into()); } @@ -2009,7 +1944,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(&geo_union_all(m.0.iter()))) + .and_then(|m| from_multipolygon(&union_all(m.0.iter()))) .map_or(std::borrow::Cow::Borrowed(g), std::borrow::Cow::Owned), _ => std::borrow::Cow::Borrowed(g), } @@ -2019,7 +1954,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 `geo_union_all` +/// The mask's polygons are in the run's plane ([`crate::convert::plane`]), oriented as [`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. @@ -2342,7 +2277,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 = || geo_union_all(near.iter().filter_map(|i| masks.get(*i)).flat_map(|(m, _)| m.0.iter())); + let make = || 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), @@ -2422,7 +2357,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 = geo_union_all(m.0.iter()); + let mask = 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) }) }, @@ -2446,16 +2381,15 @@ fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option, cache_bytes: Opti let mut out = copy_schema(ds, out_name(p, format!("{}_Clip", ds.name)), ds.geometry_type); let mut slivers = 0; let input_rows = rows(inp, p, "input", ds); - // Input features without geometry, or with an empty one: nothing of them can be kept. - let without = input_rows - .iter() - .filter(|&&r| ds.features.get(r).is_some_and(|f| f.geometry.as_ref().is_none_or(|g| g.coord_count() == 0))) - .count(); + let nothing = |g: &Geometry| g.coord_count() == 0 || unusable(g); + // Input features without geometry, with an empty one, or a polygon with a coordinate that isn't + // finite: nothing of them can be kept. + let without = input_rows.iter().filter(|&&r| ds.features.get(r).is_some_and(|f| f.geometry.as_ref().is_none_or(nothing))).count(); // The masks whose extents meet a feature's, and the poles' for a point at one. let near_of = |g: &Geometry| { let ext = projected_extent(g); - // i_overlay uses 29 integer bits about the domain centre. Allow several grid steps - // for normalization and clipping: a line just outside an edge can snap onto it. + // The overlay rounds to a grid over the domain. Allow many grid steps for normalization and + // clipping: a line just outside an edge can snap onto it. // This widens only the candidate search; the boolean overlay still decides the result. let domain = index.total.union(&ext); let margin = domain.width().max(domain.height()) / f64::from(1_u32 << 27); @@ -2511,7 +2445,9 @@ fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option, cache_bytes: Opti clip_threads, || MaskCache::new(cache_cap), |cache, _, &r| { - let Some(g) = ds.features.get(r).and_then(|f| f.geometry.as_ref()) else { return Ok::<_, String>(None) }; + let Some(g) = ds.features.get(r).and_then(|f| f.geometry.as_ref()).filter(|g| !nothing(g)) else { + return Ok::<_, String>(None); + }; let (near, ext) = near_of(g); if near.is_empty() { // A big union is kept only while the features next to each other meet it. @@ -2617,6 +2553,7 @@ fn erase_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result) -> MultiPolygon { - if poly.0.len() > 1 { geo_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) } } /// How an overlay tool uses its overlay polygons, for [`overlay_zones_on`]. @@ -2810,6 +2747,9 @@ impl Overlay { /// left out. A feature no zone overlaps is its own part outside, coordinates untouched; one that /// is cut comes out rebuilt, its overlapping parts unioned (see [`dissolved`]). fn cut(g: &Geometry, zones: &[Zone], index: (&ExtentIndex, &AtPoles), outside: bool) -> (Vec<(usize, Geometry)>, Option) { + if unusable(g) { + return (Vec::new(), outside.then(|| g.clone())); + } let ext = g.extent(); let meets = meeting(g, &ext, zones, index); // A feature of overlapping parts is unioned once, for all the zones it may meet, and only @@ -2846,7 +2786,7 @@ fn rest_outside(g: &Geometry, whole: &Geometry, hit: &[&Zone]) -> Option Some(g.clone()), [only] => part(whole, &only.poly, false), - _ => part(whole, &geo_union_all(hit.iter().flat_map(|z| z.poly.0.iter())), false), + _ => part(whole, &union_all(hit.iter().flat_map(|z| z.poly.0.iter())), false), } } @@ -2856,6 +2796,9 @@ fn rest_outside(g: &Geometry, whole: &Geometry, hit: &[&Zone]) -> Option Option { + if unusable(g) { + return Some(g.clone()); + } let ext = g.extent(); let near: Vec<&Zone> = meeting(g, &ext, zones, index).into_iter().filter_map(|zi| zones.get(zi)).collect(); if near.is_empty() { @@ -3001,6 +2944,7 @@ fn overlay_on(inp: &dyn Inputs, p: &Json, op: Overlay, threads: Option) - } let n = out.features.len(); let mut r = result(out, format!("{}: {n} features", op.name()))?; + say_uncut(&mut r, op.name(), ds, &input_rows, op.keeps_outside()); r.messages.extend(left_out.notes(op.name(), &ov.name)); Ok(r) } @@ -3189,7 +3133,9 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result) -> Result) -> Result(match polys.as_slice() { [only] => std::borrow::Cow::Borrowed(&only.poly), - _ => std::borrow::Cow::Owned(geo_union_all(polys.iter().flat_map(|z| z.poly.0.iter()))), + _ => std::borrow::Cow::Owned(union_all(polys.iter().flat_map(|z| z.poly.0.iter()))), }) }, )?; @@ -3522,11 +3468,13 @@ fn split_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result Result { crate::control::check()?; crate::control::reached(done); let n = parts.len() as i64; - let u = dissolve_union(parts.iter().flat_map(|m| m.0.iter())); + let u = union_all(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); @@ -7349,7 +7297,10 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result 0.0))); + let has_shape = |g: &Geometry| { + matches!(g, Geometry::Polygon(polys) if polys.iter().any(|rings| rings.first().is_some_and(|r| lonlat_ring_area(r) > 0.0))) + && !unusable(g) + }; let shapeless = |ds: &Dataset, rs: &[usize]| { rs.iter().filter(|&&r| ds.features.get(r).and_then(|f| f.geometry.as_ref()).is_none_or(|g| !has_shape(g))).count() }; @@ -7549,7 +7500,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(&geo_union_all(polys.iter().flat_map(|m| m.0.iter()))) else { + let Some(g) = from_multipolygon(&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", @@ -10133,7 +10084,7 @@ mod tests { } #[test] - fn dissolve_union_finishes_extracting_contours() { + fn union_all_finishes_extracting_contours() { use geo::Validation; let paths: Vec> = serde_json::from_str(include_str!("../testdata/dissolve-contours.json")).unwrap(); @@ -10152,7 +10103,7 @@ mod tests { } polys.push(rectangle(x, y, width, height)); - let union = finishes(move || dissolve_union(&polys)); + let union = finishes(move || union_all(&polys)); assert!(union.is_valid()); let mut areas: Vec<_> = union.0.iter().map(geo::Area::unsigned_area).collect(); areas.sort_by(f64::total_cmp); @@ -10163,15 +10114,74 @@ mod tests { } } + /// Every tool that overlays polygons finishes on a multipart feature whose contours trapped + /// i_overlay 4.5, given as either of its layers. + #[test] + fn overlay_tools_finish_extracting_contours() { + let paths: Vec> = serde_json::from_str(include_str!("../testdata/dissolve-contours.json")).unwrap(); + let mut parts: Vec>> = paths.iter().map(|p| vec![p.iter().map(|&(x, y)| Coord::new(x, y)).collect()]).collect(); + for p in parts.iter_mut().flatten().filter(|p| p.first() != p.last()) { + p.extend(p.first().copied()); + } + // Past the fragment solver's threshold, as in `union_all_finishes_extracting_contours`. + let (x, y, dx, dy) = (-123.796, 42.736, 0.013 / 64.0, 0.004 / 64.0); + for (row, col) in (0..64).flat_map(|r| (0..64).map(move |c| (f64::from(r), f64::from(c)))) { + let (x, y) = (x + col * dx + dx / 4.0, y + row * dy + dy / 4.0); + let corners = [(x, y), (x + dx / 2.0, y), (x + dx / 2.0, y + dy / 2.0), (x, y + dy / 2.0), (x, y)]; + parts.push(vec![corners.iter().map(|&(x, y)| Coord::new(x, y)).collect()]); + } + let trap = Geometry::Polygon(parts); + let around = Geometry::Polygon(vec![vec![ + [(-123.9, 42.6), (-123.6, 42.6), (-123.6, 42.9), (-123.9, 42.9), (-123.9, 42.6)] + .iter() + .map(|&(x, y)| Coord::new(x, y)) + .collect(), + ]]); + for (id, other) in [ + ("clip", "clip"), + ("erase", "erase"), + ("intersect", "overlay"), + ("identity", "overlay"), + ("union", "overlay"), + ("symmetricalDifference", "overlay"), + ("update", "update"), + ("split", "split"), + ("tabulateIntersection", "classes"), + ("repairGeometry", ""), + ] { + for (a, b) in [(&trap, &around), (&around, &trap)] { + let layer_of = |name: &str, g: &Geometry| { + let mut ds = Dataset::new(name, GeometryType::Polygon, vec![Field::new("k", FieldType::Text)]); + ds.push(Some(g.clone()), vec![Value::Text("k".into())]); + (name.to_string(), ds) + }; + let m = Map(HashMap::from([layer_of("a", a), layer_of("b", b)])); + let first = if id == "tabulateIntersection" { "zones" } else { "input" }; + let mut params = serde_json::json!({first: "a"}); + if !other.is_empty() { + params[other] = "b".into(); + } + if id == "split" { + params["field"] = "k".into(); + } + assert!(finishes(move || crate::run(id, &m, ¶ms).is_ok()), "{id}"); + } + } + // Merge, of the parts as they are. + let Geometry::Polygon(parts) = trap else { panic!("a polygon") }; + let parts: Vec = parts.into_iter().map(|p| Geometry::Polygon(vec![p])).collect(); + assert!(finishes(move || crate::topology::merge(&parts).is_some()), "merge"); + } + #[test] - fn dissolve_union_keeps_shells_after_a_collapsed_exterior() { + fn union_all_keeps_shells_after_a_collapsed_exterior() { 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]); + let union = union_all([&collapsed, &a, &b]); assert_eq!(union.0.len(), 2); assert!((geo::Area::unsigned_area(&union) - 2.0).abs() < 1e-9); }); @@ -10180,7 +10190,7 @@ mod tests { /// 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() { + fn union_all_leaves_a_collapsed_exteriors_holes_out() { 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(); @@ -10189,7 +10199,7 @@ mod tests { 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); + let union = union_all(group); assert!((geo::Area::unsigned_area(&union) - 1.0).abs() < 1e-9, "{union:?}"); } } @@ -10201,7 +10211,7 @@ mod tests { /// 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() { + fn union_all_keeps_rings_with_a_spike_at_their_least_vertex() { finishes(|| { use geo::{Area, MapCoords, Winding}; type Ring = geo::LineString; @@ -10236,7 +10246,7 @@ mod tests { 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); + let area = union_all(&placed).unsigned_area() / (scale * scale); assert!((area - expected).abs() < 0.01, "area {area}, expected {expected}: {placed:?}"); } } @@ -10247,36 +10257,18 @@ 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() { + fn union_all_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![])])); + let area = geo::Area::unsigned_area(&union_all([&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(|| { - 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 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])); - } - } - }); - } - /// 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 @@ -14367,7 +14359,7 @@ mod tests { .flat_map(|p| std::iter::once(p.exterior()).chain(p.interiors())) .map(|ring| Euclidean.length(ring)) .sum(); - let error = a.xor(&b).unsigned_area(); + let error = a.difference(&b).unsigned_area() + b.difference(&a).unsigned_area(); assert!(error <= perimeter * 0.1, "area error {error}: {got:?} vs {want:?}"); } else { match (got, want) { @@ -14474,7 +14466,7 @@ mod tests { .iter() .filter_map(|r| masks.features[*r].geometry.as_ref().and_then(to_multipolygon)) .collect(); - let whole = geo_union_all(polys.iter().flat_map(|m| m.0.iter())); + let whole = 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() @@ -14621,7 +14613,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 = geo_union_all(to_multipolygon(&sq(0.0, 0.0, 1.0)).unwrap().0.iter()); + let mask = 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(); @@ -14783,7 +14775,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 = geo_union_all(to_multipolygon(masks.features[0].geometry.as_ref().unwrap()).unwrap().0.iter()); + let whole = 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); @@ -15957,6 +15949,14 @@ mod tests { input.push(None, vec![]); input.push(None, vec![]); input.push(Some(Geometry::Polygon(vec![])), vec![]); + let mut broken = sq(0.0, 0.0, 1.0); + if let Geometry::Polygon(parts) = &mut broken { + // One part that can't be used leaves the whole feature out, as it is counted. + let mut bad = parts[0].clone(); + bad[0][2].x = f64::NAN; + parts.push(bad); + } + input.push(Some(broken), vec![]); let mut clean = Dataset::new("clean", GeometryType::Polygon, vec![]); clean.push(Some(sq(0.0, 0.0, 1.0)), vec![]); let mut masks = Dataset::new("masks", GeometryType::Polygon, vec![]); @@ -15964,14 +15964,66 @@ mod tests { let m = Map(HashMap::from([("input".to_string(), input), ("clean".to_string(), clean), ("masks".to_string(), masks)])); let lossy = clip(&m, &serde_json::json!({"input": "input", "clip": "masks"})).unwrap(); assert!( - said(&lossy).iter().any(|m| m == "DroppedFeature: Clip: 3 feature(s) of 'input' left out: they have no geometry to clip"), + said(&lossy).iter().any(|m| m == "DroppedFeature: Clip: 4 feature(s) of 'input' left out: they have no geometry to clip"), "{:?}", said(&lossy) ); + assert_eq!(layer(lossy).features.len(), 1, "the features it says are left out aren't written"); let clean = clip(&m, &serde_json::json!({"input": "clean", "clip": "masks"})).unwrap(); assert!(!clean.messages.iter().any(|m| m.contains("no geometry")), "{:?}", clean.messages); } + /// An input polygon with a coordinate that isn't a number can't be cut: the tools that keep what + /// lies outside keep it as it is, the others leave it out, and all say so. A clean input says + /// nothing of the kind. + #[test] + fn overlay_tools_say_which_inputs_they_cannot_cut() { + // One of its two parts is good, and meets the other layer: the whole feature counts. + let mut broken = sq(0.0, 0.0, 1.0); + if let Geometry::Polygon(parts) = &mut broken { + let mut bad = parts[0].clone(); + bad[0][2].x = f64::NAN; + parts.push(bad); + } + let of = |name: &str, shapes: Vec| { + let mut ds = Dataset::new(name, GeometryType::Polygon, vec![]); + for g in shapes { + ds.push(Some(g), vec![]); + } + (name.to_string(), ds) + }; + let m = Map(HashMap::from([ + of("input", vec![sq(0.0, 0.0, 1.0), broken]), + of("clean", vec![sq(0.0, 0.0, 1.0)]), + of("b", vec![sq(0.5, 0.0, 1.0)]), + ])); + for (id, other, kept) in [ + ("erase", "erase", true), + ("identity", "overlay", true), + ("union", "overlay", true), + ("symmetricalDifference", "overlay", true), + ("update", "update", true), + ("intersect", "overlay", false), + ("split", "split", false), + ] { + let run = |input: &str| crate::run(id, &m, &serde_json::json!({"input": input, other: "b"})).unwrap(); + let rows = |r: &ToolResult| match &r.output { + Output::Layer(d) => d.features.len(), + Output::Layers(v) => v.iter().map(|o| if let crate::OutputLayer::Vector(d) = o { d.features.len() } else { 0 }).sum(), + _ => 0, + }; + let (lossy, clean) = (run("input"), run("clean")); + let what = if kept { "kept as they are, not cut" } else { "left out" }; + let note = format!("1 feature(s) of 'input' {what}: they have a coordinate that isn't a number"); + assert!(said(&lossy).iter().any(|m| m.ends_with(¬e)), "{id}: {:?}", said(&lossy)); + assert!(!said(&clean).iter().any(|m| m.contains("isn't a number")), "{id}: {:?}", said(&clean)); + assert_eq!(rows(&lossy), rows(&clean) + usize::from(kept), "{id}"); + } + let tabulate = |zones: &str| crate::run("tabulateIntersection", &m, &serde_json::json!({"zones": zones, "classes": "b"})).unwrap(); + let no_polygon = |r: &ToolResult| said(r).iter().any(|m| m.contains("feature has no polygon and was left out")); + assert!(no_polygon(&tabulate("input")) && !no_polygon(&tabulate("clean")), "{:?}", said(&tabulate("input"))); + } + /// A shared diagonal becomes a small positive-area overlap when the mask is normalized. /// Count kept features once, across workers, without changing their geometry; an ordinary /// partial clip needs no notice. @@ -15982,7 +16034,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 = geo_union_all(to_multipolygon(&town).unwrap().0.iter()); + let mask = 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/src/tools/repair_geometry.rs b/crates/analysis/src/tools/repair_geometry.rs index c90324a10c..9bb5834e2e 100644 --- a/crates/analysis/src/tools/repair_geometry.rs +++ b/crates/analysis/src/tools/repair_geometry.rs @@ -304,7 +304,7 @@ fn notices(t: &Tally, field: &str, rule: Rule, units: &str) -> Vec { } if t.failed > 0 { messages.push(format!( - "{TOOL}: {} couldn't be repaired, because geo's geometry operations failed on {}, and {} written unchanged, with repair_failed in {field}", + "{TOOL}: {} couldn't be repaired, because the geometry operations failed on {}, and {} written unchanged, with repair_failed in {field}", features(t.failed), if t.failed == 1 { "it" } else { "them" }, is(t.failed) @@ -364,7 +364,7 @@ fn notices(t: &Tally, field: &str, rule: Rule, units: &str) -> Vec { } if t.overlaid > 0 { messages.push(format!( - "{TOOL}: {} {} rebuilt by geo's boolean overlay, which rounds coordinates to a fine grid: they may have moved by up to {} {units}, and vertices in the middle of straight edges were left out", + "{TOOL}: {} {} rebuilt by the boolean overlay, which rounds coordinates to a fine grid: they may have moved by up to {} {units}, and vertices in the middle of straight edges were left out", features(t.overlaid), was(t.overlaid), rounded_up(t.moved) @@ -482,7 +482,7 @@ mod tests { notices(&t, "repairs", Rule::default(), DEGREES), [ "Repair Geometry: repaired 0 of 9 features", - "Repair Geometry: 1 feature couldn't be repaired, because geo's geometry operations failed on it, and is written unchanged, with repair_failed in repairs", + "Repair Geometry: 1 feature couldn't be repaired, because the geometry operations failed on it, and is written unchanged, with repair_failed in repairs", ] ); let t = Tally { processed: 9, work: 2, memory: 3, failed: 2, ..Tally::default() }; @@ -491,7 +491,7 @@ mod tests { [ "Repair Geometry: 2 features were too complex to repair within the work limit and are written unchanged, with too_complex in repairs_2", "Repair Geometry: 3 features couldn't be repaired, because there wasn't enough memory to repair them, and are written unchanged, with too_complex in repairs_2", - "Repair Geometry: 2 features couldn't be repaired, because geo's geometry operations failed on them, and are written unchanged, with repair_failed in repairs_2", + "Repair Geometry: 2 features couldn't be repaired, because the geometry operations failed on them, and are written unchanged, with repair_failed in repairs_2", ] ); assert_eq!(notices(&Tally::default(), "repairs", Rule::default(), DEGREES), ["Repair Geometry: no features to repair"]); diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 796eb525e9..1e5a3b4374 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -4,7 +4,8 @@ //! in it; a projected system's own coordinates as they are, with no poles, the tolerance and the //! least area taken in its unit (#2032 C2e-5). -use geo::{Area, BooleanOps, BoundingRect, Contains, Intersects, Orient, orient::Direction}; +use geo::{Area, BoundingRect, Contains, Intersects, Orient, orient::Direction}; +use rustgis_data::overlay::Overlay as _; use rustgis_data::{Dataset, Geometry}; use rustgis_geom::{Coord, Extent, MAX_LAT, WGS84_POLAR_RADIUS_M, lonlat_to_plane, plane_to_lonlat}; @@ -80,10 +81,13 @@ thread_local! { pub fn merge(geoms: &[Geometry]) -> Option { match geoms.first()? { Geometry::Polygon(_) => { - let polys: Vec> = - geoms.iter().filter_map(to_multipolygon).map(|m| m.orient(Direction::Default)).collect(); + // Refused, not merged without a part: the features merged are deleted. + let polys: Vec> = geoms.iter().filter_map(to_multipolygon).collect(); + if !polys.iter().all(finite) { + return None; + } let all: Vec> = polys.into_iter().flat_map(|m| m.0).collect(); - from_multipolygon(&geo::unary_union(all.iter())) + from_multipolygon(&rustgis_data::overlay::union_all(all.iter())) } Geometry::Line(_) => { let parts: Vec> = @@ -114,6 +118,11 @@ pub fn explode(g: &Geometry) -> Vec { } } +fn finite(mp: &geo::MultiPolygon) -> bool { + use geo::CoordsIter; + mp.coords_iter().all(|c| c.x.is_finite() && c.y.is_finite()) +} + fn polygons(ds: &Dataset, rows: &[usize]) -> Vec<(usize, geo::MultiPolygon, geo::Rect)> { rows.iter() .filter_map(|r| { @@ -124,6 +133,14 @@ fn polygons(ds: &Dataset, rows: &[usize]) -> Vec<(usize, geo::MultiPolygon, .collect() } +/// The rows whose coordinates are all finite, which the overlay can take, and how many aren't. +fn usable(ds: &Dataset, rows: &[usize]) -> (Vec, usize) { + let whole = |r: &usize| ds.features.get(*r).and_then(|f| f.geometry.as_ref()).and_then(to_multipolygon).is_none_or(|m| finite(&m)); + let usable: Vec = rows.iter().copied().filter(whole).collect(); + let skipped = rows.len().saturating_sub(usable.len()); + (usable, skipped) +} + fn centre(mp: &geo::MultiPolygon) -> Coord { use geo::InteriorPoint; mp.interior_point().map(|p| from_plane(Coord::new(p.x(), p.y()))).unwrap_or_default() @@ -141,7 +158,8 @@ fn rects_touch(a: &geo::Rect, b: &geo::Rect) -> bool { /// Pairs of polygons that overlap (share area, not just an edge). pub fn overlaps(ds: &Dataset, rows: &[usize]) -> Checked { - let mut p = polygons(ds, rows); + let (rows, skipped) = usable(ds, rows); + let mut p = polygons(ds, &rows); // Sweep from west to east: only polygons whose boxes overlap in x are compared. p.sort_by(|a, b| a.2.min().x.total_cmp(&b.2.min().x)); let mut out = Vec::new(); @@ -149,7 +167,7 @@ pub fn overlaps(ds: &Dataset, rows: &[usize]) -> Checked { crate::control::begin(p.len()); for (i, (ra, a, ba)) in p.iter().enumerate() { if crate::control::cancelled() { - return Checked::partial(out); + return Checked { skipped, ..Checked::partial(out) }; } crate::control::reached(i); for (rb, b, bb) in p.iter().skip(i + 1) { @@ -158,7 +176,7 @@ pub fn overlaps(ds: &Dataset, rows: &[usize]) -> Checked { } work += 1; if past_limit(work) { - return Checked::partial(out); + return Checked { skipped, ..Checked::partial(out) }; } if !rects_touch(ba, bb) || !a.intersects(b) { continue; @@ -168,20 +186,21 @@ pub fn overlaps(ds: &Dataset, rows: &[usize]) -> Checked { if inter.unsigned_area() > least_area() { out.push(TopologyError { rows: vec![*ra, *rb], at: centre(&inter) }); if out.len() >= MAX_ERRORS { - return Checked::partial(out); + return Checked { skipped, ..Checked::partial(out) }; } } } } - Checked::done(out) + Checked { skipped, ..Checked::done(out) } } /// Holes in the union of a layer's polygons that no polygon covers (the outer boundary isn't a /// gap). The union of every polygon is one step: it looks at no Cancel and counts no progress /// until it is done; the holes after it are checked a polygon at a time. pub fn gaps(ds: &Dataset, rows: &[usize]) -> Checked { - let all: Vec> = polygons(ds, rows).into_iter().flat_map(|(_, m, _)| m.0).collect(); - let u = geo::unary_union(all.iter()); + let (rows, skipped) = usable(ds, rows); + let all: Vec> = polygons(ds, &rows).into_iter().flat_map(|(_, m, _)| m.0).collect(); + let u = rustgis_data::overlay::union_all(all.iter()); let mut out = Vec::new(); for poly in &u.0 { for hole in poly.interiors() { @@ -189,12 +208,12 @@ pub fn gaps(ds: &Dataset, rows: &[usize]) -> Checked { if mp.unsigned_area() > least_area() { out.push(TopologyError { rows: Vec::new(), at: centre(&mp) }); if out.len() >= MAX_ERRORS { - return Checked::partial(out); + return Checked { skipped, ..Checked::partial(out) }; } } } } - Checked::done(out) + Checked { skipped, ..Checked::done(out) } } fn segments_cross(a: (Coord, Coord), b: (Coord, Coord)) -> Option { @@ -1134,6 +1153,27 @@ pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { #[cfg(test)] mod tests { + /// A polygon with a coordinate that isn't finite: the checks skip it and count it, and Merge refuses + /// it, as it deletes the features it merges. + #[test] + fn polygons_that_are_not_finite_are_counted_and_not_merged() { + let square = |x: f64| { + let ring = [(x, 0.0), (x + 1.0, 0.0), (x + 1.0, 1.0), (x, 1.0), (x, 0.0)]; + Geometry::Polygon(vec![vec![ring.iter().map(|&(x, y)| Coord::new(x, y)).collect()]]) + }; + for bad in [f64::NAN, f64::INFINITY] { + let mut broken = square(1.0); + let Geometry::Polygon(parts) = &mut broken else { panic!("a polygon") }; + parts[0][0][2].x = bad; + assert!(merge(&[square(0.0), broken.clone()]).is_none() && merge(&[square(0.0), square(1.0)]).is_some()); + let mut ds = Dataset::new("d", rustgis_data::GeometryType::Polygon, vec![]); + ds.push(Some(square(0.0)), vec![]); + ds.push(Some(broken), vec![]); + assert_eq!((overlaps(&ds, &[0, 1]).skipped, gaps(&ds, &[0, 1]).skipped), (1, 1)); + assert_eq!((overlaps(&ds, &[0]).skipped, gaps(&ds, &[0]).skipped), (0, 0)); + } + } + use super::*; use rustgis_data::GeometryType; diff --git a/crates/analysis/tests/integration/repair_geometry.rs b/crates/analysis/tests/integration/repair_geometry.rs index 712d64bbc1..6b0626d3a8 100644 --- a/crates/analysis/tests/integration/repair_geometry.rs +++ b/crates/analysis/tests/integration/repair_geometry.rs @@ -461,7 +461,7 @@ fn a_mixed_layer_says_what_was_done_with_counts() { "Repair Geometry: the parts that overlapped or touched along a line were merged in 1 feature", "Repair Geometry: 1 feature whose interior was cut into pieces by rings touching at points is written with each piece as a part of its own", // The hole outside makes the largest extent, 21 across: a grid step of 2^-26, five of them. - "Repair Geometry: 4 features were rebuilt by geo's boolean overlay, which rounds coordinates to a fine grid: they may have moved by up to 7.5e-8 degrees of longitude or latitude, and vertices in the middle of straight edges were left out", + "Repair Geometry: 4 features were rebuilt by the boolean overlay, which rounds coordinates to a fine grid: they may have moved by up to 7.5e-8 degrees of longitude or latitude, and vertices in the middle of straight edges were left out", "DroppedGeometry: Repair Geometry: 2 features couldn't be repaired and are written without geometry (non_finite_coordinate: 1, no_area: 1)", ] ); @@ -685,7 +685,7 @@ fn a_feature_too_complex_to_repair_is_written_unchanged() { [ "Repair Geometry: repaired 1 of 3 features (self_intersection: 1)", "Repair Geometry: 2 features were too complex to repair within the work limit and are written unchanged, with too_complex in repairs", - "Repair Geometry: 1 feature was rebuilt by geo's boolean overlay, which rounds coordinates to a fine grid: they may have moved by up to 9.4e-9 degrees of longitude or latitude, and vertices in the middle of straight edges were left out", + "Repair Geometry: 1 feature was rebuilt by the boolean overlay, which rounds coordinates to a fine grid: they may have moved by up to 9.4e-9 degrees of longitude or latitude, and vertices in the middle of straight edges were left out", ] ); } diff --git a/crates/analysis/tests/reference.rs b/crates/analysis/tests/reference.rs index 8c28bc0016..57e7d45b83 100644 --- a/crates/analysis/tests/reference.rs +++ b/crates/analysis/tests/reference.rs @@ -10,6 +10,8 @@ //! When a case fails, fix the tool with RustGIS's own code. Don't translate GEOS's source to make //! it pass: GEOS is LGPL-2.1, and RustGIS is Apache-2.0 with no third-party code. +#![expect(clippy::disallowed_methods, reason = "a check on the tools, by another engine than the one they use")] + use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; diff --git a/crates/data/Cargo.toml b/crates/data/Cargo.toml index bfadf8f7cb..2be1c59bba 100644 --- a/crates/data/Cargo.toml +++ b/crates/data/Cargo.toml @@ -37,6 +37,9 @@ bytes = { workspace = true } flatgeobuf = { workspace = true } # Polygon union: a multipatch's footprint (File Geodatabase). geo = { workspace = true } +# 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" } geozero = { workspace = true } calamine = { workspace = true } # LAZ (compressed LiDAR) point clouds. diff --git a/crates/data/src/footprint.rs b/crates/data/src/footprint.rs index 92fc2fe4e3..ae3a4f0e93 100644 --- a/crates/data/src/footprint.rs +++ b/crates/data/src/footprint.rs @@ -133,7 +133,7 @@ pub(crate) fn footprint]>>( // Spent before the union runs, so faces whose union panics (and become the hull) count too: // the budget bounds the work tried, not the footprints made. *budget -= cost; - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| geo::unary_union(seen.iter()))) + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| crate::overlay::union_all(seen.iter()))) .ok() .filter(|u| !u.0.is_empty()) .map(|u| geo::MapCoords::map_coords(&u, |c| geo::coord! { x: c.x + x0, y: c.y + y0 })) diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 7c37513a9f..935b76447f 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -40,6 +40,7 @@ pub mod mbtiles; pub mod memory; pub mod ogc; pub mod osm; +pub mod overlay; pub mod photo; pub mod png; pub mod progress; diff --git a/crates/data/src/overlay.rs b/crates/data/src/overlay.rs new file mode 100644 index 0000000000..aa1ee06223 --- /dev/null +++ b/crates/data/src/overlay.rs @@ -0,0 +1,426 @@ +//! Boolean operations on polygons, for every crate: union, intersection, difference, and lines cut +//! by polygons. +//! +//! They run on i_overlay 9. Geo 0.33's own ([`geo::BooleanOps`], `geo::unary_union`) run on +//! i_overlay 4.5, which can loop forever on valid polygons while it extracts contours and drops +//! polygons whose first ring has no clear winding; `clippy.toml` refuses them. +//! +//! The arithmetic is on an integer grid fitted to each operation's extent ([`grid_step`]), about +//! 2^30 steps across. The grid is also the tolerance: corners nearer than a step meet, so neighbours +//! whose shared edges differ by rounding (each reprojected on its own) merge without pinholes. A finer grid +//! (the engine's 64-bit one) leaves those gaps open. +//! +//! An operation is one step on one thread, with no Cancel check inside it: a caller looks at Cancel +//! between operations. + +use geo::orient::Direction; +use geo::{LineString, MapCoords, MultiLineString, MultiPolygon, Orient, Polygon}; +pub use i_overlay9::core::fill_rule::FillRule; +use i_overlay9::core::overlay::ShapeType; +use i_overlay9::core::overlay_rule::OverlayRule; +use i_overlay9::float::overlay::{FloatOverlay, OverlayOptions}; +use i_overlay9::float::string_overlay::FloatStringOverlay; +use i_overlay9::i_float::adapter::FloatPointAdapter; +use i_overlay9::string::clip::ClipRule; + +/// What an operation keeps of two areas. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OpType { + Intersection, + Union, + Difference, +} + +impl From for OverlayRule { + fn from(op: OpType) -> Self { + match op { + OpType::Intersection => Self::Intersect, + OpType::Union => Self::Union, + OpType::Difference => Self::Difference, + } + } +} + +type Point = [f64; 2]; +type Adapter = FloatPointAdapter; + +/// A ring as the overlay takes it, its closing point left off. +fn path(ring: &LineString) -> Vec { + ring.0.split_last().map_or(&[][..], |(_, open)| open).iter().map(|c| [c.x, c.y]).collect() +} + +fn paths(polys: &[Polygon]) -> Vec> { + polys.iter().filter(|p| finite(p)).flat_map(|p| std::iter::once(p.exterior()).chain(p.interiors())).map(path).collect() +} + +/// Whether a polygon's coordinates are all finite. One that has others encloses no area that can be +/// told, so the operations leave it out; tools count such features before they come here. +fn finite(p: &Polygon) -> bool { + std::iter::once(p.exterior()).chain(p.interiors()).flat_map(|r| &r.0).all(|c| c.x.is_finite() && c.y.is_finite()) +} + +/// The engine panics on coordinates past 2^500 (about 3.27e150), and can't scale an extent near the +/// smallest floats. Coordinates with any past it are taken from the first one, and brought within +/// range by a power of two if they are still past it; ones all that small are enlarged by a power of +/// two. Neither loses what the grid over them can hold: a difference is exact, or rounded by far less +/// than a step of the grid. +#[derive(Clone, Copy, PartialEq)] +struct Near { + origin: Point, + by: f64, +} + +const TOO_FAR: f64 = 3.27e150; +/// 2^-500. +const TOO_SMALL: f64 = f64::from_bits(((1023 - 500) as u64) << 52); +/// 2^-525, which takes a difference of any two floats within 2^500, and its reciprocal. +const NEARER: f64 = f64::from_bits(((1023 - 525) as u64) << 52); +const LARGER: f64 = f64::from_bits(((1023 + 525) as u64) << 52); + +impl Near { + /// Nothing to do: every coordinate is within range. + const AS_IS: Near = Near { origin: [0.0, 0.0], by: 1.0 }; + + /// What the points need. + fn of<'a>(pts: impl Iterator + Clone) -> Near { + let largest = pts.clone().flatten().fold(0.0_f64, |m, v| m.max(v.abs())); + if largest > 0.0 && largest < TOO_SMALL { + return Near { by: LARGER, ..Near::AS_IS }; + } + if largest <= TOO_FAR { + return Near::AS_IS; + } + let origin = pts.clone().next().copied().unwrap_or_default(); + // A difference past the largest float is infinite, so past it too. + let spread = pts.into_iter().any(|p| (p[0] - origin[0]).abs() > TOO_FAR || (p[1] - origin[1]).abs() > TOO_FAR); + Near { origin, by: if spread { NEARER } else { 1.0 } } + } + + fn to(self, [x, y]: Point) -> Point { + let one = |v: f64, o: f64| if self.by == 1.0 { v - o } else { v * self.by - o * self.by }; + [one(x, self.origin[0]), one(y, self.origin[1])] + } + + fn bring(self, paths: &mut [Vec]) { + if self != Near::AS_IS { + for p in paths.iter_mut().flatten() { + *p = self.to(*p); + } + } + } + + /// A point of a result, taken back. One the grid rounds past the largest float stays there, and + /// adding 0 takes the sign off a negative zero. + fn back(self, [x, y]: Point) -> (f64, f64) { + let one = |v: f64, o: f64| { + let v = if self.by == 1.0 { v + o } else { (v + o * self.by) / self.by }; + v.clamp(f64::MIN, f64::MAX) + 0.0 + }; + (one(x, self.origin[0]), one(y, self.origin[1])) + } +} + +fn points<'a>(a: &'a [Vec], b: &'a [Vec]) -> impl Iterator + Clone { + a.iter().flatten().chain(b.iter().flatten()) +} + +fn count(paths: &[Vec]) -> usize { + paths.iter().map(Vec::len).sum() +} + +fn multipolygon(shapes: Vec>>, near: Near) -> MultiPolygon { + let polygon = |shape: Vec>| { + // Polygon::new closes the rings. + let mut rings = shape.into_iter().map(|path| path.into_iter().map(|p| near.back(p)).collect::>()).map(LineString::from); + Polygon::new(rings.next().unwrap_or_else(LineString::empty), rings.collect()) + }; + MultiPolygon::new(shapes.into_iter().map(polygon).collect()) +} + +/// The step of the grid the points are rounded to: half the larger side of their extent, `h`, is +/// about 2^29 steps (2^(29 - round(log2 h)) steps a unit of the coordinates). `None` when there is no +/// such grid: an extent that is empty, not finite, or so large or so small that the scale or the step +/// isn't a finite number. +pub fn grid_step(pts: impl Iterator) -> Option { + let (mut lo_x, mut lo_y, mut hi_x, mut hi_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for (x, y) in pts { + (lo_x, lo_y, hi_x, hi_y) = (lo_x.min(x), lo_y.min(y), hi_x.max(x), hi_y.max(y)); + } + let half = (hi_x - lo_x).max(hi_y - lo_y) * 0.5; + if !(half.is_finite() && half > 0.0) { + return None; + } + let e = 29.0 - half.log2().round(); + let (scale, step) = (e.exp2(), (-e).exp2()); + (scale.is_normal() && step.is_normal()).then_some(step) +} + +/// The grid for `pts`, at [`grid_step`]'s step: coordinates up to 2^29.5 steps from its middle, within +/// the 2^30 the engine's 32-bit arithmetic takes, which the 30 bits asked for here check. Points with no such step (all one point, or an extent +/// near the limits of a float) get the engine's own grid. +fn adapter<'a>(pts: impl Iterator + Clone) -> Adapter { + grid_step(pts.clone().map(|&[x, y]| (x, y))) + .and_then(|step| Adapter::try_with_iter_and_scale_and_coordinate_bits(pts.clone(), step.recip(), 30).ok()) + .unwrap_or_else(|| Adapter::with_iter_conservative(pts)) +} + +/// Runs `rule` on paths of finite coordinates. +fn overlay(mut subject: Vec>, mut clip: Vec>, rule: OverlayRule, fill: FillRule) -> MultiPolygon { + let near = Near::of(points(&subject, &clip)); + near.bring(&mut subject); + near.bring(&mut clip); + let grid = adapter(points(&subject, &clip)); + let room = count(&subject).saturating_add(count(&clip)); + let shapes = FloatOverlay::new_custom(grid, OverlayOptions::::ogc(), Default::default(), room) + .unsafe_add_source(&subject, ShapeType::Subject) + .unsafe_add_source(&clip, ShapeType::Clip) + .overlay(rule, fill); + multipolygon(shapes, near) +} + +/// Polygons the overlay operations take: one, or several. +pub trait Overlay { + /// The polygons. + fn polygons(&self) -> &[Polygon]; + + /// `op` of the two areas, each filled by `fill`. A polygon with a coordinate that isn't finite is + /// left out. + fn boolean_op_with_fill_rule(&self, other: &impl Overlay, op: OpType, fill: FillRule) -> MultiPolygon { + overlay(paths(self.polygons()), paths(other.polygons()), op.into(), fill) + } + + /// What both cover. Each side's polygons mustn't overlap each other. + fn intersection(&self, other: &impl Overlay) -> MultiPolygon { + self.boolean_op_with_fill_rule(other, OpType::Intersection, FillRule::EvenOdd) + } + + /// What either covers. Each side's polygons mustn't overlap each other. + fn union(&self, other: &impl Overlay) -> MultiPolygon { + self.boolean_op_with_fill_rule(other, OpType::Union, FillRule::EvenOdd) + } + + /// What `self` covers and `other` doesn't. Each side's polygons mustn't overlap each other. + fn difference(&self, other: &impl Overlay) -> MultiPolygon { + self.boolean_op_with_fill_rule(other, OpType::Difference, FillRule::EvenOdd) + } + + /// The stretches of `lines` inside the polygons or on their edges; those outside when `invert`. + /// A polygon with a coordinate that isn't finite is left out, and a line breaks at one. + fn clip(&self, lines: &MultiLineString, invert: bool) -> MultiLineString { + let mut shape = paths(self.polygons()); + let mut strings: Vec> = lines + .0 + .iter() + .flat_map(|l| l.0.split(|c| !(c.x.is_finite() && c.y.is_finite()))) + .filter(|run| run.len() > 1) + .map(|run| run.iter().map(|c| [c.x, c.y]).collect()) + .collect(); + let near = Near::of(points(&shape, &strings)); + near.bring(&mut shape); + near.bring(&mut strings); + let grid = adapter(points(&shape, &strings)); + let cut = FloatStringOverlay::with_adapter(grid, count(&shape).saturating_add(count(&strings))) + .unsafe_add_shapes(&shape) + .unsafe_add_string_lines(&strings) + .clip_string_lines_with_solver(FillRule::EvenOdd, ClipRule { invert, boundary_included: true }, Default::default()); + let line = |path: Vec| LineString::from(path.into_iter().map(|p| near.back(p)).collect::>()); + MultiLineString::new(cut.into_iter().map(line).collect()) + } +} + +impl Overlay for Polygon { + fn polygons(&self) -> &[Polygon] { + std::slice::from_ref(self) + } +} + +impl Overlay for MultiPolygon { + fn polygons(&self) -> &[Polygon] { + &self.0 + } +} + +/// Twice a path's signed area, taken from its first vertex so that large coordinates don't cancel out. +fn double_area(path: &[Point]) -> f64 { + let Some(&[ox, oy]) = path.first() else { return 0.0 }; + let next = path.iter().cycle().skip(1); + path.iter().zip(next).map(|(&[ax, ay], &[bx, by])| (ax - ox) * (by - oy) - (bx - ox) * (ay - oy)).sum() +} + +/// Whether a ring of this path encloses nothing. Rounding to its grid moves each vertex by at most +/// half a step on each axis, which changes its signed area by less than its length times a step and a +/// squared step a vertex: one with more has some. The overlay tells for the rest. +fn encloses_nothing(path: &[Point], double_area: f64) -> bool { + let length: f64 = path.iter().zip(path.iter().cycle().skip(1)).map(|(a, b)| (b[0] - a[0]).hypot(b[1] - a[1])).sum(); + let some = grid_step(path.iter().map(|&[x, y]| (x, y))) + .is_some_and(|step| double_area.abs() > 2.0 * (2.0 * length + path.len() as f64 * step) * step); + !some && overlay(vec![path.to_vec()], Vec::new(), OverlayRule::Subject, FillRule::NonZero).0.is_empty() +} + +/// The union of `polys`, which may overlap and wind either way. 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, which would cut +/// other polygons. A polygon with a coordinate that isn't finite is left out. +pub fn union_all<'a, P>(polys: P) -> MultiPolygon +where + P: IntoIterator>, + P::IntoIter: Clone, +{ + let polys = polys.into_iter().filter(|p| finite(p)); + // Brought near first, so that orienting and measuring a ring are the same at any size. + let all = || polys.clone().flat_map(|p| std::iter::once(p.exterior()).chain(p.interiors())).flat_map(|r| &r.0); + if all().all(|c| ordinary(c.x) && ordinary(c.y)) { + return union_near(polys); + } + let every: Vec = all().map(|c| [c.x, c.y]).collect(); + let near = Near::of(every.iter()); + let moved: Vec> = polys.map(|p| p.map_coords(|c| near.to([c.x, c.y]).into())).collect(); + union_near(moved.iter()).map_coords(|c| near.back([c.x, c.y]).into()) +} + +/// Whether a coordinate is of a size the engine takes as it is. +fn ordinary(v: f64) -> bool { + v == 0.0 || (TOO_SMALL..=TOO_FAR).contains(&v.abs()) +} + +/// [`union_all`] of polygons within range. +fn union_near<'a>(polys: impl Iterator>) -> MultiPolygon { + let mut subject = Vec::new(); + for poly in polys { + let (exterior, interiors) = poly.orient(Direction::Default).into_inner(); + let holed = !interiors.is_empty(); + for (hole, ring) in std::iter::once((false, exterior)).chain(interiors.into_iter().map(|r| (true, r))) { + let mut path = path(&ring); + let area = double_area(&path); + let nothing = !hole && holed && encloses_nothing(&path, area); + if if hole { area > 0.0 } else { area < 0.0 } { + path.reverse(); + } + subject.push(path); + if nothing { + break; + } + } + } + // Exteriors run counterclockwise and holes clockwise, by area, except rings of zero area. The + // fill is positive whichever ring comes first. + overlay(subject, Vec::new(), OverlayRule::Subject, FillRule::Positive) +} + +#[cfg(test)] +mod tests { + use super::*; + use geo::Area; + + /// Neighbours whose shared corners differ by a nanometre, as each reprojected on its own does, + /// merge into one polygon without pinholes: the grid's step is what joins them. + #[test] + fn neighbours_apart_by_rounding_merge_without_pinholes() { + let mut seed = 7_u64; + let mut noise = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed as f64 / u64::MAX as f64 - 0.5) * 2e-9 + }; + let (cos, sin) = (0.3_f64.cos(), 0.3_f64.sin()); + let mut parcels = Vec::new(); + for (i, j) in (0..20).flat_map(|i| (0..20).map(move |j| (i, j))) { + let ring: Vec<(f64, f64)> = [(0, 0), (1, 0), (1, 1), (0, 1)] + .iter() + .map(|(a, b)| (f64::from(i + a) * 30.0, f64::from(j + b) * 30.0)) + .map(|(x, y)| (500_000.0 + cos * x - sin * y + noise(), 4_980_000.0 + sin * x + cos * y + noise())) + .collect(); + parcels.push(Polygon::new(ring.into(), vec![])); + } + let whole = union_all(&parcels); + assert_eq!(whole.0.iter().map(|p| p.interiors().len()).collect::>(), [0], "one polygon, no pinholes"); + assert!((whole.unsigned_area() - 360_000.0).abs() < 1e-4, "{}", whole.unsigned_area()); + } + + /// Coordinates past the engine's range give the results the same shapes nearer by give. + #[test] + fn coordinates_past_the_engines_range_are_scaled() { + let at = |x: f64, y: f64, w: f64, by: f64| geo::Rect::new((x * by, y * by), ((x + w) * by, (y + w) * by)).to_polygon(); + let shapes = |by: f64| { + let (a, b) = (at(0.0, 0.0, 2.0, by), at(1.0, 1.0, 2.0, by)); + let line = MultiLineString::new(vec![vec![(-by, 0.5 * by), (3.0 * by, 0.5 * by)].into()]); + (a.intersection(&b), a.union(&b), a.difference(&b), union_all([&a, &b]), a.clip(&line, false)) + }; + let near = shapes(1.0); + assert_eq!((near.0.unsigned_area(), near.1.unsigned_area(), near.2.unsigned_area()), (1.0, 7.0, 3.0)); + assert_eq!(near.4.0, [LineString::from(vec![(0.0, 0.5), (2.0, 0.5)])]); + let by = 2_f64.powi(900); + let far = shapes(by); + let nearer = |m: &MultiPolygon| m.map_coords(|c| geo::coord! { x: c.x / by, y: c.y / by }); + assert_eq!((nearer(&far.0), nearer(&far.1), nearer(&far.2), nearer(&far.3)), (near.0, near.1, near.2, near.3)); + assert_eq!(far.4.map_coords(|c| geo::coord! { x: c.x / by, y: c.y / by }), near.4); + } + + /// A short span far out is kept: the grid is fitted to it, not to its distance from the origin. + #[test] + fn a_short_span_far_out_is_kept() { + let none = MultiPolygon::new(vec![]); + for (x, span) in [(1e151, 1e-200), (1e300, 1e-100), (1e308, 1.0)] { + let line = MultiLineString::new(vec![vec![(x, 0.0), (x, span)].into()]); + // To within the grid's step. + let kept = none.clip(&line, true); + let ys: Vec = kept.0.iter().flat_map(|l| &l.0).map(|c| c.y).collect(); + assert!(kept.0.iter().flat_map(|l| &l.0).all(|c| c.x == x), "{kept:?}"); + assert!(matches!(ys[..], [a, b] if a.abs() < span * 1e-8 && (b - span).abs() < span * 1e-8), "{kept:?}"); + } + let widest = geo::Rect::new((f64::MIN, f64::MIN), (f64::MAX, f64::MAX)).to_polygon(); + let whole = union_all([&widest]); + assert!(whole.0.iter().flat_map(|p| &p.exterior().0).all(|c| c.x.abs() > 1.79e308 && c.y.abs() > 1.79e308) && whole.0.len() == 1); + } + + /// A shape gives the same union at any size and place, as far as floats hold it: a bow tie whose + /// lobes cancel out, a ring both ways round, and a hole. + #[test] + fn a_union_is_the_same_at_any_size() { + let tie = vec![(0.0, 0.0), (2.0, 2.0), (2.0, 0.0), (0.0, 2.0), (0.0, 0.0)]; + let ring = vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0), (0.0, 0.0)]; + let hole: Vec<(f64, f64)> = ring.iter().map(|(x, y)| (x / 2.0 + 1.0, y / 2.0 + 1.0)).collect(); + let back: Vec<(f64, f64)> = ring.iter().rev().copied().collect(); + for (outer, inner) in [(&tie, None), (&ring, None), (&back, None), (&ring, Some(&hole)), (&back, Some(&hole))] { + let at = |by: f64| { + let line = |r: &Vec<(f64, f64)>| LineString::from(r.iter().map(|(x, y)| (x * by, y * by)).collect::>()); + union_all([&Polygon::new(line(outer), inner.iter().map(|h| line(h)).collect())]) + .map_coords(|c| geo::coord! { x: c.x / by, y: c.y / by }) + }; + let near = at(1.0); + for power in [-1060, -1000, -700, -510, -400, 400, 498, 505, 900, 1020] { + let by = 2_f64.powi(power / 2) * 2_f64.powi(power - power / 2); + assert_eq!(at(by), near, "2^{power}"); + } + } + let none = MultiPolygon::new(vec![]); + for x in [f64::from_bits(1 << 40), 1e-310, 1e-290] { + let line = MultiLineString::new(vec![vec![(0.0, 0.0), (x, 0.0)].into()]); + let kept = none.clip(&line, true); + assert!(kept.0.iter().flat_map(|l| &l.0).any(|c| (c.x / x - 1.0).abs() < 1e-8), "{x:e}: {kept:?}"); + } + } + + /// A polygon with a coordinate that isn't finite is left out, without a panic or a made-up result. + #[test] + fn polygons_that_are_not_finite_are_left_out() { + let square = geo::Rect::new((0.0, 0.0), (1.0, 1.0)).to_polygon(); + let line = MultiLineString::new(vec![vec![(-1.0, 0.5), (2.0, 0.5)].into()]); + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let broken = Polygon::new(vec![(0.0, 0.0), (1.0, 0.0), (bad, 0.5), (1.0, 1.0), (0.0, 1.0)].into(), vec![]); + let holed = Polygon::new(square.exterior().clone(), vec![broken.exterior().clone()]); + for poly in [&broken, &holed] { + assert_eq!(union_all([poly, &square]), union_all([&square])); + assert_eq!(poly.union(&square), union_all([&square])); + assert_eq!(square.difference(poly), union_all([&square])); + assert!(square.intersection(poly).0.is_empty() && poly.clip(&line, false).0.is_empty()); + } + // The vertex left alone, far off, makes no segment, and doesn't widen the grid. + let cut = MultiLineString::new(vec![vec![(0.25, 0.5), (0.5, 0.5), (bad, 0.5), (1e12, 0.5)].into()]); + assert_eq!(square.clip(&cut, false).0, [LineString::from(vec![(0.25, 0.5), (0.5, 0.5)])]); + } + } +} diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 15459ccde4..2eea14d38d 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -3248,7 +3248,7 @@ fn topology_validate(s: &mut Session, p: &Json) -> CmdResult { } if !skipped.is_empty() { s.warn(format!( - "Polygons left out of the check at a pole (a coordinate missing or infinite, or a million turns around), so its result there may be wrong: {}", + "Polygons left out of the check (a coordinate missing or infinite, or, at a pole, a million turns around), so its result there may be wrong: {}", skipped.join("; ") )); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7019fb34ed..bbfbc546cb 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -55263,7 +55263,8 @@ fn must_be_covered_by_says_which_polygons_it_left_out_at_a_pole() { assert_eq!(v["errors"], u64::from(warned)); assert_eq!(v["incomplete"].as_array().map(Vec::len), Some(usize::from(warned))); let said = s.notices_since(mark).iter().any(|n| { - n.text.contains("left out of the check at a pole") && n.text.contains("Must Be Covered By on 'Pole': 1 feature(s) of 'Caps'") + n.text.contains("left out of the check (a coordinate missing or infinite") + && n.text.contains("Must Be Covered By on 'Pole': 1 feature(s) of 'Caps'") }); assert_eq!(said, warned, "{:?}", s.notices_since(mark)); } diff --git a/crates/tiles/src/stac/area.rs b/crates/tiles/src/stac/area.rs index 4b577783aa..29c6793f69 100644 --- a/crates/tiles/src/stac/area.rs +++ b/crates/tiles/src/stac/area.rs @@ -7,7 +7,7 @@ //! what it left out, so the caller can say so. Input is hostile: coordinates must be finite and on //! the globe, and a geometry of more than [`MAX_POSITIONS`] positions is refused. -use geo::{Intersects, Orient, orient::Direction}; +use geo::Intersects; use rustgis_data::Geometry; use rustgis_geom::Coord; use serde_json::Value; @@ -128,9 +128,8 @@ fn dissolve(polygons: Vec>>) -> Geometry { if polygons.len() == 1 { return Geometry::Polygon(polygons); } - // The overlay infers its fill rule from the first ring's winding, and files mix orientations. - let oriented: Vec> = polygons.iter().filter_map(|p| geo_polygon(p)).map(|p| p.orient(Direction::Default)).collect(); - let union = geo::unary_union(oriented.iter()); + let given: Vec> = polygons.iter().filter_map(|p| geo_polygon(p)).collect(); + let union = rustgis_data::overlay::union_all(&given); let ring = |l: &geo::LineString| l.coords().map(|c| round(Coord::new(c.x, c.y))).collect::>(); let merged: Vec>> = union .0 diff --git a/crates/tiles/src/vector_export.rs b/crates/tiles/src/vector_export.rs index b2327cf43c..36ea4aa1d0 100644 --- a/crates/tiles/src/vector_export.rs +++ b/crates/tiles/src/vector_export.rs @@ -15,8 +15,9 @@ use std::collections::{BTreeMap, BTreeSet}; use std::mem::size_of; -use geo::{BooleanOps, Coord as GC, LineString, Polygon, Rect, Validation}; +use geo::{Coord as GC, LineString, Polygon, Rect, Validation}; use rustgis_data::capped::Limit; +use rustgis_data::overlay::Overlay as _; use rustgis_data::{Coord, Dataset, FieldType, Geometry, Value}; use crate::{mvt, pmtiles}; diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 83c185e3e4..3b2588c8f0 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -883,7 +883,7 @@ gp.run={"tool":"split","params":{"input":"roads","split":"districts","field":"na Clip, Erase, Intersect, Identity, Union, Symmetrical Difference, Update and Split leave out a feature of the clip, erase, overlay, update or split layer with no polygon, and say how many: one without geometry, a point or line in the polygon layer (as Minimum Bounding Geometry's flat hulls -are), or an empty polygon. Clip also leaves out a mask whose polygons, unioned, have no area, and +are), an empty polygon, or one with a coordinate that isn't a number. Clip also leaves out a mask whose polygons, unioned, have no area, and the others a feature of several parts that, unioned, come to nothing (Update writes it as it is), saying how many. Clip also says how many input features it leaves out for having no geometry, or an empty one. When none of the features of that layer is left, Clip, Intersect and Split, whose From ebdf73c551d1ec68c952b2cbb5c5aab4b5a3f352 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 01:17:31 -0600 Subject: [PATCH 02/12] fix(analysis): coordinates that aren't numbers are asked before the plane, and refusals say so --- crates/analysis/src/convert.rs | 6 + crates/analysis/src/tools.rs | 148 +++++++++++------- crates/analysis/src/topology.rs | 30 ++-- .../tests/integration/repair_geometry.rs | 2 +- crates/data/src/overlay.rs | 18 ++- crates/engine/src/cmd/design.rs | 3 + 6 files changed, 128 insertions(+), 79 deletions(-) diff --git a/crates/analysis/src/convert.rs b/crates/analysis/src/convert.rs index 98ed767c8a..08db5ff611 100644 --- a/crates/analysis/src/convert.rs +++ b/crates/analysis/src/convert.rs @@ -122,6 +122,12 @@ fn gc(c: Coord) -> GC { GC { x: m.x, y: m.y } } +/// Whether a geometry is a polygon with a coordinate that isn't finite, in its own coordinates or in +/// the run's plane. Its own are asked first: an infinite latitude is a pole once in the plane. +pub fn polygon_not_finite(g: &Geometry) -> bool { + matches!(g, Geometry::Polygon(polys) if polys.iter().flatten().flatten().any(|&c| !c.is_finite() || !to_plane(c).is_finite())) +} + fn back(c: &GC) -> Coord { from_plane(Coord::new(c.x, c.y)) } diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 51e6cf9630..1e91e14f87 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -19,7 +19,7 @@ use std::borrow::Cow; use std::collections::{HashMap, HashSet, TryReserveError, VecDeque}; use std::ops::ControlFlow; -use crate::convert::{from_line, from_multipolygon, from_point, reaches_poles, to_geo, to_multiline, to_multipolygon}; +use crate::convert::{from_line, from_multipolygon, from_point, polygon_not_finite, reaches_poles, to_geo, to_multiline, to_multipolygon}; use crate::geodesic::{PARALLEL_FEATURES, VERTEX_BUDGET_ERROR, geodesic_buffer_with_limit, geodesic_buffers_with_limit}; use crate::{Inputs, Output, OutputLayer, ParamKind as K, ParamSpec as P, ToolResult, ToolSpec}; @@ -1637,18 +1637,13 @@ fn result(ds: Dataset, msg: String) -> Result { /// coordinate that isn't finite, or a point or line, which a polygon layer can hold (Minimum Bounding /// Geometry writes its flat hulls so). fn polygon_of(g: &Geometry) -> Option> { - to_multipolygon(g).filter(|_| !unusable(g)).filter(|mp| mp.0.iter().any(|p| !p.exterior().0.is_empty())) + to_multipolygon(g).filter(|_| !polygon_not_finite(g)).filter(|mp| mp.0.iter().any(|p| !p.exterior().0.is_empty())) } -/// Whether a geometry is a polygon with a coordinate that isn't finite, which no overlay can cut. -fn unusable(g: &Geometry) -> bool { - to_multipolygon(g).is_some_and(|mp| mp.coords_iter().any(|c| !(c.x.is_finite() && c.y.is_finite()))) -} - -/// Says which input features `tool` can't cut ([`unusable`]), when there are any: those kept as they +/// Says which input features `tool` can't cut ([`polygon_not_finite`]), when there are any: those kept as they /// are in a message, as nothing of them is lost, those left out as a loss. fn say_uncut(r: &mut ToolResult, tool: &str, ds: &Dataset, rows: &[usize], kept: bool) { - let n = rows.iter().filter(|&&r| ds.features.get(r).and_then(|f| f.geometry.as_ref()).is_some_and(unusable)).count(); + let n = rows.iter().filter(|&&r| ds.features.get(r).and_then(|f| f.geometry.as_ref()).is_some_and(polygon_not_finite)).count(); let what = if kept { "kept as they are, not cut" } else { "left out" }; let text = format!("{tool}: {n} feature(s) of '{}' {what}: they have a coordinate that isn't a number", ds.name); match (n, kept) { @@ -1963,7 +1958,11 @@ fn part(g: &Geometry, mask: &MultiPolygon, inside: bool) -> Option { to_multipolygon(g).and_then(|m| from_multipolygon(&if inside { m.intersection(mask) } else { m.difference(mask) })) } - Geometry::Line(_) => to_multiline(g).and_then(|m| from_line(&mask.clip(&m, !inside))), + // Broken here, in the line's own coordinates: an infinite latitude is a pole in the plane. + Geometry::Line(parts) => { + let runs = parts.iter().flat_map(|p| p.split(|c| !c.is_finite())).map(crate::convert::ring); + from_line(&mask.clip(&geo::MultiLineString::new(runs.collect()), !inside)) + } Geometry::Point(_) | Geometry::MultiPoint(_) => { let pts: &[Coord] = match g { Geometry::Point(c) => std::slice::from_ref(c), @@ -2381,7 +2380,7 @@ fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option, cache_bytes: Opti let mut out = copy_schema(ds, out_name(p, format!("{}_Clip", ds.name)), ds.geometry_type); let mut slivers = 0; let input_rows = rows(inp, p, "input", ds); - let nothing = |g: &Geometry| g.coord_count() == 0 || unusable(g); + let nothing = |g: &Geometry| g.coord_count() == 0 || polygon_not_finite(g); // Input features without geometry, with an empty one, or a polygon with a coordinate that isn't // finite: nothing of them can be kept. let without = input_rows.iter().filter(|&&r| ds.features.get(r).is_some_and(|f| f.geometry.as_ref().is_none_or(nothing))).count(); @@ -2513,7 +2512,10 @@ fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option, cache_bytes: Opti if without > 0 { r.losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedFeature, - text: format!("Clip: {without} feature(s) of '{}' left out: they have no geometry to clip", ds.name), + text: format!( + "Clip: {without} feature(s) of '{}' left out: they have no geometry to clip, or a coordinate that isn't a number", + ds.name + ), }); } r.messages.extend(left.notes("Clip", &clip_ds.name)); @@ -2747,7 +2749,7 @@ impl Overlay { /// left out. A feature no zone overlaps is its own part outside, coordinates untouched; one that /// is cut comes out rebuilt, its overlapping parts unioned (see [`dissolved`]). fn cut(g: &Geometry, zones: &[Zone], index: (&ExtentIndex, &AtPoles), outside: bool) -> (Vec<(usize, Geometry)>, Option) { - if unusable(g) { + if polygon_not_finite(g) { return (Vec::new(), outside.then(|| g.clone())); } let ext = g.extent(); @@ -2796,7 +2798,7 @@ fn rest_outside(g: &Geometry, whole: &Geometry, hit: &[&Zone]) -> Option Option { - if unusable(g) { + if polygon_not_finite(g) { return Some(g.clone()); } let ext = g.extent(); @@ -3270,7 +3272,7 @@ fn split_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result Result { // Features read, none with a polygon: an unusable result, so an error saying why. if n == 0 && not_polygons > 0 { return Err(format!( - "Dissolve: none of the {not_polygons} feature(s) has a polygon: no geometry, an empty polygon, or a point or line" + "Dissolve: none of the {not_polygons} feature(s) has a polygon: no geometry, an empty polygon, a coordinate that isn't a number, or a point or line" )); } let mut messages = vec![format!("Dissolve: {n} features")]; let mut losses: Vec = Vec::new(); if not_polygons > 0 { losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedFeature, text: format!( - "Dissolve: {not_polygons} feature(s) left out, with their values: no geometry, an empty polygon, or a point or line rather than a polygon" + "Dissolve: {not_polygons} feature(s) left out, with their values: no geometry, an empty polygon, a coordinate that isn't a number, or a point or line rather than a polygon" ) }); } if no_shape > 0 { @@ -7299,7 +7301,7 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result 0.0))) - && !unusable(g) + && !polygon_not_finite(g) }; let shapeless = |ds: &Dataset, rs: &[usize]| { rs.iter().filter(|&&r| ds.features.get(r).and_then(|f| f.geometry.as_ref()).is_none_or(|g| !has_shape(g))).count() @@ -10299,7 +10301,7 @@ mod tests { assert_eq!( note.as_deref(), Some( - "DroppedFeature: Dissolve: 4 feature(s) left out, with their values: no geometry, an empty polygon, or a point or line rather than a polygon" + "DroppedFeature: Dissolve: 4 feature(s) left out, with their values: no geometry, an empty polygon, a coordinate that isn't a number, or a point or line rather than a polygon" ) ); assert_eq!(notice(false), (1, Some(2.0), Some(3.0), None)); @@ -15964,7 +15966,7 @@ mod tests { let m = Map(HashMap::from([("input".to_string(), input), ("clean".to_string(), clean), ("masks".to_string(), masks)])); let lossy = clip(&m, &serde_json::json!({"input": "input", "clip": "masks"})).unwrap(); assert!( - said(&lossy).iter().any(|m| m == "DroppedFeature: Clip: 4 feature(s) of 'input' left out: they have no geometry to clip"), + said(&lossy).iter().any(|m| m == "DroppedFeature: Clip: 4 feature(s) of 'input' left out: they have no geometry to clip, or a coordinate that isn't a number"), "{:?}", said(&lossy) ); @@ -15979,49 +15981,75 @@ mod tests { #[test] fn overlay_tools_say_which_inputs_they_cannot_cut() { // One of its two parts is good, and meets the other layer: the whole feature counts. - let mut broken = sq(0.0, 0.0, 1.0); - if let Geometry::Polygon(parts) = &mut broken { - let mut bad = parts[0].clone(); - bad[0][2].x = f64::NAN; - parts.push(bad); - } - let of = |name: &str, shapes: Vec| { - let mut ds = Dataset::new(name, GeometryType::Polygon, vec![]); - for g in shapes { - ds.push(Some(g), vec![]); + // An infinite latitude, a pole once in the analysis plane, is asked of the geometry itself: the + // tools refuse it before. + let broken = |x: f64, y: f64| { + let mut g = sq(0.0, 0.0, 1.0); + if let Geometry::Polygon(parts) = &mut g { + let mut bad = parts[0].clone(); + (bad[0][2].x, bad[0][2].y) = (x, y); + parts.push(bad); } - (name.to_string(), ds) + g }; - let m = Map(HashMap::from([ - of("input", vec![sq(0.0, 0.0, 1.0), broken]), - of("clean", vec![sq(0.0, 0.0, 1.0)]), - of("b", vec![sq(0.5, 0.0, 1.0)]), - ])); - for (id, other, kept) in [ - ("erase", "erase", true), - ("identity", "overlay", true), - ("union", "overlay", true), - ("symmetricalDifference", "overlay", true), - ("update", "update", true), - ("intersect", "overlay", false), - ("split", "split", false), - ] { - let run = |input: &str| crate::run(id, &m, &serde_json::json!({"input": input, other: "b"})).unwrap(); - let rows = |r: &ToolResult| match &r.output { - Output::Layer(d) => d.features.len(), - Output::Layers(v) => v.iter().map(|o| if let crate::OutputLayer::Vector(d) = o { d.features.len() } else { 0 }).sum(), - _ => 0, + assert!([f64::INFINITY, f64::NEG_INFINITY].iter().all(|&y| polygon_not_finite(&broken(1.0, y)))); + for broken in [broken(f64::NAN, 1.0), broken(1.0, f64::NAN), broken(f64::INFINITY, 1.0)] { + let of = |name: &str, shapes: Vec| { + let mut ds = Dataset::new(name, GeometryType::Polygon, vec![]); + for g in shapes { + ds.push(Some(g), vec![]); + } + (name.to_string(), ds) }; - let (lossy, clean) = (run("input"), run("clean")); - let what = if kept { "kept as they are, not cut" } else { "left out" }; - let note = format!("1 feature(s) of 'input' {what}: they have a coordinate that isn't a number"); - assert!(said(&lossy).iter().any(|m| m.ends_with(¬e)), "{id}: {:?}", said(&lossy)); - assert!(!said(&clean).iter().any(|m| m.contains("isn't a number")), "{id}: {:?}", said(&clean)); - assert_eq!(rows(&lossy), rows(&clean) + usize::from(kept), "{id}"); - } - let tabulate = |zones: &str| crate::run("tabulateIntersection", &m, &serde_json::json!({"zones": zones, "classes": "b"})).unwrap(); - let no_polygon = |r: &ToolResult| said(r).iter().any(|m| m.contains("feature has no polygon and was left out")); - assert!(no_polygon(&tabulate("input")) && !no_polygon(&tabulate("clean")), "{:?}", said(&tabulate("input"))); + let m = Map(HashMap::from([ + of("input", vec![sq(0.0, 0.0, 1.0), broken.clone()]), + of("bad", vec![sq(0.5, 0.0, 1.0), broken]), + of("clean", vec![sq(0.0, 0.0, 1.0)]), + of("b", vec![sq(0.5, 0.0, 1.0)]), + ])); + for (id, other, kept) in [ + ("erase", "erase", true), + ("identity", "overlay", true), + ("union", "overlay", true), + ("symmetricalDifference", "overlay", true), + ("update", "update", true), + ("intersect", "overlay", false), + ("split", "split", false), + ] { + let run = |input: &str| crate::run(id, &m, &serde_json::json!({"input": input, other: "b"})).unwrap(); + let rows = |r: &ToolResult| match &r.output { + Output::Layer(d) => d.features.len(), + Output::Layers(v) => v.iter().map(|o| if let crate::OutputLayer::Vector(d) = o { d.features.len() } else { 0 }).sum(), + _ => 0, + }; + let (lossy, clean) = (run("input"), run("clean")); + let what = if kept { "kept as they are, not cut" } else { "left out" }; + let note = format!("1 feature(s) of 'input' {what}: they have a coordinate that isn't a number"); + assert!(said(&lossy).iter().any(|m| m.ends_with(¬e)), "{id}: {:?}", said(&lossy)); + assert!(!said(&clean).iter().any(|m| m.contains("isn't a number")), "{id}: {:?}", said(&clean)); + assert_eq!(rows(&lossy), rows(&clean) + usize::from(kept), "{id}"); + // As the other layer, it takes no part. + let masked = crate::run(id, &m, &serde_json::json!({"input": "clean", other: "bad"})).unwrap(); + assert_eq!(rows(&masked), rows(&clean), "{id}"); + assert!(said(&masked).iter().any(|m| m.contains("1 feature(s) of 'bad' left out")), "{id}: {:?}", said(&masked)); + } + let tabulate = + |zones: &str| crate::run("tabulateIntersection", &m, &serde_json::json!({"zones": zones, "classes": "b"})).unwrap(); + let no_polygon = |r: &ToolResult| said(r).iter().any(|m| m.contains("feature has no polygon and was left out")); + assert!(no_polygon(&tabulate("input")) && !no_polygon(&tabulate("clean")), "{:?}", said(&tabulate("input"))); + } + } + + /// A line breaks at a coordinate that isn't a number: an infinite latitude isn't taken for a pole. + #[test] + fn clip_breaks_a_line_at_a_coordinate_that_is_not_a_number() { + let at = |x, y| Coord::new(x, y); + let mask = union_all(&to_multipolygon(&sq(0.0, 0.0, 1.0)).unwrap()); + for bad in [at(0.75, f64::INFINITY), at(0.75, f64::NAN), at(f64::INFINITY, 0.5)] { + let line = Geometry::Line(vec![vec![at(0.25, 0.5), at(0.5, 0.5), bad]]); + let Some(Geometry::Line(parts)) = part(&line, &mask, true) else { panic!("a line") }; + assert!(parts.iter().flatten().all(|c| (c.y - 0.5).abs() < 1e-8 && c.x < 0.5 + 1e-8), "{parts:?}"); + } } /// A shared diagonal becomes a small positive-area overlap when the mask is normalized. diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 1e5a3b4374..c6b4c0dc1f 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -9,7 +9,7 @@ use rustgis_data::overlay::Overlay as _; use rustgis_data::{Dataset, Geometry}; use rustgis_geom::{Coord, Extent, MAX_LAT, WGS84_POLAR_RADIUS_M, lonlat_to_plane, plane_to_lonlat}; -use crate::convert::{Plane, from_multipolygon, from_plane, own_length, own_unit_m, plane, to_multipolygon, to_plane}; +use crate::convert::{Plane, from_multipolygon, from_plane, own_length, own_unit_m, plane, polygon_not_finite, to_multipolygon, to_plane}; /// A topology problem: the rows involved and where it is, in the coordinates the layer was given /// in (longitude/latitude, or a projected system's own in a run there). @@ -82,10 +82,10 @@ pub fn merge(geoms: &[Geometry]) -> Option { match geoms.first()? { Geometry::Polygon(_) => { // Refused, not merged without a part: the features merged are deleted. - let polys: Vec> = geoms.iter().filter_map(to_multipolygon).collect(); - if !polys.iter().all(finite) { + if geoms.iter().any(polygon_not_finite) { return None; } + let polys: Vec> = geoms.iter().filter_map(to_multipolygon).collect(); let all: Vec> = polys.into_iter().flat_map(|m| m.0).collect(); from_multipolygon(&rustgis_data::overlay::union_all(all.iter())) } @@ -118,11 +118,6 @@ pub fn explode(g: &Geometry) -> Vec { } } -fn finite(mp: &geo::MultiPolygon) -> bool { - use geo::CoordsIter; - mp.coords_iter().all(|c| c.x.is_finite() && c.y.is_finite()) -} - fn polygons(ds: &Dataset, rows: &[usize]) -> Vec<(usize, geo::MultiPolygon, geo::Rect)> { rows.iter() .filter_map(|r| { @@ -135,7 +130,7 @@ fn polygons(ds: &Dataset, rows: &[usize]) -> Vec<(usize, geo::MultiPolygon, /// The rows whose coordinates are all finite, which the overlay can take, and how many aren't. fn usable(ds: &Dataset, rows: &[usize]) -> (Vec, usize) { - let whole = |r: &usize| ds.features.get(*r).and_then(|f| f.geometry.as_ref()).and_then(to_multipolygon).is_none_or(|m| finite(&m)); + let whole = |r: &usize| !ds.features.get(*r).and_then(|f| f.geometry.as_ref()).is_some_and(polygon_not_finite); let usable: Vec = rows.iter().copied().filter(whole).collect(); let skipped = rows.len().saturating_sub(usable.len()); (usable, skipped) @@ -1165,12 +1160,17 @@ mod tests { let mut broken = square(1.0); let Geometry::Polygon(parts) = &mut broken else { panic!("a polygon") }; parts[0][0][2].x = bad; - assert!(merge(&[square(0.0), broken.clone()]).is_none() && merge(&[square(0.0), square(1.0)]).is_some()); - let mut ds = Dataset::new("d", rustgis_data::GeometryType::Polygon, vec![]); - ds.push(Some(square(0.0)), vec![]); - ds.push(Some(broken), vec![]); - assert_eq!((overlaps(&ds, &[0, 1]).skipped, gaps(&ds, &[0, 1]).skipped), (1, 1)); - assert_eq!((overlaps(&ds, &[0]).skipped, gaps(&ds, &[0]).skipped), (0, 0)); + let mut pole = square(1.0); + let Geometry::Polygon(parts) = &mut pole else { panic!("a polygon") }; + parts[0][0][2].y = bad; + for broken in [broken, pole] { + assert!(merge(&[square(0.0), broken.clone()]).is_none() && merge(&[square(0.0), square(1.0)]).is_some()); + let mut ds = Dataset::new("d", rustgis_data::GeometryType::Polygon, vec![]); + ds.push(Some(square(0.0)), vec![]); + ds.push(Some(broken), vec![]); + assert_eq!((overlaps(&ds, &[0, 1]).skipped, gaps(&ds, &[0, 1]).skipped), (1, 1)); + assert_eq!((overlaps(&ds, &[0]).skipped, gaps(&ds, &[0]).skipped), (0, 0)); + } } } diff --git a/crates/analysis/tests/integration/repair_geometry.rs b/crates/analysis/tests/integration/repair_geometry.rs index 6b0626d3a8..70ad502118 100644 --- a/crates/analysis/tests/integration/repair_geometry.rs +++ b/crates/analysis/tests/integration/repair_geometry.rs @@ -1087,7 +1087,7 @@ fn postgis_examples() -> Vec<(Vec>, f64)> { /// The two examples of overlapping parts in the PostGIS manual's ST_MakeValid page /// (https://postgis.net/docs/ST_MakeValid.html), whose "structure" method gives one polygon for /// each, as merging the parts does here. The manual gives no areas: the expected ones are this -/// tool's own (geo's overlay), pinned so that a change shows, and checked against what any union +/// tool's own (the boolean overlay), pinned so that a change shows, and checked against what any union /// of the parts must cover: at least the largest part, less than all of them added up. #[test] fn the_postgis_manual_examples_merge_into_one_polygon() { diff --git a/crates/data/src/overlay.rs b/crates/data/src/overlay.rs index aa1ee06223..71b48257d3 100644 --- a/crates/data/src/overlay.rs +++ b/crates/data/src/overlay.rs @@ -144,6 +144,9 @@ fn multipolygon(shapes: Vec>>, near: Near) -> MultiPolygon { pub fn grid_step(pts: impl Iterator) -> Option { let (mut lo_x, mut lo_y, mut hi_x, mut hi_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); for (x, y) in pts { + if !(x.is_finite() && y.is_finite()) { + return None; + } (lo_x, lo_y, hi_x, hi_y) = (lo_x.min(x), lo_y.min(y), hi_x.max(x), hi_y.max(y)); } let half = (hi_x - lo_x).max(hi_y - lo_y) * 0.5; @@ -156,8 +159,8 @@ pub fn grid_step(pts: impl Iterator) -> Option { } /// The grid for `pts`, at [`grid_step`]'s step: coordinates up to 2^29.5 steps from its middle, within -/// the 2^30 the engine's 32-bit arithmetic takes, which the 30 bits asked for here check. Points with no such step (all one point, or an extent -/// near the limits of a float) get the engine's own grid. +/// the 2^30 the engine's 32-bit arithmetic takes (the 30 bits asked for, which it checks). Points with +/// no such step (all one point, or an extent near the limits of a float) get the engine's own grid. fn adapter<'a>(pts: impl Iterator + Clone) -> Adapter { grid_step(pts.clone().map(|&[x, y]| (x, y))) .and_then(|step| Adapter::try_with_iter_and_scale_and_coordinate_bits(pts.clone(), step.recip(), 30).ok()) @@ -295,7 +298,8 @@ fn union_near<'a>(polys: impl Iterator>) -> MultiPolygon let mut path = path(&ring); let area = double_area(&path); let nothing = !hole && holed && encloses_nothing(&path, area); - if if hole { area > 0.0 } else { area < 0.0 } { + let backwards = if hole { area > 0.0 } else { area < 0.0 }; + if backwards { path.reverse(); } subject.push(path); @@ -404,6 +408,14 @@ mod tests { } } + #[test] + fn coordinates_that_are_not_finite_have_no_grid() { + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert_eq!(grid_step([(0.0, 0.0), (1.0, 1.0), (bad, 0.5)].into_iter()), None); + } + assert!(grid_step([(0.0, 0.0), (1.0, 1.0)].into_iter()).is_some()); + } + /// A polygon with a coordinate that isn't finite is left out, without a panic or a made-up result. #[test] fn polygons_that_are_not_finite_are_left_out() { diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 2eea14d38d..8dc1b23531 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1701,6 +1701,9 @@ fn merge(s: &mut Session, _: &Json) -> CmdResult { } let merged = { let _plane = own.then(|| rustgis_analysis::convert::install(rustgis_analysis::convert::run_plane_for(l.dataset.coord_crs()))); + if geoms.iter().any(rustgis_analysis::convert::polygon_not_finite) { + return Err("these features can't be merged: one has a coordinate that isn't a number".into()); + } rustgis_analysis::topology::merge(&geoms).ok_or("these features can't be merged")? }; let merged = if own { From 61ccce85bf8c99a1e534aa6c8c91fdbea36d69fe Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 02:05:30 -0600 Subject: [PATCH 03/12] fix(analysis): lines broken at a bad coordinate are said, and Merge refuses what its grid would lose --- crates/analysis/src/convert.rs | 5 ++-- crates/analysis/src/tools.rs | 42 ++++++++++++++++++++++++++++++ crates/analysis/src/topology.rs | 46 ++++++++++++++++++++++++++++++--- crates/data/src/overlay.rs | 11 ++++---- crates/engine/src/cmd/design.rs | 4 +-- docs/user-guide/analysis.md | 8 +++--- 6 files changed, 99 insertions(+), 17 deletions(-) diff --git a/crates/analysis/src/convert.rs b/crates/analysis/src/convert.rs index 08db5ff611..6cffcf9075 100644 --- a/crates/analysis/src/convert.rs +++ b/crates/analysis/src/convert.rs @@ -123,9 +123,10 @@ fn gc(c: Coord) -> GC { } /// Whether a geometry is a polygon with a coordinate that isn't finite, in its own coordinates or in -/// the run's plane. Its own are asked first: an infinite latitude is a pole once in the plane. +/// the run's plane. Its own are asked first: an infinite latitude is a pole once in the plane, where only a longitude +/// far past any on the globe stops being finite. pub fn polygon_not_finite(g: &Geometry) -> bool { - matches!(g, Geometry::Polygon(polys) if polys.iter().flatten().flatten().any(|&c| !c.is_finite() || !to_plane(c).is_finite())) + matches!(g, Geometry::Polygon(polys) if polys.iter().flatten().flatten().any(|&c| !c.is_finite() || (c.x.abs() > 1e290 && !to_plane(c).is_finite()))) } fn back(c: &GC) -> Coord { diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 1e91e14f87..6152ff2507 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1651,6 +1651,23 @@ fn say_uncut(r: &mut ToolResult, tool: &str, ds: &Dataset, rows: &[usize], kept: (_, true) => r.messages.push(text), (_, false) => r.losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedFeature, text }), } + say_broken(r, tool, ds, rows); +} + +/// Says how many input lines have a coordinate that isn't finite: [`part`] breaks them there, without +/// the segments that meet it. +fn say_broken(r: &mut ToolResult, tool: &str, ds: &Dataset, rows: &[usize]) { + let broken = |g: &Geometry| matches!(g, Geometry::Line(parts) if parts.iter().flatten().any(|c| !c.is_finite())); + let n = rows.iter().filter(|&&r| ds.features.get(r).and_then(|f| f.geometry.as_ref()).is_some_and(broken)).count(); + if n > 0 { + r.losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedGeometry, + text: format!( + "{tool}: {n} line feature(s) of '{}' have a coordinate that isn't a number; where they are cut, they are broken there", + ds.name + ), + }); + } } /// The error when `tool`, whose output would be empty, left out every feature of `layer` it was @@ -2518,6 +2535,7 @@ fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option, cache_bytes: Opti ), }); } + say_broken(&mut r, "Clip", ds, &input_rows); r.messages.extend(left.notes("Clip", &clip_ds.name)); if slivers > 0 { r.messages.push(format!("Clip: {slivers} output feature(s) have less than one millionth of their input feature's area in the overlay plane; they may be slivers along the clip boundary (kept unchanged)")); @@ -16033,6 +16051,16 @@ mod tests { assert_eq!(rows(&masked), rows(&clean), "{id}"); assert!(said(&masked).iter().any(|m| m.contains("1 feature(s) of 'bad' left out")), "{id}: {:?}", said(&masked)); } + // Dissolve has no refusal of latitudes past ±90°: it counts them. + for y in [f64::NAN, f64::INFINITY] { + let mut bad = sq(3.0, 0.0, 1.0); + if let Geometry::Polygon(parts) = &mut bad { + parts[0][0][2].y = y; + } + let m = Map(HashMap::from([of("d", vec![sq(0.0, 0.0, 1.0), bad])])); + let r = crate::run("dissolve", &m, &serde_json::json!({"input": "d"})).unwrap(); + assert!(said(&r).iter().any(|m| m.contains("1 feature(s) left out") && m.contains("isn't a number")), "{:?}", said(&r)); + } let tabulate = |zones: &str| crate::run("tabulateIntersection", &m, &serde_json::json!({"zones": zones, "classes": "b"})).unwrap(); let no_polygon = |r: &ToolResult| said(r).iter().any(|m| m.contains("feature has no polygon and was left out")); @@ -16050,6 +16078,20 @@ mod tests { let Some(Geometry::Line(parts)) = part(&line, &mask, true) else { panic!("a line") }; assert!(parts.iter().flatten().all(|c| (c.y - 0.5).abs() < 1e-8 && c.x < 0.5 + 1e-8), "{parts:?}"); } + // Said by each tool that cuts lines, and not of a clean line. + for (id, other) in [("clip", "clip"), ("erase", "erase"), ("intersect", "overlay"), ("identity", "overlay"), ("split", "split")] { + let said = |end: f64| { + let mut lines = Dataset::new("lines", GeometryType::Polyline, vec![]); + lines.push(Some(Geometry::Line(vec![vec![at(0.25, 0.5), at(0.5, 0.5), at(0.75, end)]])), vec![]); + let mut masks = Dataset::new("masks", GeometryType::Polygon, vec![]); + masks.push(Some(sq(0.0, 0.0, 1.0)), vec![]); + let m = Map(HashMap::from([("lines".to_string(), lines), ("masks".to_string(), masks)])); + said(&crate::run(id, &m, &serde_json::json!({"input": "lines", other: "masks"})).unwrap()) + }; + let note = "1 line feature(s) of 'lines' have a coordinate that isn't a number"; + assert!(said(f64::NAN).iter().any(|m| m.contains(note)), "{id}: {:?}", said(f64::NAN)); + assert!(!said(0.5).iter().any(|m| m.contains("isn't a number")), "{id}: {:?}", said(0.5)); + } } /// A shared diagonal becomes a small positive-area overlap when the mask is normalized. diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index c6b4c0dc1f..1e48e32438 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -77,12 +77,28 @@ thread_local! { static LOOKED_AT: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// One geometry from several: polygons are unioned, lines and points gathered. +/// Why [`merge`] refuses these geometries, as it would lose one of them and the features merged are +/// deleted: a polygon with a coordinate that isn't finite, or one too small or thin beside the others' +/// extent for the union's grid to hold. +pub fn merge_refusal(geoms: &[Geometry]) -> Option<&'static str> { + use geo::CoordsIter; + if geoms.iter().any(polygon_not_finite) { + return Some("one has a coordinate that isn't a number"); + } + let polys: Vec> = geoms.iter().filter_map(to_multipolygon).collect(); + let step = rustgis_data::overlay::grid_step(polys.iter().flat_map(|m| m.coords_iter()).map(|c| (c.x, c.y)))?; + let parts = || polys.iter().flat_map(|m| &m.0); + let small = |p: &&geo::Polygon| p.bounding_rect().is_some_and(|b| b.width().min(b.height()) <= step); + let lost = parts().filter(small).any(|p| !rustgis_data::overlay::union_all([p]).0.is_empty()); + lost.then_some("one is too small or thin beside the distance between them") +} + +/// One geometry from several: polygons are unioned, lines and points gathered. None when it would lose +/// one ([`merge_refusal`]). pub fn merge(geoms: &[Geometry]) -> Option { match geoms.first()? { Geometry::Polygon(_) => { - // Refused, not merged without a part: the features merged are deleted. - if geoms.iter().any(polygon_not_finite) { + if merge_refusal(geoms).is_some() { return None; } let polys: Vec> = geoms.iter().filter_map(to_multipolygon).collect(); @@ -1094,7 +1110,8 @@ fn less(of: &[(f64, f64)], holes: &[(f64, f64)]) -> Vec<(f64, f64)> { /// as everywhere else (#1033). Features of `by` the test at a pole had to leave out (a coordinate /// missing or infinite, or a million turns around) when the rest don't surround it, or might not /// have with them, are counted in `skipped`, each once at either pole, for the check to say its -/// result there may be wrong. Each point is tested only against the polygons whose boxes may hold +/// result there may be wrong; so are those with a coordinate missing or infinite when some point is +/// found uncovered. Each point is tested only against the polygons whose boxes may hold /// it, through an index of them (#1252). pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { let all: Vec = (0..by.features.len()).collect(); @@ -1106,6 +1123,11 @@ pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { let (mut holds_north, mut holds_south): (Holds, Holds) = (None, None); let with_skipped = |c: Checked, north: &Holds, south: &Holds| { let mut left_out: Vec = north.iter().chain(south).flat_map(|(_, rows)| rows.iter().copied()).collect(); + // A point found uncovered may lie in a polygon that can't be used. + if !c.errors.is_empty() { + let bad = |r: &usize| by.features.get(*r).and_then(|f| f.geometry.as_ref()).is_some_and(polygon_not_finite); + left_out.extend(all.iter().copied().filter(bad)); + } left_out.sort_unstable(); left_out.dedup(); Checked { skipped: left_out.len(), ..c } @@ -1148,6 +1170,22 @@ pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { #[cfg(test)] mod tests { + /// Merge deletes the features it merges, so it refuses polygons its grid can't hold together, and + /// takes the same ones near each other, or one with no area to lose. + #[test] + fn merge_refuses_polygons_its_grid_would_lose() { + let _plane = crate::convert::install(crate::convert::run_plane_for(rustgis_data::raster::Crs::WebMercator)); + let square = |x: f64, w: f64| { + let ring = [(x, 0.0), (x + w, 0.0), (x + w, w), (x, w), (x, 0.0)]; + Geometry::Polygon(vec![vec![ring.iter().map(|&(x, y)| Coord::new(x, y)).collect()]]) + }; + assert!(merge(&[square(0.0, 100.0), square(1e16, 128.0)]).is_none()); + assert!( + merge_refusal(&[square(0.0, 1e10), square(1e16, 1e9)]).is_none() && merge(&[square(0.0, 100.0), square(1e6, 100.0)]).is_some() + ); + assert!(merge(&[square(0.0, 100.0), square(1e6, 0.0)]).is_some()); + } + /// A polygon with a coordinate that isn't finite: the checks skip it and count it, and Merge refuses /// it, as it deletes the features it merges. #[test] diff --git a/crates/data/src/overlay.rs b/crates/data/src/overlay.rs index 71b48257d3..888d9459bf 100644 --- a/crates/data/src/overlay.rs +++ b/crates/data/src/overlay.rs @@ -82,7 +82,7 @@ impl Near { const AS_IS: Near = Near { origin: [0.0, 0.0], by: 1.0 }; /// What the points need. - fn of<'a>(pts: impl Iterator + Clone) -> Near { + fn of(pts: impl Iterator + Clone) -> Near { let largest = pts.clone().flatten().fold(0.0_f64, |m, v| m.max(v.abs())); if largest > 0.0 && largest < TOO_SMALL { return Near { by: LARGER, ..Near::AS_IS }; @@ -90,7 +90,7 @@ impl Near { if largest <= TOO_FAR { return Near::AS_IS; } - let origin = pts.clone().next().copied().unwrap_or_default(); + let origin = pts.clone().next().unwrap_or_default(); // A difference past the largest float is infinite, so past it too. let spread = pts.into_iter().any(|p| (p[0] - origin[0]).abs() > TOO_FAR || (p[1] - origin[1]).abs() > TOO_FAR); Near { origin, by: if spread { NEARER } else { 1.0 } } @@ -169,7 +169,7 @@ fn adapter<'a>(pts: impl Iterator + Clone) -> Adapter { /// Runs `rule` on paths of finite coordinates. fn overlay(mut subject: Vec>, mut clip: Vec>, rule: OverlayRule, fill: FillRule) -> MultiPolygon { - let near = Near::of(points(&subject, &clip)); + let near = Near::of(points(&subject, &clip).copied()); near.bring(&mut subject); near.bring(&mut clip); let grid = adapter(points(&subject, &clip)); @@ -218,7 +218,7 @@ pub trait Overlay { .filter(|run| run.len() > 1) .map(|run| run.iter().map(|c| [c.x, c.y]).collect()) .collect(); - let near = Near::of(points(&shape, &strings)); + let near = Near::of(points(&shape, &strings).copied()); near.bring(&mut shape); near.bring(&mut strings); let grid = adapter(points(&shape, &strings)); @@ -277,8 +277,7 @@ where if all().all(|c| ordinary(c.x) && ordinary(c.y)) { return union_near(polys); } - let every: Vec = all().map(|c| [c.x, c.y]).collect(); - let near = Near::of(every.iter()); + let near = Near::of(all().map(|c| [c.x, c.y])); let moved: Vec> = polys.map(|p| p.map_coords(|c| near.to([c.x, c.y]).into())).collect(); union_near(moved.iter()).map_coords(|c| near.back([c.x, c.y]).into()) } diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 8dc1b23531..c630bd0718 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1701,8 +1701,8 @@ fn merge(s: &mut Session, _: &Json) -> CmdResult { } let merged = { let _plane = own.then(|| rustgis_analysis::convert::install(rustgis_analysis::convert::run_plane_for(l.dataset.coord_crs()))); - if geoms.iter().any(rustgis_analysis::convert::polygon_not_finite) { - return Err("these features can't be merged: one has a coordinate that isn't a number".into()); + if let Some(why) = rustgis_analysis::topology::merge_refusal(&geoms) { + return Err(format!("these features can't be merged: {why}")); } rustgis_analysis::topology::merge(&geoms).ok_or("these features can't be merged")? }; diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 3b2588c8f0..a380c14e21 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -883,9 +883,11 @@ gp.run={"tool":"split","params":{"input":"roads","split":"districts","field":"na Clip, Erase, Intersect, Identity, Union, Symmetrical Difference, Update and Split leave out a feature of the clip, erase, overlay, update or split layer with no polygon, and say how many: one without geometry, a point or line in the polygon layer (as Minimum Bounding Geometry's flat hulls -are), an empty polygon, or one with a coordinate that isn't a number. Clip also leaves out a mask whose polygons, unioned, have no area, and -the others a feature of several parts that, unioned, come to nothing (Update writes it as it is), -saying how many. Clip also says how many input features it leaves out for having no geometry, or +are), an empty polygon, or one with a coordinate that isn't a number. Clip also leaves out a mask +whose polygons, unioned, have no area, and the others a feature of several parts that, unioned, come +to nothing (Update writes it as it is), saying how many. An input polygon with a coordinate that +isn't a number is left out by Clip, Intersect and Split and kept uncut by the others, and a line is +broken at one; each is said, with how many. Clip also says how many input features it leaves out for having no geometry, or an empty one. When none of the features of that layer is left, Clip, Intersect and Split, whose result would be empty, stop with an error. In all of them, a feature selected twice in that layer is used once. From 0e58fe1ccab83bd3f7ffb6fece4c3c6171b842ad Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 03:01:37 -0600 Subject: [PATCH 04/12] fix(analysis): Merge refuses any polygon its union would lose, whatever its direction --- crates/analysis/src/tools.rs | 2 +- crates/analysis/src/topology.rs | 82 +++++++++++++++++++++------------ crates/engine/src/cmd/design.rs | 5 +- 3 files changed, 55 insertions(+), 34 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 6152ff2507..b7d179925b 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -10190,7 +10190,7 @@ mod tests { // Merge, of the parts as they are. let Geometry::Polygon(parts) = trap else { panic!("a polygon") }; let parts: Vec = parts.into_iter().map(|p| Geometry::Polygon(vec![p])).collect(); - assert!(finishes(move || crate::topology::merge(&parts).is_some()), "merge"); + assert!(finishes(move || crate::topology::merge(&parts).is_ok()), "merge"); } #[test] diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 1e48e32438..67c0558ffd 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -77,38 +77,46 @@ thread_local! { static LOOKED_AT: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// Why [`merge`] refuses these geometries, as it would lose one of them and the features merged are -/// deleted: a polygon with a coordinate that isn't finite, or one too small or thin beside the others' -/// extent for the union's grid to hold. -pub fn merge_refusal(geoms: &[Geometry]) -> Option<&'static str> { - use geo::CoordsIter; - if geoms.iter().any(polygon_not_finite) { - return Some("one has a coordinate that isn't a number"); - } - let polys: Vec> = geoms.iter().filter_map(to_multipolygon).collect(); - let step = rustgis_data::overlay::grid_step(polys.iter().flat_map(|m| m.coords_iter()).map(|c| (c.x, c.y)))?; - let parts = || polys.iter().flat_map(|m| &m.0); - let small = |p: &&geo::Polygon| p.bounding_rect().is_some_and(|b| b.width().min(b.height()) <= step); - let lost = parts().filter(small).any(|p| !rustgis_data::overlay::union_all([p]).0.is_empty()); - lost.then_some("one is too small or thin beside the distance between them") +/// Whether `union` has what `p` covers, to a few steps of the union's grid. Only a polygon rounding to +/// that grid could leave without area is looked at: one thinner than that lies on the union's edge or +/// in it, as a sliver along its neighbour does, or it is gone. +fn in_union(p: &geo::Polygon, union: &geo::MultiPolygon, step: f64) -> bool { + use geo::{CoordsIter, Distance, Euclidean, Length}; + let rings = || std::iter::once(p.exterior()).chain(p.interiors()); + let length: f64 = rings().map(|r| Euclidean.length(r)).sum(); + if p.unsigned_area() > (2.0 * length + p.coords_count() as f64 * step) * step { + return true; + } + let near = |c: geo::Coord| Euclidean.distance(&geo::Point(c), union) <= 4.0 * step; + p.exterior().0.iter().all(|&c| near(c)) || rustgis_data::overlay::union_all([p]).0.is_empty() } -/// One geometry from several: polygons are unioned, lines and points gathered. None when it would lose -/// one ([`merge_refusal`]). -pub fn merge(geoms: &[Geometry]) -> Option { - match geoms.first()? { +/// One geometry from several: polygons are unioned, lines and points gathered. Refused, saying why, +/// when there would be none, or the union would lose a polygon, as the features merged are deleted: one +/// with a coordinate that isn't finite, or too small or thin beside their extent for the union's grid +/// and apart from the rest. +pub fn merge(geoms: &[Geometry]) -> Result { + let nothing = "nothing of them is left"; + match geoms.first().ok_or(nothing)? { Geometry::Polygon(_) => { - if merge_refusal(geoms).is_some() { - return None; + use geo::CoordsIter; + if geoms.iter().any(polygon_not_finite) { + return Err("one has a coordinate that isn't a number"); } let polys: Vec> = geoms.iter().filter_map(to_multipolygon).collect(); let all: Vec> = polys.into_iter().flat_map(|m| m.0).collect(); - from_multipolygon(&rustgis_data::overlay::union_all(all.iter())) + let union = rustgis_data::overlay::union_all(all.iter()); + let merged = from_multipolygon(&union).ok_or(nothing)?; + let step = rustgis_data::overlay::grid_step(all.iter().flat_map(|p| p.coords_iter()).map(|c| (c.x, c.y))); + if step.is_some_and(|step| !all.iter().all(|p| in_union(p, &union, step))) { + return Err("one is too small or thin beside the distance between them"); + } + Ok(merged) } Geometry::Line(_) => { let parts: Vec> = geoms.iter().filter_map(|g| if let Geometry::Line(p) = g { Some(p.clone()) } else { None }).flatten().collect(); - (!parts.is_empty()).then_some(Geometry::Line(parts)) + (!parts.is_empty()).then_some(Geometry::Line(parts)).ok_or(nothing) } Geometry::Point(_) | Geometry::MultiPoint(_) => { let pts: Vec = geoms @@ -119,7 +127,7 @@ pub fn merge(geoms: &[Geometry]) -> Option { _ => Vec::new(), }) .collect(); - (!pts.is_empty()).then_some(Geometry::MultiPoint(pts)) + (!pts.is_empty()).then_some(Geometry::MultiPoint(pts)).ok_or(nothing) } } } @@ -1179,11 +1187,27 @@ mod tests { let ring = [(x, 0.0), (x + w, 0.0), (x + w, w), (x, w), (x, 0.0)]; Geometry::Polygon(vec![vec![ring.iter().map(|&(x, y)| Coord::new(x, y)).collect()]]) }; - assert!(merge(&[square(0.0, 100.0), square(1e16, 128.0)]).is_none()); - assert!( - merge_refusal(&[square(0.0, 1e10), square(1e16, 1e9)]).is_none() && merge(&[square(0.0, 100.0), square(1e6, 100.0)]).is_some() - ); - assert!(merge(&[square(0.0, 100.0), square(1e6, 0.0)]).is_some()); + let poly = |r: &[(f64, f64)]| Geometry::Polygon(vec![vec![r.iter().map(|&(x, y)| Coord::new(x, y)).collect()]]); + // 2^30 across, so a step is a unit: a thin diagonal triangle out of reach of the rest is lost. + let wide = poly(&[(0.0, 0.0), (1073741824.0, 0.0), (1073741824.0, 1e8), (0.0, 1e8), (0.0, 0.0)]); + let thin = |y: f64| poly(&[(0.0, y), (2.0, y + 2.0), (4.0, y + 4.125), (0.0, y)]); + assert_eq!(merge(&[square(0.0, 100.0), square(1e16, 128.0)]), Err("nothing of them is left")); + for lost in [[square(0.0, 1e10), square(1e16, 128.0)], [wide.clone(), thin(5e8)]] { + assert_eq!(merge(&lost), Err("one is too small or thin beside the distance between them")); + } + assert_eq!(merge(&[square(0.0, 1.0), square(1.0, f64::NAN)]), Err("one has a coordinate that isn't a number")); + // Slivers along a neighbour, or in it, are in the result; one with no area has none to lose. + let sliver = poly(&[(100.0, 0.0), (100.0 + 1e-9, 50.0), (100.0, 100.0), (100.0, 0.0)]); + for kept in [ + [square(0.0, 100.0), sliver], + [square(0.0, 1e6), poly(&[(1e6, 5.0), (1e6 + 1e-5, 5.5), (1e6, 6.0), (1e6, 5.0)])], + [wide, thin(1e7)], + [square(0.0, 1e10), square(1e16, 1e9)], + [square(0.0, 100.0), square(1e6, 100.0)], + [square(0.0, 100.0), square(1e6, 0.0)], + ] { + assert!(merge(&kept).is_ok(), "{kept:?}: {:?}", merge(&kept)); + } } /// A polygon with a coordinate that isn't finite: the checks skip it and count it, and Merge refuses @@ -1202,7 +1226,7 @@ mod tests { let Geometry::Polygon(parts) = &mut pole else { panic!("a polygon") }; parts[0][0][2].y = bad; for broken in [broken, pole] { - assert!(merge(&[square(0.0), broken.clone()]).is_none() && merge(&[square(0.0), square(1.0)]).is_some()); + assert!(merge(&[square(0.0), broken.clone()]).is_err() && merge(&[square(0.0), square(1.0)]).is_ok()); let mut ds = Dataset::new("d", rustgis_data::GeometryType::Polygon, vec![]); ds.push(Some(square(0.0)), vec![]); ds.push(Some(broken), vec![]); diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index c630bd0718..72a39bc9cf 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1701,10 +1701,7 @@ fn merge(s: &mut Session, _: &Json) -> CmdResult { } let merged = { let _plane = own.then(|| rustgis_analysis::convert::install(rustgis_analysis::convert::run_plane_for(l.dataset.coord_crs()))); - if let Some(why) = rustgis_analysis::topology::merge_refusal(&geoms) { - return Err(format!("these features can't be merged: {why}")); - } - rustgis_analysis::topology::merge(&geoms).ok_or("these features can't be merged")? + rustgis_analysis::topology::merge(&geoms).map_err(|why| format!("these features can't be merged: {why}"))? }; let merged = if own { merged From 07be352de83496787d201727830306e66217dadb Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 04:27:47 -0600 Subject: [PATCH 05/12] fix(analysis): Merge says which polygons its grid could thin away, and refuses what it would lose --- crates/analysis/src/tools.rs | 6 +- crates/analysis/src/topology.rs | 96 +++++++++++++++-------- crates/engine/src/cmd/design.rs | 8 +- crates/engine/src/tests/unplaced_edits.rs | 23 ++++++ 4 files changed, 98 insertions(+), 35 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index b7d179925b..5f621ca76f 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1643,7 +1643,7 @@ fn polygon_of(g: &Geometry) -> Option> { /// Says which input features `tool` can't cut ([`polygon_not_finite`]), when there are any: those kept as they /// are in a message, as nothing of them is lost, those left out as a loss. fn say_uncut(r: &mut ToolResult, tool: &str, ds: &Dataset, rows: &[usize], kept: bool) { - let n = rows.iter().filter(|&&r| ds.features.get(r).and_then(|f| f.geometry.as_ref()).is_some_and(polygon_not_finite)).count(); + let n = rows.iter().filter(|&&r| ds.features.geometry(r).is_some_and(polygon_not_finite)).count(); let what = if kept { "kept as they are, not cut" } else { "left out" }; let text = format!("{tool}: {n} feature(s) of '{}' {what}: they have a coordinate that isn't a number", ds.name); match (n, kept) { @@ -1658,7 +1658,7 @@ fn say_uncut(r: &mut ToolResult, tool: &str, ds: &Dataset, rows: &[usize], kept: /// the segments that meet it. fn say_broken(r: &mut ToolResult, tool: &str, ds: &Dataset, rows: &[usize]) { let broken = |g: &Geometry| matches!(g, Geometry::Line(parts) if parts.iter().flatten().any(|c| !c.is_finite())); - let n = rows.iter().filter(|&&r| ds.features.get(r).and_then(|f| f.geometry.as_ref()).is_some_and(broken)).count(); + let n = rows.iter().filter(|&&r| ds.features.geometry(r).is_some_and(broken)).count(); if n > 0 { r.losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedGeometry, @@ -3290,7 +3290,7 @@ fn split_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result = const { std::cell::Cell::new(0) }; } -/// Whether `union` has what `p` covers, to a few steps of the union's grid. Only a polygon rounding to -/// that grid could leave without area is looked at: one thinner than that lies on the union's edge or -/// in it, as a sliver along its neighbour does, or it is gone. -fn in_union(p: &geo::Polygon, union: &geo::MultiPolygon, step: f64) -> bool { +/// How many of `polys` the union's grid may have left without area: those of so little area beside +/// their length that rounding could take it. `None` when one of them has a corner more than two steps +/// from the union, so it is gone (rounding moves an edge by less than a step, and a sliver along its +/// neighbour is thinner). One with no area at all has none to lose. +fn thinned(polys: &[geo::Polygon], union: &geo::MultiPolygon, step: f64) -> Option { use geo::{CoordsIter, Distance, Euclidean, Length}; - let rings = || std::iter::once(p.exterior()).chain(p.interiors()); - let length: f64 = rings().map(|r| Euclidean.length(r)).sum(); - if p.unsigned_area() > (2.0 * length + p.coords_count() as f64 * step) * step { - return true; + // The union's parts by their boxes, made for the first polygon that needs them. + let index = std::cell::OnceCell::new(); + let boxes = + || union.0.iter().map(|p| p.bounding_rect().map_or(Extent::EMPTY, |b| Extent::new(b.min().x, b.min().y, b.max().x, b.max().y))); + let reach = 2.0 * step; + let mut thin = 0; + for p in polys { + let length: f64 = std::iter::once(p.exterior()).chain(p.interiors()).map(|r| Euclidean.length(r)).sum(); + if p.unsigned_area() > (2.0 * length + p.coords_count() as f64 * step) * step { + continue; + } + if p.unsigned_area() == 0.0 && rustgis_data::overlay::union_all([p]).0.is_empty() { + continue; + } + let index = index.get_or_init(|| crate::tools::ExtentIndex::new(boxes())); + let near = |c: geo::Coord| { + let around = Extent::new(c.x - reach, c.y - reach, c.x + reach, c.y + reach); + index.any_candidate(&around, |i| union.0.get(i).is_some_and(|part| Euclidean.distance(&geo::Point(c), part) <= reach)) + }; + if !p.exterior().0.iter().all(|&c| near(c)) { + return None; + } + thin += 1; } - let near = |c: geo::Coord| Euclidean.distance(&geo::Point(c), union) <= 4.0 * step; - p.exterior().0.iter().all(|&c| near(c)) || rustgis_data::overlay::union_all([p]).0.is_empty() + Some(thin) } /// One geometry from several: polygons are unioned, lines and points gathered. Refused, saying why, /// when there would be none, or the union would lose a polygon, as the features merged are deleted: one /// with a coordinate that isn't finite, or too small or thin beside their extent for the union's grid -/// and apart from the rest. -pub fn merge(geoms: &[Geometry]) -> Result { +/// and apart from the rest. With it, how many polygons were thin enough that some of them may not be in +/// it. +pub fn merge(geoms: &[Geometry]) -> Result<(Geometry, usize), &'static str> { let nothing = "nothing of them is left"; match geoms.first().ok_or(nothing)? { Geometry::Polygon(_) => { @@ -108,15 +128,14 @@ pub fn merge(geoms: &[Geometry]) -> Result { let union = rustgis_data::overlay::union_all(all.iter()); let merged = from_multipolygon(&union).ok_or(nothing)?; let step = rustgis_data::overlay::grid_step(all.iter().flat_map(|p| p.coords_iter()).map(|c| (c.x, c.y))); - if step.is_some_and(|step| !all.iter().all(|p| in_union(p, &union, step))) { - return Err("one is too small or thin beside the distance between them"); - } - Ok(merged) + let thin = step.map_or(Some(0), |step| thinned(&all, &union, step)); + let thin = thin.ok_or("one is too small or thin beside the distance between them")?; + Ok((merged, thin)) } Geometry::Line(_) => { let parts: Vec> = geoms.iter().filter_map(|g| if let Geometry::Line(p) = g { Some(p.clone()) } else { None }).flatten().collect(); - (!parts.is_empty()).then_some(Geometry::Line(parts)).ok_or(nothing) + (!parts.is_empty()).then_some((Geometry::Line(parts), 0)).ok_or(nothing) } Geometry::Point(_) | Geometry::MultiPoint(_) => { let pts: Vec = geoms @@ -127,7 +146,7 @@ pub fn merge(geoms: &[Geometry]) -> Result { _ => Vec::new(), }) .collect(); - (!pts.is_empty()).then_some(Geometry::MultiPoint(pts)).ok_or(nothing) + (!pts.is_empty()).then_some((Geometry::MultiPoint(pts), 0)).ok_or(nothing) } } } @@ -154,7 +173,7 @@ fn polygons(ds: &Dataset, rows: &[usize]) -> Vec<(usize, geo::MultiPolygon, /// The rows whose coordinates are all finite, which the overlay can take, and how many aren't. fn usable(ds: &Dataset, rows: &[usize]) -> (Vec, usize) { - let whole = |r: &usize| !ds.features.get(*r).and_then(|f| f.geometry.as_ref()).is_some_and(polygon_not_finite); + let whole = |r: &usize| !ds.features.geometry(*r).is_some_and(polygon_not_finite); let usable: Vec = rows.iter().copied().filter(whole).collect(); let skipped = rows.len().saturating_sub(usable.len()); (usable, skipped) @@ -1133,7 +1152,7 @@ pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { let mut left_out: Vec = north.iter().chain(south).flat_map(|(_, rows)| rows.iter().copied()).collect(); // A point found uncovered may lie in a polygon that can't be used. if !c.errors.is_empty() { - let bad = |r: &usize| by.features.get(*r).and_then(|f| f.geometry.as_ref()).is_some_and(polygon_not_finite); + let bad = |r: &usize| by.features.geometry(*r).is_some_and(polygon_not_finite); left_out.extend(all.iter().copied().filter(bad)); } left_out.sort_unstable(); @@ -1192,21 +1211,36 @@ mod tests { let wide = poly(&[(0.0, 0.0), (1073741824.0, 0.0), (1073741824.0, 1e8), (0.0, 1e8), (0.0, 0.0)]); let thin = |y: f64| poly(&[(0.0, y), (2.0, y + 2.0), (4.0, y + 4.125), (0.0, y)]); assert_eq!(merge(&[square(0.0, 100.0), square(1e16, 128.0)]), Err("nothing of them is left")); - for lost in [[square(0.0, 1e10), square(1e16, 128.0)], [wide.clone(), thin(5e8)]] { + // Three steps off an edge is apart from it. The shape reaches twice as high elsewhere, so the + // sliver's corners round alike. + let w = 1073741824.0; + let step_shape = poly(&[(0.0, 0.0), (w, 0.0), (w, 2e8), (w - 1e8, 2e8), (w - 1e8, 1e8), (0.0, 1e8), (0.0, 0.0)]); + let off = poly(&[(5.0, 1e8 + 3.0), (6.0, 1e8 + 3.1), (7.0, 1e8 + 3.0), (5.0, 1e8 + 3.0)]); + // So thin it has no area on a grid of its own either, but some all the same. + let thread = poly(&[(5.0, 0.0), (6.0, 0.0), (6.0, 1e-12), (5.0, 1e-12), (5.0, 0.0)]); + for lost in [[square(0.0, 1e10), square(1e16, 128.0)], [wide.clone(), thin(5e8)], [step_shape, off], [square(0.0, 1.0), thread]] { assert_eq!(merge(&lost), Err("one is too small or thin beside the distance between them")); } assert_eq!(merge(&[square(0.0, 1.0), square(1.0, f64::NAN)]), Err("one has a coordinate that isn't a number")); // Slivers along a neighbour, or in it, are in the result; one with no area has none to lose. let sliver = poly(&[(100.0, 0.0), (100.0 + 1e-9, 50.0), (100.0, 100.0), (100.0, 0.0)]); - for kept in [ - [square(0.0, 100.0), sliver], - [square(0.0, 1e6), poly(&[(1e6, 5.0), (1e6 + 1e-5, 5.5), (1e6, 6.0), (1e6, 5.0)])], - [wide, thin(1e7)], - [square(0.0, 1e10), square(1e16, 1e9)], - [square(0.0, 100.0), square(1e6, 100.0)], - [square(0.0, 100.0), square(1e6, 0.0)], + // Those that could have lost something are counted: a triangle too, whose corners each meet a + // square but whose sides between them are lost. + let at = |x: f64, y: f64| { + poly(&[(x - 10.0, y - 10.0), (x + 10.0, y - 10.0), (x + 10.0, y + 10.0), (x - 10.0, y + 10.0), (x - 10.0, y - 10.0)]) + }; + let long = poly(&[(0.0, 5e8), (10000.0, 500010000.0), (20000.0, 500020000.125), (0.0, 5e8)]); + let spread = [wide.clone(), at(0.0, 5e8), at(10000.0, 500010000.0), at(20000.0, 500020000.125), long]; + assert!(matches!(merge(&spread), Ok((_, 1))), "{:?}", merge(&spread).map(|(_, thin)| thin)); + for (kept, thin) in [ + ([square(0.0, 100.0), sliver], 1), + ([square(0.0, 1e6), poly(&[(1e6, 5.0), (1e6 + 1e-5, 5.5), (1e6, 6.0), (1e6, 5.0)])], 1), + ([wide, thin(1e7)], 1), + ([square(0.0, 1e10), square(1e16, 1e9)], 0), + ([square(0.0, 100.0), square(1e6, 100.0)], 0), + ([square(0.0, 100.0), square(1e6, 0.0)], 0), ] { - assert!(merge(&kept).is_ok(), "{kept:?}: {:?}", merge(&kept)); + assert_eq!(merge(&kept).map(|(_, thin)| thin), Ok(thin), "{kept:?}"); } } @@ -1697,8 +1731,8 @@ mod tests { pts.push(Some(Geometry::Point(Coord::new(9.0, 9.0))), vec![]); assert_eq!(not_covered(&pts, &[0, 1], &ds).errors.iter().map(|e| e.rows.clone()).collect::>(), vec![vec![1]]); // Merging two overlapping squares makes one polygon. - let m = merge(&[square(0.0, 0.0, 1.0), square(0.5, 0.0, 1.0)]).unwrap_or(Geometry::Point(Coord::default())); - assert!(matches!(&m, Geometry::Polygon(p) if p.len() == 1)); + let m = merge(&[square(0.0, 0.0, 1.0), square(0.5, 0.0, 1.0)]); + assert!(matches!(&m, Ok((Geometry::Polygon(p), 0)) if p.len() == 1), "{m:?}"); assert_eq!(explode(&Geometry::MultiPoint(vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)])).len(), 2); } diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 72a39bc9cf..06bb0fb567 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1699,7 +1699,7 @@ fn merge(s: &mut Session, _: &Json) -> CmdResult { if geoms.len() != sel.len() || geoms.windows(2).any(|w| w.first().map(kind) != w.get(1).map(kind)) { return Err("merge features of one kind (all points, all lines or all polygons), each with a shape".into()); } - let merged = { + let (merged, thin) = { let _plane = own.then(|| rustgis_analysis::convert::install(rustgis_analysis::convert::run_plane_for(l.dataset.coord_crs()))); rustgis_analysis::topology::merge(&geoms).map_err(|why| format!("these features can't be merged: {why}"))? }; @@ -1726,6 +1726,12 @@ fn merge(s: &mut Session, _: &Json) -> CmdResult { l.selection = vec![keep]; l.touch_geometry(); apply(s, id, changes)?; + if thin > 0 { + s.say(rustgis_data::loss::Note::loss( + rustgis_data::loss::LossCode::DroppedGeometry, + format!("Merge: {thin} polygon(s) are thinner than the grid the shapes were merged on; what of them lies apart from the rest isn't in the merged shape"), + )); + } Ok(json!({"merged": sel.len()})) } diff --git a/crates/engine/src/tests/unplaced_edits.rs b/crates/engine/src/tests/unplaced_edits.rs index 1f21874f83..9d098f919a 100644 --- a/crates/engine/src/tests/unplaced_edits.rs +++ b/crates/engine/src/tests/unplaced_edits.rs @@ -262,3 +262,26 @@ fn a_topology_issue_it_cant_place_is_kept_without_a_place() { assert_eq!(said.len(), 1, "{said:?}"); assert!(said[0].contains("1 topology issue(s) are at a place") && said[0].contains("can't zoom"), "{}", said[0]); } + +/// Merge says how many polygons its grid could have thinned away, and nothing of ordinary ones. +#[test] +fn merge_says_which_polygons_its_grid_could_lose() { + let said = |sliver: f64| { + let poly = |r: &[(f64, f64)]| Geometry::Polygon(vec![vec![r.iter().map(|&(x, y)| Coord::new(x, y)).collect()]]); + let mut ds = Dataset::new("polys", GeometryType::Polygon, vec![]); + ds.push(Some(poly(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)])), vec![]); + ds.push(Some(poly(&[(1.0, 0.25), (1.0 + sliver, 0.5), (1.0, 0.75), (1.0, 0.25)])), vec![]); + let mut s = Session::new(crate::Project::default()); + crate::cmd::layer::add_dataset(&mut s, ds); + select(&mut s, "polys", &[0, 1]); + let mark = s.notice_mark(); + s.run("edit.merge", &json!({})).unwrap(); + s.notices_since(mark) + .iter() + .filter(|n| n.text.contains("thinner than the grid")) + .map(|n| n.loss().map(|l| l.spec().id)) + .collect::>() + }; + assert_eq!(said(1e-12), [Some("dropped.geometry")]); + assert!(said(0.5).is_empty()); +} From 83f27736e716a9d1c5dbb510c1f76f436edfa1a5 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 05:18:01 -0600 Subject: [PATCH 06/12] fix(analysis): Merge refuses shapes too small for a grid, and a union without far coordinates copies nothing --- crates/analysis/src/topology.rs | 5 ++++- crates/data/src/overlay.rs | 4 ++++ docs/user-guide/analysis.md | 8 ++++---- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 54c58d54cb..e3ae628079 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -128,7 +128,7 @@ pub fn merge(geoms: &[Geometry]) -> Result<(Geometry, usize), &'static str> { let union = rustgis_data::overlay::union_all(all.iter()); let merged = from_multipolygon(&union).ok_or(nothing)?; let step = rustgis_data::overlay::grid_step(all.iter().flat_map(|p| p.coords_iter()).map(|c| (c.x, c.y))); - let thin = step.map_or(Some(0), |step| thinned(&all, &union, step)); + let thin = step.and_then(|step| thinned(&all, &union, step)); let thin = thin.ok_or("one is too small or thin beside the distance between them")?; Ok((merged, thin)) } @@ -1224,6 +1224,9 @@ mod tests { assert_eq!(merge(&[square(0.0, 1.0), square(1.0, f64::NAN)]), Err("one has a coordinate that isn't a number")); // Slivers along a neighbour, or in it, are in the result; one with no area has none to lose. let sliver = poly(&[(100.0, 0.0), (100.0 + 1e-9, 50.0), (100.0, 100.0), (100.0, 0.0)]); + // So small that their own coordinates have no grid, though the union scales them: refused, as + // what it lost can't be told. + assert!(merge(&[square(0.0, 1e-305), square(2e-305, 1e-305)]).is_err()); // Those that could have lost something are counted: a triangle too, whose corners each meet a // square but whose sides between them are lost. let at = |x: f64, y: f64| { diff --git a/crates/data/src/overlay.rs b/crates/data/src/overlay.rs index 888d9459bf..97f177830d 100644 --- a/crates/data/src/overlay.rs +++ b/crates/data/src/overlay.rs @@ -278,6 +278,10 @@ where return union_near(polys); } let near = Near::of(all().map(|c| [c.x, c.y])); + // A stray tiny coordinate among ordinary ones needs nothing, and no copy. + if near == Near::AS_IS { + return union_near(polys); + } let moved: Vec> = polys.map(|p| p.map_coords(|c| near.to([c.x, c.y]).into())).collect(); union_near(moved.iter()).map_coords(|c| near.back([c.x, c.y]).into()) } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index a380c14e21..05dfe64d67 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -887,10 +887,10 @@ are), an empty polygon, or one with a coordinate that isn't a number. Clip also whose polygons, unioned, have no area, and the others a feature of several parts that, unioned, come to nothing (Update writes it as it is), saying how many. An input polygon with a coordinate that isn't a number is left out by Clip, Intersect and Split and kept uncut by the others, and a line is -broken at one; each is said, with how many. Clip also says how many input features it leaves out for having no geometry, or -an empty one. When none of the features of that layer is left, Clip, Intersect and Split, whose -result would be empty, stop with an error. In all of them, a feature selected twice in that layer is -used once. +broken at one; each is said, with how many. Clip also says how many input features it leaves out +for having no geometry, or an empty one. When none of the features of that layer is left, Clip, +Intersect and Split, whose result would be empty, stop with an error. In all of them, a feature +selected twice in that layer is used once. **Near** (`near`) copies `input` and adds, for each feature, the nearest feature of `near`: its OID as the attribute table shows it (`near_fid`), the distance to it (`near_dist`, in `units`, From 1f8f1261860c23e2e6a98fc3f1a903800b1b2710 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 06:55:24 -0600 Subject: [PATCH 07/12] fix(analysis): a line breaks, and is counted, at a longitude the projection can't hold --- crates/analysis/src/convert.rs | 7 ++++++- crates/analysis/src/tools.rs | 8 +++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/analysis/src/convert.rs b/crates/analysis/src/convert.rs index 6cffcf9075..5b07b96a3c 100644 --- a/crates/analysis/src/convert.rs +++ b/crates/analysis/src/convert.rs @@ -126,7 +126,12 @@ fn gc(c: Coord) -> GC { /// the run's plane. Its own are asked first: an infinite latitude is a pole once in the plane, where only a longitude /// far past any on the globe stops being finite. pub fn polygon_not_finite(g: &Geometry) -> bool { - matches!(g, Geometry::Polygon(polys) if polys.iter().flatten().flatten().any(|&c| !c.is_finite() || (c.x.abs() > 1e290 && !to_plane(c).is_finite()))) + matches!(g, Geometry::Polygon(polys) if polys.iter().flatten().flatten().any(not_finite)) +} + +/// [`polygon_not_finite`] of one coordinate. +pub(crate) fn not_finite(c: &Coord) -> bool { + !c.is_finite() || (c.x.abs() > 1e290 && !to_plane(*c).is_finite()) } fn back(c: &GC) -> Coord { diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 5f621ca76f..48b33b74c9 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1657,7 +1657,7 @@ fn say_uncut(r: &mut ToolResult, tool: &str, ds: &Dataset, rows: &[usize], kept: /// Says how many input lines have a coordinate that isn't finite: [`part`] breaks them there, without /// the segments that meet it. fn say_broken(r: &mut ToolResult, tool: &str, ds: &Dataset, rows: &[usize]) { - let broken = |g: &Geometry| matches!(g, Geometry::Line(parts) if parts.iter().flatten().any(|c| !c.is_finite())); + let broken = |g: &Geometry| matches!(g, Geometry::Line(parts) if parts.iter().flatten().any(crate::convert::not_finite)); let n = rows.iter().filter(|&&r| ds.features.geometry(r).is_some_and(broken)).count(); if n > 0 { r.losses.push(rustgis_data::loss::LossMessage { @@ -1977,7 +1977,7 @@ fn part(g: &Geometry, mask: &MultiPolygon, inside: bool) -> Option { - let runs = parts.iter().flat_map(|p| p.split(|c| !c.is_finite())).map(crate::convert::ring); + let runs = parts.iter().flat_map(|p| p.split(crate::convert::not_finite)).map(crate::convert::ring); from_line(&mask.clip(&geo::MultiLineString::new(runs.collect()), !inside)) } Geometry::Point(_) | Geometry::MultiPoint(_) => { @@ -16071,9 +16071,10 @@ mod tests { /// A line breaks at a coordinate that isn't a number: an infinite latitude isn't taken for a pole. #[test] fn clip_breaks_a_line_at_a_coordinate_that_is_not_a_number() { + use crate::convert::not_finite; let at = |x, y| Coord::new(x, y); let mask = union_all(&to_multipolygon(&sq(0.0, 0.0, 1.0)).unwrap()); - for bad in [at(0.75, f64::INFINITY), at(0.75, f64::NAN), at(f64::INFINITY, 0.5)] { + for bad in [at(0.75, f64::INFINITY), at(0.75, f64::NAN), at(f64::INFINITY, 0.5), at(1e308, 0.5)] { let line = Geometry::Line(vec![vec![at(0.25, 0.5), at(0.5, 0.5), bad]]); let Some(Geometry::Line(parts)) = part(&line, &mask, true) else { panic!("a line") }; assert!(parts.iter().flatten().all(|c| (c.y - 0.5).abs() < 1e-8 && c.x < 0.5 + 1e-8), "{parts:?}"); @@ -16088,6 +16089,7 @@ mod tests { let m = Map(HashMap::from([("lines".to_string(), lines), ("masks".to_string(), masks)])); said(&crate::run(id, &m, &serde_json::json!({"input": "lines", other: "masks"})).unwrap()) }; + assert!(not_finite(&at(1e308, 0.0)) && !not_finite(&at(1e200, 90.0))); let note = "1 line feature(s) of 'lines' have a coordinate that isn't a number"; assert!(said(f64::NAN).iter().any(|m| m.contains(note)), "{id}: {:?}", said(f64::NAN)); assert!(!said(0.5).iter().any(|m| m.contains("isn't a number")), "{id}: {:?}", said(0.5)); From 2e71497d28850a3a414f64a3381ae6701894082e Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 08:40:09 -0600 Subject: [PATCH 08/12] fix(analysis): Merge refuses only a feature its grid loses whole, and counts only polygons that lost something --- crates/analysis/src/topology.rs | 161 ++++++++++++++-------- crates/engine/src/cmd/design.rs | 7 +- crates/engine/src/tests/unplaced_edits.rs | 15 +- 3 files changed, 117 insertions(+), 66 deletions(-) diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index e3ae628079..9c5ed3ccd2 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -77,60 +77,80 @@ thread_local! { static LOOKED_AT: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// How many of `polys` the union's grid may have left without area: those of so little area beside -/// their length that rounding could take it. `None` when one of them has a corner more than two steps -/// from the union, so it is gone (rounding moves an edge by less than a step, and a sliver along its -/// neighbour is thinner). One with no area at all has none to lose. -fn thinned(polys: &[geo::Polygon], union: &geo::MultiPolygon, step: f64) -> Option { - use geo::{CoordsIter, Distance, Euclidean, Length}; - // The union's parts by their boxes, made for the first polygon that needs them. - let index = std::cell::OnceCell::new(); - let boxes = - || union.0.iter().map(|p| p.bounding_rect().map_or(Extent::EMPTY, |b| Extent::new(b.min().x, b.min().y, b.max().x, b.max().y))); +/// How many parts of `features` (each one's, `None` for a feature without any) the union's grid left +/// out, wholly or between their corners: those of so little area beside their length that rounding +/// could take it, with a corner or the middle of an edge more than two steps from the union (rounding +/// moves an edge by less than a step, and a sliver along its neighbour is thinner). `Err` names a +/// feature all of whose parts with any area have a corner that far, so it is gone. +fn thinned(features: &[Option>], union: &geo::MultiPolygon, step: f64) -> Result { + use geo::{Contains, CoordsIter, Distance, Euclidean, Length}; + // The union's edges and parts by their boxes, made for the first polygon that needs them: a part can + // have a million edges. + let edges = || union.0.iter().flat_map(|p| std::iter::once(p.exterior()).chain(p.interiors())).flat_map(|r| r.lines()); + let indexed = std::cell::OnceCell::new(); + let by_box = || { + let edges: Vec> = edges().collect(); + let of = |b: geo::Rect| Extent::new(b.min().x, b.min().y, b.max().x, b.max().y); + let index = crate::tools::ExtentIndex::new(edges.iter().map(|e| of(e.bounding_rect()))); + let parts = crate::tools::ExtentIndex::new(union.0.iter().map(|p| p.bounding_rect().map_or(Extent::EMPTY, of))); + (edges, index, parts) + }; let reach = 2.0 * step; - let mut thin = 0; - for p in polys { - let length: f64 = std::iter::once(p.exterior()).chain(p.interiors()).map(|r| Euclidean.length(r)).sum(); - if p.unsigned_area() > (2.0 * length + p.coords_count() as f64 * step) * step { - continue; - } - if p.unsigned_area() == 0.0 && rustgis_data::overlay::union_all([p]).0.is_empty() { - continue; + let mut lost = 0; + for (i, feature) in features.iter().enumerate() { + let (mut kept, mut gone) = (false, false); + for p in feature.iter().flat_map(|m| &m.0) { + let length: f64 = std::iter::once(p.exterior()).chain(p.interiors()).map(|r| Euclidean.length(r)).sum(); + if p.unsigned_area() > (2.0 * length + p.coords_count() as f64 * step) * step { + kept = true; + continue; + } + if p.unsigned_area() == 0.0 && rustgis_data::overlay::union_all([p]).0.is_empty() { + continue; + } + let (edges, index, parts) = indexed.get_or_init(by_box); + let near = |c: geo::Coord| { + let around = Extent::new(c.x - reach, c.y - reach, c.x + reach, c.y + reach); + index.any_candidate(&around, |i| edges.get(i).is_some_and(|e| Euclidean.distance(&geo::Point(c), e) <= reach)) + || parts.any_candidate(&around, |i| union.0.get(i).is_some_and(|part| part.contains(&c))) + }; + if !p.exterior().0.iter().all(|&c| near(c)) { + (gone, lost) = (true, lost + 1); + continue; + } + kept = true; + if !p.exterior().lines().all(|e| near(e.start + (e.end - e.start) / 2.0)) { + lost += 1; + } } - let index = index.get_or_init(|| crate::tools::ExtentIndex::new(boxes())); - let near = |c: geo::Coord| { - let around = Extent::new(c.x - reach, c.y - reach, c.x + reach, c.y + reach); - index.any_candidate(&around, |i| union.0.get(i).is_some_and(|part| Euclidean.distance(&geo::Point(c), part) <= reach)) - }; - if !p.exterior().0.iter().all(|&c| near(c)) { - return None; + if gone && !kept { + return Err(i); } - thin += 1; } - Some(thin) + Ok(lost) } -/// One geometry from several: polygons are unioned, lines and points gathered. Refused, saying why, -/// when there would be none, or the union would lose a polygon, as the features merged are deleted: one -/// with a coordinate that isn't finite, or too small or thin beside their extent for the union's grid -/// and apart from the rest. With it, how many polygons were thin enough that some of them may not be in -/// it. -pub fn merge(geoms: &[Geometry]) -> Result<(Geometry, usize), &'static str> { - let nothing = "nothing of them is left"; +/// One geometry from several: polygons are unioned, lines and points gathered. Refused, saying why and +/// which of them is at fault when one is, when there would be none, or the union would lose a whole +/// polygon feature, as the features merged are deleted: one with a coordinate that isn't finite, or too +/// small or thin beside their extent for the union's grid and apart from the rest. With it, how many +/// polygons of the features merged, too thin for that grid, aren't in it or aren't whole. +pub fn merge(geoms: &[Geometry]) -> Result<(Geometry, usize), (&'static str, Option)> { + let nothing = ("nothing of them is left", None); match geoms.first().ok_or(nothing)? { Geometry::Polygon(_) => { use geo::CoordsIter; - if geoms.iter().any(polygon_not_finite) { - return Err("one has a coordinate that isn't a number"); + if let Some(i) = geoms.iter().position(polygon_not_finite) { + return Err(("it has a coordinate that isn't a number", Some(i))); } - let polys: Vec> = geoms.iter().filter_map(to_multipolygon).collect(); - let all: Vec> = polys.into_iter().flat_map(|m| m.0).collect(); - let union = rustgis_data::overlay::union_all(all.iter()); + let features: Vec>> = geoms.iter().map(to_multipolygon).collect(); + let all = || features.iter().flatten().flat_map(|m| &m.0); + let union = rustgis_data::overlay::union_all(all()); let merged = from_multipolygon(&union).ok_or(nothing)?; - let step = rustgis_data::overlay::grid_step(all.iter().flat_map(|p| p.coords_iter()).map(|c| (c.x, c.y))); - let thin = step.and_then(|step| thinned(&all, &union, step)); - let thin = thin.ok_or("one is too small or thin beside the distance between them")?; - Ok((merged, thin)) + let step = rustgis_data::overlay::grid_step(all().flat_map(|p| p.coords_iter()).map(|c| (c.x, c.y))); + let step = step.ok_or(("they are too small to merge", None))?; + let lost = thinned(&features, &union, step); + Ok((merged, lost.map_err(|i| ("it is too small or thin beside the distance between them", Some(i)))?)) } Geometry::Line(_) => { let parts: Vec> = @@ -1137,12 +1157,13 @@ fn less(of: &[(f64, f64)], holes: &[(f64, f64)]) -> Vec<(f64, f64)> { /// as everywhere else (#1033). Features of `by` the test at a pole had to leave out (a coordinate /// missing or infinite, or a million turns around) when the rest don't surround it, or might not /// have with them, are counted in `skipped`, each once at either pole, for the check to say its -/// result there may be wrong; so are those with a coordinate missing or infinite when some point is -/// found uncovered. Each point is tested only against the polygons whose boxes may hold +/// result there may be wrong; so are those with a coordinate missing or infinite, which no point is +/// tested against. Each point is tested only against the polygons whose boxes may hold /// it, through an index of them (#1252). pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { let all: Vec = (0..by.features.len()).collect(); - let polys = polygons(by, &all); + let (whole, not_finite) = usable(by, &all); + let polys = polygons(by, &whole); let index = crate::tools::ExtentIndex::new(polys.iter().map(|(_, _, bb)| Extent::new(bb.min().x, bb.min().y, bb.max().x, bb.max().y))); // Whether the polygons together surround each pole, found at the first point there, with the // features left out. @@ -1150,14 +1171,9 @@ pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { let (mut holds_north, mut holds_south): (Holds, Holds) = (None, None); let with_skipped = |c: Checked, north: &Holds, south: &Holds| { let mut left_out: Vec = north.iter().chain(south).flat_map(|(_, rows)| rows.iter().copied()).collect(); - // A point found uncovered may lie in a polygon that can't be used. - if !c.errors.is_empty() { - let bad = |r: &usize| by.features.geometry(*r).is_some_and(polygon_not_finite); - left_out.extend(all.iter().copied().filter(bad)); - } left_out.sort_unstable(); left_out.dedup(); - Checked { skipped: left_out.len(), ..c } + Checked { skipped: not_finite + left_out.len(), ..c } }; let parts = || polys.iter().flat_map(|(r, mp, _)| mp.0.iter().map(move |p| (*r, p))); let mut out = Vec::new(); @@ -1210,7 +1226,7 @@ mod tests { // 2^30 across, so a step is a unit: a thin diagonal triangle out of reach of the rest is lost. let wide = poly(&[(0.0, 0.0), (1073741824.0, 0.0), (1073741824.0, 1e8), (0.0, 1e8), (0.0, 0.0)]); let thin = |y: f64| poly(&[(0.0, y), (2.0, y + 2.0), (4.0, y + 4.125), (0.0, y)]); - assert_eq!(merge(&[square(0.0, 100.0), square(1e16, 128.0)]), Err("nothing of them is left")); + assert_eq!(merge(&[square(0.0, 100.0), square(1e16, 128.0)]), Err(("nothing of them is left", None))); // Three steps off an edge is apart from it. The shape reaches twice as high elsewhere, so the // sliver's corners round alike. let w = 1073741824.0; @@ -1219,15 +1235,35 @@ mod tests { // So thin it has no area on a grid of its own either, but some all the same. let thread = poly(&[(5.0, 0.0), (6.0, 0.0), (6.0, 1e-12), (5.0, 1e-12), (5.0, 0.0)]); for lost in [[square(0.0, 1e10), square(1e16, 128.0)], [wide.clone(), thin(5e8)], [step_shape, off], [square(0.0, 1.0), thread]] { - assert_eq!(merge(&lost), Err("one is too small or thin beside the distance between them")); + assert_eq!(merge(&lost), Err(("it is too small or thin beside the distance between them", Some(1)))); } - assert_eq!(merge(&[square(0.0, 1.0), square(1.0, f64::NAN)]), Err("one has a coordinate that isn't a number")); + assert_eq!(merge(&[square(0.0, 1.0), square(1.0, f64::NAN)]), Err(("it has a coordinate that isn't a number", Some(1)))); // Slivers along a neighbour, or in it, are in the result; one with no area has none to lose. + // A part lost from a feature that keeps another is counted, and not a feature lost. + let parts = |of: &[&Geometry]| { + Geometry::Polygon( + of.iter() + .flat_map(|g| match g { + Geometry::Polygon(p) => p.clone(), + _ => vec![], + }) + .collect(), + ) + }; + for (some, lost) in + [([wide.clone(), parts(&[&thin(5e8), &thin(1e7)])], 1), ([parts(&[&wide, &thin(5e8), &thin(6e8)]), thin(1e7)], 2)] + { + assert_eq!(merge(&some).map(|(_, lost)| lost), Ok(lost), "{some:?}"); + } + assert_eq!( + merge(&[wide.clone(), parts(&[&thin(5e8), &thin(6e8)])]).map(|_| ()), + Err(("it is too small or thin beside the distance between them", Some(1))) + ); let sliver = poly(&[(100.0, 0.0), (100.0 + 1e-9, 50.0), (100.0, 100.0), (100.0, 0.0)]); // So small that their own coordinates have no grid, though the union scales them: refused, as // what it lost can't be told. assert!(merge(&[square(0.0, 1e-305), square(2e-305, 1e-305)]).is_err()); - // Those that could have lost something are counted: a triangle too, whose corners each meet a + // One that lost something is counted: a triangle too, whose corners each meet a // square but whose sides between them are lost. let at = |x: f64, y: f64| { poly(&[(x - 10.0, y - 10.0), (x + 10.0, y - 10.0), (x + 10.0, y + 10.0), (x - 10.0, y + 10.0), (x - 10.0, y - 10.0)]) @@ -1236,9 +1272,9 @@ mod tests { let spread = [wide.clone(), at(0.0, 5e8), at(10000.0, 500010000.0), at(20000.0, 500020000.125), long]; assert!(matches!(merge(&spread), Ok((_, 1))), "{:?}", merge(&spread).map(|(_, thin)| thin)); for (kept, thin) in [ - ([square(0.0, 100.0), sliver], 1), - ([square(0.0, 1e6), poly(&[(1e6, 5.0), (1e6 + 1e-5, 5.5), (1e6, 6.0), (1e6, 5.0)])], 1), - ([wide, thin(1e7)], 1), + ([square(0.0, 100.0), sliver], 0), + ([square(0.0, 1e6), poly(&[(1e6, 5.0), (1e6 + 1e-5, 5.5), (1e6, 6.0), (1e6, 5.0)])], 0), + ([wide, thin(1e7)], 0), ([square(0.0, 1e10), square(1e16, 1e9)], 0), ([square(0.0, 100.0), square(1e6, 100.0)], 0), ([square(0.0, 100.0), square(1e6, 0.0)], 0), @@ -1268,6 +1304,13 @@ mod tests { ds.push(Some(square(0.0)), vec![]); ds.push(Some(broken), vec![]); assert_eq!((overlaps(&ds, &[0, 1]).skipped, gaps(&ds, &[0, 1]).skipped), (1, 1)); + let mut points = Dataset::new("p", rustgis_data::GeometryType::Point, vec![]); + points.push(Some(Geometry::Point(Coord::new(0.5, 0.25))), vec![]); + let covered = not_covered(&points, &[0], &ds); + assert_eq!((covered.errors.len(), covered.skipped), (0, 1)); + points.push(Some(Geometry::Point(Coord::new(1.5, 0.25))), vec![]); + let covered = not_covered(&points, &[0, 1], &ds); + assert_eq!((covered.errors.len(), covered.skipped), (1, 1)); assert_eq!((overlaps(&ds, &[0]).skipped, gaps(&ds, &[0]).skipped), (0, 0)); } } diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index c15f066f43..02224bcf5d 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1716,7 +1716,10 @@ fn merge(s: &mut Session, _: &Json) -> CmdResult { } let (merged, thin) = { let _plane = own.then(|| rustgis_analysis::convert::install(rustgis_analysis::convert::run_plane_for(l.dataset.coord_crs()))); - rustgis_analysis::topology::merge(&geoms).map_err(|why| format!("these features can't be merged: {why}"))? + rustgis_analysis::topology::merge(&geoms).map_err(|(why, which)| match which.and_then(|i| with_ids.get(i)) { + Some((fid, _)) => format!("these features can't be merged because of feature {fid}: {why}"), + None => format!("these features can't be merged: {why}"), + })? }; let merged = if own { merged @@ -1744,7 +1747,7 @@ fn merge(s: &mut Session, _: &Json) -> CmdResult { if thin > 0 { s.say(rustgis_data::loss::Note::loss( rustgis_data::loss::LossCode::DroppedGeometry, - format!("Merge: {thin} polygon(s) are thinner than the grid the shapes were merged on; what of them lies apart from the rest isn't in the merged shape"), + format!("Merge: {thin} polygon(s) of the features are thinner than the grid the shapes were merged on, so they, or part of them, aren't in the merged shape"), )); } Ok(json!({"merged": sel.len()})) diff --git a/crates/engine/src/tests/unplaced_edits.rs b/crates/engine/src/tests/unplaced_edits.rs index 9d098f919a..b4fbc6757d 100644 --- a/crates/engine/src/tests/unplaced_edits.rs +++ b/crates/engine/src/tests/unplaced_edits.rs @@ -265,12 +265,13 @@ fn a_topology_issue_it_cant_place_is_kept_without_a_place() { /// Merge says how many polygons its grid could have thinned away, and nothing of ordinary ones. #[test] -fn merge_says_which_polygons_its_grid_could_lose() { - let said = |sliver: f64| { +fn merge_says_which_polygons_its_grid_loses() { + let said = |other: &[&[(f64, f64)]]| { let poly = |r: &[(f64, f64)]| Geometry::Polygon(vec![vec![r.iter().map(|&(x, y)| Coord::new(x, y)).collect()]]); let mut ds = Dataset::new("polys", GeometryType::Polygon, vec![]); ds.push(Some(poly(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)])), vec![]); - ds.push(Some(poly(&[(1.0, 0.25), (1.0 + sliver, 0.5), (1.0, 0.75), (1.0, 0.25)])), vec![]); + let parts = other.iter().map(|r| vec![r.iter().map(|&(x, y)| Coord::new(x, y)).collect()]).collect(); + ds.push(Some(Geometry::Polygon(parts)), vec![]); let mut s = Session::new(crate::Project::default()); crate::cmd::layer::add_dataset(&mut s, ds); select(&mut s, "polys", &[0, 1]); @@ -282,6 +283,10 @@ fn merge_says_which_polygons_its_grid_could_lose() { .map(|n| n.loss().map(|l| l.spec().id)) .collect::>() }; - assert_eq!(said(1e-12), [Some("dropped.geometry")]); - assert!(said(0.5).is_empty()); + let beside = |w: f64| [(1.0, 0.25), (1.0 + w, 0.5), (1.0, 0.75), (1.0, 0.25)]; + // A sliver along its neighbour is in the merged shape; one apart from it, and from its own feature's + // other part, isn't. + let apart = [(2.0, 0.25), (2.0 + 1e-12, 0.5), (2.0, 0.75), (2.0, 0.25)]; + assert_eq!(said(&[&beside(0.5), &apart]), [Some("dropped.geometry")]); + assert!(said(&[&beside(1e-12)]).is_empty() && said(&[&beside(0.5)]).is_empty()); } From 60de889b788883541d6be32c02255ef81aff650c Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 09:16:52 -0600 Subject: [PATCH 09/12] fix(analysis): the covered-by check counts every covering polygon with a coordinate that isn't a number --- crates/analysis/src/topology.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 9c5ed3ccd2..aa1b218e99 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -1157,12 +1157,17 @@ fn less(of: &[(f64, f64)], holes: &[(f64, f64)]) -> Vec<(f64, f64)> { /// as everywhere else (#1033). Features of `by` the test at a pole had to leave out (a coordinate /// missing or infinite, or a million turns around) when the rest don't surround it, or might not /// have with them, are counted in `skipped`, each once at either pole, for the check to say its -/// result there may be wrong; so are those with a coordinate missing or infinite, which no point is +/// result there may be wrong; so are those with a coordinate infinite, or missing, which no point is /// tested against. Each point is tested only against the polygons whose boxes may hold /// it, through an index of them (#1252). pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { let all: Vec = (0..by.features.len()).collect(); - let (whole, not_finite) = usable(by, &all); + // Geo can't orient a ring with a coordinate missing, so one with it can't be tested. + let missing = |r: &usize| { + let no_number = |c: &Coord| c.x.is_nan() || c.y.is_nan(); + matches!(by.features.geometry(*r), Some(Geometry::Polygon(parts)) if parts.iter().flatten().flatten().any(no_number)) + }; + let whole: Vec = all.iter().copied().filter(|r| !missing(r)).collect(); let polys = polygons(by, &whole); let index = crate::tools::ExtentIndex::new(polys.iter().map(|(_, _, bb)| Extent::new(bb.min().x, bb.min().y, bb.max().x, bb.max().y))); // Whether the polygons together surround each pole, found at the first point there, with the @@ -1171,9 +1176,11 @@ pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { let (mut holds_north, mut holds_south): (Holds, Holds) = (None, None); let with_skipped = |c: Checked, north: &Holds, south: &Holds| { let mut left_out: Vec = north.iter().chain(south).flat_map(|(_, rows)| rows.iter().copied()).collect(); + let bad = |r: &usize| by.features.geometry(*r).is_some_and(polygon_not_finite); + left_out.extend(all.iter().copied().filter(bad)); left_out.sort_unstable(); left_out.dedup(); - Checked { skipped: not_finite + left_out.len(), ..c } + Checked { skipped: left_out.len(), ..c } }; let parts = || polys.iter().flat_map(|(r, mp, _)| mp.0.iter().map(move |p| (*r, p))); let mut out = Vec::new(); @@ -1308,9 +1315,11 @@ mod tests { points.push(Some(Geometry::Point(Coord::new(0.5, 0.25))), vec![]); let covered = not_covered(&points, &[0], &ds); assert_eq!((covered.errors.len(), covered.skipped), (0, 1)); + // An infinite one is still tested, but may cover what it shouldn't: counted either way. points.push(Some(Geometry::Point(Coord::new(1.5, 0.25))), vec![]); let covered = not_covered(&points, &[0, 1], &ds); - assert_eq!((covered.errors.len(), covered.skipped), (1, 1)); + assert_eq!(covered.skipped, 1); + assert!(covered.errors.len() == 1 || !bad.is_nan()); assert_eq!((overlaps(&ds, &[0]).skipped, gaps(&ds, &[0]).skipped), (0, 0)); } } From 4015bfdc9b9a4b92745c2befe16fc3a5cd43af2c Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 10:11:07 -0600 Subject: [PATCH 10/12] fix(analysis): Merge's loss check looks at the whole of each edge --- crates/analysis/src/topology.rs | 113 ++++++++++++++++++++++++++++++-- crates/engine/src/cmd/design.rs | 2 + xtask/row-uses.txt | 2 +- 3 files changed, 110 insertions(+), 7 deletions(-) diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index aa1b218e99..819482c0d9 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -77,10 +77,60 @@ thread_local! { static LOOKED_AT: std::cell::Cell = const { std::cell::Cell::new(0) }; } +/// The stretch of `line` within `reach` of `edge`, as fractions of its length: one, as what lies within +/// a distance of a segment is convex. +fn stretch_near(line: geo::Line, edge: geo::Line, reach: f64) -> Option<(f64, f64)> { + let (d, e) = (line.delta(), edge.delta()); + let dot = |a: geo::Coord, b: geo::Coord| a.x * b.x + a.y * b.y; + let mut near: Option<(f64, f64)> = None; + let mut take = |from: f64, to: f64| { + let (from, to) = (from.max(0.0), to.min(1.0)); + if from <= to { + near = Some(near.map_or((from, to), |(a, b)| (a.min(from), b.max(to)))); + } + }; + // Around each end of the edge. + let len2 = dot(d, d); + for end in [edge.start, edge.end] { + let off = line.start - end; + if len2 == 0.0 { + if dot(off, off) <= reach * reach { + take(0.0, 1.0); + } + continue; + } + let middle = -dot(off, d) / len2; + let nearest = off + d * middle; + let half2 = (reach * reach - dot(nearest, nearest)) / len2; + if half2 >= 0.0 { + take(middle - half2.sqrt(), middle + half2.sqrt()); + } + } + // Between them: along the edge from 0 to its length, and to either side of it by `reach`. + let length = dot(e, e).sqrt(); + if length > 0.0 { + let (u, off) = (e / length, line.start - edge.start); + let side = geo::Coord { x: -u.y, y: u.x }; + let (mut from, mut to) = (0.0_f64, 1.0_f64); + for (at, by, low, high) in [(dot(off, u), dot(d, u), 0.0, length), (dot(off, side), dot(d, side), -reach, reach)] { + if by == 0.0 { + if at < low || at > high { + (from, to) = (1.0, 0.0); + } + } else { + let (a, b) = ((low - at) / by, (high - at) / by); + (from, to) = (from.max(a.min(b)), to.min(a.max(b))); + } + } + take(from, to); + } + near +} + /// How many parts of `features` (each one's, `None` for a feature without any) the union's grid left -/// out, wholly or between their corners: those of so little area beside their length that rounding -/// could take it, with a corner or the middle of an edge more than two steps from the union (rounding -/// moves an edge by less than a step, and a sliver along its neighbour is thinner). `Err` names a +/// out, wholly or in stretches: those of so little area beside their length that rounding could take it, +/// with a corner or some of an edge more than two steps from the union (rounding moves an edge by less +/// than a step, and a sliver along its neighbour is thinner). `Err` names a /// feature all of whose parts with any area have a corner that far, so it is gone. fn thinned(features: &[Option>], union: &geo::MultiPolygon, step: f64) -> Result { use geo::{Contains, CoordsIter, Distance, Euclidean, Length}; @@ -119,7 +169,25 @@ fn thinned(features: &[Option>], union: &geo::MultiPolygo continue; } kept = true; - if !p.exterior().lines().all(|e| near(e.start + (e.end - e.start) / 2.0)) { + let whole = |line: geo::Line| { + let b = line.bounding_rect(); + let around = Extent::new(b.min().x - reach, b.min().y - reach, b.max().x + reach, b.max().y + reach); + let mut close = Vec::new(); + index.any_candidate(&around, |i| { + close.extend(edges.get(i).and_then(|e| stretch_near(line, *e, reach))); + false + }); + close.sort_by(|a: &(f64, f64), b| a.0.total_cmp(&b.0)); + // What is left between them meets no edge of the union, so all of it is inside or outside, + // and after the last it is as the corner there, which was found near. + let mut reached = 0.0; + close.into_iter().all(|(from, to)| { + let covered = from <= reached || near(line.start + line.delta() * ((reached + from) / 2.0)); + reached = f64::max(reached, to); + covered + }) + }; + if !p.exterior().lines().all(whole) { lost += 1; } } @@ -1157,8 +1225,8 @@ fn less(of: &[(f64, f64)], holes: &[(f64, f64)]) -> Vec<(f64, f64)> { /// as everywhere else (#1033). Features of `by` the test at a pole had to leave out (a coordinate /// missing or infinite, or a million turns around) when the rest don't surround it, or might not /// have with them, are counted in `skipped`, each once at either pole, for the check to say its -/// result there may be wrong; so are those with a coordinate infinite, or missing, which no point is -/// tested against. Each point is tested only against the polygons whose boxes may hold +/// result there may be wrong; so are those with a coordinate that isn't a number (no point is tested +/// against one with a coordinate missing). Each point is tested only against the polygons whose boxes may hold /// it, through an index of them (#1252). pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { let all: Vec = (0..by.features.len()).collect(); @@ -1220,6 +1288,34 @@ pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { #[cfg(test)] mod tests { + /// The stretch of a line near an edge is what a walk along it finds. + #[test] + fn the_stretch_of_a_line_near_an_edge_is_what_a_walk_finds() { + use geo::{Distance, Euclidean}; + let mut seed = 5_u64; + let mut at = || { + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 11) as f64 - 5.0 + }; + geo::Coord { x: next(), y: next() } + }; + for _ in 0..3000 { + let (line, edge) = (geo::Line::new(at(), at()), geo::Line::new(at(), at())); + let near = stretch_near(line, edge, 1.5); + for i in 0..=50 { + let t = f64::from(i) / 50.0; + let d = Euclidean.distance(&geo::Point(line.start + line.delta() * t), &edge); + // A walk's step on the limit itself may go either way. + if (d - 1.5).abs() > 1e-9 { + assert_eq!(near.is_some_and(|(a, b)| a <= t && t <= b), d < 1.5, "{line:?} {edge:?} {t}"); + } + } + } + } + /// Merge deletes the features it merges, so it refuses polygons its grid can't hold together, and /// takes the same ones near each other, or one with no area to lose. #[test] @@ -1278,6 +1374,11 @@ mod tests { let long = poly(&[(0.0, 5e8), (10000.0, 500010000.0), (20000.0, 500020000.125), (0.0, 5e8)]); let spread = [wide.clone(), at(0.0, 5e8), at(10000.0, 500010000.0), at(20000.0, 500020000.125), long]; assert!(matches!(merge(&spread), Ok((_, 1))), "{:?}", merge(&spread).map(|(_, thin)| thin)); + // Neighbours at its corners and the middles of its edges don't make it whole. + let long = poly(&[(1000.0, 5e8), (11000.0, 500010000.0), (21000.0, 500020000.125), (1000.0, 5e8)]); + let mut spread = vec![wide.clone(), at(1000.0, 5e8), at(11000.0, 500010000.0), at(21000.0, 500020000.125)]; + spread.extend([at(6000.0, 500005000.0), at(16000.0, 500015000.0625), long]); + assert_eq!(merge(&spread).map(|(_, lost)| lost), Ok(1)); for (kept, thin) in [ ([square(0.0, 100.0), sliver], 0), ([square(0.0, 1e6), poly(&[(1e6, 5.0), (1e6 + 1e-5, 5.5), (1e6, 6.0), (1e6, 5.0)])], 0), diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 02224bcf5d..4554d9be33 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1683,6 +1683,8 @@ fn selection_layer(s: &Session) -> Result { } } +/// Runs on the UI thread, as the other edits of the selection do: it replaces rows of the layer's own +/// data. Its union is one step of the overlay engine, with no Cancel check inside it. fn merge(s: &mut Session, _: &Json) -> CmdResult { let id = selection_layer(s)?; let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index d449074834..daebc5e4e3 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 760 +count = 749 From 00bd194fdd8e58a2cb1f709eb05857fb20f8e869 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 11:15:25 -0600 Subject: [PATCH 11/12] fix(data): a union judges an exterior with holes on its own grid, and Merge's edge test is the same at any size --- crates/analysis/src/repair.rs | 2 +- crates/analysis/src/topology.rs | 10 +++++++- crates/data/src/overlay.rs | 44 +++++++++++++++++++++++++++------ crates/engine/src/cmd/design.rs | 4 +-- 4 files changed, 48 insertions(+), 12 deletions(-) diff --git a/crates/analysis/src/repair.rs b/crates/analysis/src/repair.rs index 606b83ab8c..ea77f53a1c 100644 --- a/crates/analysis/src/repair.rs +++ b/crates/analysis/src/repair.rs @@ -38,7 +38,7 @@ use rustgis_data::{Coord, Geometry}; /// Work per vertex the overlay takes in or makes, against the same bound as a check /// ([`validity::MAX_WORK`]): at 25, up to 2 million vertices a feature, as Buffer allows. const OVERLAY_COST: u64 = 25; -/// The memory the overlay holds per vertex, as estimated: geo's and i_overlay's copies of the +/// The memory the overlay holds per vertex, as estimated: our and i_overlay's copies of the /// rings in floats and on the grid, their segments and sort, the overlay's graph and its output. const OVERLAY_BYTES: u64 = 160; /// How far a coordinate may move through the overlays of one repair, in steps of the grid: a diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 819482c0d9..747f74b0cf 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -80,6 +80,9 @@ thread_local! { /// The stretch of `line` within `reach` of `edge`, as fractions of its length: one, as what lies within /// a distance of a segment is convex. fn stretch_near(line: geo::Line, edge: geo::Line, reach: f64) -> Option<(f64, f64)> { + // In units of the reach, so that the squares of large or small coordinates stay numbers. + let [line, edge] = [line, edge].map(|l| geo::Line::new(l.start / reach, l.end / reach)); + let reach = 1.0; let (d, e) = (line.delta(), edge.delta()); let dot = |a: geo::Coord, b: geo::Coord| a.x * b.x + a.y * b.y; let mut near: Option<(f64, f64)> = None; @@ -1305,6 +1308,11 @@ mod tests { for _ in 0..3000 { let (line, edge) = (geo::Line::new(at(), at()), geo::Line::new(at(), at())); let near = stretch_near(line, edge, 1.5); + // The same at any size. + for by in [f64::exp2(600.0), f64::exp2(-600.0)] { + let [line, edge] = [line, edge].map(|l| geo::Line::new(l.start * by, l.end * by)); + assert_eq!(stretch_near(line, edge, 1.5 * by), near, "{line:?} {edge:?}"); + } for i in 0..=50 { let t = f64::from(i) / 50.0; let d = Euclidean.distance(&geo::Point(line.start + line.delta() * t), &edge); @@ -1420,7 +1428,7 @@ mod tests { points.push(Some(Geometry::Point(Coord::new(1.5, 0.25))), vec![]); let covered = not_covered(&points, &[0, 1], &ds); assert_eq!(covered.skipped, 1); - assert!(covered.errors.len() == 1 || !bad.is_nan()); + assert_eq!(covered.errors.len(), usize::from(bad.is_nan()), "{bad}"); assert_eq!((overlaps(&ds, &[0]).skipped, gaps(&ds, &[0]).skipped), (0, 0)); } } diff --git a/crates/data/src/overlay.rs b/crates/data/src/overlay.rs index 97f177830d..82068b0647 100644 --- a/crates/data/src/overlay.rs +++ b/crates/data/src/overlay.rs @@ -250,14 +250,18 @@ fn double_area(path: &[Point]) -> f64 { path.iter().zip(next).map(|(&[ax, ay], &[bx, by])| (ax - ox) * (by - oy) - (bx - ox) * (ay - oy)).sum() } -/// Whether a ring of this path encloses nothing. Rounding to its grid moves each vertex by at most -/// half a step on each axis, which changes its signed area by less than its length times a step and a +/// Whether a ring of this path encloses nothing on the union's `grid`, of this `step`. Rounding to it +/// moves each vertex by at most half a step on each axis, which changes its signed area by less than its length times a step and a /// squared step a vertex: one with more has some. The overlay tells for the rest. -fn encloses_nothing(path: &[Point], double_area: f64) -> bool { +fn encloses_nothing(path: &[Point], double_area: f64, step: Option, grid: &Adapter) -> bool { let length: f64 = path.iter().zip(path.iter().cycle().skip(1)).map(|(a, b)| (b[0] - a[0]).hypot(b[1] - a[1])).sum(); - let some = grid_step(path.iter().map(|&[x, y]| (x, y))) - .is_some_and(|step| double_area.abs() > 2.0 * (2.0 * length + path.len() as f64 * step) * step); - !some && overlay(vec![path.to_vec()], Vec::new(), OverlayRule::Subject, FillRule::NonZero).0.is_empty() + let some = step.is_some_and(|step| double_area.abs() > 2.0 * (2.0 * length + path.len() as f64 * step) * step); + let on_grid = || { + FloatOverlay::new_custom(grid.clone(), OverlayOptions::::ogc(), Default::default(), path.len()) + .unsafe_add_source(path, ShapeType::Subject) + .overlay(OverlayRule::Subject, FillRule::NonZero) + }; + !some && on_grid().is_empty() } /// The union of `polys`, which may overlap and wind either way. Each ring is oriented by its signed @@ -292,7 +296,14 @@ fn ordinary(v: f64) -> bool { } /// [`union_all`] of polygons within range. -fn union_near<'a>(polys: impl Iterator>) -> MultiPolygon { +fn union_near<'a>(polys: impl Iterator> + Clone) -> MultiPolygon { + // The grid the holes are cut on, which a hole that counts lies within. + let grid = std::cell::OnceCell::new(); + let exteriors = polys.clone(); + let of_exteriors = || { + let pts: Vec = exteriors.clone().flat_map(|p| &p.exterior().0).map(|c| [c.x, c.y]).collect(); + (grid_step(pts.iter().map(|&[x, y]| (x, y))), adapter(pts.iter())) + }; let mut subject = Vec::new(); for poly in polys { let (exterior, interiors) = poly.orient(Direction::Default).into_inner(); @@ -300,7 +311,10 @@ fn union_near<'a>(polys: impl Iterator>) -> MultiPolygon for (hole, ring) in std::iter::once((false, exterior)).chain(interiors.into_iter().map(|r| (true, r))) { let mut path = path(&ring); let area = double_area(&path); - let nothing = !hole && holed && encloses_nothing(&path, area); + let nothing = !hole && holed && { + let (step, grid) = grid.get_or_init(of_exteriors); + encloses_nothing(&path, area, *step, grid) + }; let backwards = if hole { area > 0.0 } else { area < 0.0 }; if backwards { path.reverse(); @@ -321,6 +335,20 @@ mod tests { use super::*; use geo::Area; + /// An exterior with area on a grid of its own but none on the union's is taken without its holes + /// too, as it is on the union's that they would cut other polygons. + #[test] + fn the_holes_of_an_exterior_too_small_for_the_unions_grid_cut_nothing() { + let square = geo::Rect::new((0.0, 0.0), (1.0, 1.0)).to_polygon(); + let tiny = geo::Triangle::new((0.125, 0.125).into(), (0.125 + 1e-10, 0.125).into(), (0.125, 0.125 + 1e-10).into()).to_polygon(); + let hole = geo::Rect::new((0.25, 0.25), (0.75, 0.75)).to_polygon(); + let holed = Polygon::new(tiny.exterior().clone(), vec![hole.exterior().clone()]); + assert_eq!(union_all([&square, &holed]).unsigned_area(), 1.0); + // An exterior the grid holds keeps its hole. + let holed = Polygon::new(square.exterior().clone(), vec![hole.exterior().clone()]); + assert_eq!(union_all([&holed, &tiny]).unsigned_area(), 0.75); + } + /// Neighbours whose shared corners differ by a nanometre, as each reprojected on its own does, /// merge into one polygon without pinholes: the grid's step is what joins them. #[test] diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 4554d9be33..8dd5fa85c4 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1683,8 +1683,8 @@ fn selection_layer(s: &Session) -> Result { } } -/// Runs on the UI thread, as the other edits of the selection do: it replaces rows of the layer's own -/// data. Its union is one step of the overlay engine, with no Cancel check inside it. +/// Runs on the UI thread: it replaces the rows selected when it is run, which could be edited, or the +/// selection changed, while it worked elsewhere. Its union is one step of the overlay engine, with no Cancel check inside it. fn merge(s: &mut Session, _: &Json) -> CmdResult { let id = selection_layer(s)?; let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; From 077edfb0950d4a5461eed9292537b1c6374f7682 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 12:26:35 -0600 Subject: [PATCH 12/12] fix(data): a union judges an exterior with holes on the grid its holes are cut on, and copies nothing to find it --- crates/analysis/src/topology.rs | 6 ++- crates/data/src/overlay.rs | 66 ++++++++++++++++++++++++--------- 2 files changed, 52 insertions(+), 20 deletions(-) diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 747f74b0cf..6bba3b721d 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -80,8 +80,10 @@ thread_local! { /// The stretch of `line` within `reach` of `edge`, as fractions of its length: one, as what lies within /// a distance of a segment is convex. fn stretch_near(line: geo::Line, edge: geo::Line, reach: f64) -> Option<(f64, f64)> { - // In units of the reach, so that the squares of large or small coordinates stay numbers. - let [line, edge] = [line, edge].map(|l| geo::Line::new(l.start / reach, l.end / reach)); + // In units of the reach from the line's start, so that the squares of large or small coordinates + // stay numbers. + let from = line.start; + let [line, edge] = [line, edge].map(|l| geo::Line::new((l.start - from) / reach, (l.end - from) / reach)); let reach = 1.0; let (d, e) = (line.delta(), edge.delta()); let dot = |a: geo::Coord, b: geo::Coord| a.x * b.x + a.y * b.y; diff --git a/crates/data/src/overlay.rs b/crates/data/src/overlay.rs index 82068b0647..fd7ad802e6 100644 --- a/crates/data/src/overlay.rs +++ b/crates/data/src/overlay.rs @@ -250,14 +250,14 @@ fn double_area(path: &[Point]) -> f64 { path.iter().zip(next).map(|(&[ax, ay], &[bx, by])| (ax - ox) * (by - oy) - (bx - ox) * (ay - oy)).sum() } -/// Whether a ring of this path encloses nothing on the union's `grid`, of this `step`. Rounding to it +/// Whether a ring of this path encloses nothing `on` the union's grid. Rounding to it /// moves each vertex by at most half a step on each axis, which changes its signed area by less than its length times a step and a /// squared step a vertex: one with more has some. The overlay tells for the rest. -fn encloses_nothing(path: &[Point], double_area: f64, step: Option, grid: &Adapter) -> bool { +fn encloses_nothing(path: &[Point], double_area: f64, on: &Grid) -> bool { let length: f64 = path.iter().zip(path.iter().cycle().skip(1)).map(|(a, b)| (b[0] - a[0]).hypot(b[1] - a[1])).sum(); - let some = step.is_some_and(|step| double_area.abs() > 2.0 * (2.0 * length + path.len() as f64 * step) * step); + let some = on.step.is_some_and(|step| double_area.abs() > 2.0 * (2.0 * length + path.len() as f64 * step) * step); let on_grid = || { - FloatOverlay::new_custom(grid.clone(), OverlayOptions::::ogc(), Default::default(), path.len()) + FloatOverlay::new_custom(on.adapter.clone(), OverlayOptions::::ogc(), Default::default(), path.len()) .unsafe_add_source(path, ShapeType::Subject) .overlay(OverlayRule::Subject, FillRule::NonZero) }; @@ -297,13 +297,43 @@ fn ordinary(v: f64) -> bool { /// [`union_all`] of polygons within range. fn union_near<'a>(polys: impl Iterator> + Clone) -> MultiPolygon { - // The grid the holes are cut on, which a hole that counts lies within. - let grid = std::cell::OnceCell::new(); - let exteriors = polys.clone(); - let of_exteriors = || { - let pts: Vec = exteriors.clone().flat_map(|p| &p.exterior().0).map(|c| [c.x, c.y]).collect(); - (grid_step(pts.iter().map(|&[x, y]| (x, y))), adapter(pts.iter())) - }; + let mut holed = false; + let mut on = Grid::of(polys.clone().inspect(|p| holed |= !p.interiors().is_empty()).flat_map(|p| &p.exterior().0).map(|c| [c.x, c.y])); + let mut subject = rings(polys.clone(), &on); + // A hole outside every exterior can make the grid coarser, one that holds fewer exteriors. Each + // time round it is at least twice as coarse. + let coarser = + |subject: &[Vec], on: &Grid| holed.then(|| Grid::of(subject.iter().flatten().copied())).filter(|all| all.step > on.step); + while let Some(all) = coarser(&subject, &on) { + on = all; + // Not two copies at a time. + drop(subject); + subject = rings(polys.clone(), &on); + } + // Exteriors run counterclockwise and holes clockwise, by area, except rings of zero area. The + // fill is positive whichever ring comes first. + overlay(subject, Vec::new(), OverlayRule::Subject, FillRule::Positive) +} + +/// The grid of points, and its step. +struct Grid { + step: Option, + adapter: Adapter, +} + +impl Grid { + fn of(pts: impl Iterator) -> Self { + // The corners of their extent have the same grid. + let start = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + let (lo, hi) = pts.fold(start, |(lo, hi), [x, y]| ([lo[0].min(x), lo[1].min(y)], [hi[0].max(x), hi[1].max(y)])); + let corners = if lo[0] <= hi[0] { [lo, hi] } else { [[0.0; 2]; 2] }; + Grid { step: grid_step(corners.iter().map(|&[x, y]| (x, y))), adapter: adapter(corners.iter()) } + } +} + +/// The rings of `polys` as a union takes them, its holes left out of an exterior that encloses nothing +/// `on` the grid. +fn rings<'a>(polys: impl Iterator>, on: &Grid) -> Vec> { let mut subject = Vec::new(); for poly in polys { let (exterior, interiors) = poly.orient(Direction::Default).into_inner(); @@ -311,10 +341,7 @@ fn union_near<'a>(polys: impl Iterator> + Clone) -> Mult for (hole, ring) in std::iter::once((false, exterior)).chain(interiors.into_iter().map(|r| (true, r))) { let mut path = path(&ring); let area = double_area(&path); - let nothing = !hole && holed && { - let (step, grid) = grid.get_or_init(of_exteriors); - encloses_nothing(&path, area, *step, grid) - }; + let nothing = !hole && holed && encloses_nothing(&path, area, on); let backwards = if hole { area > 0.0 } else { area < 0.0 }; if backwards { path.reverse(); @@ -325,9 +352,7 @@ fn union_near<'a>(polys: impl Iterator> + Clone) -> Mult } } } - // Exteriors run counterclockwise and holes clockwise, by area, except rings of zero area. The - // fill is positive whichever ring comes first. - overlay(subject, Vec::new(), OverlayRule::Subject, FillRule::Positive) + subject } #[cfg(test)] @@ -344,6 +369,11 @@ mod tests { let hole = geo::Rect::new((0.25, 0.25), (0.75, 0.75)).to_polygon(); let holed = Polygon::new(tiny.exterior().clone(), vec![hole.exterior().clone()]); assert_eq!(union_all([&square, &holed]).unsigned_area(), 1.0); + // Nor does one a hole outside every exterior makes the grid too coarse for. + let far = geo::Rect::new((0.25, 0.25), (64.0, 0.75)).to_polygon(); + let small = geo::Triangle::new((0.125, 0.125).into(), (0.125 + 1e-8, 0.125).into(), (0.125, 0.125 + 1e-8).into()).to_polygon(); + let holed = Polygon::new(small.exterior().clone(), vec![far.exterior().clone()]); + assert_eq!(union_all([&square, &holed]).unsigned_area(), 1.0); // An exterior the grid holds keeps its hole. let holed = Polygon::new(square.exterior().clone(), vec![hole.exterior().clone()]); assert_eq!(union_all([&holed, &tiny]).unsigned_area(), 0.75);