From 6c98cd71d787436e8a5715ff4d87d8d34a3260fc Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 18:44:31 -0600 Subject: [PATCH 1/2] perf(analysis): reuse the input polygon index in Erase and Update --- crates/analysis/src/tools.rs | 81 ++++++++++++++++++++++++++++++------ 1 file changed, 69 insertions(+), 12 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 2c3e9b55ef..e895720965 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -9,7 +9,9 @@ mod repair_geometry; mod tabulate_area; mod texture_shading; -use geo::{Contains, ConvexHull, CoordsIter, InteriorPoint, Intersects, MultiPolygon, Orient, Relate, orient::Direction}; +use geo::{ + Contains, ConvexHull, CoordsIter, InteriorPoint, Intersects, MultiPolygon, Orient, Relate, indexed::PreparedGeometry, 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}; @@ -2224,12 +2226,20 @@ fn largest_geometry_bytes(ds: &Dataset, rows: &[usize]) -> Result Ok(largest) } +/// Prepare only when enough masks will reuse the input geometry's segment index. +const PREPARE_ERASE_MASKS: usize = 32; +/// Limit the size of a single input's prepared graph, including on the browser. +const PREPARE_ERASE_COORDS: std::ops::RangeInclusive = 128..=16_384; +/// Budget space for the projected validity check, R-tree, cached edges and graph clone per vertex. +const PREPARE_ERASE_BYTES_PER_COORD: usize = 256; + /// Peak per-feature overlay storage, estimated from the masks it may actually meet: converted /// and dissolved input, the masks' union and output. Overlapping masks can each retain the /// entire input as an inside piece, so cuts budget another input copy per candidate mask. /// Four input copies allow conversion, dissolve, intermediate and output; three mask copies -/// allow the union, boolean-operation work and output. The index's candidate references can -/// exceed the number of zones before deduplication. +/// allow the union, boolean-operation work and output. Erase and Update budget one prepared +/// graph when a polygon meets enough masks. Its coordinate cap allows for growth during dissolve. +/// The index's candidate references can exceed the number of zones before deduplication. /// Like Clip's estimate this sizes coordinate storage, not a worst-case bound on edge crossings. fn overlay_scratch(ds: &Dataset, rows: &[usize], zones: &[Zone], near: (&ExtentIndex, &AtPoles), inside: bool) -> Result { crate::control::begin(rows.len().saturating_add(zones.len())); @@ -2247,7 +2257,12 @@ fn overlay_scratch(ds: &Dataset, rows: &[usize], zones: &[Zone], near: (&ExtentI let hits = meeting(g, &g.extent(), zones, near); let masks = hits.iter().filter_map(|&i| sizes.get(i)).fold(0usize, |n, &b| n.saturating_add(b)); let copies = if inside { hits.len().saturating_add(4) } else { 4 }; - largest = largest.max(coord_bytes(g).saturating_mul(copies).saturating_add(masks.saturating_mul(3))); + let prepared = if !inside && hits.len() >= PREPARE_ERASE_MASKS && matches!(g, Geometry::Polygon(_)) { + *PREPARE_ERASE_COORDS.end() * PREPARE_ERASE_BYTES_PER_COORD + } else { + 0 + }; + largest = largest.max(coord_bytes(g).saturating_mul(copies).saturating_add(masks.saturating_mul(3)).saturating_add(prepared)); } crate::control::advance(1); } @@ -2791,6 +2806,28 @@ fn rest_outside(g: &Geometry, whole: &Geometry, hit: &[&Zone]) -> Option) -> bool { + let m = zone.poly.relate(whole); + m.is_intersects() && !m.is_touches() +} + +/// Keep the same DE-9IM test, preparing the dissolved input once for a large set of candidates. +/// Check validity in the run's plane before caching self-noding results. A bounded check keeps +/// complicated or invalid polygons on the existing path and limits the graph we have to hold. +fn polygon_zone_hits<'a>(near: Vec<&'a Zone>, whole: &geo::Geometry, polygons: &MultiPolygon) -> Vec<&'a Zone> { + let coords = polygons.coords_count(); + if near.len() >= PREPARE_ERASE_MASKS + && PREPARE_ERASE_COORDS.contains(&coords) + && crate::validity::check(Some(&in_plane(polygons)), coords as u64 * PREPARE_ERASE_BYTES_PER_COORD as u64).problems.is_empty() + { + let prepared = PreparedGeometry::from(whole); + near.into_iter().filter(|z| polygon_zone_cuts(z, &prepared)).collect() + } else { + near.into_iter().filter(|z| polygon_zone_cuts(z, whole)).collect() + } +} + /// A feature's part outside every zone, as [`part`] gives it, for tools that keep only that /// (Erase, Update): it is cut once, by the zones that cut it (that zone itself, so its edges stay /// exactly where they are, or their union), without [`cut`]'s part in each zone. Only zones whose @@ -2811,15 +2848,12 @@ fn outside(g: &Geometry, zones: &[Zone], index: (&ExtentIndex, &AtPoles)) -> Opt // The zones that cut it: a polygon is cut by those it overlaps, a line or point by those it // meets (an edge counts as inside, and a point at a pole meets a zone reaching it). Each is // tested on its own, before any union. - let cuts = |z: &&Zone| match g { - Geometry::Polygon(_) => { - let m = z.poly.relate(&geo_g); - m.is_intersects() && !m.is_touches() - } - Geometry::Point(_) | Geometry::MultiPoint(_) => meet_at_a_pole(poles(&ext), poles(&z.ext)) || z.poly.intersects(&geo_g), - Geometry::Line(_) => z.poly.intersects(&geo_g), + let hit = if let geo::Geometry::MultiPolygon(polygons) = &geo_g { + polygon_zone_hits(near, &geo_g, polygons) + } else { + let points = matches!(g, Geometry::Point(_) | Geometry::MultiPoint(_)); + near.into_iter().filter(|z| (points && meet_at_a_pole(poles(&ext), poles(&z.ext))) || z.poly.intersects(&geo_g)).collect() }; - let hit: Vec<&Zone> = near.into_iter().filter(cuts).collect(); rest_outside(g, &whole, &hit) } @@ -15256,6 +15290,29 @@ mod tests { assert!((rest.unsigned_area() - want.unsigned_area()).abs() < 1e-6 * want.unsigned_area(), "{rest:?}"); } + /// A complex feature can have thousands of bounding-box matches without any cuts. + /// Rebuilding its segment index for each mask makes this finish too slowly. + #[test] + fn erase_finishes_with_many_masks_outside_a_complex_feature() { + let ring = (0..=8192) + .map(|i| { + let angle = (i % 8192) as f64 * std::f64::consts::TAU / 8192.0; + Coord::new(angle.cos(), angle.sin()) + }) + .collect(); + let g = Geometry::Polygon(vec![vec![ring]]); + let mut input = Dataset::new("input", GeometryType::Polygon, vec![]); + input.push(Some(g.clone()), vec![]); + let mut zones = Dataset::new("zones", GeometryType::Polygon, vec![]); + for _ in 0..4096 { + zones.push(Some(sq(0.85, 0.85, 0.1)), vec![]); + } + let m = Map(HashMap::from([("input".into(), input), ("zones".into(), zones)])); + let out = layer(finishes(move || crate::run("erase", &m, &serde_json::json!({"input": "input", "erase": "zones"})).unwrap())); + assert_eq!(out.features.len(), 1); + assert_eq!(out.features.geometry(0), Some(&g)); + } + #[test] fn update_replaces_the_covered_part_with_the_update_polygons() { let mut m = parcels_and_zones(); From 6b94986b690ed587e47425e28353018da154eeb3 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 23:11:31 -0600 Subject: [PATCH 2/2] test(analysis): a prepared feature is cut by the same masks --- crates/analysis/src/tools.rs | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index e895720965..287916140c 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2232,6 +2232,8 @@ const PREPARE_ERASE_MASKS: usize = 32; const PREPARE_ERASE_COORDS: std::ops::RangeInclusive = 128..=16_384; /// Budget space for the projected validity check, R-tree, cached edges and graph clone per vertex. const PREPARE_ERASE_BYTES_PER_COORD: usize = 256; +/// The work a vertex allows the validity check before preparing: one that needs more isn't prepared. +const PREPARE_ERASE_CHECK_WORK: u64 = 256; /// Peak per-feature overlay storage, estimated from the masks it may actually meet: converted /// and dissolved input, the masks' union and output. Overlapping masks can each retain the @@ -2819,7 +2821,7 @@ fn polygon_zone_hits<'a>(near: Vec<&'a Zone>, whole: &geo::Geometry, polygo let coords = polygons.coords_count(); if near.len() >= PREPARE_ERASE_MASKS && PREPARE_ERASE_COORDS.contains(&coords) - && crate::validity::check(Some(&in_plane(polygons)), coords as u64 * PREPARE_ERASE_BYTES_PER_COORD as u64).problems.is_empty() + && crate::validity::check(Some(&in_plane(polygons)), coords as u64 * PREPARE_ERASE_CHECK_WORK).problems.is_empty() { let prepared = PreparedGeometry::from(whole); near.into_iter().filter(|z| polygon_zone_cuts(z, &prepared)).collect() @@ -15313,6 +15315,37 @@ mod tests { assert_eq!(out.features.geometry(0), Some(&g)); } + /// The masks picked for a prepared feature are the ones picked for it unprepared: ones that cut it, + /// touch it along an edge or at a corner, cover it, or lie in its hole, in order. + #[test] + fn a_prepared_feature_is_cut_by_the_same_masks() { + let ring = |r: f64| { + (0..=256) + .map(|i| (f64::from(i % 256) * std::f64::consts::TAU / 256.0).sin_cos()) + .map(|(y, x)| Coord::new(x * r, y * r)) + .collect::>() + }; + let whole = to_multipolygon(&Geometry::Polygon(vec![vec![ring(1.0), ring(0.3).into_iter().rev().collect()]])).unwrap(); + let mut zones: Vec = (0..64).map(|i| sq(0.85, 0.85 + f64::from(i) * 1e-4, 0.1)).collect(); + zones.extend([ + sq(0.5, 0.0, 0.2), + sq(1.0, 0.0, 0.5), + sq(0.9, -0.2, 0.4), + sq(-2.0, -2.0, 4.0), + sq(-0.1, -0.1, 0.2), + sq(-0.1, 0.9, 0.2), + ]); + let side: Vec = ring(1.0)[..2].to_vec(); + zones.push(Geometry::Polygon(vec![vec![vec![side[0], Coord::new(1.5, 0.0), side[1], side[0]]]])); + let zones: Vec = zones.iter().map(|g| Zone { row: 0, ext: g.extent(), poly: to_multipolygon(g).unwrap() }).collect(); + let geo_whole = geo::Geometry::MultiPolygon(whole.clone()); + let at = |hits: Vec<&Zone>| hits.iter().map(|h| zones.iter().position(|z| std::ptr::eq(z, *h)).unwrap()).collect::>(); + let picked = at(polygon_zone_hits(zones.iter().collect(), &geo_whole, &whole)); + let unprepared = at(zones.iter().filter(|z| polygon_zone_cuts(z, &geo_whole)).collect()); + assert_eq!(picked, unprepared); + assert_eq!(picked, [64, 66, 67, 69]); + } + #[test] fn update_replaces_the_covered_part_with_the_update_polygons() { let mut m = parcels_and_zones();