From fbf8081fd314aca121a726017008e0e453191aa0 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 13:21:47 -0600 Subject: [PATCH 1/6] fix(analysis): Spatial Join and route lengths measure the Earth on the ellipsoid; lint the sphere Spatial Join's Largest overlap ranked overlaps by their area or length on the sphere, and a route's length (when the server gave none) was a sum of haversines. Both now use the WGS 84 ellipsoid functions, as Measure does. clippy.toml disallows the four spherical measures in rustgis-geom. Each call that keeps the sphere (other bodies, tolerances, bounds, View Clipping's draw distance, code waiting on #2032) says why with #[expect(clippy::disallowed_methods, reason = "...")]. Part of the follow-up to #2568 (A3). --- clippy.toml | 11 +++ crates/analysis/src/geodesic.rs | 7 ++ crates/analysis/src/join.rs | 71 +++++++++++++++++-- crates/analysis/src/network.rs | 5 ++ crates/analysis/src/rasterops.rs | 4 ++ crates/analysis/src/tools.rs | 4 ++ crates/engine/src/cmd/design.rs | 21 ++++++ crates/engine/src/cmd/imagery.rs | 6 ++ crates/engine/src/tests.rs | 2 + .../engine/tests/integration/polar_edits.rs | 2 + crates/geolibre/src/tests.rs | 1 + crates/geom/src/body.rs | 1 + crates/geom/src/lib.rs | 2 + crates/geom/tests/geodesic_identities.rs | 1 + crates/map/src/projection.rs | 2 + crates/render/src/lib.rs | 8 +++ crates/tiles/src/routing.rs | 16 ++++- crates/ui-egui/src/mapview.rs | 6 ++ .../tests/integration/measurement_units.rs | 1 + 19 files changed, 164 insertions(+), 7 deletions(-) diff --git a/clippy.toml b/clippy.toml index 7bada5473b..c7a236bd4f 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,3 +1,14 @@ allow-unwrap-in-tests = true allow-expect-in-tests = true allow-panic-in-tests = true + +# The Earth measures on the WGS 84 ellipsoid (`wgs84_distance_m`, `wgs84_length_m`, +# `wgs84_ring_perimeter_area_m2`), as the Measure tool does (#939, #2568). These measure on a sphere: +# a call says why with `#[expect(clippy::disallowed_methods, reason = "…")]`, for another body +# (scaled by `Body`) or a comparison the sphere can't change. +disallowed-methods = [ + { path = "rustgis_geom::haversine_m", reason = "the sphere; the Earth measures with `wgs84_distance_m`" }, + { path = "rustgis_geom::geodesic_length_m", reason = "the sphere; the Earth measures with `wgs84_length_m`" }, + { path = "rustgis_geom::geodesic_ring_perimeter_m", reason = "the sphere; the Earth measures with `wgs84_ring_perimeter_area_m2`" }, + { path = "rustgis_geom::geodesic_ring_area_m2", reason = "the sphere; the Earth measures with `wgs84_ring_perimeter_area_m2`" }, +] diff --git a/crates/analysis/src/geodesic.rs b/crates/analysis/src/geodesic.rs index 0ac8d71145..ac0048954f 100644 --- a/crates/analysis/src/geodesic.rs +++ b/crates/analysis/src/geodesic.rs @@ -322,6 +322,10 @@ impl Plane { /// from the same edge straight in the analysis plane ([`lonlat_to_plane`]: Web Mercator within /// ±85.05°, straight in lon/lat beyond) by more than `tolerance` meters at its quarter points /// or midpoint. + #[expect( + clippy::disallowed_methods, + reason = "a tolerance for splitting an edge, not a measurement: ellipsoid distances are within 0.6% of the sphere's" + )] fn strays(&self, a: GC, b: GC, la: Coord, lb: Coord, tolerance: f64) -> bool { let at = |t: f64| self.0.inverse(Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y))); // `b` on `a`'s side of the antimeridian, so the straight edge is the short one. @@ -495,6 +499,7 @@ fn finite(parts: &[Vec]) -> Vec> { parts.iter().map(|p| p.iter().copied().filter(|c| c.is_finite()).collect::>()).filter(|p| !p.is_empty()).collect() } +#[expect(clippy::disallowed_methods, reason = "sizes the pieces a buffer is cut into, not a measurement")] fn fits(pts: &[Coord], centre: Coord) -> bool { pts.iter().all(|c| haversine_m(centre, *c) <= ONE_PIECE_M) } @@ -504,6 +509,7 @@ fn stretched(parts: &[Vec], metres: f64) -> Vec> { let mut out = Vec::new(); for part in parts { let d = densify(part); + #[expect(clippy::disallowed_methods, reason = "sizes the pieces a buffer is cut into, not a measurement")] let near = |a: usize, b: usize| d.get(a).zip(d.get(b)).is_some_and(|(a, b)| haversine_m(*a, *b) <= STRETCH_M); let mut start = 0; loop { @@ -528,6 +534,7 @@ fn stretched(parts: &[Vec], metres: f64) -> Vec> { /// A line with every edge split along its geodesic on WGS 84 into pieces of at most [`DENSIFY_M`], or /// longer ones for a line so long it would gain more than [`MAX_ADDED`] vertices. +#[expect(clippy::disallowed_methods, reason = "the densify step: it sets how many vertices an edge gains, not a measurement")] fn densify(pts: &[Coord]) -> Vec { let step = DENSIFY_M.max(rustgis_geom::geodesic_length_m(pts) / MAX_ADDED); let mut out: Vec = pts.first().copied().into_iter().collect(); diff --git a/crates/analysis/src/join.rs b/crates/analysis/src/join.rs index 655ecff801..0668f452c4 100644 --- a/crates/analysis/src/join.rs +++ b/crates/analysis/src/join.rs @@ -10,7 +10,9 @@ //! 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}; +use rustgis_geom::{ + Aeqd, Extent, WGS84_MIN_RADIUS_M, geodesic_interpolate, wgs84_distance_m, wgs84_length_m, wgs84_ring_perimeter_area_m2, +}; use serde_json::Value as Json; /// Whether a coordinate is a place on the Earth in lon/lat: finite, with a latitude of ±90° at most @@ -229,20 +231,24 @@ fn lon_gap(a: &Extent, b: &Extent) -> f64 { [-360.0, 0.0, 360.0].iter().map(|k| (b.min_x + k - a.max_x).max(a.min_x - (b.max_x + k)).max(0.0)).fold(f64::INFINITY, f64::min) } -/// The ground area (square metres) of a lon/lat polygon geometry, holes taken out. +/// The ground area (square metres) of a lon/lat polygon geometry on the WGS 84 ellipsoid, holes +/// taken out, as the Measure tool gives it. NaN for a ring whose winding is ambiguous. pub fn area_m2(g: &Geometry) -> f64 { let Geometry::Polygon(polys) = g else { return 0.0 }; polys .iter() .flat_map(|rings| rings.iter().enumerate()) - .map(|(i, r)| if i == 0 { geodesic_ring_area_m2(r) } else { -geodesic_ring_area_m2(r) }) + .map(|(i, r)| { + let (_, area) = wgs84_ring_perimeter_area_m2(r); + if i == 0 { area } else { -area } + }) .sum() } -/// The ground length (metres) of a lon/lat line geometry. +/// The ground length (metres) of a lon/lat line geometry on the WGS 84 ellipsoid. pub fn length_m(g: &Geometry) -> f64 { let Geometry::Line(parts) = g else { return 0.0 }; - parts.iter().map(|p| geodesic_length_m(p)).sum() + parts.iter().map(|p| wgs84_length_m(p)).sum() } /// How the values of a join field's matches become one value in a one-to-one join. @@ -495,6 +501,7 @@ mod tests { /// The ground distance from `p` to a line, by sampling each edge finely along its great circle. /// Only the samples within 1.2% of the nearest on the sphere are measured on the ellipsoid, /// whose distances are within 0.6% of the sphere's. + #[expect(clippy::disallowed_methods, reason = "the test ranks samples on the sphere and measures the nearest on the ellipsoid")] fn brute(p: Coord, line: &[Coord]) -> f64 { let samples: Vec<(Coord, f64)> = line .windows(2) @@ -506,6 +513,7 @@ mod tests { } #[test] + #[expect(clippy::disallowed_methods, reason = "the test tells the ellipsoid's distance from the sphere's")] fn distances_are_on_the_wgs84_ellipsoid() { // 0.0904369° north of the equator is 10,000 m on WGS 84 (GeographicLib) but 10,056 m on the // mean sphere: within 10 km in the measure, and not ruled out before it (#888). @@ -518,6 +526,59 @@ mod tests { assert!(search_box(&ea, 10_000.0).is_some_and(|e| e.max_y >= b.y)); } + /// Spatial Join's Largest overlap ranks overlaps by their area or length on the WGS 84 + /// ellipsoid, as the Measure tool measures them. A 1° square on the equator, listed first, and a + /// band at 60°N that the ellipsoid makes 0.5% larger but the sphere 0.5% smaller: the band + /// wins. Likewise for a line along a meridian through a 1° zone and a shorter one at 60°N. + #[test] + #[expect(clippy::disallowed_methods, reason = "the test sets the sphere's ranking against the ellipsoid's")] + fn largest_overlap_ranks_overlaps_on_the_ellipsoid() { + use crate::{Inputs, Output}; + use rustgis_data::{Field, GeometryType}; + use rustgis_geom::{geodesic_length_m, geodesic_ring_area_m2}; + use std::collections::HashMap; + struct Layers(HashMap); + impl Inputs for Layers { + fn dataset(&self, layer: &str) -> Option<&Dataset> { + self.0.get(layer) + } + fn selection(&self, _: &str) -> &[usize] { + &[] + } + } + let ring = |x0: f64, x1: f64, y0: f64, y1: f64| { + vec![Coord::new(x0, y0), Coord::new(x1, y0), Coord::new(x1, y1), Coord::new(x0, y1), Coord::new(x0, y0)] + }; + let zones = |band_top: f64| { + let mut ds = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]); + for (name, r) in [("equator", ring(0.0, 1.0, 0.0, 1.0)), ("north", ring(0.0, 1.0, 60.0, band_top))] { + ds.push(Some(Geometry::Polygon(vec![vec![r]])), vec![Value::Text(name.into())]); + } + ds + }; + let joined = |target: Dataset, zones: Dataset| { + let layers = Layers(HashMap::from([("t".to_string(), target), ("zones".to_string(), zones)])); + let r = crate::run("spatialJoin", &layers, &serde_json::json!({"target": "t", "join": "zones", "match": "Largest overlap"})); + let Ok(crate::ToolResult { output: Output::Layer(ds), .. }) = r else { panic!("a layer") }; + ds.field_index("join_zone").map(|i| ds.value(0, i).clone()) + }; + let north = Some(Value::Text("north".into())); + + let (square, band) = (ring(0.0, 1.0, 0.0, 1.0), ring(0.0, 1.0, 60.0, 62.054)); + let area = |r: &Vec| wgs84_ring_perimeter_area_m2(r).1; + assert!(area(&band) > area(&square) * 1.004 && geodesic_ring_area_m2(&band) < geodesic_ring_area_m2(&square) * 0.996); + let mut parcel = Dataset::new("t", GeometryType::Polygon, vec![]); + parcel.push(Some(Geometry::Polygon(vec![vec![ring(0.0, 1.0, -1.0, 63.0)]])), vec![]); + assert_eq!(joined(parcel, zones(62.054)), north); + + let (near_equator, near_pole) = ([Coord::new(0.5, 0.0), Coord::new(0.5, 1.0)], [Coord::new(0.5, 60.0), Coord::new(0.5, 60.995)]); + assert!(wgs84_length_m(&near_pole) > wgs84_length_m(&near_equator) * 1.002); + assert!(geodesic_length_m(&near_pole) < geodesic_length_m(&near_equator) * 0.996); + let mut road = Dataset::new("t", GeometryType::Polyline, vec![]); + road.push(Some(Geometry::Line(vec![vec![Coord::new(0.5, -1.0), Coord::new(0.5, 63.0)]])), vec![]); + assert_eq!(joined(road, zones(60.995)), north); + } + #[test] fn an_integer_sum_takes_decimals_over_the_whole_i64_range() { let sum = Merge { field: 0, rule: Rule::Sum, delimiter: String::new() }; diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index a57a97d5e9..b6b35599a7 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -295,6 +295,10 @@ fn shortest_route_with( /// The closest point on any of `segs` to `p`: (segment, fraction along it, the point, metres /// away). With `within`, only segments whose box comes within about that many metres of `p` are /// measured; one farther can't be within it, so a nearer one is never missed. +#[expect( + clippy::disallowed_methods, + reason = "a lower bound that skips candidates, scaled to the ellipsoid's smallest radius; the distance kept is the ellipsoid's" +)] fn nearest_segment(segs: &[Segment], nodes: &[Coord], p: Coord, within: Option) -> Result, String> { crate::control::check()?; let window = within.and_then(|m| snap_window(p, m)); @@ -1733,6 +1737,7 @@ mod tests { } #[test] + #[expect(clippy::disallowed_methods, reason = "the test compares the sphere's ranking with the ellipsoid's")] fn snap_acceptance_uses_the_nearest_ellipsoidal_candidate() { let mut ds = Dataset::new("roads", GeometryType::Polyline, vec![]); // At the equator, 0.001 degrees east is nearer on the sphere than 0.001003 diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 43e529f967..5a3ed7a386 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -411,6 +411,10 @@ pub fn weighted_overlay(criteria: &[(Vec, f64)]) -> Result, String } /// Metres between two longitude/latitude points. +#[expect( + clippy::disallowed_methods, + reason = "the elevation profile's distances are on the sphere; moving them to the ellipsoid waits on #2032's open change to this file (#2721)" +)] fn dist_m(a: Coord, b: Coord) -> f64 { rustgis_geom::haversine_m(a, b) } diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 6a8caba26d..9a7200ddc7 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -3840,6 +3840,7 @@ 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. In a projected system's own plane, the bound /// is the edges' flat metres, as the walk adds them up, and a hair more. +#[expect(clippy::disallowed_methods, reason = "an upper bound, stretched by `ELLIPSOID_STRETCH` to cover the ellipsoid's longer paths")] 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()); @@ -11139,6 +11140,7 @@ mod tests { /// The distance on WGS 84 (km) from `c` to a line, sampled every `step` metres along it. /// Only the samples within 1.2% of the nearest on the sphere are measured on the ellipsoid, /// whose distances are within 0.6% of the sphere's. + #[expect(clippy::disallowed_methods, reason = "tests sample on the sphere and measure the nearest samples on the ellipsoid")] fn km_to_every(c: Coord, line: &[Coord], step: f64) -> f64 { let samples: Vec<(Coord, f64)> = line .windows(2) @@ -11203,6 +11205,7 @@ mod tests { } /// Points along the geodesic from `a` to `b` on WGS 84, at most 20 m apart. + #[expect(clippy::disallowed_methods, reason = "tests sample on the sphere and measure the nearest samples on the ellipsoid")] fn geodesic_samples(a: Coord, b: Coord) -> Vec { use geo::InterpolatePoint; let n = (rustgis_geom::haversine_m(a, b) / 20.0).ceil().max(1.0) as usize; @@ -11216,6 +11219,7 @@ mod tests { /// its nearest point is strictly between the ends: the nearest sample on the sphere (among /// every 50th, then its neighbours), then the nearest point on the ellipsoid along the geodesic /// either side of it, by golden-section search to well under a millimetre. + #[expect(clippy::disallowed_methods, reason = "tests sample on the sphere and measure the nearest samples on the ellipsoid")] fn m_to_geodesic(c: Coord, samples: &[Coord]) -> (f64, bool) { use geo::InterpolatePoint; let near = |range: std::ops::Range, step: usize| { diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 9354ee0025..b147825bb5 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -796,6 +796,10 @@ fn plane_at<'a>(geoms: impl IntoIterator, steps: &mut Cente let mut last = a; for k in 1..=n as usize { let q = if k as f64 >= n { b } else { at(k as f64 / n) }; + #[expect( + clippy::disallowed_methods, + reason = "weighs a centre by its pieces' lengths, not a measurement; polar edits wait on #2032 step C2f-6" + )] edges.add_weighted(at((k as f64 - 0.5) / n), haversine_m(last, q)); last = q; } @@ -1389,6 +1393,10 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { let mut dists: Vec = Vec::new(); if ground { dists.try_reserve(parts.iter().map(Vec::len).sum()).map_err(|_| "not enough memory to split the selected lines")?; + #[expect( + clippy::disallowed_methods, + reason = "finds the point of a line nearest the cut, a comparison, not a measurement; polar edits wait on #2032 step C2f-6" + )] dists.extend( parts .iter() @@ -1442,6 +1450,10 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { // nearer than the one found. let unsure = d > steps.floor; // At a vertex (to within a millimeter), the parts meet there, without it repeated. + #[expect( + clippy::disallowed_methods, + reason = "finds the point of a line nearest the cut, a comparison, not a measurement; polar edits wait on #2032 step C2f-6" + )] let at_end = [part.get(si), part.get(si + 1)].into_iter().flatten().find(|v| rustgis_geom::haversine_m(**v, q) < 0.001); let q = at_end.copied().unwrap_or(q); let mut first: Vec = part.iter().take(si + 1).copied().collect(); @@ -1451,6 +1463,10 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { let mut second = vec![q]; second.extend(part.iter().skip(si + 1).copied().skip_while(|c| *c == q)); // At (or within a centimetre of) the line's ends isn't a split. + #[expect( + clippy::disallowed_methods, + reason = "finds the point of a line nearest the cut, a comparison, not a measurement; polar edits wait on #2032 step C2f-6" + )] let near = |a: Option<&Coord>| a.is_some_and(|a| rustgis_geom::haversine_m(*a, q) < 0.01); if first.len() < 2 || second.len() < 2 || near(first.first()) || near(second.last()) { whole += usize::from(unsure); @@ -1522,6 +1538,10 @@ struct SplitSteps { /// a millimeter, nearest first, while it could hold a point nearer than the nearest found, or than /// `bound`. Each distance takes one of the command's `steps`; once they're spent, the nearest /// found (the nearer end, at first) stands, and `steps` notes how near the rest might be. +#[expect( + clippy::disallowed_methods, + reason = "finds the point of a line nearest the cut, a comparison, not a measurement; polar edits wait on #2032 step C2f-6" +)] fn nearest_on_ground(at: Coord, (a, b): (Coord, Coord), (da, db): (f64, f64), bound: f64, steps: &mut SplitSteps) -> Option<(f64, Coord)> { const STEP_DEG: f64 = 22.5; const PIECES_MIN: usize = 8; @@ -2868,6 +2888,7 @@ mod tests { } #[test] + #[expect(clippy::disallowed_methods, reason = "the test checks the split's search on the sphere it uses")] fn a_split_searches_a_segment_within_its_budget() { // From 89°N on 0°, along 88°N from 30°W to 30°E: searched, its nearest point is on 0°, a // kilometer nearer than its ends, and the search takes a few dozen of the budget; with diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 7bd2f0ab02..76ec0c1c74 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1904,6 +1904,10 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult { } // On the Earth, each leg's length on the sphere (as the profile below spaces its // samples) and on the ellipsoid; the flat length is the ellipsoid's. + #[expect( + clippy::disallowed_methods, + reason = "the sphere spaces the profile's samples, as `rasterops::profile` does; the lengths are the ellipsoid's" + )] let legs: Vec<(f64, f64)> = if earth { pts.windows(2) .map(|w| match w { @@ -1914,6 +1918,7 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult { } else { Vec::new() }; + #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")] let flat = if earth { legs.iter().map(|l| l.1).sum() } else { body.length(rustgis_geom::geodesic_length_m(&pts)) }; // Along the surface when there's an elevation raster. The profile spaces its samples // along the path on the sphere; on the Earth each step's ground run is taken from the @@ -1949,6 +1954,7 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult { if rustgis_geom::ring_area_is_ambiguous(&ring) { return Err("the area is ambiguous: 1 ring winds beyond one whole surface".into()); } + #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")] let (perimeter, area) = if earth { rustgis_geom::wgs84_ring_perimeter_area_m2(&ring) } else { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 99a32d25f9..403f480ac1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -17665,6 +17665,7 @@ fn exporting_a_raster_as_a_cog() { /// Mensuration measures the Earth on the WGS 84 ellipsoid, as the Measure tool does, so the same /// points give the same numbers in both; another body keeps its sphere (#2568). #[test] +#[expect(clippy::disallowed_methods, reason = "the test tells the ellipsoid's area from the sphere's")] fn mensuration_measures_the_earth_on_the_ellipsoid() { use rustgis_geom::Coord; let mut s = world(); @@ -41980,6 +41981,7 @@ fn scripts_refuse_edits_to_streamed_layers() { /// A map on Mars (#223): the body switcher puts a Mars basemap under it, its measurements and /// scale are Mars', and the project keeps the body; back on the Earth the Mars basemap goes. #[test] +#[expect(clippy::disallowed_methods, reason = "another body measures on its sphere")] fn celestial_bodies_set_the_basemap_and_the_measurements() { let mut s = Session::new(Project::default()); let earth = |s: &mut Session| { diff --git a/crates/engine/tests/integration/polar_edits.rs b/crates/engine/tests/integration/polar_edits.rs index c276253845..82d679750e 100644 --- a/crates/engine/tests/integration/polar_edits.rs +++ b/crates/engine/tests/integration/polar_edits.rs @@ -298,6 +298,7 @@ fn points_around_a_pole_moved_keep_their_longitudes_as_written() { } #[test] +#[expect(clippy::disallowed_methods, reason = "the test finds the nearest point as the split does, on the sphere")] fn a_split_beyond_85_degrees_cuts_at_the_point_nearest_on_the_ground() { // From 86°N on 0° to 89°N on 60°E, straight in longitude and latitude. Its nearest point to // 88.5°N on 0° is near 47°E on the ground, while the plane's would be near 13°E. @@ -389,6 +390,7 @@ fn a_split_too_long_to_search_in_full_says_so() { } #[test] +#[expect(clippy::disallowed_methods, reason = "the test finds the nearest point as the split does, on the sphere")] fn a_split_along_an_edge_going_around_a_pole_finds_its_nearest_turn() { // One edge from 87°N to 89°N, straight in longitude and latitude, going twice around the pole: // asked at 87.56°N on 144°W, it's cut where it comes nearest, as a fine sampling finds. diff --git a/crates/geolibre/src/tests.rs b/crates/geolibre/src/tests.rs index c6f77797a5..ae52ab0e9e 100644 --- a/crates/geolibre/src/tests.rs +++ b/crates/geolibre/src/tests.rs @@ -492,6 +492,7 @@ fn slope_runs_on_a_raster_layer() { } #[test] +#[expect(clippy::disallowed_methods, reason = "a rough check of a buffer's area, to within 5%")] fn vector_tools_work_in_metres_and_return_lonlat() { let Some(f) = setup() else { return }; let r = rustgis_analysis::run("geolibre:buffer_vector", &f, &json!({"input": "pts", "distance": "1000"})).unwrap(); diff --git a/crates/geom/src/body.rs b/crates/geom/src/body.rs index 0bc6a3a9e5..af1b94e8bc 100644 --- a/crates/geom/src/body.rs +++ b/crates/geom/src/body.rs @@ -88,6 +88,7 @@ mod tests { use super::*; #[test] + #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere")] fn bodies_scale_measurements_by_their_radius() { assert_eq!(Body::get("earth").ratio(), 1.0); assert_eq!(Body::get("nope").id, "earth"); diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 618ea9754a..bfdf7ad272 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -735,6 +735,7 @@ fn ring_lon_steps(ring: &[Coord]) -> Vec<(f64, bool)> { /// [`ring_lon_steps`]), which is its whole parallel. The sphere's counterpart of /// [`wgs84_ring_perimeter_area_m2`]'s perimeter; [`geodesic_length_m`] of the closed ring counts /// a full turn as nothing, the distance between its two ends. +#[expect(clippy::disallowed_methods, reason = "the sphere's own perimeter, for other bodies scaled by `Body`")] pub fn geodesic_ring_perimeter_m(ring: &[Coord]) -> f64 { if ring.len() < 2 { return 0.0; @@ -1015,6 +1016,7 @@ pub fn format_dms(c: Coord) -> String { format!("{} {ew} {} {ns}", dms(c.x), dms(c.y)) } +#[expect(clippy::disallowed_methods, reason = "tests check the sphere's formulas, against the ellipsoid's among others")] #[cfg(test)] mod tests { use super::*; diff --git a/crates/geom/tests/geodesic_identities.rs b/crates/geom/tests/geodesic_identities.rs index 58b85d1d99..9763ecedef 100644 --- a/crates/geom/tests/geodesic_identities.rs +++ b/crates/geom/tests/geodesic_identities.rs @@ -8,6 +8,7 @@ //! Pull requests run a fixed seed; the nightly a new one with more cases. A failure gives its seed //! and the smallest input found. To run a seed again, or deeper: //! `PROPERTY_SEED=7 PROPERTY_CASES=50000 cargo test -p rustgis-geom --test geodesic_identities`. +#![expect(clippy::disallowed_methods, reason = "the properties hold for the sphere's measures as for the ellipsoid's")] use proptest::prelude::*; use proptest::test_runner::{Config, RngAlgorithm, TestCaseError, TestRng, TestRunner}; use rustgis_geom::{Coord, geodesic_ring_area_m2, geodesic_ring_perimeter_m, haversine_m, wgs84_distance_m, wgs84_ring_perimeter_area_m2}; diff --git a/crates/map/src/projection.rs b/crates/map/src/projection.rs index e87833a28e..a8f2f44608 100644 --- a/crates/map/src/projection.rs +++ b/crates/map/src/projection.rs @@ -474,6 +474,7 @@ impl Domain { } } + #[expect(clippy::disallowed_methods, reason = "a cap's radius is an angle on the sphere, so the sphere decides what it holds")] pub fn contains(&self, c: Coord) -> bool { match *self { Domain::World => true, @@ -741,6 +742,7 @@ impl Projector { /// bar's direction; north-south on the projection's edge) compared with the great-circle /// distance it covers, on the sphere Web Mercator's scale uses so both agree. Falls back to /// the unit size where no step stays in the projection. + #[expect(clippy::disallowed_methods, reason = "Web Mercator's scale is the sphere's: with `MERCATOR_R` this matches its scale factor")] pub fn ground_per_unit(&self, at: Coord) -> f64 { let Some(c) = self.inverse(at) else { return self.to_meter }; let step = 1000.0 / self.to_meter; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 78ad8c8b27..0d4cf487b4 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -3893,6 +3893,10 @@ fn upright_markers_with(map: &mut Map, view: &View, margin: f64, env: &Env) -> V let own = layer.dataset.features.get(row).and_then(|f| f.geometry.as_ref())?.extent(); Some(to_lonlat.as_ref().map_or(rustgis_geom::Extent::EMPTY, |t| t.feature_extent(&own))) }); + #[expect( + clippy::disallowed_methods, + reason = "View Clipping's draw distance, tested for each feature every frame: a cut-off, not a measurement, within 0.6% of the ellipsoid's at its edge; the renderer and the map view test it alike" + )] if let (Some((centre, d)), Some(e)) = (clip, lonlat) { let near = Coord::new(centre.x.clamp(e.min_x, e.max_x), centre.y.clamp(e.min_y, e.max_y)); if e.is_empty() || rustgis_geom::haversine_m(centre, near) > d { @@ -4256,6 +4260,10 @@ impl Drop for TiltGlint { /// Leaves out of `rows` the features of `dataset` entirely beyond `d` metres of `centre` (the /// map's view distance, lon/lat): one reaching into it (its box's nearest point within the /// distance) is kept, one with no geometry isn't. +#[expect( + clippy::disallowed_methods, + reason = "View Clipping's draw distance, tested for each feature every frame: a cut-off, not a measurement, within 0.6% of the ellipsoid's at its edge; the renderer and the map view test it alike" +)] pub(crate) fn within_view_distance(rows: &mut [bool], dataset: &rustgis_data::Dataset, centre: Coord, d: f64) { // Each box in longitude/latitude, from the dataset's own coordinates: none is drawn when they // can't be converted, as `Layer::projected_in` draws none. diff --git a/crates/tiles/src/routing.rs b/crates/tiles/src/routing.rs index 97d06e87f1..b122091dd7 100644 --- a/crates/tiles/src/routing.rs +++ b/crates/tiles/src/routing.rs @@ -5,7 +5,7 @@ //! Answers are asked for in OSRM's form, whose steps carry a maneuver (its type and direction), //! an instruction, the street, and spoken announcements. -use rustgis_geom::{Coord, haversine_m}; +use rustgis_geom::{Coord, wgs84_distance_m}; use serde_json::{Value, json}; /// The public Valhalla server (FOSSGIS), the default. @@ -237,7 +237,7 @@ fn route(r: &Value) -> Option { match line.last() { Some(last) if *last == p => {} Some(last) => { - let d = along.last().copied().unwrap_or(0.0) + haversine_m(*last, p); + let d = along.last().copied().unwrap_or(0.0) + wgs84_distance_m(*last, p); line.push(p); along.push(d); } @@ -525,6 +525,18 @@ mod tests { assert!(explain("http status: 400").contains("no route")); } + /// Distances along a route are on the WGS 84 ellipsoid, as the Measure tool's are, and so is + /// the route's length when the server doesn't give one. + #[test] + fn a_route_without_a_distance_measures_its_line_on_the_ellipsoid() { + let r = Router::new(None).unwrap(); + let routes = r.parse(ANSWER.replace(r#""duration":302.776,"distance":1921.553,"#, r#""duration":302.776,"#).as_bytes()).unwrap(); + let a = &routes[0]; + let ellipsoid = rustgis_geom::wgs84_length_m(&a.line); + assert!((a.distance_m - ellipsoid).abs() < 1e-6, "{} m, {ellipsoid} m on the ellipsoid", a.distance_m); + assert_eq!(a.along.last().copied(), Some(a.distance_m)); + } + #[test] fn typed_places() { assert_eq!(parse_latlon("52.52, 13.405"), Some(Coord::new(13.405, 52.52))); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 3294b12a16..74c3666fe0 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -2380,6 +2380,10 @@ pub(crate) fn text_graphic_at(app: &RustGisApp, ctx: &egui::Context, rect: Rect, let to_lonlat = l.dataset.lonlat_conversion().ok()?; (0..l.dataset.features.len()).rev().filter(|r| drawn.get(*r) == Some(&true)).find_map(|row| { let g = l.dataset.features.get(row)?.geometry.as_ref()?; + #[expect( + clippy::disallowed_methods, + reason = "View Clipping's draw distance: picks only what the renderer draws, by its test (`within_view_distance`)" + )] if let Some((centre, d)) = clip { // No extent (an empty geometry, or one whose conversion isn't a number): nothing // of it is drawn, and clamping to its extent would panic. @@ -3827,10 +3831,12 @@ fn overlays(app: &mut RustGisApp, ui: &mut Ui, p: &egui::Painter, rect: Rect, t: // On the map's body: the Earth measures on the WGS 84 ellipsoid, so the panel agrees // with the geoprocessing tools (#939); another body measures on its sphere and scales. let body = app.session.map().body(); + #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")] let measure_length = |pts: &[Coord]| { if body.is_earth() { wgs84_length_m(pts) } else { body.length(geodesic_length_m(pts)) } }; // Perimeter and area in the map body's measurement model. + #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")] let measure_ring = |ring: &[Coord]| { if body.is_earth() { wgs84_ring_perimeter_area_m2(ring) diff --git a/crates/ui-egui/tests/integration/measurement_units.rs b/crates/ui-egui/tests/integration/measurement_units.rs index 3bee6331ac..037b51a6c3 100644 --- a/crates/ui-egui/tests/integration/measurement_units.rs +++ b/crates/ui-egui/tests/integration/measurement_units.rs @@ -393,6 +393,7 @@ fn measurement_unit_choice_is_saved_restored_and_available_to_scripts() { } #[test] +#[expect(clippy::disallowed_methods, reason = "another body measures on its sphere")] fn moon_measure_readout_uses_its_sphere_instead_of_wgs84() { let mut h = harness(); h.state_mut().run("map.body", json!({"name": "moon", "basemap": false})).unwrap(); From 02115c758982463ea25c3e81a6dd07436bcf6684 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 14:11:02 -0600 Subject: [PATCH 2/6] fix(analysis): elevation profiles measure on the ellipsoid; routes stay on the sphere for now The elevation profile's distances (and so Line of Sight's and Mensuration's surface distance) are now on the WGS 84 ellipsoid. Mensuration no longer needs to map sphere-spaced samples onto the ellipsoid's legs; on another body it passes its sphere to the new profile_by and scales. A route's distances go back to the haversine, with the reason at the call: the answer is parsed in the Directions pane's frame, where a geodesic solve per vertex could hold it on a long route. --- crates/analysis/src/rasterops.rs | 31 ++++++++++++------- crates/engine/src/cmd/imagery.rs | 51 +++++++------------------------- crates/tiles/src/routing.rs | 20 ++++--------- 3 files changed, 37 insertions(+), 65 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 5a3ed7a386..1dc6bbb06e 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -410,15 +410,6 @@ pub fn weighted_overlay(criteria: &[(Vec, f64)]) -> Result, String ) } -/// Metres between two longitude/latitude points. -#[expect( - clippy::disallowed_methods, - reason = "the elevation profile's distances are on the sphere; moving them to the ellipsoid waits on #2032's open change to this file (#2721)" -)] -fn dist_m(a: Coord, b: Coord) -> f64 { - rustgis_geom::haversine_m(a, b) -} - /// Elevation (bilinear) at a longitude/latitude point. pub fn elevation_at(r: &Raster, b: usize, ll: Coord) -> Option { let w = r.transformer().from_lonlat(ll)?; @@ -436,13 +427,26 @@ pub fn elevation_at(r: &Raster, b: usize, ll: Coord) -> Option { } } -/// An elevation profile along a path: (distance from the start in metres, point, elevation). +/// An elevation profile along a path: (distance from the start in metres, point, elevation), the +/// distances on the WGS 84 ellipsoid, as the Measure tool measures them. pub fn profile(r: &Raster, b: usize, path: &[Coord], samples: usize) -> Vec<(f64, Coord, Option)> { + profile_by(r, b, path, samples, rustgis_geom::wgs84_distance_m) +} + +/// [`profile`] with each leg of the path `metres` long: on another body, its sphere's distance. +/// Samples are spaced evenly by those distances. +pub fn profile_by( + r: &Raster, + b: usize, + path: &[Coord], + samples: usize, + metres: impl Fn(Coord, Coord) -> f64, +) -> Vec<(f64, Coord, Option)> { let samples = samples.clamp(2, 10_000); let legs: Vec = path .windows(2) .map(|w| match w { - [a, c] => dist_m(*a, *c), + [a, c] => metres(*a, *c), _ => 0.0, }) .collect(); @@ -2861,6 +2865,11 @@ mod tests { let p = profile(&r, 0, &[Coord::new(0.0005, 0.01), Coord::new(0.0195, 0.01)], 20); assert_eq!(p.len(), 20); assert!(p.last().and_then(|x| x.2).unwrap_or(0.0) > p[0].2.unwrap_or(0.0) + 150.0); + // Distances along it are the ellipsoid's, as Measure gives them, not the sphere's, which + // makes this path about 0.2% longer. + let path = [Coord::new(0.0005, 0.0005), Coord::new(0.0195, 0.0005), Coord::new(0.0195, 0.0195)]; + let (along, ellipsoid) = (profile(&r, 0, &path, 20).last().map_or(0.0, |x| x.0), rustgis_geom::wgs84_length_m(&path)); + assert!((along - ellipsoid).abs() < 1e-6, "{along} m along, {ellipsoid} m on the ellipsoid"); } #[test] diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 76ec0c1c74..120733fd8e 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1853,23 +1853,6 @@ fn edit_pixels(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"pixels": n})) } -/// The ground distance on the WGS 84 ellipsoid from the start of a path to the point `along` -/// metres along it as the sphere measures it (as `rasterops::profile` spaces its samples), given -/// each leg's length on the sphere and on the ellipsoid: the legs before it at their ellipsoid -/// length, and the same share of the leg it falls in. -fn ellipsoid_along(legs: &[(f64, f64)], along: f64) -> f64 { - let (mut sphere, mut ground) = (0.0, 0.0); - for &(on_sphere, on_ellipsoid) in legs { - if along <= sphere + on_sphere { - let share = if on_sphere > 0.0 { ((along - sphere) / on_sphere).clamp(0.0, 1.0) } else { 0.0 }; - return ground + on_ellipsoid * share; - } - sphere += on_sphere; - ground += on_ellipsoid; - } - ground -} - /// The most points `raster.measure` takes. const MAX_MEASURE_POINTS: usize = 10_000; @@ -1902,31 +1885,19 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult { if pts.len() < 2 { return Err("a distance needs two or more points".into()); } - // On the Earth, each leg's length on the sphere (as the profile below spaces its - // samples) and on the ellipsoid; the flat length is the ellipsoid's. - #[expect( - clippy::disallowed_methods, - reason = "the sphere spaces the profile's samples, as `rasterops::profile` does; the lengths are the ellipsoid's" - )] - let legs: Vec<(f64, f64)> = if earth { - pts.windows(2) - .map(|w| match w { - [a, c] => (rustgis_geom::haversine_m(*a, *c), rustgis_geom::wgs84_distance_m(*a, *c)), - _ => (0.0, 0.0), - }) - .collect() - } else { - Vec::new() - }; #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")] - let flat = if earth { legs.iter().map(|l| l.1).sum() } else { body.length(rustgis_geom::geodesic_length_m(&pts)) }; - // Along the surface when there's an elevation raster. The profile spaces its samples - // along the path on the sphere; on the Earth each step's ground run is taken from the - // legs it covers at their length on the ellipsoid, so level ground gives the flat - // length exactly. + let flat = if earth { rustgis_geom::wgs84_length_m(&pts) } else { body.length(rustgis_geom::geodesic_length_m(&pts)) }; + // Along the surface when there's an elevation raster. The profile measures along the + // path as the flat length does (on the Earth the ellipsoid, on another body its sphere, + // scaled), so level ground gives the flat length exactly. let surface = dem.as_ref().map(|d| { - let ground = |along: f64| if earth { ellipsoid_along(&legs, along) } else { body.length(along) }; - let prof = rasterops::profile(d, 0, &pts, 500); + let ground = |along: f64| if earth { along } else { body.length(along) }; + #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")] + let prof = if earth { + rasterops::profile(d, 0, &pts, 500) + } else { + rasterops::profile_by(d, 0, &pts, 500, rustgis_geom::haversine_m) + }; prof.windows(2) .map(|w| match w { [a, c] => { diff --git a/crates/tiles/src/routing.rs b/crates/tiles/src/routing.rs index b122091dd7..d6ab760484 100644 --- a/crates/tiles/src/routing.rs +++ b/crates/tiles/src/routing.rs @@ -5,7 +5,7 @@ //! Answers are asked for in OSRM's form, whose steps carry a maneuver (its type and direction), //! an instruction, the street, and spoken announcements. -use rustgis_geom::{Coord, wgs84_distance_m}; +use rustgis_geom::{Coord, haversine_m}; use serde_json::{Value, json}; /// The public Valhalla server (FOSSGIS), the default. @@ -237,7 +237,11 @@ fn route(r: &Value) -> Option { match line.last() { Some(last) if *last == p => {} Some(last) => { - let d = along.last().copied().unwrap_or(0.0) + wgs84_distance_m(*last, p); + #[expect( + clippy::disallowed_methods, + reason = "positions along the route, a step per vertex while the answer is parsed in the Directions pane's frame, where a geodesic solve each would hold it on a long route; the route's length is the server's, this sum standing in only when it sends none" + )] + let d = along.last().copied().unwrap_or(0.0) + haversine_m(*last, p); line.push(p); along.push(d); } @@ -525,18 +529,6 @@ mod tests { assert!(explain("http status: 400").contains("no route")); } - /// Distances along a route are on the WGS 84 ellipsoid, as the Measure tool's are, and so is - /// the route's length when the server doesn't give one. - #[test] - fn a_route_without_a_distance_measures_its_line_on_the_ellipsoid() { - let r = Router::new(None).unwrap(); - let routes = r.parse(ANSWER.replace(r#""duration":302.776,"distance":1921.553,"#, r#""duration":302.776,"#).as_bytes()).unwrap(); - let a = &routes[0]; - let ellipsoid = rustgis_geom::wgs84_length_m(&a.line); - assert!((a.distance_m - ellipsoid).abs() < 1e-6, "{} m, {ellipsoid} m on the ellipsoid", a.distance_m); - assert_eq!(a.along.last().copied(), Some(a.distance_m)); - } - #[test] fn typed_places() { assert_eq!(parse_latlon("52.52, 13.405"), Some(Coord::new(13.405, 52.52))); From 3c995c15031ea77eb762ed53f58c454d7cf50a93 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 14:55:43 -0600 Subject: [PATCH 3/6] fix(tiles): routes measure on the ellipsoid, read off the frame The distance along a route (and the route's length when the server sends none) is summed with wgs84_distance_m. A geodesic solve costs about 20 times a haversine, so the Directions pane reads the routing answer where the download lands, on its own thread on the desktop, not in the frame. --- crates/tiles/src/routing.rs | 20 ++++++++++++++------ crates/ui-egui/src/navui.rs | 31 +++++++++++++++++++++++-------- 2 files changed, 37 insertions(+), 14 deletions(-) diff --git a/crates/tiles/src/routing.rs b/crates/tiles/src/routing.rs index d6ab760484..b122091dd7 100644 --- a/crates/tiles/src/routing.rs +++ b/crates/tiles/src/routing.rs @@ -5,7 +5,7 @@ //! Answers are asked for in OSRM's form, whose steps carry a maneuver (its type and direction), //! an instruction, the street, and spoken announcements. -use rustgis_geom::{Coord, haversine_m}; +use rustgis_geom::{Coord, wgs84_distance_m}; use serde_json::{Value, json}; /// The public Valhalla server (FOSSGIS), the default. @@ -237,11 +237,7 @@ fn route(r: &Value) -> Option { match line.last() { Some(last) if *last == p => {} Some(last) => { - #[expect( - clippy::disallowed_methods, - reason = "positions along the route, a step per vertex while the answer is parsed in the Directions pane's frame, where a geodesic solve each would hold it on a long route; the route's length is the server's, this sum standing in only when it sends none" - )] - let d = along.last().copied().unwrap_or(0.0) + haversine_m(*last, p); + let d = along.last().copied().unwrap_or(0.0) + wgs84_distance_m(*last, p); line.push(p); along.push(d); } @@ -529,6 +525,18 @@ mod tests { assert!(explain("http status: 400").contains("no route")); } + /// Distances along a route are on the WGS 84 ellipsoid, as the Measure tool's are, and so is + /// the route's length when the server doesn't give one. + #[test] + fn a_route_without_a_distance_measures_its_line_on_the_ellipsoid() { + let r = Router::new(None).unwrap(); + let routes = r.parse(ANSWER.replace(r#""duration":302.776,"distance":1921.553,"#, r#""duration":302.776,"#).as_bytes()).unwrap(); + let a = &routes[0]; + let ellipsoid = rustgis_geom::wgs84_length_m(&a.line); + assert!((a.distance_m - ellipsoid).abs() < 1e-6, "{} m, {ellipsoid} m on the ellipsoid", a.distance_m); + assert_eq!(a.along.last().copied(), Some(a.distance_m)); + } + #[test] fn typed_places() { assert_eq!(parse_latlon("52.52, 13.405"), Some(Coord::new(13.405, 52.52))); diff --git a/crates/ui-egui/src/navui.rs b/crates/ui-egui/src/navui.rs index a311d940f8..5db3ebf830 100644 --- a/crates/ui-egui/src/navui.rs +++ b/crates/ui-egui/src/navui.rs @@ -17,6 +17,8 @@ use crate::theme::{Tokens, regular, semibold}; use crate::{RustGisApp, Slot, i18n}; type Answer = Slot, String>>; +/// A routing answer read where it landed: its routes and its text, or what went wrong. +type Routed = Slot, String), String>>; /// The start, a stop, or the destination. #[derive(Clone, Debug, Default)] @@ -52,7 +54,7 @@ pub struct State { pub consent: bool, loaded: bool, /// A request under way, and what it asked. - pending: Option<(Answer, String)>, + pending: Option<(Routed, String)>, /// What the routes shown (or the request under way) were asked for. asked: String, pub routes: Vec, @@ -157,6 +159,22 @@ fn fetch(url: &str) -> Answer { slot } +/// Asks for routes at `url`. The answer is read where it lands, on the download's thread on the +/// desktop, not on the frame: measuring a long route's line on the ellipsoid takes a while. +fn fetch_routes(url: &str) -> Routed { + let slot: Routed = Slot::default(); + let land = slot.clone(); + cache::download( + url, + Box::new(move |r| { + let router = Router { base: routing::VALHALLA.into() }; + let read = r.map_err(|e| routing::explain(&e)).and_then(|b| Ok((router.parse(&b)?, String::from_utf8_lossy(&b).into_owned()))); + *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(read); + }), + ); + slot +} + fn take(slot: &Answer) -> Option, String>> { slot.lock().unwrap_or_else(|e| e.into_inner()).take() } @@ -311,17 +329,14 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { } // A route answered. if let Some((slot, key)) = &st.pending { - match take(slot) { + let read = slot.lock().unwrap_or_else(|e| e.into_inner()).take(); + match read { Some(r) => { let key = key.clone(); st.pending = None; // Only the answer to what's asked now (the places may have changed meanwhile). if key == st.key(&language) { - let router = Router { base: routing::VALHALLA.into() }; - match r.map_err(|e| routing::explain(&e)).and_then(|b| { - let routes = router.parse(&b)?; - Ok((routes, String::from_utf8_lossy(&b).into_owned())) - }) { + match r { Ok((routes, text)) => { st.routes = routes; st.answer = text; @@ -360,7 +375,7 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { language, }; match Router::new(None).and_then(|r| r.url(&req)) { - Ok(url) => st.pending = Some((fetch(&url), key)), + Ok(url) => st.pending = Some((fetch_routes(&url), key)), Err(e) => st.error = Some(e), } } From dbe11f8a98ebfdb75729c8dca2f3e959a71e2f30 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 15:40:19 -0600 Subject: [PATCH 4/6] fix(analysis): elevation profiles stay on the sphere for now A solve per path vertex costs about 20 times a haversine, and the profile commands run on the command thread: Profile Along Selected Lines would hold the window that much longer. The profile and Mensuration go back to how they were, and the reason at the call says so. navui: one fetch helper and one take for both answers. --- crates/analysis/src/rasterops.rs | 31 +++++++------------ crates/engine/src/cmd/imagery.rs | 51 +++++++++++++++++++++++++------- crates/ui-egui/src/navui.rs | 29 ++++++++---------- 3 files changed, 64 insertions(+), 47 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 1dc6bbb06e..0ee679419b 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -410,6 +410,15 @@ pub fn weighted_overlay(criteria: &[(Vec, f64)]) -> Result, String ) } +/// Metres between two longitude/latitude points. +#[expect( + clippy::disallowed_methods, + reason = "the elevation profile's distances stay on the sphere for now: a solve per path vertex costs about 20 times as much on the ellipsoid, and the profile commands run on the command thread" +)] +fn dist_m(a: Coord, b: Coord) -> f64 { + rustgis_geom::haversine_m(a, b) +} + /// Elevation (bilinear) at a longitude/latitude point. pub fn elevation_at(r: &Raster, b: usize, ll: Coord) -> Option { let w = r.transformer().from_lonlat(ll)?; @@ -427,26 +436,13 @@ pub fn elevation_at(r: &Raster, b: usize, ll: Coord) -> Option { } } -/// An elevation profile along a path: (distance from the start in metres, point, elevation), the -/// distances on the WGS 84 ellipsoid, as the Measure tool measures them. +/// An elevation profile along a path: (distance from the start in metres, point, elevation). pub fn profile(r: &Raster, b: usize, path: &[Coord], samples: usize) -> Vec<(f64, Coord, Option)> { - profile_by(r, b, path, samples, rustgis_geom::wgs84_distance_m) -} - -/// [`profile`] with each leg of the path `metres` long: on another body, its sphere's distance. -/// Samples are spaced evenly by those distances. -pub fn profile_by( - r: &Raster, - b: usize, - path: &[Coord], - samples: usize, - metres: impl Fn(Coord, Coord) -> f64, -) -> Vec<(f64, Coord, Option)> { let samples = samples.clamp(2, 10_000); let legs: Vec = path .windows(2) .map(|w| match w { - [a, c] => metres(*a, *c), + [a, c] => dist_m(*a, *c), _ => 0.0, }) .collect(); @@ -2865,11 +2861,6 @@ mod tests { let p = profile(&r, 0, &[Coord::new(0.0005, 0.01), Coord::new(0.0195, 0.01)], 20); assert_eq!(p.len(), 20); assert!(p.last().and_then(|x| x.2).unwrap_or(0.0) > p[0].2.unwrap_or(0.0) + 150.0); - // Distances along it are the ellipsoid's, as Measure gives them, not the sphere's, which - // makes this path about 0.2% longer. - let path = [Coord::new(0.0005, 0.0005), Coord::new(0.0195, 0.0005), Coord::new(0.0195, 0.0195)]; - let (along, ellipsoid) = (profile(&r, 0, &path, 20).last().map_or(0.0, |x| x.0), rustgis_geom::wgs84_length_m(&path)); - assert!((along - ellipsoid).abs() < 1e-6, "{along} m along, {ellipsoid} m on the ellipsoid"); } #[test] diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 120733fd8e..76ec0c1c74 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1853,6 +1853,23 @@ fn edit_pixels(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"pixels": n})) } +/// The ground distance on the WGS 84 ellipsoid from the start of a path to the point `along` +/// metres along it as the sphere measures it (as `rasterops::profile` spaces its samples), given +/// each leg's length on the sphere and on the ellipsoid: the legs before it at their ellipsoid +/// length, and the same share of the leg it falls in. +fn ellipsoid_along(legs: &[(f64, f64)], along: f64) -> f64 { + let (mut sphere, mut ground) = (0.0, 0.0); + for &(on_sphere, on_ellipsoid) in legs { + if along <= sphere + on_sphere { + let share = if on_sphere > 0.0 { ((along - sphere) / on_sphere).clamp(0.0, 1.0) } else { 0.0 }; + return ground + on_ellipsoid * share; + } + sphere += on_sphere; + ground += on_ellipsoid; + } + ground +} + /// The most points `raster.measure` takes. const MAX_MEASURE_POINTS: usize = 10_000; @@ -1885,19 +1902,31 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult { if pts.len() < 2 { return Err("a distance needs two or more points".into()); } + // On the Earth, each leg's length on the sphere (as the profile below spaces its + // samples) and on the ellipsoid; the flat length is the ellipsoid's. + #[expect( + clippy::disallowed_methods, + reason = "the sphere spaces the profile's samples, as `rasterops::profile` does; the lengths are the ellipsoid's" + )] + let legs: Vec<(f64, f64)> = if earth { + pts.windows(2) + .map(|w| match w { + [a, c] => (rustgis_geom::haversine_m(*a, *c), rustgis_geom::wgs84_distance_m(*a, *c)), + _ => (0.0, 0.0), + }) + .collect() + } else { + Vec::new() + }; #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")] - let flat = if earth { rustgis_geom::wgs84_length_m(&pts) } else { body.length(rustgis_geom::geodesic_length_m(&pts)) }; - // Along the surface when there's an elevation raster. The profile measures along the - // path as the flat length does (on the Earth the ellipsoid, on another body its sphere, - // scaled), so level ground gives the flat length exactly. + let flat = if earth { legs.iter().map(|l| l.1).sum() } else { body.length(rustgis_geom::geodesic_length_m(&pts)) }; + // Along the surface when there's an elevation raster. The profile spaces its samples + // along the path on the sphere; on the Earth each step's ground run is taken from the + // legs it covers at their length on the ellipsoid, so level ground gives the flat + // length exactly. let surface = dem.as_ref().map(|d| { - let ground = |along: f64| if earth { along } else { body.length(along) }; - #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")] - let prof = if earth { - rasterops::profile(d, 0, &pts, 500) - } else { - rasterops::profile_by(d, 0, &pts, 500, rustgis_geom::haversine_m) - }; + let ground = |along: f64| if earth { ellipsoid_along(&legs, along) } else { body.length(along) }; + let prof = rasterops::profile(d, 0, &pts, 500); prof.windows(2) .map(|w| match w { [a, c] => { diff --git a/crates/ui-egui/src/navui.rs b/crates/ui-egui/src/navui.rs index 5db3ebf830..ff6848256b 100644 --- a/crates/ui-egui/src/navui.rs +++ b/crates/ui-egui/src/navui.rs @@ -153,29 +153,27 @@ impl State { } fn fetch(url: &str) -> Answer { - let slot: Answer = Slot::default(); + fetch_read(url, |r| r) +} + +/// Downloads `url`; the slot gets the answer as `read` reads it where it lands. +fn fetch_read(url: &str, read: impl FnOnce(Result, String>) -> T + Send + 'static) -> Slot { + let slot: Slot = Slot::default(); let land = slot.clone(); - cache::download(url, Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r))); + cache::download(url, Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(read(r)))); slot } /// Asks for routes at `url`. The answer is read where it lands, on the download's thread on the /// desktop, not on the frame: measuring a long route's line on the ellipsoid takes a while. fn fetch_routes(url: &str) -> Routed { - let slot: Routed = Slot::default(); - let land = slot.clone(); - cache::download( - url, - Box::new(move |r| { - let router = Router { base: routing::VALHALLA.into() }; - let read = r.map_err(|e| routing::explain(&e)).and_then(|b| Ok((router.parse(&b)?, String::from_utf8_lossy(&b).into_owned()))); - *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(read); - }), - ); - slot + fetch_read(url, |r| { + let router = Router { base: routing::VALHALLA.into() }; + r.map_err(|e| routing::explain(&e)).and_then(|b| Ok((router.parse(&b)?, String::from_utf8_lossy(&b).into_owned()))) + }) } -fn take(slot: &Answer) -> Option, String>> { +fn take(slot: &Slot) -> Option { slot.lock().unwrap_or_else(|e| e.into_inner()).take() } @@ -329,8 +327,7 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { } // A route answered. if let Some((slot, key)) = &st.pending { - let read = slot.lock().unwrap_or_else(|e| e.into_inner()).take(); - match read { + match take(slot) { Some(r) => { let key = key.clone(); st.pending = None; From c45eb23cb3ac577c209fd0dded391f0f4f33fb36 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 16:18:31 -0600 Subject: [PATCH 5/6] fix(tiles): route steps measure on the ellipsoid cheaply; the pane parses on the frame again wgs84_step_m measures a short step from the ellipsoid's radii of curvature at its mean latitude, within a millionth of the geodesic solve for steps up to 0.05 degrees below 89 degrees, and is the solve for any other. A route's many steps use it, so neither the Directions pane nor Save as Layer pays a solve per vertex, and the pane goes back to parsing the answer as before. AGENTS.md: the lint's line under Quality gates. --- AGENTS.md | 5 +++++ crates/geom/src/lib.rs | 44 +++++++++++++++++++++++++++++++++++++ crates/tiles/src/routing.rs | 7 +++--- crates/ui-egui/src/navui.rs | 32 +++++++++------------------ 4 files changed, 63 insertions(+), 25 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cad3c3bddc..f259862429 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -152,6 +152,11 @@ the pull request which of these it reaches and why the rest don't apply: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers) before every commit. `cargo xtask test-hygiene` (also in CI) requires `// test-wait: reason` on timer waits in tests and `#[ignore = "reason"]` on ignored tests; prefer completion or progress signals. +`clippy.toml` refuses the four sphere measures in `rustgis-geom` (`haversine_m`, `geodesic_length_m`, +`geodesic_ring_perimeter_m`, `geodesic_ring_area_m2`): the Earth measures on the WGS 84 ellipsoid +(`wgs84_distance_m`, `wgs84_length_m`, `wgs84_step_m`, `wgs84_ring_perimeter_area_m2`), and a call kept on +the sphere, for another body or a comparison it can't change, says why in its +`#[expect(clippy::disallowed_methods, reason = "…")]`. `cargo xtask memory` (in CI on Linux) fails when a command line workflow's peak memory grows past its limit in `xtask/memory-limits.txt`; a change that lowers one commits the lower limit with it. `cargo xtask rows` (also in CI) fails when code outside `rustgis-data` uses a layer's rows directly diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index bfdf7ad272..5c8eb7fcfc 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -451,6 +451,27 @@ pub fn wgs84_direct(c: Coord, azimuth_deg: f64, dist_m: f64) -> (Coord, f64) { (Coord::new(lon, lat), azi2) } +/// The distance (metres) between two nearby lon/lat points on the WGS 84 ellipsoid, for the many +/// short steps of a long line (a route's): from the ellipsoid's radii of curvature along and across +/// the meridian at the two points' mean latitude, within a millionth of [`wgs84_distance_m`] for a +/// step of up to 0.05° in latitude and in longitude below 89°, and [`wgs84_distance_m`] itself for +/// any other. It costs a few operations, where a geodesic solve costs about 20 times a haversine. +/// NaN for a coordinate that isn't finite. +pub fn wgs84_step_m(a: Coord, b: Coord) -> f64 { + if !a.is_finite() || !b.is_finite() { + return f64::NAN; + } + let (dlat, dlon) = (b.y - a.y, wrap_lon(b.x - a.x)); + if dlat.abs() > 0.05 || dlon.abs() > 0.05 || a.y.abs().max(b.y.abs()) > 89.0 { + return wgs84_distance_m(a, b); + } + let (s, c) = ((a.y + b.y) / 2.0).to_radians().sin_cos(); + let w2 = 1.0 - WGS84_E2 * s * s; + let across = WGS84_A / w2.sqrt(); + let along = across * (1.0 - WGS84_E2) / w2; + (along * dlat.to_radians()).hypot(across * c * dlon.to_radians()) +} + /// Length of a lon/lat polyline along the WGS 84 ellipsoid's geodesics (metres): each segment is /// an inverse geodesic solve, so it is exact, unlike [`geodesic_length_m`]'s great circles. Long /// lines of many vertices cost a solve per segment (a few microseconds each). @@ -1551,6 +1572,29 @@ mod tests { assert!(geodesic_destination(Coord::new(10.0, 50.0), 90.0, f64::NAN).x.is_nan()); } + /// A short step measured from the ellipsoid's radii agrees with the geodesic solve to within a + /// millionth, at every latitude below 89° and across the antimeridian; a longer step, or one by + /// a pole, is the solve itself. + #[test] + fn wgs84_steps_agree_with_the_geodesic() { + let mut worst: f64 = 0.0; + for lat in (-89..=88).map(f64::from) { + for (dx, dy) in [(0.05, 0.0), (0.0, 0.05), (0.05, 0.05), (-0.03, 0.01), (1e-5, -2e-5)] { + for lon in [-179.98, -12.0, 0.0, 179.99] { + let (a, b) = (Coord::new(lon, lat), Coord::new(lon + dx, lat + dy)); + let exact = wgs84_distance_m(a, b); + worst = worst.max((wgs84_step_m(a, b) - exact).abs() / exact); + } + } + } + assert!(worst < 1e-6, "{worst}"); + let far = (Coord::new(10.0, 40.0), Coord::new(10.2, 40.0)); + assert_eq!(wgs84_step_m(far.0, far.1), wgs84_distance_m(far.0, far.1)); + let polar = (Coord::new(10.0, 89.5), Coord::new(10.01, 89.5)); + assert_eq!(wgs84_step_m(polar.0, polar.1), wgs84_distance_m(polar.0, polar.1)); + assert!(wgs84_step_m(Coord::new(f64::NAN, 0.0), Coord::new(0.0, 0.0)).is_nan()); + } + #[test] fn geodesic_length_matches_summed_haversine_across_the_antimeridian() { let poly = [Coord::new(0.0, 0.0), Coord::new(10.0, 20.0), Coord::new(179.0, -30.0), Coord::new(-179.0, -31.0)]; diff --git a/crates/tiles/src/routing.rs b/crates/tiles/src/routing.rs index b122091dd7..3930e85729 100644 --- a/crates/tiles/src/routing.rs +++ b/crates/tiles/src/routing.rs @@ -5,7 +5,7 @@ //! Answers are asked for in OSRM's form, whose steps carry a maneuver (its type and direction), //! an instruction, the street, and spoken announcements. -use rustgis_geom::{Coord, wgs84_distance_m}; +use rustgis_geom::{Coord, wgs84_step_m}; use serde_json::{Value, json}; /// The public Valhalla server (FOSSGIS), the default. @@ -237,7 +237,8 @@ fn route(r: &Value) -> Option { match line.last() { Some(last) if *last == p => {} Some(last) => { - let d = along.last().copied().unwrap_or(0.0) + wgs84_distance_m(*last, p); + // On the ellipsoid, a few operations a step: a route can hold half a million. + let d = along.last().copied().unwrap_or(0.0) + wgs84_step_m(*last, p); line.push(p); along.push(d); } @@ -533,7 +534,7 @@ mod tests { let routes = r.parse(ANSWER.replace(r#""duration":302.776,"distance":1921.553,"#, r#""duration":302.776,"#).as_bytes()).unwrap(); let a = &routes[0]; let ellipsoid = rustgis_geom::wgs84_length_m(&a.line); - assert!((a.distance_m - ellipsoid).abs() < 1e-6, "{} m, {ellipsoid} m on the ellipsoid", a.distance_m); + assert!((a.distance_m / ellipsoid - 1.0).abs() < 1e-6, "{} m, {ellipsoid} m on the ellipsoid", a.distance_m); assert_eq!(a.along.last().copied(), Some(a.distance_m)); } diff --git a/crates/ui-egui/src/navui.rs b/crates/ui-egui/src/navui.rs index ff6848256b..a311d940f8 100644 --- a/crates/ui-egui/src/navui.rs +++ b/crates/ui-egui/src/navui.rs @@ -17,8 +17,6 @@ use crate::theme::{Tokens, regular, semibold}; use crate::{RustGisApp, Slot, i18n}; type Answer = Slot, String>>; -/// A routing answer read where it landed: its routes and its text, or what went wrong. -type Routed = Slot, String), String>>; /// The start, a stop, or the destination. #[derive(Clone, Debug, Default)] @@ -54,7 +52,7 @@ pub struct State { pub consent: bool, loaded: bool, /// A request under way, and what it asked. - pending: Option<(Routed, String)>, + pending: Option<(Answer, String)>, /// What the routes shown (or the request under way) were asked for. asked: String, pub routes: Vec, @@ -153,27 +151,13 @@ impl State { } fn fetch(url: &str) -> Answer { - fetch_read(url, |r| r) -} - -/// Downloads `url`; the slot gets the answer as `read` reads it where it lands. -fn fetch_read(url: &str, read: impl FnOnce(Result, String>) -> T + Send + 'static) -> Slot { - let slot: Slot = Slot::default(); + let slot: Answer = Slot::default(); let land = slot.clone(); - cache::download(url, Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(read(r)))); + cache::download(url, Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r))); slot } -/// Asks for routes at `url`. The answer is read where it lands, on the download's thread on the -/// desktop, not on the frame: measuring a long route's line on the ellipsoid takes a while. -fn fetch_routes(url: &str) -> Routed { - fetch_read(url, |r| { - let router = Router { base: routing::VALHALLA.into() }; - r.map_err(|e| routing::explain(&e)).and_then(|b| Ok((router.parse(&b)?, String::from_utf8_lossy(&b).into_owned()))) - }) -} - -fn take(slot: &Slot) -> Option { +fn take(slot: &Answer) -> Option, String>> { slot.lock().unwrap_or_else(|e| e.into_inner()).take() } @@ -333,7 +317,11 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { st.pending = None; // Only the answer to what's asked now (the places may have changed meanwhile). if key == st.key(&language) { - match r { + let router = Router { base: routing::VALHALLA.into() }; + match r.map_err(|e| routing::explain(&e)).and_then(|b| { + let routes = router.parse(&b)?; + Ok((routes, String::from_utf8_lossy(&b).into_owned())) + }) { Ok((routes, text)) => { st.routes = routes; st.answer = text; @@ -372,7 +360,7 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { language, }; match Router::new(None).and_then(|r| r.url(&req)) { - Ok(url) => st.pending = Some((fetch_routes(&url), key)), + Ok(url) => st.pending = Some((fetch(&url), key)), Err(e) => st.error = Some(e), } } From 2665b44b10f5fd6044584ee7df0dbd608c06c638 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 17:12:13 -0600 Subject: [PATCH 6/6] docs(analysis): Largest overlap now measures on the ellipsoid --- docs/user-guide/analysis.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index bf2ff77153..bc414ba407 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -602,9 +602,8 @@ and features, before changing any fields. The attribute table's Calculate Geomet same for its chosen rows. Spatial Join's Largest overlap refuses affected selected target or join features before writing output. Ordinary polar caps and whole-world rectangles remain measurable. Measure Area explains the ambiguity and still shows the perimeter. -Spatial Join's **Largest overlap** still measures area on a sphere of radius 6,371 km; it can -differ from the ellipsoid by up to about 0.9 % (a small area near a pole). The same WGS 84 -measure backs the attribute table's **Calculate Geometry** (`edit.calculateGeometry`), the +Spatial Join's **Largest overlap** ranks overlaps by their area or length on the same ellipsoid. +The same WGS 84 measure backs the attribute table's **Calculate Geometry** (`edit.calculateGeometry`), the [expressions](expressions.md#values)' `$area`, `$perimeter` and `$length`, the map's **Measure** tools on the Earth, and every network tool's edge and route lengths, so all of these read the same number for the same geometry, with one exception. A polygon ring with a full-turn