From 661f492c860f8fb93dd1f9a63da5a5baf038b3f0 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 09:38:12 +0100 Subject: [PATCH 1/4] Distances in metres are measured flat in a layer's own projected system: Buffer, Simplify, Points Along Lines, Near, and Select Layer By Location and Spatial Join with a distance (#2032 C2e-3) --- crates/analysis/src/convert.rs | 59 ++++++++- crates/analysis/src/geodesic.rs | 15 ++- crates/analysis/src/join.rs | 54 ++++++-- crates/analysis/src/lib.rs | 37 ++++-- crates/analysis/src/parallel.rs | 12 +- crates/analysis/src/tools.rs | 143 +++++++++++++++------ crates/data/src/raster/crs.rs | 70 ++++++++++- crates/engine/src/cmd/gp.rs | 2 +- crates/engine/src/tests/held_layers.rs | 164 ++++++++++++++++++++++++- docs/user-guide/analysis.md | 74 ++++++----- 10 files changed, 523 insertions(+), 107 deletions(-) diff --git a/crates/analysis/src/convert.rs b/crates/analysis/src/convert.rs index 8a120940ac..4eb3442fee 100644 --- a/crates/analysis/src/convert.rs +++ b/crates/analysis/src/convert.rs @@ -20,19 +20,53 @@ pub enum Plane { Own, } +/// The plane of a run and the length of its unit on the ground: what [`install`] puts in place. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct RunPlane { + pub plane: Plane, + /// Metres per unit of a projected system's own plane ([`Plane::Own`]): 1 for one in metres, + /// 0.3048 for one in feet. 1 in the analysis plane, whose metres are Web Mercator's. + pub unit_m: f64, + /// Which way a projected system's x and y point: the (east, north) of a step of one along + /// each ([`rustgis_data::raster::Crs::axis_directions`]); east, then north, otherwise. + pub axes: [(f64, f64); 2], +} + +/// East, then north: the axes of a plane whose x points east and y north. +pub const EAST_NORTH: [(f64, f64); 2] = [(1.0, 0.0), (0.0, 1.0)]; + thread_local! { - static PLANE: std::cell::Cell = const { std::cell::Cell::new(Plane::Analysis) }; + static PLANE: std::cell::Cell = + const { std::cell::Cell::new(RunPlane { plane: Plane::Analysis, unit_m: 1.0, axes: EAST_NORTH }) }; } -/// The plane of the run on this thread ([`install_plane`]): [`Plane::Analysis`] unless a run in a +/// The plane of the run on this thread ([`install`]): [`Plane::Analysis`] unless a run in a /// projected system installed [`Plane::Own`]. The threads of [`crate::parallel`] take it over from /// the thread that starts them. pub fn plane() -> Plane { + run_plane().plane +} + +/// The plane of the run on this thread with its unit ([`install`]). +pub fn run_plane() -> RunPlane { PLANE.with(std::cell::Cell::get) } +/// A distance on the ground in metres as a length in a projected system's own plane, for a run +/// there ([`Plane::Own`]): measured flat, as in a projected system tools measure (#2032 C2e-3). +/// `None` in a run in longitude/latitude, which measures on the ellipsoid. +pub fn own_length(metres: f64) -> Option { + own_unit_m().map(|u| metres / u) +} + +/// Metres per unit of a projected system's own plane, for a run there ([`Plane::Own`]). +pub fn own_unit_m() -> Option { + let r = run_plane(); + (r.plane == Plane::Own).then_some(r.unit_m) +} + /// Puts the plane back as it was when dropped. -pub struct PlaneInstalled(Plane); +pub struct PlaneInstalled(RunPlane); impl Drop for PlaneInstalled { fn drop(&mut self) { @@ -40,9 +74,16 @@ impl Drop for PlaneInstalled { } } -/// Makes `plane` the plane of the work on this thread until the guard is dropped. -pub fn install_plane(plane: Plane) -> PlaneInstalled { - PlaneInstalled(PLANE.with(|p| p.replace(plane))) +/// Makes `run` the plane of the work on this thread until the guard is dropped. +pub fn install(run: RunPlane) -> PlaneInstalled { + PlaneInstalled(PLANE.with(|p| p.replace(run))) +} + +/// A step `(dx, dy)` in a projected system's own plane as (east, north), by the order and +/// direction of its axes ([`RunPlane::axes`]): for a direction from grid north. +pub fn own_east_north(dx: f64, dy: f64) -> (f64, f64) { + let [(xe, xn), (ye, yn)] = run_plane().axes; + (dx * xe + dy * ye, dx * xn + dy * yn) } /// A place of a run's geometry in its plane ([`plane`]): in the analysis plane for @@ -154,6 +195,12 @@ pub fn from_point(p: &Point) -> Geometry { mod tests { use super::*; + /// Makes `plane` the plane of the work on this thread until the guard is dropped, its unit a + /// metre and its axes east and north, as a run installs its own ([`install`]). + fn install_plane(plane: Plane) -> PlaneInstalled { + install(RunPlane { plane, unit_m: 1.0, axes: EAST_NORTH }) + } + /// In a projected system's own plane a place is worked on as it is, and nothing reaches a /// pole however large its y; the analysis plane is put back after. #[test] diff --git a/crates/analysis/src/geodesic.rs b/crates/analysis/src/geodesic.rs index 84bf064c47..0ac8d71145 100644 --- a/crates/analysis/src/geodesic.rs +++ b/crates/analysis/src/geodesic.rs @@ -22,6 +22,10 @@ //! Between vertices, those edges cut at most 0.031% of the distance inside the circle in the //! projection plane. A short corner can have a step approaching 5.625° when the backend rounds //! its segment count down, cutting at most 0.125% inside, on top of the projection error. +//! +//! In a run in a projected system's own plane ([`crate::convert::Plane::Own`], #2032 C2e-3), a +//! feature is buffered there as it is, the distance measured flat in the system's unit +//! ([`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, @@ -431,12 +435,18 @@ fn point(c: Coord, metres: f64) -> MultiPolygon { if !c.is_finite() { return MultiPolygon::new(vec![]); } + if let Some(d) = crate::convert::own_length(metres) { + return Point::new(c.x, c.y).buffer_with_style(buffer_style(d)); + } let plane = Plane::new(c, c.x); plane.back(&Point::new(0.0, 0.0).buffer_with_style(buffer_style(metres)), metres) } /// A line's buffer: in one projection centred on it when it fits, else in stretches. fn lines(parts: &[Vec], metres: f64) -> MultiPolygon { + if let Some(d) = crate::convert::own_length(metres) { + return MultiLineString::new(parts.iter().map(|p| crate::convert::ring(p)).collect()).buffer_with_style(buffer_style(d)); + } let all: Vec = parts.iter().flatten().copied().collect(); let Some(centre) = spherical_centre(&all) else { return MultiPolygon::new(vec![]) }; if fits(&all, centre) { @@ -451,7 +461,6 @@ fn lines(parts: &[Vec], metres: f64) -> MultiPolygon { /// outline's buffer (in stretches) added or, inward, taken away. fn polygons(polys: &[Vec>], metres: f64) -> MultiPolygon { let all: Vec = polys.iter().flatten().flatten().copied().collect(); - let Some(centre) = spherical_centre(&all) else { return MultiPolygon::new(vec![]) }; let shape = |ring: &dyn Fn(&[Coord]) -> LineString| { MultiPolygon::new( polys @@ -464,6 +473,10 @@ fn polygons(polys: &[Vec>], metres: f64) -> MultiPolygon { .collect(), ) }; + if let Some(d) = crate::convert::own_length(metres) { + return shape(&|r| crate::convert::ring(r)).buffer_with_style(buffer_style(d)); + } + let Some(centre) = spherical_centre(&all) else { return MultiPolygon::new(vec![]) }; if fits(&all, centre) { let plane = Plane::new(centre, all.first().map_or(centre.x, |c| c.x)); return plane.back(&shape(&|r| plane.line(r)).buffer_with_style(buffer_style(metres)), metres); diff --git a/crates/analysis/src/join.rs b/crates/analysis/src/join.rs index 4aef7eb2d4..08dd92ac5a 100644 --- a/crates/analysis/src/join.rs +++ b/crates/analysis/src/join.rs @@ -5,7 +5,9 @@ //! //! Distances are on the WGS 84 ellipsoid, as buffers' are. The nearest points of two features are //! found in an azimuthal equidistant plane, centred first between the features and then between -//! the points found, and measured along the geodesic between them. +//! the points found, and measured along the geodesic between them. In a run in a projected +//! system's own plane ([`crate::convert::Plane::Own`], #2032 C2e-3), they are found there and +//! measured straight, in the system's unit times its length. use rustgis_data::{Coord, Dataset, FieldType, Geometry, Value}; use rustgis_geom::{Aeqd, Extent, WGS84_MIN_RADIUS_M, geodesic_interpolate, geodesic_length_m, geodesic_ring_area_m2, wgs84_distance_m}; @@ -15,7 +17,29 @@ use serde_json::Value as Json; /// and a longitude within 540° of the meridian (a shape across the antimeridian goes past 180°). /// Distances leave other coordinates out, as places they can't measure from. fn on_earth(c: &Coord) -> bool { - c.is_finite() && c.x.abs() <= 540.0 && c.y.abs() <= 90.0 + c.is_finite() && (crate::convert::plane() == crate::convert::Plane::Own || (c.x.abs() <= 540.0 && c.y.abs() <= 90.0)) +} + +/// The plane nearest points are found in: an azimuthal equidistant one, or a projected system's +/// own as it is. +enum Flat { + Aeqd(Aeqd), + Own, +} + +impl Flat { + fn forward(&self, c: Coord) -> Coord { + match self { + Flat::Aeqd(p) => p.forward(c), + Flat::Own => c, + } + } + fn inverse(&self, c: Coord) -> Coord { + match self { + Flat::Aeqd(p) => p.inverse(c), + Flat::Own => c, + } + } } /// The first coordinate of a geometry that is a place on the Earth. @@ -37,7 +61,10 @@ pub fn first_coord(g: &Geometry) -> Option { /// the features are. pub fn distance_m(a: &Geometry, b: &Geometry) -> Option { let (p, q) = nearest_points(a, b)?; - let d = wgs84_distance_m(p, q); + let d = match crate::convert::own_unit_m() { + Some(unit) => (p.x - q.x).hypot(p.y - q.y) * unit, + None => wgs84_distance_m(p, q), + }; d.is_finite().then_some(d) } @@ -46,13 +73,16 @@ pub fn distance_m(a: &Geometry, b: &Geometry) -> Option { pub fn nearest_points(a: &Geometry, b: &Geometry) -> Option<(Coord, Coord)> { // The features' first vertices are a pair of their points: the search starts from them. let (fa, fb) = (first_coord(a)?, first_coord(b)?); - let (p, q) = nearest_pair(a, b, &Aeqd::new(geodesic_interpolate(fa, fb, 0.5)), Some((fa, fb)))?; - Some(nearest_pair(a, b, &Aeqd::new(geodesic_interpolate(p, q, 0.5)), Some((p, q))).unwrap_or((p, q))) + if crate::convert::plane() == crate::convert::Plane::Own { + return nearest_pair(a, b, &Flat::Own, Some((fa, fb))); + } + let (p, q) = nearest_pair(a, b, &Flat::Aeqd(Aeqd::new(geodesic_interpolate(fa, fb, 0.5))), Some((fa, fb)))?; + Some(nearest_pair(a, b, &Flat::Aeqd(Aeqd::new(geodesic_interpolate(p, q, 0.5))), Some((p, q))).unwrap_or((p, q))) } /// The nearest points of two geometries (lon/lat) as found in `plane`: a point of `a`, one of `b`. /// `seed`, a pair already found, starts the search, so pairs no nearer than it are skipped. -fn nearest_pair(a: &Geometry, b: &Geometry, plane: &Aeqd, seed: Option<(Coord, Coord)>) -> Option<(Coord, Coord)> { +fn nearest_pair(a: &Geometry, b: &Geometry, plane: &Flat, seed: Option<(Coord, Coord)>) -> Option<(Coord, Coord)> { let boxed = |segs: Vec<(Coord, Coord)>| -> Vec<((Coord, Coord), [f64; 4])> { segs.into_iter().map(|(s, e)| ((s, e), [s.x.min(e.x), s.y.min(e.y), s.x.max(e.x), s.y.max(e.y)])).collect() }; @@ -94,7 +124,7 @@ fn nearest_pair(a: &Geometry, b: &Geometry, plane: &Aeqd, seed: Option<(Coord, C } /// A geometry's edges in the plane; a point is an edge of no length. -fn segments(g: &Geometry, plane: &Aeqd) -> Vec<(Coord, Coord)> { +fn segments(g: &Geometry, plane: &Flat) -> Vec<(Coord, Coord)> { let mut out = Vec::new(); let mut path = |pts: &[Coord], closed: bool| { // A coordinate left out ends a run: no edge joins the runs on either side of it, and a @@ -159,6 +189,11 @@ pub fn may_be_within(a: &Extent, b: &Extent, metres: f64) -> bool { if a.is_empty() || b.is_empty() { return false; } + // In a projected system's own plane, extents there: their gap measured straight. + if let Some(d) = crate::convert::own_length(metres) { + let gap = (b.min_x - a.max_x).max(a.min_x - b.max_x).max(0.0).hypot((b.min_y - a.max_y).max(a.min_y - b.max_y).max(0.0)); + return gap <= d.max(0.0) * (1.0 + 1e-9) + 1e-9; + } let (dlat, dlon) = spread(a.min_y.abs().max(a.max_y.abs()), metres); let lat_gap = (b.min_y - a.max_y).max(a.min_y - b.max_y).max(0.0); if lat_gap > dlat { @@ -174,6 +209,11 @@ pub fn search_box(ext: &Extent, metres: f64) -> Option { if ext.is_empty() || !metres.is_finite() { return None; } + // In a projected system's own plane, the extent there widened by the distance in its unit. + if let Some(d) = crate::convert::own_length(metres) { + let d = d.max(0.0) * (1.0 + 1e-9) + 1e-9; + return Some(Extent::new(ext.min_x - d, ext.min_y - d, ext.max_x + d, ext.max_y + d)); + } let (dlat, dlon) = spread(ext.min_y.abs().max(ext.max_y.abs()), metres); let dlon = dlon?; let (x0, x1) = (ext.min_x - dlon, ext.max_x + dlon); diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 7378d905b8..42036ef78f 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -239,9 +239,10 @@ pub struct ToolSpec { /// The built-in tools that work in their first input's own coordinate system when it is a /// projected one, rather than in longitude/latitude ([`ToolSpec::works_in_own_system`]): those /// whose results don't depend on the system's units or shape beyond what the input's own -/// coordinates give (attributes, vertices, envelopes, validity), and the overlays and spatial -/// relations, worked on in its plane rather than the analysis plane. Areas they report are -/// still measured on the ground. +/// coordinates give (attributes, vertices, envelopes, validity), the overlays and spatial +/// relations, worked on in its plane rather than the analysis plane, and the tools that measure +/// distances in metres, measured flat there in its unit ([`convert::own_length`]). Areas they +/// report are still measured on the ground. const OWN_SYSTEM_TOOLS: &[&str] = &[ "summaryStatistics", "pivotTable", @@ -271,6 +272,11 @@ const OWN_SYSTEM_TOOLS: &[&str] = &[ "countPoints", "selectByLocation", "spatialJoin", + // Distances in metres, measured flat in the system's unit (#2032 C2e-3). + "buffer", + "simplify", + "pointsAlongLines", + "near", ]; impl ToolSpec { @@ -279,16 +285,16 @@ impl ToolSpec { /// into it, and its outputs are held there. Every other tool, and every external one, works in /// longitude/latitude. /// - /// For some it depends on `params`: Select Layer By Location and Spatial Join measure no - /// distance only without a search distance, or with a match that measures none. - pub fn works_in_own_system(&self, params: &Value) -> bool { - OWN_SYSTEM_TOOLS.contains(&self.id) && TOOLS.iter().any(|t| std::ptr::eq(t, self)) && !tools::measures_distance(self.id, params) + /// Distances in metres are measured flat there, in the system's unit (#2032 C2e-3). + pub fn works_in_own_system(&self) -> bool { + OWN_SYSTEM_TOOLS.contains(&self.id) && TOOLS.iter().any(|t| std::ptr::eq(t, self)) } /// Whether the tool crosses its inputs' edges with each other's (overlays and spatial - /// relations), where how an edge runs between its vertices decides the result, not only where - /// they are: a run in its first input's own system then says when another input's edges, - /// converted into it, run far from where a run in longitude/latitude takes them. + /// relations) or measures to them (Near), where how an edge runs between its vertices decides + /// the result, not only where they are: a run in its first input's own system then says when + /// another input's edges, converted into it, run far from where a run in longitude/latitude + /// takes them. pub fn reads_edges(&self) -> bool { matches!( self.id, @@ -303,6 +309,7 @@ impl ToolSpec { | "countPoints" | "selectByLocation" | "spatialJoin" + | "near" ) } @@ -743,8 +750,14 @@ pub fn run(id: &str, inputs: &dyn Inputs, params: &Value) -> Result(inputs: &dyn Inputs, work: impl FnOnce() -> T) -> T { - let plane = if inputs.work_crs() == rustgis_data::raster::Crs::LonLat { convert::Plane::Analysis } else { convert::Plane::Own }; - let _plane = convert::install_plane(plane); + let crs = inputs.work_crs(); + let run = if crs == rustgis_data::raster::Crs::LonLat { + convert::RunPlane { plane: convert::Plane::Analysis, unit_m: 1.0, axes: convert::EAST_NORTH } + } else { + let (unit_m, axes) = crs.unit_and_axes(); + convert::RunPlane { plane: convert::Plane::Own, unit_m, axes } + }; + let _plane = convert::install(run); work() } diff --git a/crates/analysis/src/parallel.rs b/crates/analysis/src/parallel.rs index a13d224851..54caf53d15 100644 --- a/crates/analysis/src/parallel.rs +++ b/crates/analysis/src/parallel.rs @@ -106,7 +106,7 @@ pub(crate) fn for_each_row( return Ok(()); } let run = control::current(); - let plane = crate::convert::plane(); + let plane = crate::convert::run_plane(); let still = rustgis_data::source::remote::current_still(); let rows = std::sync::Mutex::new(rows.enumerate()); let failed = AtomicBool::new(false); @@ -114,7 +114,7 @@ pub(crate) fn for_each_row( rustgis_data::source::remote::with_optional_still(still.clone(), || { let _stop = StopOnPanic(&failed); let _run = control::install(run.clone()); - let _plane = crate::convert::install_plane(plane); + let _plane = crate::convert::install(plane); let mut s = scratch(); let mut taken = Vec::with_capacity(BATCH); while !failed.load(Ordering::Relaxed) && !control::cancelled() { @@ -211,7 +211,7 @@ fn try_map_by>( .collect(); } let run = control::current(); - let plane = crate::convert::plane(); + let plane = crate::convert::run_plane(); let still = rustgis_data::source::remote::current_still(); let next = AtomicUsize::new(0); let failed = AtomicBool::new(false); @@ -219,7 +219,7 @@ fn try_map_by>( rustgis_data::source::remote::with_optional_still(still.clone(), || { let _stop = StopOnPanic(&failed); let _run = control::install(run.clone()); - let _plane = crate::convert::install_plane(plane); + let _plane = crate::convert::install(plane); let mut s = scratch(); let mut made = Vec::new(); while !failed.load(Ordering::Relaxed) { @@ -508,8 +508,8 @@ mod tests { /// plane isn't worked on in the analysis plane on the threads it hands rows or items to. #[test] fn the_threads_work_in_the_runs_plane() { - use crate::convert::{Plane, install_plane, plane}; - let _own = install_plane(Plane::Own); + use crate::convert::{EAST_NORTH, Plane, RunPlane, install, plane}; + let _own = install(RunPlane { plane: Plane::Own, unit_m: 1.0, axes: EAST_NORTH }); let items: Vec = (0..5_000).collect(); let planes = try_map_on(&items, 4, || (), |_, _, _| Ok::<_, Cancelled>(plane())).unwrap(); assert!(planes.iter().all(|p| *p == Plane::Own)); diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 8d5a8f01b4..ddb74f9129 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -120,7 +120,14 @@ pub static TOOLS: &[ToolSpec] = &[ summary: "Creates polygons around input features at a given distance.", params: &[ P { name: "input", label: "Input Features", kind: K::Layer, required: true, default: "", help: "" }, - P { name: "distance", label: "Distance", kind: K::Number, required: true, default: "100", help: "" }, + P { + name: "distance", + label: "Distance", + kind: K::Number, + required: true, + default: "100", + help: "Measured on the ground, or flat for a layer in a projected system. Negative shrinks polygons.", + }, P { name: "units", label: "Units", kind: K::Choice(UNITS), required: false, default: "\"Kilometers\"", help: "" }, P { name: "dissolve", label: "Dissolve", kind: K::Choice(&["None", "All"]), required: false, default: "\"None\"", help: "" }, P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" }, @@ -478,7 +485,7 @@ pub static TOOLS: &[ToolSpec] = &[ kind: K::Number, required: true, default: "1", - help: "The distance between points, measured on the ground.", + help: "The distance between points, measured on the ground, or flat for a layer in a projected system.", }, P { name: "units", label: "Units", kind: K::Choice(UNITS), required: false, default: "\"Kilometers\"", help: "" }, P { @@ -922,7 +929,7 @@ pub static TOOLS: &[ToolSpec] = &[ kind: K::Number, required: false, default: "", - help: "Closest: how far to look (no limit when empty). Within a distance: required. Measured on the ground.", + help: "Closest: how far to look (no limit when empty). Within a distance: required. Measured on the ground, or flat for a target in a projected system.", }, P { name: "units", label: "Distance Units", kind: K::Choice(UNITS), required: false, default: "\"Kilometers\"", help: "" }, P { @@ -3645,6 +3652,10 @@ const SEAM: f64 = 1e-9; /// on opposite sides of the antimeridian; a part that touches it and turns back, or two that only /// meet there, stay apart, as parts meeting anywhere else do. fn meet_at_seam(part: &[Coord], next: &[Coord]) -> bool { + // No antimeridian in a projected system's own plane. + if crate::convert::plane() == crate::convert::Plane::Own { + return false; + } fn on_seam(c: &Coord) -> bool { 180.0 - rustgis_geom::fold_lon(c.x).abs() <= SEAM } @@ -3668,7 +3679,7 @@ fn meet_at_seam(part: &[Coord], next: &[Coord]) -> bool { fn for_each_line(g: &Geometry, mut f: impl FnMut(&[Vec], bool)) { let closed = |run: &[Vec]| { let mut v = run.iter().flatten().filter(|c| c.is_finite()); - matches!((v.next(), v.next_back()), (Some(a), Some(b)) if a == b || rustgis_geom::wgs84_inverse(*a, *b).0 < MIN_SEGMENT) + matches!((v.next(), v.next_back()), (Some(a), Some(b)) if a == b || inverse(*a, *b).0 < MIN_SEGMENT) }; match g { Geometry::Line(parts) => { @@ -3692,8 +3703,9 @@ fn for_each_line(g: &Geometry, mut f: impl FnMut(&[Vec], bool)) { } } -/// A segment of a part on the WGS 84 ellipsoid: its ends, its length in meters, and its azimuths -/// at either end (degrees clockwise from north). +/// A segment of a part on the WGS 84 ellipsoid, or straight in a projected system's own plane: its +/// ends, its length in meters, and its azimuths at either end (degrees clockwise from north, grid +/// north in a projected system). #[derive(Clone, Copy, Debug)] struct Segment { a: Coord, @@ -3718,7 +3730,7 @@ fn segments(line: &[Vec], ring: bool) -> impl Iterator + .chain(first.filter(|_| ring)) .scan(first, |kept, b| { let a = (*kept)?; - let (len, azi_a, azi_b) = rustgis_geom::wgs84_inverse(a, b); + let (len, azi_a, azi_b) = inverse(a, b); // False for NaN; a vertex passed over leaves the next segment starting at `a`. let long_enough = len >= MIN_SEGMENT; if long_enough { @@ -3741,6 +3753,16 @@ const ELLIPSOID_STRETCH: f64 = 1.005; /// (Leaving out a vertex only shortens a part.) Coordinates are folded and clamped as GeographicLib /// takes them, so the bound holds for any finite ones. fn length_bound(line: &[Vec], ring: bool) -> f64 { + if let Some(unit) = crate::convert::own_unit_m() { + let mut verts = line.iter().flatten().filter(|c| c.is_finite()); + let Some(first) = verts.next() else { return 0.0 }; + let (mut prev, mut sum) = (first, 0.0); + for c in verts.chain(ring.then_some(first)) { + sum += (c.x - prev.x).hypot(c.y - prev.y); + prev = c; + } + return sum * unit; + } let fold = |c: &Coord| Coord::new(rustgis_geom::fold_lon(c.x), c.y.clamp(-90.0, 90.0)); let mut verts = line.iter().flatten().filter(|c| c.is_finite()).map(fold); let Some(first) = verts.next() else { return 0.0 }; @@ -3752,6 +3774,34 @@ fn length_bound(line: &[Vec], ring: bool) -> f64 { sum * ELLIPSOID_STRETCH } +/// The length in meters from `a` to `b` and the azimuths at either end (degrees clockwise from +/// north): on the WGS 84 ellipsoid ([`rustgis_geom::wgs84_inverse`]), or straight in a projected +/// system's own plane, its length in its unit times the unit's ([`crate::convert::own_unit_m`]), +/// from grid north, whichever way the system's axes point (`+axis=wsu`). +fn inverse(a: Coord, b: Coord) -> (f64, f64, f64) { + match crate::convert::own_unit_m() { + Some(unit) => { + let (east, north) = crate::convert::own_east_north(b.x - a.x, b.y - a.y); + let azimuth = east.atan2(north).to_degrees(); + ((b.x - a.x).hypot(b.y - a.y) * unit, azimuth, azimuth) + } + None => rustgis_geom::wgs84_inverse(a, b), + } +} + +/// The place `along` meters from a segment's start toward its end, and the direction there: by a +/// direct solution on the ellipsoid ([`rustgis_geom::wgs84_direct`]), or straight along it in a +/// projected system's own plane. +fn direct(seg: &Segment, along: f64) -> (Coord, f64) { + match crate::convert::plane() { + crate::convert::Plane::Own => { + let t = if seg.len > 0.0 { along / seg.len } else { 0.0 }; + (Coord::new(seg.a.x + t * (seg.b.x - seg.a.x), seg.a.y + t * (seg.b.y - seg.a.y)), seg.azi_a) + } + crate::convert::Plane::Analysis => rustgis_geom::wgs84_direct(seg.a, seg.azi_a, along), + } +} + /// The direction halfway between two azimuths (degrees), or `b` when they are opposite. fn mean_azimuth(a: f64, b: f64) -> f64 { let ((sa, ca), (sb, cb)) = (a.to_radians().sin_cos(), b.to_radians().sin_cos()); @@ -3789,11 +3839,8 @@ fn walk_line(segs: &[Segment], ring: bool, spacing: Spacing, mut emit: impl FnMu // The points before this segment's end; one at its end is on the next one's start. while k < n && at(k) < walked + seg.len - tol { let along = at(k) - walked; - let (c, azimuth) = if along <= tol { - (seg.a, arriving.map_or(seg.azi_a, |inc| mean_azimuth(inc, seg.azi_a))) - } else { - rustgis_geom::wgs84_direct(seg.a, seg.azi_a, along) - }; + let (c, azimuth) = + if along <= tol { (seg.a, arriving.map_or(seg.azi_a, |inc| mean_azimuth(inc, seg.azi_a))) } else { direct(seg, along) }; let vertex = (along <= tol).then_some(i); if vertex.is_none() || vertex != on_vertex { if emit(c, at(k), bearing(azimuth)).is_break() { @@ -3828,6 +3875,9 @@ fn points_along_lines(inp: &dyn Inputs, p: &Json) -> Result return Err(format!("{TOOL} needs a line or polygon layer")); } let unit = to_metres(1.0, s(p, "units"))?; + // Measured straight in a projected system's own plane (#2032 C2e-3), with no antimeridian or + // poles there. + let own_plane = crate::convert::plane() == crate::convert::Plane::Own; // Finite in meters too: 1e308 miles is not a distance. let step = num(p, "distance") .map(|d| d * unit) @@ -3956,7 +4006,9 @@ fn points_along_lines(inp: &dyn Inputs, p: &Json) -> Result return; } missing = missing.saturating_add(line.iter().flatten().filter(|c| !c.is_finite()).count()); - past_pole = past_pole.saturating_add(line.iter().flatten().filter(|c| c.is_finite() && c.y.abs() > 90.0).count()); + if !own_plane { + past_pole = past_pole.saturating_add(line.iter().flatten().filter(|c| c.is_finite() && c.y.abs() > 90.0).count()); + } // Each segment solved once. A line has no more segments than vertices, so the list // stays within the room reserved for the longest. segs.clear(); @@ -3969,7 +4021,8 @@ fn points_along_lines(inp: &dyn Inputs, p: &Json) -> Result } // Folded into −180..180: a point past the antimeridian is on the far side of the map. // A vertex's latitude past a pole (bad data) is the pole, where the walk measured it. - let c = Coord::new(rustgis_geom::fold_lon(c.x), c.y.clamp(-90.0, 90.0)); + // (In a projected system's own plane, as it is.) + let c = if own_plane { c } else { Coord::new(rustgis_geom::fold_lon(c.x), c.y.clamp(-90.0, 90.0)) }; list.push(c, own, kept, [fid.clone(), Value::Float(along / unit), Value::Float(angle)]) }); }); @@ -4161,11 +4214,15 @@ fn simplify_coords_within(pts: &[geo::Coord], tol_m: f64, run: &SimplifyRun { return pts.to_vec(); } + // In a projected system's own plane, the tolerance is a length there, at one scale + // ([`crate::convert::own_length`]): every vertex's scale is 1 and its "latitude" 0. + let own = crate::convert::own_length(tol_m); // On the ellipsoid, not the sphere ([`SPHERE_TO_WGS84`]). - let tol_m = tol_m * SPHERE_TO_WGS84; + let tol_m = own.unwrap_or(tol_m * SPHERE_TO_WGS84); // Each vertex's latitude and scale (plane meters per ground meter, [`merc_scale`]), worked out // once. - let lat: Vec = pts.iter().map(|c| rustgis_geom::plane_to_lonlat(Coord::new(c.x, c.y)).y).collect(); + let lat: Vec = + if own.is_some() { vec![0.0; n] } else { pts.iter().map(|c| rustgis_geom::plane_to_lonlat(Coord::new(c.x, c.y)).y).collect() }; let scale: Vec = lat.iter().map(|&y| merc_scale(y)).collect(); let mut keep = vec![false; n]; if let Some(k) = keep.first_mut() { @@ -4290,20 +4347,23 @@ pub fn simplify_geometry(g: &Geometry, tol_m: f64) -> (Geometry, SimplifyNotes) // plane, is left exactly as it was (`simplify_checked`), and the feature is counted. Otherwise // a latitude past ±90° (bad data), infinite ones included, is taken as that pole by the plane, // and the vertices are counted; a line part of fewer than 2 vertices has no line to keep - // (`from_line`), and is counted. Points aren't simplified. + // (`from_line`), and is counted. Points aren't simplified. A projected system's own plane has + // no latitude, and no pole to take a vertex to. + let own = crate::convert::plane() == crate::convert::Plane::Own; if tol_m > 0.0 && !s.broken && !matches!(g, Geometry::Point(_) | Geometry::MultiPoint(_)) { let mut beyond = false; - g.for_each_coord(|c| beyond |= !c.y.is_nan() && c.y.abs() > rustgis_geom::MAX_LAT); + g.for_each_coord(|c| beyond |= !own && !c.y.is_nan() && c.y.abs() > rustgis_geom::MAX_LAT); notes.polar = usize::from(beyond); + let past_pole = |coords: &mut dyn Iterator| if own { 0 } else { past_pole(coords) }; // The vertices taken to a pole are those in what's kept: a line's parts of 2 vertices or // more, a polygon's rings. A line whose parts are all that short is kept as it was // (`from_line` has none to give), so only the short parts beside a longer one go. (notes.past_pole, notes.short) = match g { Geometry::Line(parts) if parts.iter().any(|p| p.len() >= 2) => { - (past_pole(parts.iter().filter(|p| p.len() >= 2).flatten()), parts.iter().filter(|p| p.len() < 2).count()) + (past_pole(&mut parts.iter().filter(|p| p.len() >= 2).flatten()), parts.iter().filter(|p| p.len() < 2).count()) } Geometry::Line(_) => (0, 0), - Geometry::Polygon(polygons) => (past_pole(polygons.iter().flatten().flatten()), 0), + Geometry::Polygon(polygons) => (past_pole(&mut polygons.iter().flatten().flatten()), 0), _ => (0, 0), }; // A geometry given back as it was (nothing to keep in the plane, or canceled) moved nothing @@ -4413,7 +4473,7 @@ fn simplify_checked(g: &Geometry, tol_m: f64) -> Simplified { // overflow; no place on Earth is within a hair of it. const PLANE_LIMIT: f64 = 1e150; g.for_each_coord(|c| { - let p = rustgis_geom::lonlat_to_plane(c); + let p = crate::convert::to_plane(c); broken |= p.x.is_nan() || p.y.is_nan() || p.x.abs() > PLANE_LIMIT || p.y.abs() > PLANE_LIMIT; }); if broken { @@ -6749,17 +6809,6 @@ fn extent_contains(a: &Extent, b: &Extent) -> bool { !a.is_empty() && !b.is_empty() && a.min_x <= b.min_x && a.max_x >= b.max_x && a.min_y <= b.min_y && a.max_y >= b.max_y } -/// Whether a run of tool `id` with `params` measures a distance on the ground: Select Layer By -/// Location with a search distance, Spatial Join with a match that measures one. Such a run works -/// in longitude/latitude, where its distances are geodesic ([`crate::ToolSpec::works_in_own_system`]). -pub(crate) fn measures_distance(id: &str, params: &Json) -> bool { - match id { - "selectByLocation" => num(params, "distance").is_some_and(|d| d > 0.0), - "spatialJoin" => matches!(JoinMatch::parse(s(params, "match")), JoinMatch::Closest | JoinMatch::WithinDistance), - _ => false, - } -} - /// Whether a tool's parameter applies, given the values of the others (`value` gives one's /// value as text, empty when unset, which stands for its default). The Tools pane hides and leaves /// out one that doesn't. Spatial Join's search distance, units and distance field apply only to the @@ -7042,7 +7091,13 @@ impl ExtentIndex { (kx.clamp(0.0, 512.0) as i64, ky.clamp(0.0, 512.0) as i64) } - /// The larger side of a cell in degrees, when there is a grid. + /// Whether `b` holds every feature's extent. + fn covered_by(&self, b: &Extent) -> bool { + extent_contains(b, &self.total) + } + + /// The larger side of a cell in degrees (the system's unit in a projected system's own plane), + /// when there is a grid. fn cell_size(&self) -> Option { self.grid.as_ref().map(|_| self.cell_w.max(self.cell_h)) } @@ -7215,15 +7270,21 @@ impl Nearby<'_, '_> { exclude: Option, ) -> Option<(usize, f64)> { let mut measured = std::collections::HashMap::new(); + // A cell is degrees in longitude/latitude, the system's unit in a projected system's own + // plane. let mut reach = match self.index.cell_size() { - Some(cell) => (cell.to_radians() * rustgis_geom::EARTH_RADIUS_M).max(MIN_REACH_M), + Some(cell) => match crate::convert::own_unit_m() { + Some(unit) => cell * unit, + None => cell.to_radians() * rustgis_geom::EARTH_RADIUS_M, + } + .max(MIN_REACH_M), None => f64::INFINITY, }; let mut near = loop { let r = limit.map_or(reach, |l| reach.min(l)); - // A search reaching a pole or across the antimeridian looks at every feature anyway: it - // measures them out to the limit. - if crate::join::search_box(t_ext, r).is_none() { + // A search reaching a pole or across the antimeridian looks at every feature anyway, as + // does one holding them all: it measures them out to the limit. + if crate::join::search_box(t_ext, r).is_none_or(|b| self.index.covered_by(&b)) { break self.within(t, t_ext, t_geo, limit.unwrap_or(f64::INFINITY), true, exclude, &mut measured); } let found = self.within(t, t_ext, t_geo, r, true, exclude, &mut measured); @@ -7374,8 +7435,12 @@ fn near_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result 0.0 { None } else { shared_point(g, &t_geo, j.geom, &j.geo) }; let at = shared.or_else(|| crate::join::nearest_points(g, j.geom).map(|(_, q)| q)); // The plane's longitudes run on past ±180°, and so can a shared point's: back within - // [−180°, 180°). - let at = at.map(|c| Coord::new((c.x + 180.0).rem_euclid(360.0) - 180.0, c.y)); + // [−180°, 180°). (In a projected system's own plane, the point as it is.) + let at = if crate::convert::plane() == crate::convert::Plane::Own { + at + } else { + at.map(|c| Coord::new((c.x + 180.0).rem_euclid(360.0) - 180.0, c.y)) + }; Some((near_ds.features.get(j.row)?.id, d, at)) }); Ok::<_, String>(hit) diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index 86759fa334..0479214c34 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -604,6 +604,29 @@ impl Crs { } } + /// Metres per unit of its coordinates: 1 for a system in metres, 0.3048 for one in feet, + /// 0.304800609601219 for one in US survey feet; 1 when its conversion gives none (longitude/ + /// latitude, whose degrees are no length, and Web Mercator) or can't be made (a layer held in + /// a system has made it: [`Dataset::hold_in`] converts through it). + /// + /// [`Dataset::hold_in`]: crate::Dataset::hold_in + pub fn metres_per_unit(self) -> f64 { + self.unit_and_axes().0 + } + + /// [`Crs::metres_per_unit`] and [`Crs::axis_directions`] together, from one conversion. + pub fn unit_and_axes(self) -> (f64, [(f64, f64); 2]) { + let t = self.transformer().ok(); + let unit = t.as_ref().and_then(|t| t.params().map(|p| p.to_meter)).filter(|m| m.is_finite() && *m > 0.0).unwrap_or(1.0); + (unit, t.map_or([(1.0, 0.0), (0.0, 1.0)], |t| t.axis_directions())) + } + + /// Which way its coordinates point ([`Transformer::axis_directions`]): east, then north, for + /// one whose conversion can't be made (as [`Crs::metres_per_unit`], not one a layer is held in). + pub fn axis_directions(self) -> [(f64, f64); 2] { + self.unit_and_axes().1 + } + /// Whether it is a projection of the whole world whose plane has the antimeridian as a seam /// across it and the poles as lines (cylindrical and pseudocylindrical maps: World Mercator, /// Plate Carrée, Robinson, Equal Earth, Mollweide and the like), by its PROJ method. A place @@ -1007,7 +1030,8 @@ fn build_sr(sr: &terrio_crs::SpatialRef) -> Result { let geographic = sr.is_geographic(); let lat_first = !geographic && axis.starts_with(['n', 's']); let west = axis.chars().take(2).any(|c| c == 'w'); - let t = Transformer::of(sr, geographic, (lat_first, west))?; + let south = !geographic && axis.chars().take(2).any(|c| c == 's'); + let t = Transformer::of(sr, geographic, (lat_first, west, south))?; let centre = t.params().map_or(Coord::new(0.0, 0.0), |p| Coord::new(p.lon_0 + p.prime_meridian, p.lat_0.clamp(-89.0, 89.0))); if !t.is_geographic() && t.from_lonlat_unchecked(centre).is_none() { return Err("it can't place its own centre".into()); @@ -1626,7 +1650,8 @@ fn build(def: &str) -> Result { let axis = def.split_whitespace().find_map(|t| t.strip_prefix("+axis=")).unwrap_or("enu"); let lat_first = axis.starts_with(['n', 's']); let west = axis.chars().take(2).any(|c| c == 'w'); - let t = Transformer::of(&sr, geographic_def(def), (lat_first, west))?; + let south = axis.chars().take(2).any(|c| c == 's'); + let t = Transformer::of(&sr, geographic_def(def), (lat_first, west, south))?; // A definition that can't place its own centre (a unit of 0 metres) is no system. let centre = t.params().map_or(Coord::new(0.0, 0.0), |p| Coord::new(p.lon_0 + p.prime_meridian, p.lat_0.clamp(-89.0, 89.0))); if !t.is_geographic() && t.from_lonlat_unchecked(centre).is_none() { @@ -1926,6 +1951,8 @@ struct Terrio { lat_first: bool, /// Its east-west coordinate points west (`+axis=wnu`, `wsu`): -1, else 1. lon_sign: f64, + /// Its north-south coordinate points south (`+axis=wsu`, `swu`): -1, else 1. + lat_sign: f64, /// The conversion's parameters (centre, offsets, unit, prime meridian), when it has some. params: Option, /// A world projection whose inverse may go on past its edges ([`WRAPPING`]). @@ -2337,7 +2364,7 @@ impl Transformer { /// The transformer between `sr` and WGS 84 longitude/latitude; `geographic` when its /// coordinates are degrees. A system on another body than the Earth goes to and from its own /// longitude/latitude instead, which is read as it is, on the Earth ([`Crs::is_planetary`]). - fn of(sr: &terrio_crs::SpatialRef, geographic: bool, (lat_first, west): (bool, bool)) -> Result { + fn of(sr: &terrio_crs::SpatialRef, geographic: bool, (lat_first, west, south): (bool, bool, bool)) -> Result { grids_set_up(); let wgs84 = terrio_crs::SpatialRef::from_epsg(4326).map_err(|e| e.to_string())?; let pair = |to: &terrio_crs::SpatialRef| -> Result<_, String> { @@ -2382,6 +2409,7 @@ impl Transformer { unit, lat_first, lon_sign: if west { -1.0 } else { 1.0 }, + lat_sign: if south { -1.0 } else { 1.0 }, params, wraps, eck4, @@ -2522,6 +2550,20 @@ impl Transformer { } } + /// Which way its coordinates point: for x, then y, the (east, north) of a step of one along it, + /// by the order and direction of its axes (`+axis=wsu`: x west, y south). East, then north, + /// for a system without its own. + pub fn axis_directions(&self) -> [(f64, f64); 2] { + match &self.kind { + Kind::Terrio(live) => { + let t = &live.first; + let (east, north) = ((t.lon_sign, 0.0), (0.0, t.lat_sign)); + if t.lat_first { [north, east] } else { [east, north] } + } + _ => [(1.0, 0.0), (0.0, 1.0)], + } + } + /// The conversion's parameters (method, centre, offsets, unit, prime meridian), for a system /// terrio-crs computes that has some. pub fn params(&self) -> Option<&terrio_crs::ProjParams> { @@ -2553,6 +2595,28 @@ impl Transformer { mod tests { use super::*; + /// The length of a system's unit, as PROJ 9.9.0 gives its axes' `LENGTHUNIT` + /// (`projinfo -o WKT2_2019 EPSG:2227`: "US survey foot",0.304800609601219; EPSG:3361: "foot", + /// 0.3048; EPSG:32632: "metre",1). + #[test] + fn a_systems_unit_has_its_length() { + assert!((Crs::Epsg(2227).metres_per_unit() - 0.304_800_609_601_219).abs() < 1e-15); + assert!((Crs::Epsg(3361).metres_per_unit() - 0.3048).abs() < 1e-15); + assert_eq!(Crs::Epsg(32632).metres_per_unit(), 1.0); + assert_eq!(Crs::parse("+proj=utm +zone=32 +datum=WGS84 +units=km").unwrap().metres_per_unit(), 1000.0); + assert_eq!(Crs::LonLat.metres_per_unit(), 1.0); + } + + /// Which way a system's x and y point, as PROJ 9.9.0 gives its axes (`projinfo -o PROJ + /// EPSG:22275`: `+axis=wsu`, x west and y south; EPSG:2065: `+axis=swu`, x south and y west). + #[test] + fn a_systems_axes_have_their_directions() { + assert_eq!(Crs::Epsg(32632).axis_directions(), [(1.0, 0.0), (0.0, 1.0)]); + assert_eq!(Crs::Epsg(22275).axis_directions(), [(-1.0, 0.0), (0.0, -1.0)]); + assert_eq!(Crs::Epsg(2065).axis_directions(), [(0.0, -1.0), (-1.0, 0.0)]); + assert_eq!(Crs::parse("+proj=utm +zone=32 +datum=WGS84 +axis=neu").unwrap().axis_directions(), [(0.0, 1.0), (1.0, 0.0)]); + } + /// World projections, whose planes have the antimeridian as a seam, are told apart from regional /// ones by their method. #[test] diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 6c2ac3c03a..4b9cc49a6a 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1541,7 +1541,7 @@ fn work_system( full: &std::collections::HashMap, ) -> Crs { use rustgis_analysis::ParamKind as K; - let Some(spec) = spec.filter(|t| t.works_in_own_system(params)) else { return Crs::LonLat }; + let Some(spec) = spec.filter(|t| t.works_in_own_system()) else { return Crs::LonLat }; // The tool's first layer parameter, under its name or one of the names it also accepts // (Join Field's `input`), taken as the tool takes it: the first that isn't blank. A table // given by its number (read unconverted, [`Inputs::table`]) or by name leaves the run in diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index d6b8c35552..1fdbcf8d9a 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -217,7 +217,8 @@ fn a_held_layer_is_exported_alike() { assert_close(&read[0], &read[1], "data.convert"); } -/// Geometry calculations and a buffer give the same measures and places. +/// Geometry calculations give the same measures, and a buffer the same places to within UTM's +/// scale there. #[test] fn a_held_layer_is_analysed_alike() { let mut ss = both(); @@ -237,8 +238,22 @@ fn a_held_layer_is_analysed_alike() { assert!((p - q).abs() <= 1e-6 * p.abs().max(1.0), "{layer}: {a:?} vs {b:?}"); } } + // A buffer of 100 km: on the ground in longitude/latitude, flat in UTM (#2032 C2e-3). UTM's + // scale runs from 0.99969 at the buffer's west side (10.14°E) to 1.00059 at its east side + // (12.86°E, `proj -S`), so the flat 100 km reach 100,017 m to 99,972 m on the ground. run_both(&mut ss, "gp.run", &json!({"tool": "buffer", "params": {"input": "Wells", "distance": 100}})); - assert_close(&lonlat(&ss[0], "Wells_Buffer"), &lonlat(&ss[1], "Wells_Buffer"), "buffer"); + let well = lonlat(&ss[0], "Wells")[0].clone(); + let Some(Geometry::Point(well)) = well else { panic!("{well:?}") }; + let held_well = held_coords(&ss[1], "Wells")[0][0]; + for c in &held_coords(&ss[1], "Wells_Buffer")[0] { + assert!(((c.x - held_well.x).hypot(c.y - held_well.y) - 100_000.0).abs() < 1e-6, "flat: {c:?}"); + } + for (session, (low, high)) in [(&ss[0], (99_999.99, 100_000.01)), (&ss[1], (99_970.0, 100_020.0))] { + let Some(Geometry::Polygon(rings)) = &lonlat(session, "Wells_Buffer")[0] else { panic!("no buffer") }; + let d: Vec = rings[0][0].iter().map(|c| rustgis_geom::wgs84_distance_m(well, *c)).collect(); + let (min, max) = (d.iter().copied().fold(f64::INFINITY, f64::min), d.iter().copied().fold(0.0, f64::max)); + assert!(min >= low && max <= high, "{min}..{max} m on the ground"); + } } /// A geometry set, a move in metres and an undo leave the same places, and a held layer keeps @@ -1852,3 +1867,148 @@ fn a_numbered_table_is_converted_into_the_held_system() { assert_eq!((0..ds.features.len()).map(|r| ds.value(r, 0).to_string()).collect::>(), vec!["11.51,48.71"]); } } + +/// A place given by its UTM zone 32N coordinates, in longitude/latitude. +fn utm_place(x: f64, y: f64) -> Coord { + UTM.to(Crs::LonLat).unwrap().point(Coord::new(x, y)).unwrap() +} + +/// Adds a layer of `geoms` (in longitude/latitude) to `s`, held in `crs`, its features named +/// `0`, `1`… in their order. +fn add_held(s: &mut Session, name: &str, kind: GeometryType, geoms: Vec, crs: Crs) { + let mut d = Dataset::new(name, kind, vec![Field::new("name", FieldType::Text)]); + for (i, g) in geoms.into_iter().enumerate() { + d.push(Some(g), vec![Cell::Text(format!("{name}{i}"))]); + } + d.hold_in(crs).unwrap(); + s.map_mut().add_dataset(d); +} + +/// A layer's numbers in field `field`, in row order (empty values as NaN). +fn field_numbers(s: &Session, layer: &str, field: &str) -> Vec { + let ds = &s.map().layer_by_name(layer).unwrap_or_else(|| panic!("no layer {layer}")).dataset; + let f = ds.field_index(field).unwrap_or_else(|| panic!("{layer}: no field {field}")); + (0..ds.features.len()).map(|r| ds.value(r, f).as_f64().unwrap_or(f64::NAN)).collect() +} + +/// In a run in UTM, distances in metres are measured flat there, as in a projected system tools +/// measure them: a buffer is a circle of that radius in UTM, Select Layer By Location and Spatial +/// Join take what lies within it there, Near measures to the nearest point there and gives it in +/// UTM, Points Along Lines steps along the line there from grid north, and Simplify's tolerance is +/// a length there. At the origin (12.86°E, 48.70°N, 3.86° east of the central meridian), UTM's +/// scale is 1.00059 (`proj -S +proj=utm +zone=32 +datum=WGS84`), a UTM metre 0.99941 m on the +/// ground: a point 1000.3 UTM metres away is 999.71 m away on the ground, within a kilometre for a +/// run in longitude/latitude and not for one in UTM. The places and lengths checked are UTM's own. +#[test] +fn distances_are_measured_flat_in_the_held_system() { + let (x0, y0) = (784_000.0, 5_401_300.0); + let pt = |x: f64, y: f64| Geometry::Point(utm_place(x, y)); + let mut s = session(UTM); + add_held(&mut s, "Origin", GeometryType::Point, vec![pt(x0, y0)], UTM); + add_held(&mut s, "Around", GeometryType::Point, vec![pt(x0 + 999.7, y0), pt(x0 + 1000.3, y0), pt(x0, y0 + 500.0)], UTM); + let held = held_coords(&s, "Origin")[0][0]; + assert!((held.x - x0).abs() < 1e-6 && (held.y - y0).abs() < 1e-6, "{held:?}"); + + // A buffer of a kilometre: a circle of 1000 UTM metres. + s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "Origin", "distance": 1, "units": "Kilometers", "output": "Disc"}})) + .unwrap(); + assert_eq!(s.map().layer_by_name("Disc").unwrap().dataset.coord_crs(), UTM); + let disc = &held_coords(&s, "Disc")[0]; + assert!(disc.len() > 100, "{}", disc.len()); + for c in disc { + assert!(((c.x - x0).hypot(c.y - y0) - 1000.0).abs() < 1e-6, "{c:?}"); + } + + // Select Layer By Location within a kilometre: the points 999.7 m and 500 m away, not the one + // 1000.3 m away (999.71 m on the ground, which a run in longitude/latitude selects). + s.run( + "gp.run", + &json!({"tool": "selectByLocation", "params": {"input": "Around", "select": "Origin", "distance": 1000, "units": "Meters"}}), + ) + .unwrap(); + assert_eq!(selected(&s, "Around"), vec![0, 2]); + + // Near: the point 500 m north, at 0.5 km, where it is in UTM. + s.run("gp.run", &json!({"tool": "near", "params": {"input": "Origin", "near": "Around", "output": "Nearest"}})).unwrap(); + assert_eq!(s.map().layer_by_name("Nearest").unwrap().dataset.coord_crs(), UTM); + assert!((field_numbers(&s, "Nearest", "near_dist")[0] - 0.5).abs() < 1e-9); + assert!((field_numbers(&s, "Nearest", "near_x")[0] - x0).abs() < 1e-6); + assert!((field_numbers(&s, "Nearest", "near_y")[0] - (y0 + 500.0)).abs() < 1e-6); + + // Spatial Join: the closest, and those within a kilometre, nearest first. + let p = json!({"tool": "spatialJoin", "params": {"target": "Origin", "join": "Around", "match": "Closest", "units": "Meters", "distanceField": "dist", "output": "Closest"}}); + s.run("gp.run", &p).unwrap(); + assert!((field_numbers(&s, "Closest", "dist")[0] - 500.0).abs() < 1e-6); + let p = json!({"tool": "spatialJoin", "params": {"target": "Origin", "join": "Around", "match": "Within a distance", "distance": 1000, "units": "Meters", "distanceField": "dist", "operation": "Join one to many", "output": "Within"}}); + s.run("gp.run", &p).unwrap(); + let within = field_numbers(&s, "Within", "dist"); + assert_eq!(within.len(), 2, "{within:?}"); + assert!((within[0] - 500.0).abs() < 1e-6 && (within[1] - 999.7).abs() < 1e-6, "{within:?}"); + + // Points Along Lines: every kilometre along a 3 km line due east in UTM, heading 90° from grid + // north. + add_held(&mut s, "East", GeometryType::Polyline, vec![Geometry::Line(vec![vec![utm_place(x0, y0), utm_place(x0 + 3000.0, y0)]])], UTM); + s.run( + "gp.run", + &json!({"tool": "pointsAlongLines", "params": {"input": "East", "distance": 1, "units": "Kilometers", "output": "Steps"}}), + ) + .unwrap(); + assert_eq!(s.map().layer_by_name("Steps").unwrap().dataset.coord_crs(), UTM); + let steps = held_coords(&s, "Steps"); + assert_eq!(steps.len(), 4, "{steps:?}"); + for (k, c) in steps.iter().map(|p| p[0]).enumerate() { + assert!((c.x - (x0 + 1000.0 * k as f64)).abs() < 1e-6 && (c.y - y0).abs() < 1e-6, "{k}: {c:?}"); + } + let along = field_numbers(&s, "Steps", "distance"); + assert!(along.iter().zip([0.0, 1.0, 2.0, 3.0]).all(|(d, want)| (d - want).abs() < 1e-9), "{along:?}"); + assert!(field_numbers(&s, "Steps", "angle").iter().all(|a| (a - 90.0).abs() < 1e-9)); + + // Simplify: a bend of 0.4 UTM metres goes at a tolerance of half a metre, and stays at 0.3 m. + let bend = vec![utm_place(x0, y0), utm_place(x0 + 500.0, y0 + 0.4), utm_place(x0 + 1000.0, y0)]; + add_held(&mut s, "Bend", GeometryType::Polyline, vec![Geometry::Line(vec![bend])], UTM); + for (km, left, out) in [(0.0005, 2, "Plain"), (0.0003, 3, "Bent")] { + s.run("gp.run", &json!({"tool": "simplify", "params": {"input": "Bend", "tolerance": km, "output": out}})).unwrap(); + assert_eq!(s.map().layer_by_name(out).unwrap().dataset.coord_crs(), UTM); + assert_eq!(held_coords(&s, out)[0].len(), left, "{km} km"); + } +} + +/// In a system in US survey feet, a distance in metres is that many metres' worth of its feet: +/// a buffer of 1000 m in NAD83 / California zone 3 (ftUS, EPSG:2227) is a circle of +/// 1000 / 0.304800609601219 = 3280.833 ft. +#[test] +fn a_distance_is_in_the_systems_own_unit() { + const FEET: Crs = Crs::Epsg(2227); + let mut s = Session::new(Project::default()); + let place = FEET.to(Crs::LonLat).unwrap().point(Coord::new(6_000_000.0, 2_100_000.0)).unwrap(); + add_held(&mut s, "Spot", GeometryType::Point, vec![Geometry::Point(place)], FEET); + s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "Spot", "distance": 1000, "units": "Meters", "output": "Disc"}})) + .unwrap(); + let centre = held_coords(&s, "Spot")[0][0]; + let radius = 1000.0 / 0.304_800_609_601_219; + for c in &held_coords(&s, "Disc")[0] { + assert!(((c.x - centre.x).hypot(c.y - centre.y) - radius).abs() < 1e-6, "{c:?}"); + } +} + +/// Points Along Lines' angle is from grid north whichever way a system's axes point: due east is +/// 90° in Hartebeesthoek94 / Lo27 (EPSG:22275, `+axis=wsu`), whose x grows westward and y +/// southward. +#[test] +fn a_direction_is_from_grid_north_whatever_the_axes() { + const LO27: Crs = Crs::Epsg(22275); + let mut s = Session::new(Project::default()); + let back = LO27.to(Crs::LonLat).unwrap(); + // 1 km due east in the grid: x (westing) down by 1000. + let (a, b) = (back.point(Coord::new(10_000.0, 3_000_000.0)).unwrap(), back.point(Coord::new(9_000.0, 3_000_000.0)).unwrap()); + add_held(&mut s, "East", GeometryType::Polyline, vec![Geometry::Line(vec![vec![a, b]])], LO27); + s.run( + "gp.run", + &json!({"tool": "pointsAlongLines", "params": {"input": "East", "distance": 500, "units": "Meters", "output": "Steps"}}), + ) + .unwrap(); + assert_eq!(s.map().layer_by_name("Steps").unwrap().dataset.coord_crs(), LO27); + let angles = field_numbers(&s, "Steps", "angle"); + assert_eq!(angles.len(), 3, "{angles:?}"); + assert!(angles.iter().all(|a| (a - 90.0).abs() < 1e-9), "{angles:?}"); +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index fa78003363..2a2723eb24 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -181,23 +181,30 @@ Statistics, Pivot Table, Join Field, Select Layer By Attribute, Export Features, Line, Split Line At Vertices, Feature Envelope To Polygon, Unsplit Line, Feature Vertices To Points, Check Geometry and Repair Geometry; the overlays Clip, Erase, Intersect, Identity, Union, Symmetrical Difference, Update, Split and Dissolve; Minimum Bounding Geometry (convex hull), -Feature To Point and Summarize Within; and Select Layer By Location and Spatial Join when they -measure no distance (no search distance, a match other than Closest or Within a distance). Their -other inputs are converted into that system for the run, and their new layers are kept in it, so -the coordinates of what they copy stay exactly as they were. An overlay there takes each edge as -straight in that system, not in Web Mercator as it does in longitude/latitude, so where an edge -crosses another can differ from the same tool's result in longitude/latitude, by up to about L² tan -φ / 8R for an edge L long at latitude φ: some 20 cm for a 3 km edge at 48°N, 2 m for a 10 km one, -220 m for a 100 km one. An input in another system is converted vertex by vertex, as the map draws -it in that system, and its long edges can run much farther from where they run in -longitude/latitude: a degree-wide box's east-west edges, which follow their parallels there, are -chords in UTM up to 120 m away. The tool then says how many edges of which layer run more than a -metre away, and how far the farthest does. A world projection (World Mercator, Plate Carrée, -Robinson, Equal Earth and the like), whose plane has the antimeridian as a seam and the poles as -lines, is worked on in longitude/latitude, as Web Mercator is. If another input has a place that -system can't hold, the tool works in longitude/latitude instead, and its message says so. A layer -in longitude/latitude, Web Mercator or another geographic system is worked on in -longitude/latitude, as before. +Feature To Point and Summarize Within; Select Layer By Location and Spatial Join; and Buffer, +Simplify, Points Along Lines and Near. Their other inputs are converted into that system for the +run, and their new layers are kept in it, so the coordinates of what they copy stay exactly as they +were. An overlay there takes each edge as straight in that system, not in Web Mercator as it does in +longitude/latitude, so where an edge crosses another can differ from the same tool's result in +longitude/latitude, by up to about L² tan φ / 8R for an edge L long at latitude φ: some 20 cm for a +3 km edge at 48°N, 2 m for a 10 km one, 220 m for a 100 km one. An input in another system is +converted vertex by vertex, as the map draws it in that system, and its long edges can run much +farther from where they run in longitude/latitude: a degree-wide box's east-west edges, which follow +their parallels there, are chords in UTM up to 120 m away. The tool then says how many edges of +which layer run more than a metre away, and how far the farthest does. A world projection (World +Mercator, Plate Carrée, Robinson, Equal Earth and the like), whose plane has the antimeridian as a +seam and the poles as lines, is worked on in longitude/latitude, as Web Mercator is. If another +input has a place that system can't hold, the tool works in longitude/latitude instead, and its +message says so. A layer in longitude/latitude, Web Mercator or another geographic system is worked +on in longitude/latitude, as before. In a projected system a tool works in, distances in metres (Buffer's, +Simplify's tolerance, Points Along Lines' spacing, Near's, and the search distances of Select Layer +By Location and Spatial Join) are measured flat there, in its unit, as distances in a projected +system are: a kilometre is 1000 of its metres, or 3280.833 of its US survey feet. A flat metre is +not quite a metre on the ground: in a UTM zone, from 1.0004 m on its central meridian to about 0.999 +m at its edges on the equator (0.9998 m at 48.7°N), so a buffer of 100 km around a point 2.5° east +of the central meridian at 48.7°N reaches 100,017 m on the ground on its west side and 99,972 m on +its east side. Near's nearest point is that system's x and y, and Points Along Lines' angle is from +grid north. Area, length and perimeter fields stay on the ellipsoid. In the desktop app a tool runs in the background, so the map and the rest of the window stay in use. While it runs, the Tools pane shows its name, a **Cancel** button and, for the tools that @@ -494,10 +501,11 @@ simplified more than asked: no vertex moves farther on the ground (on the WGS 84 the tolerance. Near a long stretch reaching toward the equator it can be simplified a little less than asked. The scale stops at 85°'s, so beyond 85.05°, where the ground is far narrower, less is simplified away than asked (a 3 km tolerance at 89.9°N takes out only what lies within about 60 m -east–west), and the tool says how many features reach that far. A feature without geometry is -left out, and the tool says how many. A tolerance of 0 leaves every line and polygon as it is. -Otherwise a line or polygon with a coordinate missing, or a longitude too far out to place, is -left as it was; a latitude past ±90° is taken as the pole; a line part of fewer than 2 vertices +east–west), and the tool says how many features reach that far. For a layer in a projected system +(see above), the tolerance is a length in that system, the same everywhere. A feature without +geometry is left out, and the tool says how many. A tolerance of 0 leaves every line and polygon as +it is. Otherwise a line or polygon with a coordinate missing, or a longitude too far out to place, +is left as it was; a latitude past ±90° is taken as the pole; a line part of fewer than 2 vertices beside a longer one is left out; and, in a run that can't be canceled, a feature too intricate to simplify whole within the work allowed keeps more vertices than asked in part of it (a run you can cancel takes no limit, looking at Cancel within each feature). The tool says how many of each. @@ -542,7 +550,9 @@ uses it as a file destination. **Buffer** distances, and the distance of **Select Layer By Location**, are measured on the Earth (the WGS 84 ellipsoid, as PROJ and GeographicLib measure it), not in the map's display -projection. Each feature is buffered in an azimuthal equidistant projection on the ellipsoid +projection, except for a layer in a projected system, which is buffered flat in it (see above); a +buffer of hundreds of kilometres there can reach past the area the system is made for, where the map +may not place it. Each feature is buffered in an azimuthal equidistant projection on the ellipsoid centred on it, so distances from a point are true; long lines and large polygon outlines are buffered in stretches of a few hundred kilometres to limit projection error. Up to 85° of latitude, a buffer's sides are within 0.012 % of the distance (or 1 cm), and within 0.05 % along @@ -646,8 +656,9 @@ gp.run={"tool":"featureVerticesToPoints","params":{"input":"Rivers","output":"ri **Points Along Lines** (`pointsAlongLines`) writes points at a set `distance` along each part of the `input` layer's lines, or each ring of its polygons (holes too), measured on the WGS 84 -ellipsoid as Buffer's distances are, in `units` (Kilometers by default): a point at `startOffset` -(0 by default), then one every `distance`, stopping `endOffset` before the part's end. +ellipsoid as Buffer's distances are (flat, for a layer in a projected system, see above), in `units` +(Kilometers by default): a point at `startOffset` (0 by default), then one every `distance`, +stopping `endOffset` before the part's end. `includeEnd` adds a point where they stop when the distance doesn't land there (the first is always at the start offset). Each part and ring is walked on its own from its first vertex, so the gap between two parts never counts; a line's parts that cross the antimeridian, one ending on it @@ -823,8 +834,9 @@ 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`, Kilometers by default) and the point on it nearest the input feature (`near_x` and `near_y`, in -longitude from −180° up to 180° and latitude). Distances are measured as Spatial Join's **Closest** -measures them: on the ground, between the features' nearest points, and zero for features that +longitude from −180° up to 180° and latitude; for an input in a projected system, its x and y, +measured flat there, see above). Distances are measured as Spatial Join's **Closest** measures them: +on the ground, between the features' nearest points, and zero for features that intersect, whose point is one they share. The point is found as the distance is, in a plane centred between the features, so on a long edge it can sit off the geodesic by up to about 0.01 % of the distance (5 m at 50 km). A `distance` limits how far it looks; features with nothing that near, or @@ -838,7 +850,8 @@ gp.run={"tool":"near","params":{"input":"addresses","near":"hydrants","units":"F **Spatial Join** (`spatialJoin`, also `gp.spatialJoin`) copies attributes from `join` features to `target` features. Layers may have different source coordinate systems: their geometry is -converted to longitude/latitude for the join. `match` is one of: +converted for the join into the target's system when that is a projected one (see above), else +to longitude/latitude. `match` is one of: - **Intersects** (default), **Contains** (target contains join) or **Within** (target lies within join). @@ -852,9 +865,10 @@ converted to longitude/latitude for the join. `match` is one of: one, every target gets its nearest feature. Ties keep the join layer's order. - **Within a distance**: every join feature within `distance` (required), nearest first. -Distances are on the ground (the WGS 84 ellipsoid, as for Buffer), between the features' nearest -points (edges and vertices alike), and are zero for features that intersect. `distanceField` -names a field added for the distance to the joined feature, in `units`; it applies to +Distances are on the ground (the WGS 84 ellipsoid, as for Buffer; flat, for a target layer in a +projected system, see above), between the features' nearest points (edges and vertices alike), and +are zero for features that intersect. `distanceField` names a field added for the distance to the +joined feature, in `units`; it applies to **Closest** and **Within a distance** only, as `distance` does, and the Tools pane shows them only for those. From 4a4732b0671541b30eb94df6626f7ea6023df954 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 11:06:56 +0100 Subject: [PATCH 2/4] Review: a system whose conversion can't be made stays in lon/lat; Points Along Lines' length bound covers the walk's rounding; threads carry the run's unit and axes (tested); help and doc wording --- crates/analysis/src/convert.rs | 2 ++ crates/analysis/src/parallel.rs | 19 +++++++++----- crates/analysis/src/tools.rs | 44 +++++++++++++++++++++++++++------ crates/engine/src/cmd/gp.rs | 5 ++-- docs/user-guide/analysis.md | 15 +++++------ 5 files changed, 63 insertions(+), 22 deletions(-) diff --git a/crates/analysis/src/convert.rs b/crates/analysis/src/convert.rs index 4eb3442fee..308432c606 100644 --- a/crates/analysis/src/convert.rs +++ b/crates/analysis/src/convert.rs @@ -124,6 +124,8 @@ pub(crate) fn reaches_poles(south: f64, north: f64) -> (bool, bool) { (north >= 90.0 - rustgis_geom::POLE_TOLERANCE, south <= -90.0 + rustgis_geom::POLE_TOLERANCE) } +/// A run of coordinates as a `LineString` in the run's plane: a ring's (closed when its coordinates +/// close it) or a line's, which it doesn't close. pub fn ring(r: &[Coord]) -> LineString { LineString::new(r.iter().map(|c| gc(*c)).collect()) } diff --git a/crates/analysis/src/parallel.rs b/crates/analysis/src/parallel.rs index 54caf53d15..6a5ebbbef5 100644 --- a/crates/analysis/src/parallel.rs +++ b/crates/analysis/src/parallel.rs @@ -508,15 +508,22 @@ mod tests { /// plane isn't worked on in the analysis plane on the threads it hands rows or items to. #[test] fn the_threads_work_in_the_runs_plane() { - use crate::convert::{EAST_NORTH, Plane, RunPlane, install, plane}; - let _own = install(RunPlane { plane: Plane::Own, unit_m: 1.0, axes: EAST_NORTH }); + use crate::convert::{Plane, RunPlane, install, run_plane}; + // A plane in US survey feet with x west and y south (`+axis=wsu`): its unit and axes go to + // the threads with it, into their scratch set-up too (#2032 C2e-3). + let run = RunPlane { plane: Plane::Own, unit_m: 0.304_800_609_601_219, axes: [(-1.0, 0.0), (0.0, -1.0)] }; + let _own = install(run); let items: Vec = (0..5_000).collect(); - let planes = try_map_on(&items, 4, || (), |_, _, _| Ok::<_, Cancelled>(plane())).unwrap(); - assert!(planes.iter().all(|p| *p == Plane::Own)); + let set_up = std::sync::Mutex::new(Vec::new()); + let planes = try_map_on(&items, 4, || set_up.lock().unwrap().push(run_plane()), |_, _, _| Ok::<_, Cancelled>(run_plane())).unwrap(); + assert!(planes.iter().all(|p| *p == run)); let seen = std::sync::Mutex::new(Vec::new()); let mut rows = vec![0u8; 5_000]; - for_each_row(rows.chunks_mut(1), 4, || (), |_, _, _| seen.lock().unwrap().push(plane())).unwrap(); - assert!(seen.lock().unwrap().iter().all(|p| *p == Plane::Own)); + for_each_row(rows.chunks_mut(1), 4, || set_up.lock().unwrap().push(run_plane()), |_, _, _| seen.lock().unwrap().push(run_plane())) + .unwrap(); + assert!(seen.lock().unwrap().iter().all(|p| *p == run)); + let set_up = set_up.into_inner().unwrap(); + assert!(!set_up.is_empty() && set_up.iter().all(|p| *p == run), "{set_up:?}"); } #[test] diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index ddb74f9129..e9e73fe2cd 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -558,7 +558,14 @@ pub static TOOLS: &[ToolSpec] = &[ summary: "Removes vertices that deviate less than a tolerance (Douglas–Peucker).", params: &[ P { name: "input", label: "Input Features", kind: K::Layer, required: true, default: "", help: "" }, - P { name: "tolerance", label: "Tolerance (km)", kind: K::Number, required: true, default: "25", help: "" }, + P { + name: "tolerance", + label: "Tolerance (km)", + kind: K::Number, + required: true, + default: "25", + help: "How far a vertex may move, on the ground, or flat for a layer in a projected system.", + }, P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" }, ], run: simplify, @@ -646,7 +653,14 @@ pub static TOOLS: &[ToolSpec] = &[ params: &[ P { name: "input", label: "Input Features", kind: K::Layer, required: true, default: "", help: "" }, P { name: "select", label: "Selecting Features", kind: K::Layer, required: true, default: "", help: "" }, - P { name: "distance", label: "Search Distance", kind: K::Number, required: false, default: "0", help: "" }, + P { + name: "distance", + label: "Search Distance", + kind: K::Number, + required: false, + default: "0", + help: "Measured on the ground, or flat for a layer in a projected system.", + }, P { name: "units", label: "Units", kind: K::Choice(UNITS), required: false, default: "\"Kilometers\"", help: "" }, P { name: "invert", label: "Invert", kind: K::Choice(&["No", "Yes"]), required: false, default: "\"No\"", help: "" }, ], @@ -3756,12 +3770,14 @@ fn length_bound(line: &[Vec], ring: bool) -> f64 { if let Some(unit) = crate::convert::own_unit_m() { let mut verts = line.iter().flatten().filter(|c| c.is_finite()); let Some(first) = verts.next() else { return 0.0 }; + // Each edge's metres, as `segments` makes them and the walk adds them up, and a hair more + // for the rounding of the sums (a vertex `segments` passes over only shortens the line). let (mut prev, mut sum) = (first, 0.0); for c in verts.chain(ring.then_some(first)) { - sum += (c.x - prev.x).hypot(c.y - prev.y); + sum += (c.x - prev.x).hypot(c.y - prev.y) * unit; prev = c; } - return sum * unit; + return sum * (1.0 + 1e-9); } let fold = |c: &Coord| Coord::new(rustgis_geom::fold_lon(c.x), c.y.clamp(-90.0, 90.0)); let mut verts = line.iter().flatten().filter(|c| c.is_finite()).map(fold); @@ -4354,16 +4370,16 @@ pub fn simplify_geometry(g: &Geometry, tol_m: f64) -> (Geometry, SimplifyNotes) let mut beyond = false; g.for_each_coord(|c| beyond |= !own && !c.y.is_nan() && c.y.abs() > rustgis_geom::MAX_LAT); notes.polar = usize::from(beyond); - let past_pole = |coords: &mut dyn Iterator| if own { 0 } else { past_pole(coords) }; + let count_past_pole = |coords: &mut dyn Iterator| if own { 0 } else { past_pole(coords) }; // The vertices taken to a pole are those in what's kept: a line's parts of 2 vertices or // more, a polygon's rings. A line whose parts are all that short is kept as it was // (`from_line` has none to give), so only the short parts beside a longer one go. (notes.past_pole, notes.short) = match g { Geometry::Line(parts) if parts.iter().any(|p| p.len() >= 2) => { - (past_pole(&mut parts.iter().filter(|p| p.len() >= 2).flatten()), parts.iter().filter(|p| p.len() < 2).count()) + (count_past_pole(&mut parts.iter().filter(|p| p.len() >= 2).flatten()), parts.iter().filter(|p| p.len() < 2).count()) } Geometry::Line(_) => (0, 0), - Geometry::Polygon(polygons) => (past_pole(&mut polygons.iter().flatten().flatten()), 0), + Geometry::Polygon(polygons) => (count_past_pole(&mut polygons.iter().flatten().flatten()), 0), _ => (0, 0), }; // A geometry given back as it was (nothing to keep in the plane, or canceled) moved nothing @@ -10112,6 +10128,20 @@ mod tests { assert_eq!(p["attributes"], serde_json::json!(true)); } + /// In a projected system's own plane, the bound covers the walk's sum of each segment's metres: + /// ten one-foot segments walk 3.0480000000000005 m, where 10 ft × 0.3048 is 3.048, and a start + /// offset between the two would find no room for the point the walk makes there. + #[test] + fn length_bound_covers_the_walk_in_a_projected_plane() { + use crate::convert::{EAST_NORTH, Plane, RunPlane, install}; + let _feet = install(RunPlane { plane: Plane::Own, unit_m: 0.3048, axes: EAST_NORTH }); + let line = [(0..=10).map(|k| Coord::new(f64::from(k), 0.0)).collect::>()]; + let walked: f64 = segments(&line, false).map(|s| s.len).sum(); + assert!(walked > 10.0 * 0.3048, "{walked}"); + let bound = length_bound(&line, false); + assert!(bound >= walked && bound <= walked * (1.0 + 1e-8), "{walked} {bound}"); + } + #[test] fn length_bound_is_never_short_of_the_ellipsoid() { let c = Coord::new; diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 4b9cc49a6a..b6e3cc92b2 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1525,11 +1525,12 @@ fn streamed_inputs( /// works in `crs`: a projected system, whose coordinates are a plane's. Longitude/latitude, Web /// Mercator and the other world projections (whose plane has the antimeridian as a seam and the /// poles as lines, [`Crs::is_world_projection`]), and other geographic or geocentric systems, keep -/// the longitude/latitude path, whose plane and geodesics their coordinates need. +/// the longitude/latitude path, whose plane and geodesics their coordinates need. So does a system +/// whose conversion can't be made, whose unit and axes ([`Crs::unit_and_axes`]) aren't known. /// /// [`ToolSpec::works_in_own_system`]: rustgis_analysis::ToolSpec::works_in_own_system fn works_in(crs: Crs) -> bool { - crs != Crs::LonLat && !crs.is_world_projection() && !crs.is_geographic() && !crs.is_geocentric() + crs != Crs::LonLat && !crs.is_world_projection() && !crs.is_geographic() && !crs.is_geocentric() && crs.transformer().is_ok() } /// The system a run works in: its first input's own ([`Dataset::coord_crs`]) when the tool works diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 2a2723eb24..f45004a7f9 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -836,13 +836,14 @@ as the attribute table shows it (`near_fid`), the distance to it (`near_dist`, i Kilometers by default) and the point on it nearest the input feature (`near_x` and `near_y`, in longitude from −180° up to 180° and latitude; for an input in a projected system, its x and y, measured flat there, see above). Distances are measured as Spatial Join's **Closest** measures them: -on the ground, between the features' nearest points, and zero for features that -intersect, whose point is one they share. The point is found as the distance is, in a plane centred -between the features, so on a long edge it can sit off the geodesic by up to about 0.01 % of the -distance (5 m at 50 km). A `distance` limits how far it looks; features with nothing that near, or -without geometry, get empty values. Of equally near features, the first in the near layer wins. -With the same layer as both, each feature's nearest is another feature, not itself. A field name -the input already has gets a suffix (`near_dist_2`). Selections in both layers are honoured: +on the ground (flat, for an input in a projected system), between the features' nearest points, and +zero for features that intersect, whose point is one they share. The point is found as the distance +is, in a plane centred between the features, so on a long edge it can sit off the geodesic by up to +about 0.01 % of the distance (5 m at 50 km). A `distance` limits how far it looks; features with +nothing that near, or without geometry, get empty values. Of equally near features, the first in the +near layer wins. With the same layer as both, each feature's nearest is another feature, not itself. +A field name the input already has gets a suffix (`near_dist_2`). Selections in both layers are +honoured: ```text gp.run={"tool":"near","params":{"input":"addresses","near":"hydrants","units":"Feet"}} From efefaa336662dece5c5e285b6c9fabe5c383d8e5 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 11:15:33 +0100 Subject: [PATCH 3/4] Review: a system whose conversion gives no parameters stays in lon/lat; docs rewrapped --- crates/engine/src/cmd/gp.rs | 9 +++++++-- docs/user-guide/analysis.md | 23 +++++++++++------------ 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index b6e3cc92b2..f56a1f5f0a 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1526,11 +1526,16 @@ fn streamed_inputs( /// Mercator and the other world projections (whose plane has the antimeridian as a seam and the /// poles as lines, [`Crs::is_world_projection`]), and other geographic or geocentric systems, keep /// the longitude/latitude path, whose plane and geodesics their coordinates need. So does a system -/// whose conversion can't be made, whose unit and axes ([`Crs::unit_and_axes`]) aren't known. +/// whose conversion can't be made or gives no parameters, whose unit and axes +/// ([`Crs::unit_and_axes`]) aren't known. /// /// [`ToolSpec::works_in_own_system`]: rustgis_analysis::ToolSpec::works_in_own_system fn works_in(crs: Crs) -> bool { - crs != Crs::LonLat && !crs.is_world_projection() && !crs.is_geographic() && !crs.is_geocentric() && crs.transformer().is_ok() + crs != Crs::LonLat + && !crs.is_world_projection() + && !crs.is_geographic() + && !crs.is_geocentric() + && crs.transformer().is_ok_and(|t| t.params().is_some()) } /// The system a run works in: its first input's own ([`Dataset::coord_crs`]) when the tool works diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index f45004a7f9..cb1f1f5ddc 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -196,15 +196,15 @@ Mercator, Plate Carrée, Robinson, Equal Earth and the like), whose plane has th seam and the poles as lines, is worked on in longitude/latitude, as Web Mercator is. If another input has a place that system can't hold, the tool works in longitude/latitude instead, and its message says so. A layer in longitude/latitude, Web Mercator or another geographic system is worked -on in longitude/latitude, as before. In a projected system a tool works in, distances in metres (Buffer's, -Simplify's tolerance, Points Along Lines' spacing, Near's, and the search distances of Select Layer -By Location and Spatial Join) are measured flat there, in its unit, as distances in a projected -system are: a kilometre is 1000 of its metres, or 3280.833 of its US survey feet. A flat metre is -not quite a metre on the ground: in a UTM zone, from 1.0004 m on its central meridian to about 0.999 -m at its edges on the equator (0.9998 m at 48.7°N), so a buffer of 100 km around a point 2.5° east -of the central meridian at 48.7°N reaches 100,017 m on the ground on its west side and 99,972 m on -its east side. Near's nearest point is that system's x and y, and Points Along Lines' angle is from -grid north. Area, length and perimeter fields stay on the ellipsoid. +on in longitude/latitude, as before. In a projected system a tool works in, distances in metres +(Buffer's, Simplify's tolerance, Points Along Lines' spacing, Near's, and the search distances of +Select Layer By Location and Spatial Join) are measured flat there, in its unit, as distances in a +projected system are: a kilometre is 1000 of its metres, or 3280.833 of its US survey feet. A flat +metre is not quite a metre on the ground: in a UTM zone, from 1.0004 m on its central meridian to +about 0.999 m at its edges on the equator (0.9998 m at 48.7°N), so a buffer of 100 km around a point +2.5° east of the central meridian at 48.7°N reaches 100,017 m on the ground on its west side and +99,972 m on its east side. Near's nearest point is that system's x and y, and Points Along Lines' +angle is from grid north. Area, length and perimeter fields stay on the ellipsoid. In the desktop app a tool runs in the background, so the map and the rest of the window stay in use. While it runs, the Tools pane shows its name, a **Cancel** button and, for the tools that @@ -869,9 +869,8 @@ to longitude/latitude. `match` is one of: Distances are on the ground (the WGS 84 ellipsoid, as for Buffer; flat, for a target layer in a projected system, see above), between the features' nearest points (edges and vertices alike), and are zero for features that intersect. `distanceField` names a field added for the distance to the -joined feature, in `units`; it applies to -**Closest** and **Within a distance** only, as `distance` does, and the Tools pane shows them -only for those. +joined feature, in `units`; it applies to **Closest** and **Within a distance** only, as `distance` +does, and the Tools pane shows them only for those. **Join one to one** (the default `operation`) copies the first matching feature's attributes; **Join one to many** makes a row for each match. Both add `join_count`, the total matches for From 2ac72c5307cf80954c3d4f402c9294d5069f8a14 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 11:24:13 +0100 Subject: [PATCH 4/4] Review: join and length-bound docs name the own plane; distance tools take junk in a held system (tested); test lines wrapped --- crates/analysis/src/join.rs | 13 ++++----- crates/analysis/src/tools.rs | 3 ++- crates/engine/src/tests/held_layers.rs | 37 ++++++++++++++++++++++++-- 3 files changed, 44 insertions(+), 9 deletions(-) diff --git a/crates/analysis/src/join.rs b/crates/analysis/src/join.rs index 08dd92ac5a..655ecff801 100644 --- a/crates/analysis/src/join.rs +++ b/crates/analysis/src/join.rs @@ -3,11 +3,11 @@ //! the overlap a feature has with a polygon, and the rules that roll the values of several matches //! up into one. //! -//! Distances are on the WGS 84 ellipsoid, as buffers' are. The nearest points of two features are -//! found in an azimuthal equidistant plane, centred first between the features and then between -//! the points found, and measured along the geodesic between them. In a run in a projected -//! system's own plane ([`crate::convert::Plane::Own`], #2032 C2e-3), they are found there and -//! measured straight, in the system's unit times its length. +//! In a run in longitude/latitude, distances are on the WGS 84 ellipsoid, as buffers' are. The +//! nearest points of two features are found in an azimuthal equidistant plane, centred first +//! between the features and then between the points found, and measured along the geodesic between +//! them. In a run in a projected system's own plane ([`crate::convert::Plane::Own`], #2032 C2e-3), +//! they are found there and measured straight, in the system's unit times its length. use rustgis_data::{Coord, Dataset, FieldType, Geometry, Value}; use rustgis_geom::{Aeqd, Extent, WGS84_MIN_RADIUS_M, geodesic_interpolate, geodesic_length_m, geodesic_ring_area_m2, wgs84_distance_m}; @@ -53,7 +53,8 @@ pub fn first_coord(g: &Geometry) -> Option { first } -/// The ground distance (metres) between two features that don't intersect: between their nearest +/// The distance (metres) between two features that don't intersect, on the ground (flat in a +/// projected system's own plane, see the module's docs): between their nearest /// points, edges and vertices alike. `None` for a geometry without a finite coordinate. /// /// The nearest pair is found in a plane centred between the features' first vertices, then again diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index e9e73fe2cd..39ee5962b3 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -3765,7 +3765,8 @@ const ELLIPSOID_STRETCH: f64 = 1.005; /// sphere, stretched by [`ELLIPSOID_STRETCH`]. A few operations a segment, against an iterative /// solution for the exact length, it sizes the point list before each segment is solved, once. /// (Leaving out a vertex only shortens a part.) Coordinates are folded and clamped as GeographicLib -/// takes them, so the bound holds for any finite ones. +/// takes them, so the bound holds for any finite ones. In a projected system's own plane, the bound +/// is the edges' flat metres, as the walk adds them up, and a hair more. fn length_bound(line: &[Vec], ring: bool) -> f64 { if let Some(unit) = crate::convert::own_unit_m() { let mut verts = line.iter().flatten().filter(|c| c.is_finite()); diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 1fdbcf8d9a..81486cbf37 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1936,10 +1936,15 @@ fn distances_are_measured_flat_in_the_held_system() { assert!((field_numbers(&s, "Nearest", "near_y")[0] - (y0 + 500.0)).abs() < 1e-6); // Spatial Join: the closest, and those within a kilometre, nearest first. - let p = json!({"tool": "spatialJoin", "params": {"target": "Origin", "join": "Around", "match": "Closest", "units": "Meters", "distanceField": "dist", "output": "Closest"}}); + let p = json!({"tool": "spatialJoin", "params": { + "target": "Origin", "join": "Around", "match": "Closest", "units": "Meters", "distanceField": "dist", "output": "Closest" + }}); s.run("gp.run", &p).unwrap(); assert!((field_numbers(&s, "Closest", "dist")[0] - 500.0).abs() < 1e-6); - let p = json!({"tool": "spatialJoin", "params": {"target": "Origin", "join": "Around", "match": "Within a distance", "distance": 1000, "units": "Meters", "distanceField": "dist", "operation": "Join one to many", "output": "Within"}}); + let p = json!({"tool": "spatialJoin", "params": { + "target": "Origin", "join": "Around", "match": "Within a distance", "distance": 1000, "units": "Meters", + "distanceField": "dist", "operation": "Join one to many", "output": "Within" + }}); s.run("gp.run", &p).unwrap(); let within = field_numbers(&s, "Within", "dist"); assert_eq!(within.len(), 2, "{within:?}"); @@ -2012,3 +2017,31 @@ fn a_direction_is_from_grid_north_whatever_the_axes() { assert_eq!(angles.len(), 3, "{angles:?}"); assert!(angles.iter().all(|a| (a - 90.0).abs() < 1e-9), "{angles:?}"); } + +/// The tools that measure flat in a held layer's own system take junk distances and places without +/// a panic: they refuse, or make what they can. +#[test] +fn distance_tools_take_junk_in_the_held_system() { + let mut s = session(UTM); + let far = UTM.to(Crs::LonLat).unwrap().point(Coord::new(500_000.0, 5_400_000.0)).unwrap(); + add_held(&mut s, "Junk", GeometryType::Polyline, vec![Geometry::Line(vec![vec![far, far, Coord::new(f64::NAN, 1.0)]])], UTM); + for d in [json!(0), json!(-1), json!(1e308), json!(-1e308), json!("x"), json!(null), json!(5e-324)] { + for (tool, params) in [ + ("buffer", json!({"input": "Junk", "distance": d})), + ("buffer", json!({"input": "Parcels", "distance": d, "dissolve": "All"})), + ("simplify", json!({"input": "Roads", "tolerance": d})), + ("pointsAlongLines", json!({"input": "Junk", "distance": d})), + ("pointsAlongLines", json!({"input": "Roads", "distance": d, "startOffset": d, "endOffset": d, "includeEnd": "Yes"})), + ("near", json!({"input": "Wells", "near": "Junk", "distance": d})), + ("selectByLocation", json!({"input": "Wells", "select": "Junk", "distance": d})), + ("spatialJoin", json!({"target": "Wells", "join": "Roads", "match": "Closest", "distance": d})), + ("spatialJoin", json!({"target": "Wells", "join": "Junk", "match": "Within a distance", "distance": d})), + ] { + // Refused or done: not a panic, which a tool run gives back as " failed + // unexpectedly". + if let Err(e) = s.run("gp.run", &json!({"tool": tool, "params": params})) { + assert!(!e.contains("failed unexpectedly"), "{tool} {params}: {e}"); + } + } + } +}