From 89180dcb5813e7f2b91f1eacb3738f6eaf636848 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Wed, 25 Nov 2026 14:13:18 -0300 Subject: [PATCH 1/3] perf(map): clicks, box selection and snapping look at the kept boxes first (#2330) Each layer keeps the box of every projected shape, which drawing culls by. `hits_at`, `hits_in` and snapping now test it before reading a shape's coordinates. `hits_at` widens it by the tolerance and a margin for rounding, so the result is that of a search of every shape. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/design.rs | 4 +- crates/engine/tests/integration/main.rs | 1 + crates/engine/tests/integration/snap_boxes.rs | 125 +++++++++++ crates/map/src/lib.rs | 194 +++++++++++++++++- 4 files changed, 316 insertions(+), 8 deletions(-) create mode 100644 crates/engine/tests/integration/snap_boxes.rs diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 69afe3a336..00206b60d7 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2608,9 +2608,11 @@ fn snap_excluding( } let id = l.id; l.projected_in(&flat, &key); + let boxes = l.projected_extents(); for (row, g) in l.projected_cache().iter().enumerate() { let Some(g) = g.as_ref().filter(|_| skip != Some((id, row))) else { continue }; - if !g.extent().padded(0.0, tol).contains(m) { + // Its box as kept with the projected shape: a snap asks on every pointer move. + if !boxes.get(row).copied().unwrap_or_else(|| g.extent()).padded(0.0, tol).contains(m) { continue; } of.set((id, row)); diff --git a/crates/engine/tests/integration/main.rs b/crates/engine/tests/integration/main.rs index 31a9edec21..6bacd67110 100644 --- a/crates/engine/tests/integration/main.rs +++ b/crates/engine/tests/integration/main.rs @@ -20,6 +20,7 @@ mod project_save; mod project_save_roundtrip; mod raster_crs_notices; mod recovery_paths; +mod snap_boxes; mod snapping_point_types; mod vertex_snap_identity; mod workflows; diff --git a/crates/engine/tests/integration/snap_boxes.rs b/crates/engine/tests/integration/snap_boxes.rs new file mode 100644 index 0000000000..9c3d9985df --- /dev/null +++ b/crates/engine/tests/integration/snap_boxes.rs @@ -0,0 +1,125 @@ +//! Snapping, which reads only the shapes whose kept box is near, finds what a search of every +//! shape finds. +use rustgis_engine::{ + Project, Session, + cmd::design::snap_except, + data::{Dataset, Geometry, GeometryType}, + geom::{Coord, merc_to_lonlat}, + map::design::Snapping, +}; + +const TOLERANCE: f64 = 10.0; + +/// Metre-sized fixtures in the longitude/latitude coordinates of feature layers. +fn c(x: f64, y: f64) -> Coord { + merc_to_lonlat(Coord::new(x, y)) +} + +/// A repeatable pseudo-random sequence in 0..1. +fn sequence(mut seed: u64) -> impl FnMut() -> f64 { + move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + } +} + +fn layer(next: &mut impl FnMut() -> f64, name: &str, n: usize) -> Dataset { + let mut d = Dataset::new(name, GeometryType::Polygon, vec![]); + for i in 0..n { + let (x, y) = (next() * 400.0 - 5e6, next() * 400.0 - 2e6); + let mut path = |n: usize| -> Vec { (0..n).map(|_| c(x + next() * 60.0, y + next() * 60.0)).collect() }; + let square = |r: f64| vec![c(x - r, y - r), c(x + r, y - r), c(x + r, y + r), c(x - r, y + r), c(x - r, y - r)]; + let g = match i % 6 { + 0 => Some(Geometry::Point(c(x, y))), + 1 => Some(Geometry::MultiPoint(path(3))), + 2 => Some(Geometry::Line(vec![path(4), path(2)])), + 3 => Some(Geometry::Polygon(vec![vec![square(40.0), square(20.0)]])), + 4 => Some(Geometry::Polygon(vec![vec![path(4)], vec![path(3)]])), + _ => None, + }; + d.push(g, vec![]); + } + d +} + +/// The kind and the map place a search of every shape but `skip` finds nearest to `m`: a vertex or +/// a line's end before an edge, the first of those as near. +fn nearest_of_every_shape(s: &mut Session, m: Coord, skip: Option<(u32, usize)>) -> Option<(Coord, &'static str)> { + let (mut point, mut edge): (Option<(f64, Coord, &str)>, Option<(f64, Coord, &str)>) = (None, None); + let mut consider = |at: Coord, kind: &'static str| { + let d = (at.x - m.x).powi(2) + (at.y - m.y).powi(2); + let slot = if kind == "edge" { &mut edge } else { &mut point }; + if d <= TOLERANCE * TOLERANCE && slot.is_none_or(|b| d < b.0) { + *slot = Some((d, at, kind)); + } + }; + for l in &mut s.map_mut().layers { + let id = l.id; + for (_, g) in l.projected().iter().enumerate().filter(|(row, _)| skip != Some((id, *row))) { + let (points, paths): (&[Coord], Vec<&Vec>) = match g { + Some(Geometry::Point(p)) => (std::slice::from_ref(p), vec![]), + Some(Geometry::MultiPoint(p)) => (p, vec![]), + Some(Geometry::Line(parts)) => (&[], parts.iter().collect()), + Some(Geometry::Polygon(polys)) => (&[], polys.iter().flatten().collect()), + None => continue, + }; + points.iter().for_each(|p| consider(*p, "vertex")); + for path in paths { + if matches!(g, Some(Geometry::Line(_))) { + [path.first(), path.last()].into_iter().flatten().for_each(|p| consider(*p, "end")); + } + path.iter().for_each(|p| consider(*p, "vertex")); + for w in path.windows(2) { + let (dx, dy) = (w[1].x - w[0].x, w[1].y - w[0].y); + let len2 = dx * dx + dy * dy; + let t = if len2 > 0.0 { (((m.x - w[0].x) * dx + (m.y - w[0].y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; + consider(Coord::new(w[0].x + t * dx, w[0].y + t * dy), "edge"); + } + } + } + } + point.or(edge).map(|(_, at, kind)| (at, kind)) +} + +fn check(s: &mut Session, next: &mut impl FnMut() -> f64, skip: Option<(u32, usize)>) { + let mut kinds = std::collections::BTreeMap::new(); + for _ in 0..600 { + let at = c(next() * 500.0 - 5e6 - 20.0, next() * 500.0 - 2e6 - 20.0); + let m = s.map().to_map(at).unwrap(); + let expected = nearest_of_every_shape(s, m, skip); + let got = snap_except(s, at, skip); + assert_eq!(got.map(|g| g.1), expected.map(|e| e.1), "{at:?}"); + *kinds.entry(got.map(|g| g.1)).or_insert(0) += 1; + if let (Some((got, _)), Some((expected, _))) = (got, expected) { + let got = s.map().to_map(got).unwrap(); + assert!((got.x - expected.x).abs() < 1e-6 && (got.y - expected.y).abs() < 1e-6, "{got:?} != {expected:?}"); + } + } + // Every kind, and nothing near too. + assert_eq!(kinds.len(), 4, "{kinds:?}"); +} + +#[test] +fn snapping_finds_what_a_search_of_every_shape_finds() { + let mut next = sequence(0x9E37_79B9_7F4A_7C15); + let mut s = Session::new(Project::new("Snap boxes")); + s.map_mut().layers.clear(); + let id = s.map_mut().add_dataset(layer(&mut next, "A", 48)); + s.map_mut().add_dataset(layer(&mut next, "B", 48)); + s.map_mut().camera.res = 1.0; + s.map_mut().editing.snapping = Snapping { enabled: true, tolerance_px: TOLERANCE, vertex: true, edge: true, end: true }; + check(&mut s, &mut next, None); + // All but one shape. + check(&mut s, &mut next, Some((id, 3))); + // Shapes moved, added and removed: their boxes are those of the new ones. + let l = s.map_mut().layer_mut(id).unwrap(); + let far = c(-5e6 + 900.0, -2e6); + l.dataset.features.set_geometry(0, Some(Geometry::Point(far))); + l.dataset.features.set_geometry(3, None); + l.dataset.features.set_geometry(5, Some(Geometry::Line(vec![vec![c(-5e6, -2e6), c(-5e6 + 400.0, -2e6 + 400.0)]]))); + l.touch_geometry(); + assert_eq!(snap_except(&mut s, c(-5e6 + 905.0, -2e6), None), Some((far, "vertex"))); + check(&mut s, &mut next, None); +} diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index dd71189725..db3b1a1252 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -3481,7 +3481,10 @@ impl Map { /// Every feature under a point in the visible layers `keep` accepts: top layer first and, in /// a layer, the one drawn on top first. At most `limit` of them; with `first_layer`, only - /// those of the top layer with any. + /// those of the top layer with any. A shape whose kept box ([`Layer::projected_extents`]) is + /// farther than `tol` isn't read: so one with a place the projection can't show (its ring has + /// a gap, through which its inside would run on past it) is hit only in or near its box, as it + /// is drawn. pub fn hits_at( &mut self, p: Coord, @@ -3508,12 +3511,18 @@ impl Map { // Only features drawn: the definition query and the display filters let them through. let rows = l.drawn_rows(scale); let id = l.id; - let proj = l.projected_in(&flat, &key); - let hits = proj + l.projected_in(&flat, &key); + let boxes = l.projected_extents(); + let hits = l + .projected_cache() .iter() .enumerate() .rev() - .filter(|(row, g)| rows.get(*row) == Some(&true) && g.as_ref().is_some_and(|g| g.hit(p, tol))) + .filter(|(row, g)| { + // A point is measured sooner than its box. + let near = |g: &Geometry| matches!(g, Geometry::Point(_)) || boxes.get(*row).is_none_or(|e| box_may_hit(e, p, tol)); + rows.get(*row) == Some(&true) && g.as_ref().is_some_and(|g| near(g) && g.hit(p, tol)) + }) .map(|(row, _)| (id, row)); out.extend(hits.take(limit - out.len())); } @@ -3526,7 +3535,8 @@ impl Map { self.layers.iter_mut().filter(move |l| l.visible && l.selectable && l.in_scale_range(scale) && !held.contains(&l.id)) } - /// Rows of each selectable, visible layer inside a rectangle in the camera's coordinates. + /// Rows of each selectable, visible layer inside a rectangle in the camera's coordinates. A + /// shape whose kept box ([`Layer::projected_extents`]) misses it isn't read. pub fn hits_in(&mut self, e: &Extent, scale: f64) -> Vec<(u32, Vec)> { let (flat, key) = (self.flat(), self.projection.code()); let mut out = Vec::new(); @@ -3534,11 +3544,16 @@ impl Map { // Only features drawn: the definition query and the display filters let them through. let rows = l.drawn_rows(scale); let id = l.id; + l.projected_in(&flat, &key); + let boxes = l.projected_extents(); let hits: Vec = l - .projected_in(&flat, &key) + .projected_cache() .iter() .enumerate() - .filter(|(r, g)| rows.get(*r) == Some(&true) && g.as_ref().is_some_and(|g| g.intersects_extent(e))) + .filter(|(r, g)| { + rows.get(*r) == Some(&true) + && g.as_ref().is_some_and(|g| boxes.get(*r).is_none_or(|b| b.intersects(e)) && g.intersects_extent(e)) + }) .map(|(r, _)| r) .collect(); if !hits.is_empty() { @@ -3549,6 +3564,17 @@ impl Map { } } +/// Whether a shape with the box `e` can be within `tol` of `p` ([`Geometry::hit`]): false only +/// when it can't. The box is widened by a little more than `tol`, as the place of a segment nearest +/// to `p` is rounded, so `hit` may find one at the very limit a hair outside its own box. +fn box_may_hit(e: &Extent, p: Coord, tol: f64) -> bool { + let tol = tol.abs(); + // Some thousands of times the rounding of the largest coordinate that goes into a distance: + // 0.02 mm on Web Mercator. + let size = e.min_x.abs().max(e.max_x.abs()).max(e.min_y.abs()).max(e.max_y.abs()).max(tol); + e.padded(0.0, tol + size * 1e-12).contains(p) +} + /// The reference scales a layer takes (1:N), as [`Layer::reference_scale`]. pub const REFERENCE_SCALES: (f64, f64) = (1.0, 1e9); @@ -5078,6 +5104,160 @@ mod tests { assert_eq!(m.hits_at(p, 1000.0, 1e6, |_| true, false, 100), vec![(id, 2), (id, 0)]); } + /// A repeatable pseudo-random sequence in 0..1. + fn sequence(mut seed: u64) -> impl FnMut() -> f64 { + move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + } + } + + /// Features of every kind over a few degrees, some without a shape: polygons with a hole and + /// of several parts, lines of several parts, a line of one place and shapes without any. + fn shapes_of_every_kind(next: &mut impl FnMut() -> f64, n: usize) -> Dataset { + let mut d = Dataset::new("shapes", GeometryType::Polygon, vec![Field::new("n", FieldType::Integer)]); + for i in 0..n { + let at = Coord::new(next() * 4.0 - 52.0, next() * 4.0 - 22.0); + let mut path = |by: f64, n: usize| -> Vec { + (0..n).map(|_| Coord::new(at.x + (next() - 0.5) * by, at.y + (next() - 0.5) * by)).collect() + }; + let square = |r: f64| -> Vec { + [(-r, -r), (r, -r), (r, r), (-r, r), (-r, -r)].iter().map(|(x, y)| Coord::new(at.x + x, at.y + y)).collect() + }; + let g = match i % 9 { + 0 => Some(Geometry::Point(at)), + 1 => Some(Geometry::MultiPoint(path(0.5, 4))), + 2 => Some(Geometry::Line(vec![path(0.6, 5), path(0.6, 3)])), + 3 => Some(Geometry::Line(vec![vec![at]])), + 4 => Some(Geometry::Polygon(vec![vec![square(0.3), square(0.2)]])), + 5 => Some(Geometry::Polygon(vec![vec![path(0.4, 6)], vec![path(0.4, 4), path(0.1, 4)]])), + 6 => Some(Geometry::Polygon(vec![vec![square(0.1)]])), + 7 => Some(if i % 2 == 0 { Geometry::MultiPoint(vec![]) } else { Geometry::Polygon(vec![vec![vec![]]]) }), + _ => None, + }; + d.push(g, vec![Value::Int(i as i64)]); + } + d + } + + /// What a click and a box find is what a search of every drawn shape finds, whatever the + /// kind, at the very limit of the tolerance and beside it too. + fn assert_finds_what_every_shape_gives(m: &mut Map, next: &mut impl FnMut() -> f64) { + let scale = 1e6; + let id = m.layers[0].id; + let (flat, key) = (m.flat(), m.projection.code()); + let shapes = m.layers[0].projected_in(&flat, &key).to_vec(); + let drawn = m.layers[0].drawn_rows(scale); + let places: Vec = { + let mut v = Vec::new(); + shapes.iter().flatten().for_each(|g| g.for_each_coord(|c| v.push(c))); + v + }; + let (mut found, mut boxed) = (0, 0); + let mut check = |p: Coord, tol: f64| { + let every: Vec<(u32, usize)> = (0..shapes.len()) + .rev() + .filter(|r| drawn[*r] && shapes[*r].as_ref().is_some_and(|g| g.hit(p, tol))) + .map(|r| (id, r)) + .collect(); + found += every.len(); + assert_eq!(m.hits_at(p, tol, scale, |_| true, false, usize::MAX), every, "{p:?} within {tol}"); + }; + for tol in [0.0, 1e-9, 0.1, 777.7, 20_000.0] { + for c in places.iter().copied().filter(|c| c.is_finite()) { + check(c, tol); + // The limit on each side, and the numbers next to it. + for x in [c.x + tol, c.x - tol] { + for x in [x.next_down(), x, x.next_up()] { + check(Coord::new(x, c.y), tol); + } + } + for y in [c.y + tol, c.y - tol] { + for y in [y.next_down(), y, y.next_up()] { + check(Coord::new(c.x, y), tol); + } + } + } + for _ in 0..200 { + check(lonlat_to_merc(Coord::new(next() * 5.0 - 52.5, next() * 5.0 - 22.5)), tol); + } + } + for i in 0..400 { + let (a, b) = (places[(next() * places.len() as f64) as usize], places[(next() * places.len() as f64) as usize]); + let near = Coord::new(a.x + (next() - 0.5) * 2e4, a.y + (next() - 0.5) * 2e4); + // Corners on the shapes' own places (so boxes that only touch), and small boxes beside one. + let e = Extent::from_points(a, if i % 2 == 0 { b } else { near }); + let every: Vec = + (0..shapes.len()).filter(|r| drawn[*r] && shapes[*r].as_ref().is_some_and(|g| g.intersects_extent(&e))).collect(); + boxed += every.len(); + let expected = if every.is_empty() { vec![] } else { vec![(id, every)] }; + assert_eq!(m.hits_in(&e, scale), expected, "{e:?}"); + } + assert!(found > 1000 && boxed > 100, "the fixture hits too little: {found} and {boxed}"); + } + + #[test] + fn clicks_and_boxes_find_what_a_search_of_every_shape_finds() { + let mut next = sequence(0x9E37_79B9_7F4A_7C15); + for code in ["mercator", "EPSG:31983", "mollweide +lon_0=-90"] { + let mut m = Map::new("Map"); + let id = m.add_dataset(shapes_of_every_kind(&mut next, 54)); + m.projection = Projection::from_code(code).unwrap(); + assert_finds_what_every_shape_gives(&mut m, &mut next); + // Rows the definition query leaves out. + m.layers[0].definition_query = Some("n > 20".into()); + assert_finds_what_every_shape_gives(&mut m, &mut next); + m.layers[0].definition_query = None; + // Shapes moved, added and removed: their boxes are those of the new ones. + let l = m.layer_mut(id).unwrap(); + let far = Coord::new(-40.0, -10.0); + l.dataset.features.set_geometry(0, Some(Geometry::Point(far))); + l.dataset.features.set_geometry(4, None); + l.dataset.features.set_geometry(8, Some(Geometry::Line(vec![vec![far, Coord::new(-39.0, -10.0)]]))); + l.touch_geometry(); + let at = m.flat().forward(far).unwrap(); + assert_eq!(m.hits_at(at, 1.0, 1e6, |_| true, false, 10), vec![(id, 8), (id, 0)], "{code}"); + assert_finds_what_every_shape_gives(&mut m, &mut next); + } + } + + #[test] + fn a_row_without_a_kept_box_is_searched_in_full() { + let mut m = Map::new("Map"); + let mut d = Dataset::new("lines", GeometryType::Polyline, vec![]); + let (a, b) = (Coord::new(0.0, 0.0), Coord::new(10.0, 10.0)); + d.push(Some(Geometry::Line(vec![vec![a, Coord::new(0.0, 10.0)]])), vec![]); + d.push(Some(Geometry::Line(vec![vec![b, Coord::new(0.0, 10.0)]])), vec![]); + let id = m.add_dataset(d); + let (a, b) = (lonlat_to_merc(a), lonlat_to_merc(b)); + m.layers[0].projected(); + // Never left like this by drawing or reading; a shape isn't lost to it. + m.layers[0].projected_extents = Default::default(); + assert_eq!(m.hits_at(b, 1.0, 1e6, |_| true, false, 10), vec![(id, 1)]); + assert_eq!(m.hits_in(&Extent::from_points(a, b), 1e6), vec![(id, vec![0, 1])]); + } + + /// A ring with a place the projection can't show has a gap, through which its inside runs on + /// to the left of it ([`Geometry::hit`]): it is hit where its other places are, as drawn. + #[test] + fn a_shape_with_a_place_not_shown_is_hit_only_by_its_box() { + let mut m = Map::new("Map"); + let mut d = Dataset::new("p", GeometryType::Polygon, vec![]); + let ring = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (f64::NAN, f64::NAN), (0.0, 0.0)]; + d.push(Some(Geometry::Polygon(vec![vec![ring.iter().map(|(x, y)| Coord::new(*x, *y)).collect()]])), vec![]); + // And one with no place at all. + d.push(Some(Geometry::Point(Coord::new(f64::NAN, 5.0))), vec![]); + let id = m.add_dataset(d); + let at = |x: f64, y: f64| lonlat_to_merc(Coord::new(x, y)); + let outside = at(-50.0, 5.0); + assert!(m.layers[0].projected()[0].as_ref().unwrap().hit(outside, 1000.0), "the gap lets the inside out"); + assert_eq!(m.hits_at(outside, 1000.0, 1e6, |_| true, false, 10), vec![]); + assert_eq!(m.hits_at(at(5.0, 5.0), 1000.0, 1e6, |_| true, false, 10), vec![(id, 0)]); + assert_eq!(m.hits_at(at(10.0, 5.0), 1000.0, 1e6, |_| true, false, 10), vec![(id, 0)]); + } + #[test] fn select_hits_skip_hidden_features_and_follow_draw_order() { let mut m = Map::new("Map"); From 9a4cf59942526766d64232761399cb1004dfe78c Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 26 Nov 2026 16:49:54 -0300 Subject: [PATCH 2/3] Run the snapping check as a property test; say the rounding margin snap_boxes.rs now follows the property-test pattern of docs/contributing.md: proptest seeded from PROPERTY_SEED, PROPERTY_CASES cases, invalid values rejected, a failure reporting its seed and the smallest layers and places found. It joins the nightly property step. The doc of Map::hits_at says the box is widened by a rounding margin too. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/nightly.yml | 1 + crates/engine/tests/integration/snap_boxes.rs | 155 +++++++++++------- crates/map/src/lib.rs | 6 +- 3 files changed, 104 insertions(+), 58 deletions(-) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index fe3d129887..bd66f092e7 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -127,6 +127,7 @@ jobs: PROPERTY_CASES=200 cargo test --locked -p rustgis-analysis --test parallel_serial cargo test --locked -p rustgis-analysis --test overlay_identities cargo test --locked -p rustgis-engine --test integration project_save_roundtrip:: + cargo test --locked -p rustgis-engine --test integration snap_boxes:: PROPERTY_CASES=200000 cargo test --locked -p rustgis-data --test integration reprojection_round_trip:: PROPERTY_CASES=100000 cargo test --locked -p rustgis-geom --test geodesic_identities cargo test --locked -p rustgis-data --test integration extent_query_properties:: diff --git a/crates/engine/tests/integration/snap_boxes.rs b/crates/engine/tests/integration/snap_boxes.rs index 9c3d9985df..b43767f5b8 100644 --- a/crates/engine/tests/integration/snap_boxes.rs +++ b/crates/engine/tests/integration/snap_boxes.rs @@ -1,5 +1,13 @@ //! Snapping, which reads only the shapes whose kept box is near, finds what a search of every -//! shape finds. +//! shape finds, as a property: over two generated layers, with one feature left out, and after +//! shapes are moved, added and removed. +//! +//! Pull requests run a fixed seed; the nightly a new one with more cases. A failure gives its seed +//! and the smallest layers and places found. To run a seed again, or deeper: +//! `PROPERTY_SEED=7 PROPERTY_CASES=2000 cargo test -p rustgis-engine --test integration snap_boxes::`. +use proptest::prelude::*; +use proptest::sample::Index; +use proptest::test_runner::{Config, RngAlgorithm, TestCaseError, TestRng, TestRunner}; use rustgis_engine::{ Project, Session, cmd::design::snap_except, @@ -7,40 +15,53 @@ use rustgis_engine::{ geom::{Coord, merc_to_lonlat}, map::design::Snapping, }; +use std::cell::RefCell; +use std::collections::BTreeMap; const TOLERANCE: f64 = 10.0; -/// Metre-sized fixtures in the longitude/latitude coordinates of feature layers. -fn c(x: f64, y: f64) -> Coord { - merc_to_lonlat(Coord::new(x, y)) +/// A number from the environment, else `default`; one set that isn't a whole number fails, so a +/// typo doesn't run the defaults without a word (#2639). +fn env(name: &str, default: u64) -> u64 { + match std::env::var(name) { + Ok(v) => v.trim().parse().unwrap_or_else(|_| panic!("{name}={v:?} isn't a whole number")), + Err(std::env::VarError::NotPresent) => default, + Err(e) => panic!("{name}: {e}"), + } } -/// A repeatable pseudo-random sequence in 0..1. -fn sequence(mut seed: u64) -> impl FnMut() -> f64 { - move || { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - (seed >> 11) as f64 / (1u64 << 53) as f64 - } +/// Metre-sized fixtures in the longitude/latitude coordinates of feature layers, a few hundred +/// metres from a corner far from the map's origin. +fn c((x, y): (f64, f64)) -> Coord { + merc_to_lonlat(Coord::new(x - 5e6, y - 2e6)) +} + +/// A shape of any kind, or none, a few tens of metres across, somewhere in 400 m square. +fn shape() -> BoxedStrategy> { + let path = |at: (f64, f64), n: std::ops::Range| { + proptest::collection::vec((0.0..60.0f64, 0.0..60.0f64), n) + .prop_map(move |v| v.into_iter().map(|(dx, dy)| c((at.0 + dx, at.1 + dy))).collect::>()) + }; + let square = + |(x, y): (f64, f64), r: f64| vec![c((x - r, y - r)), c((x + r, y - r)), c((x + r, y + r)), c((x - r, y + r)), c((x - r, y - r))]; + (0.0..400.0f64, 0.0..400.0f64) + .prop_flat_map(move |at| { + prop_oneof![ + Just(Some(Geometry::Point(c(at)))), + path(at, 1..4).prop_map(|p| Some(Geometry::MultiPoint(p))), + // A part of one place too, whose end is its vertex. + (path(at, 2..5), path(at, 1..3)).prop_map(|(a, b)| Some(Geometry::Line(vec![a, b]))), + (1.0..40.0f64).prop_map(move |r| Some(Geometry::Polygon(vec![vec![square(at, r), square(at, r / 2.0)]]))), + (path(at, 3..6), path(at, 3..5)).prop_map(|(a, b)| Some(Geometry::Polygon(vec![vec![a], vec![b]]))), + Just(None), + ] + }) + .boxed() } -fn layer(next: &mut impl FnMut() -> f64, name: &str, n: usize) -> Dataset { +fn dataset(name: &str, shapes: Vec>) -> Dataset { let mut d = Dataset::new(name, GeometryType::Polygon, vec![]); - for i in 0..n { - let (x, y) = (next() * 400.0 - 5e6, next() * 400.0 - 2e6); - let mut path = |n: usize| -> Vec { (0..n).map(|_| c(x + next() * 60.0, y + next() * 60.0)).collect() }; - let square = |r: f64| vec![c(x - r, y - r), c(x + r, y - r), c(x + r, y + r), c(x - r, y + r), c(x - r, y - r)]; - let g = match i % 6 { - 0 => Some(Geometry::Point(c(x, y))), - 1 => Some(Geometry::MultiPoint(path(3))), - 2 => Some(Geometry::Line(vec![path(4), path(2)])), - 3 => Some(Geometry::Polygon(vec![vec![square(40.0), square(20.0)]])), - 4 => Some(Geometry::Polygon(vec![vec![path(4)], vec![path(3)]])), - _ => None, - }; - d.push(g, vec![]); - } + shapes.into_iter().for_each(|g| d.push(g, vec![])); d } @@ -83,43 +104,67 @@ fn nearest_of_every_shape(s: &mut Session, m: Coord, skip: Option<(u32, usize)>) point.or(edge).map(|(_, at, kind)| (at, kind)) } -fn check(s: &mut Session, next: &mut impl FnMut() -> f64, skip: Option<(u32, usize)>) { - let mut kinds = std::collections::BTreeMap::new(); - for _ in 0..600 { - let at = c(next() * 500.0 - 5e6 - 20.0, next() * 500.0 - 2e6 - 20.0); +/// Snapping at each place finds what the search of every shape finds; each kind found is counted. +fn check( + s: &mut Session, + places: &[(f64, f64)], + skip: Option<(u32, usize)>, + kinds: &RefCell, u32>>, +) -> Result<(), TestCaseError> { + for at in places.iter().map(|p| c(*p)) { let m = s.map().to_map(at).unwrap(); let expected = nearest_of_every_shape(s, m, skip); let got = snap_except(s, at, skip); - assert_eq!(got.map(|g| g.1), expected.map(|e| e.1), "{at:?}"); - *kinds.entry(got.map(|g| g.1)).or_insert(0) += 1; + prop_assert_eq!(got.map(|g| g.1), expected.map(|e| e.1), "at {:?}, leaving out {:?}", at, skip); + *kinds.borrow_mut().entry(got.map(|g| g.1)).or_insert(0) += 1; if let (Some((got, _)), Some((expected, _))) = (got, expected) { let got = s.map().to_map(got).unwrap(); - assert!((got.x - expected.x).abs() < 1e-6 && (got.y - expected.y).abs() < 1e-6, "{got:?} != {expected:?}"); + prop_assert!((got.x - expected.x).abs() < 1e-6 && (got.y - expected.y).abs() < 1e-6, "{:?} != {:?}", got, expected); } } - // Every kind, and nothing near too. - assert_eq!(kinds.len(), 4, "{kinds:?}"); + Ok(()) } #[test] fn snapping_finds_what_a_search_of_every_shape_finds() { - let mut next = sequence(0x9E37_79B9_7F4A_7C15); - let mut s = Session::new(Project::new("Snap boxes")); - s.map_mut().layers.clear(); - let id = s.map_mut().add_dataset(layer(&mut next, "A", 48)); - s.map_mut().add_dataset(layer(&mut next, "B", 48)); - s.map_mut().camera.res = 1.0; - s.map_mut().editing.snapping = Snapping { enabled: true, tolerance_px: TOLERANCE, vertex: true, edge: true, end: true }; - check(&mut s, &mut next, None); - // All but one shape. - check(&mut s, &mut next, Some((id, 3))); - // Shapes moved, added and removed: their boxes are those of the new ones. - let l = s.map_mut().layer_mut(id).unwrap(); - let far = c(-5e6 + 900.0, -2e6); - l.dataset.features.set_geometry(0, Some(Geometry::Point(far))); - l.dataset.features.set_geometry(3, None); - l.dataset.features.set_geometry(5, Some(Geometry::Line(vec![vec![c(-5e6, -2e6), c(-5e6 + 400.0, -2e6 + 400.0)]]))); - l.touch_geometry(); - assert_eq!(snap_except(&mut s, c(-5e6 + 905.0, -2e6), None), Some((far, "vertex"))); - check(&mut s, &mut next, None); + let seed = env("PROPERTY_SEED", 1); + let mut bytes = [0u8; 32]; + bytes[..8].copy_from_slice(&seed.to_le_bytes()); + let cases = env("PROPERTY_CASES", 256); + let cases = u32::try_from(cases).unwrap_or_else(|_| panic!("PROPERTY_CASES={cases} is past {}", u32::MAX)); + let config = Config { cases, failure_persistence: None, ..Config::default() }; + let mut runner = TestRunner::new_with_rng(config, TestRng::from_seed(RngAlgorithm::ChaCha, &bytes)); + let layer = || proptest::collection::vec(shape(), 1..40); + let places = proptest::collection::vec((-50.0..500.0f64, -50.0..500.0f64), 1..40); + let skip = proptest::option::of((any::(), any::())); + let edits = proptest::collection::vec((any::(), shape()), 0..4); + // What snapping found over every case: one that never finds a kind checks nothing of it. + let kinds = RefCell::new(BTreeMap::new()); + let result = runner.run(&(layer(), layer(), places, skip, edits), |(a, b, places, skip, edits)| { + let (na, nb) = (a.len(), b.len()); + let mut s = Session::new(Project::new("Snap boxes")); + s.map_mut().layers.clear(); + let ia = s.map_mut().add_dataset(dataset("A", a)); + let ib = s.map_mut().add_dataset(dataset("B", b)); + s.map_mut().camera.res = 1.0; + s.map_mut().editing.snapping = Snapping { enabled: true, tolerance_px: TOLERANCE, vertex: true, edge: true, end: true }; + check(&mut s, &places, None, &kinds)?; + let skip = skip.map(|(first, i)| if first { (ia, i.index(na)) } else { (ib, i.index(nb)) }); + check(&mut s, &places, skip, &kinds)?; + // Shapes moved, added and removed: their boxes are those of the new ones. + let l = s.map_mut().layer_mut(ia).unwrap(); + for (i, g) in edits { + l.dataset.features.set_geometry(i.index(na), g); + } + let far = c((900.0, 0.0)); + l.dataset.features.set_geometry(0, Some(Geometry::Point(far))); + l.touch_geometry(); + prop_assert_eq!(snap_except(&mut s, c((905.0, 0.0)), None), Some((far, "vertex"))); + check(&mut s, &places, None, &kinds) + }); + if let Err(e) = result { + panic!("PROPERTY_SEED={seed}: {e}"); + } + let kinds = kinds.into_inner(); + assert_eq!(kinds.len(), 4, "PROPERTY_SEED={seed}: snapping found only {kinds:?}"); } diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index db3b1a1252..b00eb752fe 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -3482,9 +3482,9 @@ impl Map { /// Every feature under a point in the visible layers `keep` accepts: top layer first and, in /// a layer, the one drawn on top first. At most `limit` of them; with `first_layer`, only /// those of the top layer with any. A shape whose kept box ([`Layer::projected_extents`]) is - /// farther than `tol` isn't read: so one with a place the projection can't show (its ring has - /// a gap, through which its inside would run on past it) is hit only in or near its box, as it - /// is drawn. + /// farther than `tol` (and a rounding margin, see `box_may_hit`) isn't read: so one with a + /// place the projection can't show (its ring has a gap, through which its inside would run on + /// past it) is hit only in or near its box, as it is drawn. pub fn hits_at( &mut self, p: Coord, From d24d368ca5f42e02f0889c52ed76e172b6029e90 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 26 Nov 2026 18:23:26 -0300 Subject: [PATCH 3/3] Check each snap kind on a fixed line in every case The kinds tally summed over cases could miss one with few cases (PROPERTY_CASES=1 failed on 40 of 50 seeds) and failed outside the runner. A line far from the generated shapes now gives an end, a vertex, an edge and nothing in every case, inside the runner. Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/integration/snap_boxes.rs | 47 ++++++++++++------- 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/crates/engine/tests/integration/snap_boxes.rs b/crates/engine/tests/integration/snap_boxes.rs index b43767f5b8..b5f32cff2f 100644 --- a/crates/engine/tests/integration/snap_boxes.rs +++ b/crates/engine/tests/integration/snap_boxes.rs @@ -15,8 +15,6 @@ use rustgis_engine::{ geom::{Coord, merc_to_lonlat}, map::design::Snapping, }; -use std::cell::RefCell; -use std::collections::BTreeMap; const TOLERANCE: f64 = 10.0; @@ -104,19 +102,13 @@ fn nearest_of_every_shape(s: &mut Session, m: Coord, skip: Option<(u32, usize)>) point.or(edge).map(|(_, at, kind)| (at, kind)) } -/// Snapping at each place finds what the search of every shape finds; each kind found is counted. -fn check( - s: &mut Session, - places: &[(f64, f64)], - skip: Option<(u32, usize)>, - kinds: &RefCell, u32>>, -) -> Result<(), TestCaseError> { +/// Snapping at each place finds what the search of every shape finds. +fn check(s: &mut Session, places: &[(f64, f64)], skip: Option<(u32, usize)>) -> Result<(), TestCaseError> { for at in places.iter().map(|p| c(*p)) { let m = s.map().to_map(at).unwrap(); let expected = nearest_of_every_shape(s, m, skip); let got = snap_except(s, at, skip); prop_assert_eq!(got.map(|g| g.1), expected.map(|e| e.1), "at {:?}, leaving out {:?}", at, skip); - *kinds.borrow_mut().entry(got.map(|g| g.1)).or_insert(0) += 1; if let (Some((got, _)), Some((expected, _))) = (got, expected) { let got = s.map().to_map(got).unwrap(); prop_assert!((got.x - expected.x).abs() < 1e-6 && (got.y - expected.y).abs() < 1e-6, "{:?} != {:?}", got, expected); @@ -125,6 +117,26 @@ fn check( Ok(()) } +/// A line far from the generated shapes, which every case snaps to by its end, its other vertex +/// and its edge, and beside which it finds nothing: each kind is checked in every case. +const FIXED: [(f64, f64); 3] = [(1000.0, 0.0), (1100.0, 0.0), (1100.0, 100.0)]; + +fn check_fixed(s: &mut Session) -> Result<(), TestCaseError> { + for (at, expected) in [ + ((1003.0, 2.0), Some(((1000.0, 0.0), "end"))), + ((1102.0, 3.0), Some(((1100.0, 0.0), "vertex"))), + ((1050.0, 4.0), Some(((1050.0, 0.0), "edge"))), + ((1050.0, 50.0), None), + ] { + let got = snap_except(s, c(at), None).map(|(g, kind)| (s.map().to_map(g).unwrap(), kind)); + prop_assert_eq!(got.map(|g| g.1), expected.map(|e| e.1), "at {:?}", at); + if let (Some((got, _)), Some(((x, y), _))) = (got, expected) { + prop_assert!((got.x - (x - 5e6)).abs() < 1e-6 && (got.y - (y - 2e6)).abs() < 1e-6, "{:?} at {:?}", got, at); + } + } + Ok(()) +} + #[test] fn snapping_finds_what_a_search_of_every_shape_finds() { let seed = env("PROPERTY_SEED", 1); @@ -138,19 +150,20 @@ fn snapping_finds_what_a_search_of_every_shape_finds() { let places = proptest::collection::vec((-50.0..500.0f64, -50.0..500.0f64), 1..40); let skip = proptest::option::of((any::(), any::())); let edits = proptest::collection::vec((any::(), shape()), 0..4); - // What snapping found over every case: one that never finds a kind checks nothing of it. - let kinds = RefCell::new(BTreeMap::new()); - let result = runner.run(&(layer(), layer(), places, skip, edits), |(a, b, places, skip, edits)| { + let result = runner.run(&(layer(), layer(), places, skip, edits), |(a, mut b, places, skip, edits)| { let (na, nb) = (a.len(), b.len()); + b.push(Some(Geometry::Line(vec![FIXED.iter().map(|p| c(*p)).collect()]))); let mut s = Session::new(Project::new("Snap boxes")); s.map_mut().layers.clear(); let ia = s.map_mut().add_dataset(dataset("A", a)); let ib = s.map_mut().add_dataset(dataset("B", b)); s.map_mut().camera.res = 1.0; s.map_mut().editing.snapping = Snapping { enabled: true, tolerance_px: TOLERANCE, vertex: true, edge: true, end: true }; - check(&mut s, &places, None, &kinds)?; + check_fixed(&mut s)?; + check(&mut s, &places, None)?; + // The fixed line is never the one left out. let skip = skip.map(|(first, i)| if first { (ia, i.index(na)) } else { (ib, i.index(nb)) }); - check(&mut s, &places, skip, &kinds)?; + check(&mut s, &places, skip)?; // Shapes moved, added and removed: their boxes are those of the new ones. let l = s.map_mut().layer_mut(ia).unwrap(); for (i, g) in edits { @@ -160,11 +173,9 @@ fn snapping_finds_what_a_search_of_every_shape_finds() { l.dataset.features.set_geometry(0, Some(Geometry::Point(far))); l.touch_geometry(); prop_assert_eq!(snap_except(&mut s, c((905.0, 0.0)), None), Some((far, "vertex"))); - check(&mut s, &places, None, &kinds) + check(&mut s, &places, None) }); if let Err(e) = result { panic!("PROPERTY_SEED={seed}: {e}"); } - let kinds = kinds.into_inner(); - assert_eq!(kinds.len(), 4, "PROPERTY_SEED={seed}: snapping found only {kinds:?}"); }