From 687010bcf6ed42454fbdb8e772307e0bcc7d471b Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:22:40 -0600 Subject: [PATCH 1/4] fix(analysis): Simplify counts its work toward Cancel across a feature's parts, and says its past-pole count is from before simplifying Simplify looked at Cancel every 65,536 distances within a run, but each line part and polygon ring started its own count, so a feature of very many short parts never looked at all and ran to its end after Cancel. Its work now counts across the feature's parts and rings (SimplifyRun, on the crate's control::Pace): each vertex set up, each distance, each ring's anchor scans. Once canceled, the rest of the feature is left alone, and the feature is given back as it was rather than part-simplified, for callers outside a tool run (a tool run stops as canceled). The past-pole notice counts the vertices found past a pole, before simplifying, some of which may then go; it now says so. --- crates/analysis/src/control.rs | 4 +- crates/analysis/src/tools.rs | 202 ++++++++++++++++++++++++--------- 2 files changed, 151 insertions(+), 55 deletions(-) diff --git a/crates/analysis/src/control.rs b/crates/analysis/src/control.rs index eedd7dd5c4..5cd6a6e146 100644 --- a/crates/analysis/src/control.rs +++ b/crates/analysis/src/control.rs @@ -192,11 +192,11 @@ pub(crate) fn uncapped() -> bool { /// The work units (a distance, a ray step, a multiply-add) between two looks at the cancel flag /// inside an item of a loop ([`Pace`]): a few milliseconds. -const PACE_WORK: usize = 1 << 22; +pub(crate) const PACE_WORK: usize = 1 << 22; /// Looks at the cancel flag about every [`PACE_WORK`] units of work, within an item that may /// take long on its own (a row of a wide grid without a work cap), so Cancel stops the run soon. -#[derive(Default)] +#[derive(Clone, Copy, Debug, Default)] pub(crate) struct Pace(usize); impl Pace { diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index c13f609f47..67ba54854c 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -3823,17 +3823,47 @@ const SPHERE_TO_WGS84: f64 = 6_378_137.0 / 6_399_593.625_8; /// ground than asked; of the vertices beyond theirs, the one farthest from the chord on the ground /// (its plane distance over that scale) is kept and splits the run. The ends are kept. Worked with /// a stack, not recursion, within [`SIMPLIFY_WORK`]: past it, the spans still open keep their -/// vertices, and `capped` is set. At one scale it gives what `geo`'s Douglas–Peucker gives, which -/// Simplify used before: a tolerance of 0 or less leaves the run as it is, and of equally far -/// vertices the last is kept. A run with a coordinate missing or infinite is left as it is. -fn simplify_coords(pts: &[geo::Coord], tol_m: f64, capped: &std::cell::Cell) -> Vec> { - simplify_coords_within(pts, tol_m, capped, SIMPLIFY_WORK) +/// vertices, and `run.capped` is set. Its work counts toward Cancel across the feature (`run`): +/// once canceled, the spans still open, and every later run, are left as they are. At one scale it +/// gives what `geo`'s Douglas–Peucker gives, which Simplify used before: a tolerance of 0 or less +/// leaves the run as it is, and of equally far vertices the last is kept. A run with a coordinate +/// missing or infinite is left as it is. +fn simplify_coords(pts: &[geo::Coord], tol_m: f64, run: &SimplifyRun) -> Vec> { + simplify_coords_within(pts, tol_m, run, SIMPLIFY_WORK) +} + +/// What the runs of one feature share as Simplify works through its parts and rings: the work done +/// since Cancel was last looked at ([`crate::control::Pace`]), counted across them all (each +/// vertex set up, each distance, each ring's anchor scans), so a feature of a million short parts +/// is looked at as often as one long run; whether it was canceled; and whether a run's work ran out +/// ([`SIMPLIFY_WORK`]). +#[derive(Default)] +struct SimplifyRun { + pace: std::cell::Cell, + canceled: std::cell::Cell, + capped: std::cell::Cell, +} + +impl SimplifyRun { + /// Counts `work` more units; whether the feature was canceled, now or before (then nothing more + /// of it is simplified). + fn stop(&self, work: usize) -> bool { + if self.canceled.get() { + return true; + } + let mut pace = self.pace.get(); + let stop = pace.stop(work); + self.pace.set(pace); + self.canceled.set(stop); + stop + } } /// [`simplify_coords`] with `work` distances a vertex allowed rather than [`SIMPLIFY_WORK`]. -fn simplify_coords_within(pts: &[geo::Coord], tol_m: f64, capped: &std::cell::Cell, work: usize) -> Vec> { +fn simplify_coords_within(pts: &[geo::Coord], tol_m: f64, run: &SimplifyRun, work: usize) -> Vec> { let n = pts.len(); - if n <= 2 || tol_m.is_nan() || tol_m <= 0.0 || pts.iter().any(|c| !c.x.is_finite() || !c.y.is_finite()) { + // Each vertex set up (its latitude and scale) counts toward Cancel, short runs too. + if run.stop(n) || n <= 2 || tol_m.is_nan() || tol_m <= 0.0 || pts.iter().any(|c| !c.x.is_finite() || !c.y.is_finite()) { return pts.to_vec(); } // On the ellipsoid, not the sphere ([`SPHERE_TO_WGS84`]). @@ -3851,9 +3881,8 @@ fn simplify_coords_within(pts: &[geo::Coord], tol_m: f64, capped: &std::cel } // A run someone can stop while it goes takes no cap (`control::uncapped`), as other tools'. let mut budget = if crate::control::uncapped() { usize::MAX } else { n.saturating_mul(work) }; - // Distances measured since Cancel was last looked at: it's looked at every 65,536, inside a - // span's scan too, so one large feature doesn't hold the run. - let mut since_check = 0usize; + // Each distance counts toward Cancel (`run.stop`), inside a span's scan too, so one large + // feature doesn't hold the run. // Out of work, or canceled (the run then stops as an error): the spans still open keep their // vertices. let keep_open = |keep: &mut Vec, spans: &mut dyn Iterator| { @@ -3867,7 +3896,7 @@ fn simplify_coords_within(pts: &[geo::Coord], tol_m: f64, capped: &std::cel 'spans: while let Some((i, j)) = stack.pop() { let span = j - i - 1; if span > budget { - capped.set(true); + run.capped.set(true); keep_open(&mut keep, &mut std::iter::once((i, j)).chain(stack.drain(..))); break; } @@ -3885,13 +3914,9 @@ fn simplify_coords_within(pts: &[geo::Coord], tol_m: f64, capped: &std::cel // The farthest vertex on the ground of those beyond their tolerance. let mut far: Option<(usize, f64)> = None; for k in i + 1..j { - since_check += 1; - if since_check >= 1 << 16 { - since_check = 0; - if crate::control::cancelled() { - keep_open(&mut keep, &mut std::iter::once((i, j)).chain(stack.drain(..))); - break 'spans; - } + if run.stop(1) { + keep_open(&mut keep, &mut std::iter::once((i, j)).chain(stack.drain(..))); + break 'spans; } let (Some(c), Some(&lk), Some(&sk)) = (pts.get(k), lat.get(k), scale.get(k)) else { continue }; // The smallest scale between the vertex and the chord: the equator's (1) where their @@ -3923,9 +3948,10 @@ fn simplify_coords_within(pts: &[geo::Coord], tol_m: f64, capped: &std::cel } // Three fixed non-collinear anchors prevent ring collapse and keep vertex counts monotonic. -fn simplify_ring(ring: &geo::LineString, tol_m: f64, capped: &std::cell::Cell) -> geo::LineString { +fn simplify_ring(ring: &geo::LineString, tol_m: f64, run: &SimplifyRun) -> geo::LineString { use geo::{Distance, Euclidean}; - if ring.0.len() <= 4 || ring.0.iter().any(|c| !c.x.is_finite() || !c.y.is_finite()) { + // Its two anchor scans count toward Cancel; once canceled, the ring is left as it is. + if run.stop(ring.0.len().saturating_mul(2)) || ring.0.len() <= 4 || ring.0.iter().any(|c| !c.x.is_finite() || !c.y.is_finite()) { return ring.clone(); } let Some(&first) = ring.0.first() else { return ring.clone() }; @@ -3949,7 +3975,7 @@ fn simplify_ring(ring: &geo::LineString, tol_m: f64, capped: &std::cell::Ce for bounds in stops.windows(2) { let [start, end] = bounds else { return ring.clone() }; let Some(arc) = ring.0.get(*start..=*end) else { return ring.clone() }; - let simple = simplify_coords(arc, tol_m, capped); + let simple = simplify_coords(arc, tol_m, run); corners.extend(simple.into_iter().skip(usize::from(!corners.is_empty()))); } geo::LineString::new(corners) @@ -3974,7 +4000,7 @@ struct Simplified { /// [`simplify_geometry`], saying what it left alone ([`Simplified`]). A line or polygon with a /// coordinate the plane can't hold isn't moved through the plane and back at all. fn simplify_checked(g: &Geometry, tol_m: f64) -> Simplified { - let capped = std::cell::Cell::new(false); + let run = SimplifyRun::default(); let unchanged = |broken| Simplified { geometry: g.clone(), broken, capped: false }; // A tolerance of 0 (or one that isn't a number) simplifies nothing: the geometry as it is, not // moved through the plane and back. @@ -3997,21 +4023,26 @@ fn simplify_checked(g: &Geometry, tol_m: f64) -> Simplified { let sg = match g { Geometry::Polygon(_) => to_multipolygon(g).and_then(|mut m| { for p in &mut m.0 { - p.exterior_mut(|r| *r = simplify_ring(r, tol_m, &capped)); + p.exterior_mut(|r| *r = simplify_ring(r, tol_m, &run)); p.interiors_mut(|rings| { for r in rings { - *r = simplify_ring(r, tol_m, &capped); + *r = simplify_ring(r, tol_m, &run); } }); } from_multipolygon(&m) }), Geometry::Line(_) => to_multiline(g).and_then(|m| { - from_line(&geo::MultiLineString::new(m.0.iter().map(|l| geo::LineString::new(simplify_coords(&l.0, tol_m, &capped))).collect())) + from_line(&geo::MultiLineString::new(m.0.iter().map(|l| geo::LineString::new(simplify_coords(&l.0, tol_m, &run))).collect())) }), _ => None, }; - Simplified { geometry: sg.unwrap_or_else(|| g.clone()), broken: false, capped: capped.get() } + // Canceled partway: the feature as it was, not part-simplified, for callers outside a tool run + // (a tool run stops as canceled). + if run.canceled.get() { + return unchanged(false); + } + Simplified { geometry: sg.unwrap_or_else(|| g.clone()), broken: false, capped: run.capped.get() } } fn simplify(inp: &dyn Inputs, p: &Json) -> Result { @@ -4112,7 +4143,7 @@ fn simplify_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result 0 { - messages.push(format!("Simplify: {past_pole} vertex(es) with a latitude past a pole found (taken as that pole)")); + messages.push(format!("Simplify: {past_pole} vertex(es) with a latitude past a pole found (taken as that pole before simplifying, so some may then go)")); } if without > 0 { messages.push(format!("Simplify: {without} feature(s) left out: they have no geometry to simplify")); @@ -7598,9 +7629,9 @@ mod tests { /// [`simplify_coords`] on its own, its work allowance asserted not to have run out. fn dp(pts: &[geo::Coord], tol_m: f64) -> Vec> { - let capped = std::cell::Cell::new(false); - let out = simplify_coords(pts, tol_m, &capped); - assert!(!capped.get(), "work allowance ran out"); + let run = SimplifyRun::default(); + let out = simplify_coords(pts, tol_m, &run); + assert!(!run.capped.get(), "work allowance ran out"); out } @@ -7779,9 +7810,9 @@ mod tests { let big: Vec> = zigzag.iter().enumerate().filter(|(i, _)| i % 10 == 5).map(|(_, c)| *c).collect(); assert!(big.iter().all(|c| whole.contains(c))); assert!(whole.len() < 1_000, "{}", whole.len()); - let capped = std::cell::Cell::new(false); - let short = simplify_coords_within(&zigzag, 20.0, &capped, 1); - assert!(capped.get()); + let run = SimplifyRun::default(); + let short = simplify_coords_within(&zigzag, 20.0, &run, 1); + assert!(run.capped.get()); assert!(short.len() > whole.len(), "{} {}", short.len(), whole.len()); // The ends and every big tooth (beyond its tolerance) are among those kept, all original. assert_eq!(short.first(), zigzag.first()); @@ -7790,33 +7821,97 @@ mod tests { assert!(short.iter().all(|c| zigzag.contains(c))); } - /// A run looks at Cancel inside one feature: canceled, a 200,000-vertex line that would be - /// simplified to a few vertices stops in its first span's scan and keeps them all (the run then - /// ends as canceled), without calling it a work cap. A run someone can stop takes no cap. - #[test] - fn simplify_coords_looks_at_cancel_inside_a_feature() { - let zigzag: Vec> = (0..200_000) + /// A zigzag line of `n` vertices in the analysis plane, 1 cm teeth: at 100 m, simplified to its + /// two ends. + fn cancel_zigzag(n: usize) -> Vec> { + (0..n) .map(|i| { let c = rustgis_geom::lonlat_to_plane(Coord::new(i as f64 * 1e-5, if i % 2 == 0 { 0.0 } else { 1e-7 })); geo::coord! { x: c.x, y: c.y } }) - .collect(); + .collect() + } + + /// A run looks at Cancel inside one span's scan: with the run's work counted to just short of a + /// look ([`crate::control::PACE_WORK`]), a canceled 200,000-vertex line gets past its set-up, + /// stops some 1,000 distances into its first scan, and keeps all its vertices, without calling it + /// a work cap. A run someone can stop takes no cap. + #[test] + fn simplify_coords_looks_at_cancel_inside_a_feature() { + let zigzag = cancel_zigzag(200_000); assert_eq!(dp(&zigzag, 100.0).len(), 2); let control = crate::control::Control::new(); control.cancel(); let canceled = { let _installed = crate::control::install(Some(control)); - let capped = std::cell::Cell::new(false); - let out = simplify_coords(&zigzag, 100.0, &capped); - assert!(!capped.get(), "a cancel isn't a work cap"); + let run = SimplifyRun::default(); + assert!(!run.stop(crate::control::PACE_WORK - zigzag.len() - 1_000)); + let out = simplify_coords(&zigzag, 100.0, &run); + assert!(run.canceled.get()); + assert!(!run.capped.get(), "a cancel isn't a work cap"); out }; assert_eq!(canceled.len(), zigzag.len()); // Stoppable: no cap, however little work is allowed, and the whole run simplified. let _installed = crate::control::install(Some(crate::control::Control::stoppable())); - let capped = std::cell::Cell::new(false); - assert_eq!(simplify_coords_within(&zigzag, 100.0, &capped, 1).len(), 2); - assert!(!capped.get()); + let run = SimplifyRun::default(); + assert_eq!(simplify_coords_within(&zigzag, 100.0, &run, 1).len(), 2); + assert!(!run.capped.get()); + } + + /// Cancel is counted across a feature's parts and rings, not per part: with the work just short + /// of a look, a three-vertex part is simplified, and the next part's set-up crosses it, so it and + /// every part after are left as they are; the same across a polygon's rings. Before, each part + /// started its own count, so a feature of many short parts never looked at all. + #[test] + fn simplify_looks_at_cancel_across_a_features_parts() { + let control = crate::control::Control::new(); + control.cancel(); + let _installed = crate::control::install(Some(control)); + // Lines: 3 for the first part's set-up and 1 for its distance stay short of the look. + let parts: Vec>> = + (0..10).map(|k| cancel_zigzag(3).into_iter().map(|c| geo::coord! { x: c.x + k as f64 * 1e4, y: c.y }).collect()).collect(); + let run = SimplifyRun::default(); + assert!(!run.stop(crate::control::PACE_WORK - 5)); + let lens: Vec = parts.iter().map(|p| simplify_coords(p, 100.0, &run).len()).collect(); + assert_eq!(lens, [2, 3, 3, 3, 3, 3, 3, 3, 3, 3]); + assert!(run.canceled.get()); + // Rings: each ring's anchor scans count too; once canceled, a ring is left as it is. + let ring = |dx: f64| -> geo::LineString { + let mut r: Vec> = (0..12) + .map(|i| { + let a = i as f64 * std::f64::consts::TAU / 12.0; + let c = rustgis_geom::lonlat_to_plane(Coord::new(dx + 0.01 * a.cos(), 0.01 * a.sin())); + geo::coord! { x: c.x, y: c.y } + }) + .collect(); + r.push(r[0]); + geo::LineString::new(r) + }; + let run = SimplifyRun::default(); + assert!(!run.stop(crate::control::PACE_WORK - 70)); + let first = simplify_ring(&ring(0.0), 1e6, &run); + let second = simplify_ring(&ring(1.0), 1e6, &run); + assert!(first.0.len() < 13, "the first ring is simplified: {}", first.0.len()); + assert_eq!(second, ring(1.0), "the second ring is left as it is"); + } + + /// Canceled partway, a feature is given back as it was rather than part-simplified, for callers + /// outside a tool run: a 2.2-million-vertex ring's anchor scans alone cross a look at Cancel. + #[test] + fn simplify_gives_back_a_canceled_feature_as_it_was() { + let ring: Vec = (0..2_200_000) + .map(|i| { + let a = i as f64 * std::f64::consts::TAU / 2_200_000.0; + Coord::new(10.0 * a.cos(), 10.0 * a.sin()) + }) + .chain(std::iter::once(Coord::new(10.0, 0.0))) + .collect(); + let polygon = Geometry::Polygon(vec![vec![ring]]); + let control = crate::control::Control::new(); + control.cancel(); + let _installed = crate::control::install(Some(control)); + assert_eq!(simplify_geometry(&polygon, 1_000.0), polygon); } /// The bound holds on WGS 84, not only on the sphere: at 60°N, a vertex 0.01795° east of a @@ -7944,7 +8039,8 @@ mod tests { "{messages:?}" ); assert!( - messages.iter().any(|m| m == "Simplify: 1 vertex(es) with a latitude past a pole found (taken as that pole)"), + messages.iter().any(|m| m + == "Simplify: 1 vertex(es) with a latitude past a pole found (taken as that pole before simplifying, so some may then go)"), "{messages:?}" ); // With a tolerance of 0 nothing is simplified, so the broken lines aren't blamed for it. @@ -7990,16 +8086,16 @@ mod tests { let line = Geometry::Line(vec![vec![Coord::new(10.0, 46.0), Coord::new(10.1, 46.0), Coord::new(10.2, 46.0)]]); assert_eq!(simplify_geometry(&line, 1e6).coord_count(), 2); let repeated = geo::LineString::new(vec![geo::Coord { x: 1.0, y: 1.0 }; 6]); - assert_eq!(simplify_ring(&repeated, 1e6, &std::cell::Cell::new(false)), repeated); + assert_eq!(simplify_ring(&repeated, 1e6, &SimplifyRun::default()), repeated); let collinear = geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0), (0.0, 0.0)]); - assert_eq!(simplify_ring(&collinear, 1e6, &std::cell::Cell::new(false)), collinear); + assert_eq!(simplify_ring(&collinear, 1e6, &SimplifyRun::default()), collinear); let both_sides = geo::LineString::from(vec![(0.0, 0.0), (3.0, 0.0), (-3.0, 0.0), (0.0, 0.0), (1.0, 0.0), (0.0, 0.0)]); - assert_eq!(simplify_ring(&both_sides, 1e6, &std::cell::Cell::new(false)), both_sides); + assert_eq!(simplify_ring(&both_sides, 1e6, &SimplifyRun::default()), both_sides); let concave = geo::LineString::from(vec![(0.0, 0.0), (3.0, 0.0), (2.0, 1.0), (-2.0, 1.0), (-3.0, 0.0), (-2.0, -1.0), (0.0, 0.0)]); let mut previous = concave.0.len(); for tolerance in [0.1, 1.1, 2.5, 1e6] { use geo::{Distance, Euclidean}; - let reduced = simplify_ring(&concave, tolerance, &std::cell::Cell::new(false)); + let reduced = simplify_ring(&concave, tolerance, &SimplifyRun::default()); assert!((4..=previous).contains(&reduced.0.len())); previous = reduced.0.len(); let deviation = concave.0.iter().map(|c| Euclidean.distance(&geo::Point::from(*c), &reduced)).fold(0.0_f64, f64::max); @@ -8008,9 +8104,9 @@ mod tests { } assert_eq!(previous, 4); let triangle = geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (0.0, 0.0)]); - assert_eq!(simplify_ring(&triangle, 1e6, &std::cell::Cell::new(false)), triangle); + assert_eq!(simplify_ring(&triangle, 1e6, &SimplifyRun::default()), triangle); let nonfinite = geo::LineString::from(vec![(0.0, 0.0), (f64::INFINITY, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)]); - assert_eq!(simplify_ring(&nonfinite, 1e6, &std::cell::Cell::new(false)), nonfinite); + assert_eq!(simplify_ring(&nonfinite, 1e6, &SimplifyRun::default()), nonfinite); } /// Feature To Point, Minimum Bounding Geometry without grouping and Calculate Geometry make From 4ada7169c77d9f0f5b98757f49fe374144bc7cd0 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:10:45 -0600 Subject: [PATCH 2/4] fix(analysis): Simplify weighs a vertex's set-up toward Cancel and stops walking a canceled feature's parts --- crates/analysis/src/tools.rs | 45 +++++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 11 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 67ba54854c..faf2a2c5b7 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -3859,11 +3859,20 @@ impl SimplifyRun { } } +/// The work units toward Cancel of setting up one vertex (its latitude and scale, a few +/// transcendentals): it takes some 3 to 8 times one distance. +const SETUP_WORK: usize = 4; + /// [`simplify_coords`] with `work` distances a vertex allowed rather than [`SIMPLIFY_WORK`]. fn simplify_coords_within(pts: &[geo::Coord], tol_m: f64, run: &SimplifyRun, work: usize) -> Vec> { let n = pts.len(); // Each vertex set up (its latitude and scale) counts toward Cancel, short runs too. - if run.stop(n) || n <= 2 || tol_m.is_nan() || tol_m <= 0.0 || pts.iter().any(|c| !c.x.is_finite() || !c.y.is_finite()) { + if run.stop(n.saturating_mul(SETUP_WORK)) + || n <= 2 + || tol_m.is_nan() + || tol_m <= 0.0 + || pts.iter().any(|c| !c.x.is_finite() || !c.y.is_finite()) + { return pts.to_vec(); } // On the ellipsoid, not the sphere ([`SPHERE_TO_WGS84`]). @@ -3883,7 +3892,7 @@ fn simplify_coords_within(pts: &[geo::Coord], tol_m: f64, run: &SimplifyRun let mut budget = if crate::control::uncapped() { usize::MAX } else { n.saturating_mul(work) }; // Each distance counts toward Cancel (`run.stop`), inside a span's scan too, so one large // feature doesn't hold the run. - // Out of work, or canceled (the run then stops as an error): the spans still open keep their + // Out of work, or canceled (the feature is then given back as it was): the spans still open keep their // vertices. let keep_open = |keep: &mut Vec, spans: &mut dyn Iterator| { for k in spans.flat_map(|(i, j)| i + 1..j) { @@ -4021,24 +4030,36 @@ fn simplify_checked(g: &Geometry, tol_m: f64) -> Simplified { } } let sg = match g { + // Once canceled, the parts left aren't walked nor the feature put back together. Geometry::Polygon(_) => to_multipolygon(g).and_then(|mut m| { for p in &mut m.0 { + if run.canceled.get() { + return None; + } p.exterior_mut(|r| *r = simplify_ring(r, tol_m, &run)); p.interiors_mut(|rings| { - for r in rings { + for r in rings.iter_mut().take_while(|_| !run.canceled.get()) { *r = simplify_ring(r, tol_m, &run); } }); } - from_multipolygon(&m) + if run.canceled.get() { None } else { from_multipolygon(&m) } }), Geometry::Line(_) => to_multiline(g).and_then(|m| { - from_line(&geo::MultiLineString::new(m.0.iter().map(|l| geo::LineString::new(simplify_coords(&l.0, tol_m, &run))).collect())) + let mut parts = Vec::with_capacity(m.0.len()); + for l in &m.0 { + let simple = simplify_coords(&l.0, tol_m, &run); + if run.canceled.get() { + return None; + } + parts.push(geo::LineString::new(simple)); + } + from_line(&geo::MultiLineString::new(parts)) }), _ => None, }; - // Canceled partway: the feature as it was, not part-simplified, for callers outside a tool run - // (a tool run stops as canceled). + // Canceled partway: the feature as it was, never part-simplified (a tool run then stops as + // canceled, and its features aren't used). if run.canceled.get() { return unchanged(false); } @@ -4051,7 +4072,8 @@ fn simplify(inp: &dyn Inputs, p: &Json) -> Result { /// [`simplify`] on `threads` threads (by the number of features when `None`): each feature is /// simplified on its own (#1252), and the rows and vertex counts are made in input order, as on -/// one thread. Cancel is looked at, and progress counted, between features. +/// one thread. Cancel is looked at, and progress counted, between features, and within a feature +/// as its work adds up across its parts ([`SimplifyRun`]). fn simplify_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result { let ds = input(inp, p, "input")?; let tol = num(p, "tolerance").ok_or("Tolerance must be a number")?.abs() * 1000.0; @@ -7845,7 +7867,7 @@ mod tests { let canceled = { let _installed = crate::control::install(Some(control)); let run = SimplifyRun::default(); - assert!(!run.stop(crate::control::PACE_WORK - zigzag.len() - 1_000)); + assert!(!run.stop(crate::control::PACE_WORK - SETUP_WORK * zigzag.len() - 1_000)); let out = simplify_coords(&zigzag, 100.0, &run); assert!(run.canceled.get()); assert!(!run.capped.get(), "a cancel isn't a work cap"); @@ -7868,11 +7890,11 @@ mod tests { let control = crate::control::Control::new(); control.cancel(); let _installed = crate::control::install(Some(control)); - // Lines: 3 for the first part's set-up and 1 for its distance stay short of the look. + // Lines: 12 for the first part's set-up (3 vertices) and 1 for its distance stay short of the look. let parts: Vec>> = (0..10).map(|k| cancel_zigzag(3).into_iter().map(|c| geo::coord! { x: c.x + k as f64 * 1e4, y: c.y }).collect()).collect(); let run = SimplifyRun::default(); - assert!(!run.stop(crate::control::PACE_WORK - 5)); + assert!(!run.stop(crate::control::PACE_WORK - 14)); let lens: Vec = parts.iter().map(|p| simplify_coords(p, 100.0, &run).len()).collect(); assert_eq!(lens, [2, 3, 3, 3, 3, 3, 3, 3, 3, 3]); assert!(run.canceled.get()); @@ -7888,6 +7910,7 @@ mod tests { r.push(r[0]); geo::LineString::new(r) }; + // The first ring's work (59) stays short of the look; the second's anchor scans cross it. let run = SimplifyRun::default(); assert!(!run.stop(crate::control::PACE_WORK - 70)); let first = simplify_ring(&ring(0.0), 1e6, &run); From a56d503b2cca250055a6bd62efff490e2f5d856b Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:22:53 -0600 Subject: [PATCH 3/4] fix(analysis): Simplify's ring test checks that a ring's own work counts toward Cancel; a canceled ring isn't copied arc by arc --- crates/analysis/src/tools.rs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index faf2a2c5b7..360f72e63c 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -3985,6 +3985,10 @@ fn simplify_ring(ring: &geo::LineString, tol_m: f64, run: &SimplifyRun) -> let [start, end] = bounds else { return ring.clone() }; let Some(arc) = ring.0.get(*start..=*end) else { return ring.clone() }; let simple = simplify_coords(arc, tol_m, run); + // Canceled: the ring as it is, its arcs left not copied. + if run.canceled.get() { + return ring.clone(); + } corners.extend(simple.into_iter().skip(usize::from(!corners.is_empty()))); } geo::LineString::new(corners) @@ -4073,7 +4077,10 @@ fn simplify(inp: &dyn Inputs, p: &Json) -> Result { /// [`simplify`] on `threads` threads (by the number of features when `None`): each feature is /// simplified on its own (#1252), and the rows and vertex counts are made in input order, as on /// one thread. Cancel is looked at, and progress counted, between features, and within a feature -/// as its work adds up across its parts ([`SimplifyRun`]). +/// as its work adds up across its parts ([`SimplifyRun`]). A feature's passes over all its +/// vertices without a look (checking it and moving it into the plane and back, setting up a run's +/// latitudes and scales, comparing and counting the result) each take about as long as one +/// distance per vertex, so only a feature of tens of millions of vertices holds the run for long. fn simplify_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result { let ds = input(inp, p, "input")?; let tol = num(p, "tolerance").ok_or("Tolerance must be a number")?.abs() * 1000.0; @@ -7910,13 +7917,26 @@ mod tests { r.push(r[0]); geo::LineString::new(r) }; - // The first ring's work (59) stays short of the look; the second's anchor scans cross it. + // The first ring's work (26 for its anchor scans, 60 for its arcs' 15 vertices set up, 9 + // distances: 95) stays short of the look, and the last unit of the second's anchor scans + // reaches it. + let full = simplify_ring(&ring(0.0), 1e6, &SimplifyRun::default()); + assert_eq!(full.0.len(), 4); let run = SimplifyRun::default(); - assert!(!run.stop(crate::control::PACE_WORK - 70)); + assert!(!run.stop(crate::control::PACE_WORK - 121)); let first = simplify_ring(&ring(0.0), 1e6, &run); + assert!(!run.canceled.get(), "the first ring's work stays short of the look"); + assert_eq!(first, full, "the first ring is simplified"); let second = simplify_ring(&ring(1.0), 1e6, &run); - assert!(first.0.len() < 13, "the first ring is simplified: {}", first.0.len()); + assert!(run.canceled.get()); assert_eq!(second, ring(1.0), "the second ring is left as it is"); + // A ring too small to simplify counts too (8 for a closed triangle), so a polygon of a + // million small holes is looked at. + let triangle = geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (0.0, 0.0)]); + let run = SimplifyRun::default(); + assert!(!run.stop(crate::control::PACE_WORK - 8)); + assert_eq!(simplify_ring(&triangle, 1e6, &run), triangle); + assert!(run.canceled.get(), "a small ring's work counts toward Cancel"); } /// Canceled partway, a feature is given back as it was rather than part-simplified, for callers From 5db2f1bceefef47f956435650758fa2ec46bed4d Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:25:58 -0600 Subject: [PATCH 4/4] refactor(analysis): Simplify takes its Pace out of the cell, so Pace stays a counter that can't be copied --- crates/analysis/src/control.rs | 2 +- crates/analysis/src/tools.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/analysis/src/control.rs b/crates/analysis/src/control.rs index 5cd6a6e146..fc1a64c346 100644 --- a/crates/analysis/src/control.rs +++ b/crates/analysis/src/control.rs @@ -196,7 +196,7 @@ pub(crate) const PACE_WORK: usize = 1 << 22; /// Looks at the cancel flag about every [`PACE_WORK`] units of work, within an item that may /// take long on its own (a row of a wide grid without a work cap), so Cancel stops the run soon. -#[derive(Clone, Copy, Debug, Default)] +#[derive(Default)] pub(crate) struct Pace(usize); impl Pace { diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 360f72e63c..1ccdcc849e 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -3851,7 +3851,7 @@ impl SimplifyRun { if self.canceled.get() { return true; } - let mut pace = self.pace.get(); + let mut pace = self.pace.take(); let stop = pace.stop(work); self.pace.set(pace); self.canceled.set(stop);