Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
686a381
measure on the WGS 84 ellipsoid everywhere lengths and areas are name…
subarna-kandel Oct 26, 2026
94b6d92
fix(geom): address review of the WGS 84 measures
subarna-kandel Oct 27, 2026
4e94638
Merge branch 'main' into fix/939-wgs84-measures-rebased
giswqs Oct 27, 2026
5f5fcdc
fix(geom): test polar and band rings, and measure the ring once
giswqs Oct 27, 2026
eb349c0
fix(geom): reject broken vertices in short WGS 84 rings
giswqs Oct 27, 2026
2a72752
fix(geom): keep a two-vertex ring's perimeter as 2d
giswqs Oct 27, 2026
511c75b
Merge branch 'main' into fix/939-wgs84-measures-rebased
giswqs Oct 27, 2026
f02b08f
fix(geom): correct the perimeter test and document polar rings
giswqs Oct 27, 2026
45a901a
docs(analysis): name the measures not yet on WGS 84
giswqs Oct 27, 2026
7131b54
fix(analysis): reject NaN route ends; document polar measures
giswqs Oct 27, 2026
6698418
fix(analysis): keep broken segments out of the route snap
giswqs Oct 27, 2026
56d579c
test(analysis,engine): pin the ellipsoid lengths; docs: Spatial Join …
subarna-kandel Oct 28, 2026
c9f8d88
fix(geom): lonlat_to_merc folds a longitude outside -180..180 into th…
subarna-kandel Oct 26, 2026
6914c37
fix(geom): review fixes for WGS 84 measures and antimeridian shapes
giswqs Oct 27, 2026
2f6db78
fix(geom,analysis): measure parallel rings once, project points unfolded
giswqs Oct 27, 2026
9f95071
fix(geom): keep lonlat_to_merc unwrapped; fold only single points wit…
subarna-kandel Oct 28, 2026
ffcbf7c
fix(geom): preserve unwrapped Mercator geometry and bound world extents
Mavrick-F Nov 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions crates/analysis/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use geo::{Coord as GC, LineString, MultiLineString, MultiPoint, MultiPolygon, Po
use rustgis_data::Geometry;
use rustgis_geom::{Coord, lonlat_to_merc, merc_to_lonlat};

/// Projects without folding the longitude: a ring kept unwrapped across the antimeridian (as a
/// geodesic buffer is) stays one piece, rather than folding its far vertex across the world.
fn gc(c: Coord) -> GC<f64> {
let m = lonlat_to_merc(c);
GC { x: m.x, y: m.y }
Expand Down Expand Up @@ -79,3 +81,24 @@ pub fn from_line(ml: &MultiLineString<f64>) -> Option<Geometry> {
pub fn from_point(p: &Point<f64>) -> Geometry {
Geometry::Point(back(&p.0))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn an_antimeridian_ring_stays_a_sliver_through_geo() {
// Unwrapped across the antimeridian (179.9° to 180.1°): about 22 km wide in Mercator, not
// a band folded to the far west, and it comes back to the same longitudes.
let ring =
vec![Coord::new(179.9, 0.0), Coord::new(180.1, 0.0), Coord::new(180.1, 1.0), Coord::new(179.9, 1.0), Coord::new(179.9, 0.0)];
let mp = to_multipolygon(&Geometry::Polygon(vec![vec![ring.clone()]])).unwrap();
let xs: Vec<f64> = mp.0.iter().flat_map(|p| p.exterior().0.iter().map(|c| c.x)).collect();
let width = xs.iter().copied().fold(f64::NEG_INFINITY, f64::max) - xs.iter().copied().fold(f64::INFINITY, f64::min);
assert!(width > 20_000.0 && width < 25_000.0, "{width}");
let back: Vec<Coord> = mp.0.iter().flat_map(|p| p.exterior().0.iter().map(|c| merc_to_lonlat(Coord::new(c.x, c.y)))).collect();
for (a, b) in ring.iter().zip(back.iter()) {
assert!((a.x - b.x).abs() < 1e-9 && (a.y - b.y).abs() < 1e-9, "{a:?} → {b:?}");
}
}
}
13 changes: 13 additions & 0 deletions crates/analysis/src/topology.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,19 @@ mod tests {
assert_eq!(explode(&Geometry::MultiPoint(vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)])).len(), 2);
}

#[test]
fn a_point_across_the_antimeridian_is_covered_by_its_polygon() {
// A polygon kept unwrapped (179.9° to 180.1°) covers a point at 180.05°, which is -179.95° once
// folded: the point is covered, not reported as outside the polygon.
let ring =
vec![Coord::new(179.9, 0.0), Coord::new(180.1, 0.0), Coord::new(180.1, 1.0), Coord::new(179.9, 1.0), Coord::new(179.9, 0.0)];
let mut ds = Dataset::new("p", GeometryType::Polygon, vec![]);
ds.push(Some(Geometry::Polygon(vec![vec![ring]])), vec![]);
let mut pts = Dataset::new("pt", GeometryType::Point, vec![]);
pts.push(Some(Geometry::Point(Coord::new(180.05, 0.5))), vec![]);
assert!(not_covered(&pts, &[0], &ds).errors.is_empty());
}

#[test]
fn long_paths_are_checked_not_skipped() {
// 10,000 segments zigzagging east without crossing...
Expand Down
37 changes: 37 additions & 0 deletions crates/engine/tests/antimeridian_edit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//! Editing a shape kept unwrapped across 180° (as a geodesic buffer returns one) keeps it narrow (#940).

use rustgis_engine::{
Project, Session,
data::{Dataset, Feature, Field, FieldType, Geometry, GeometryType, Value},
geom::Coord,
};
use serde_json::json;

/// A selected, editable polygon with unwrapped antimeridian coordinates.
fn across_180() -> (Session, u32) {
let c = Coord::new;
let ring = vec![c(179.6, 10.0), c(180.2, 10.0), c(180.2, 10.3), c(179.6, 10.3), c(179.6, 10.0)];
let mut data = Dataset::new("Across", GeometryType::Polygon, vec![Field::new("n", FieldType::Integer)]);
data.features = vec![Feature { id: 1, geometry: Some(Geometry::Polygon(vec![vec![ring]])), attrs: vec![Value::Int(0)] }].into();
let mut s = Session::new(Project::new("Across 180"));
let id = s.map_mut().add_dataset(data);
s.active_layer = Some(id);
s.map_mut().editing.settings.enabled = true;
s.map_mut().layer_mut(id).unwrap().selection = vec![0];
(s, id)
}

#[test]
fn small_edits_keep_a_polygon_across_180_narrow() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test coverage (high confidence): this test does not guard the change. Nothing in the edit path calls lonlat_to_merc_folded (it is referenced only in crates/geom/src/lib.rs), and lonlat_to_merc and extent_to_merc for sub-360° spans are unchanged from main. So edit.move, edit.rotate and edit.scale on an unwrapped polygon should already keep it narrow on the base branch. If the intent is to pin current behaviour for #940, say so in the doc comment. If it is meant to catch the fix, it needs a case that fails on main.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this intentionally pins existing behavior on main. It reproduces the human reviewer’s counterexample against the earlier folding commits and verifies that all three real edit commands change coordinates without widening the geometry across the world. The module comment states that continuity contract. Retaining it prevents a future accidental migration of shape vertices to the folded-point API.

for (cmd, params) in
[("edit.move", json!({"dx": 1000.0, "dy": 0.0})), ("edit.rotate", json!({"angle": 10.0})), ("edit.scale", json!({"factor": 1.01}))]
{
let (mut s, id) = across_180();
let before = s.map().layer(id).unwrap().dataset.features[0].geometry.clone();
s.run(cmd, &params).unwrap();
assert_ne!(s.map().layer(id).unwrap().dataset.features[0].geometry, before, "{cmd} must change coordinates");
let Some(Geometry::Polygon(p)) = &s.map().layer(id).unwrap().dataset.features[0].geometry else { panic!("{cmd}") };
let (lo, hi) = p[0][0].iter().fold((f64::MAX, f64::MIN), |(a, b), c| (a.min(c.x), b.max(c.x)));
assert!(hi - lo < 1.0, "{cmd}: the polygon is now {:.1}° wide", hi - lo);
}
}
76 changes: 73 additions & 3 deletions crates/geom/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,25 +146,46 @@ impl Extent {
}
}

/// Longitude/latitude (degrees) → Web Mercator metres. Latitude is clamped to ±85.05°.
/// Longitude/latitude (degrees) → Web Mercator metres, without folding the longitude: one past
/// ±180° lands past the world's edge (±20,037,508.34 m), so a shape kept unwrapped across the
/// antimeridian (as `geodesic_interpolate` and `Aeqd::inverse` keep one, and a geodesic buffer
/// returns) stays the sliver it is, and `merc_to_lonlat` returns the longitude it was given. Edits,
/// overlays and hulls rely on that. Latitude is clamped to ±85.05°. A caller that needs one point
/// inside the world uses [`lonlat_to_merc_folded`] (#940).
pub fn lonlat_to_merc(c: Coord) -> Coord {
let lat = c.y.clamp(-MAX_LAT, MAX_LAT).to_radians();
Coord::new(MERCATOR_R * c.x.to_radians(), MERCATOR_R * (std::f64::consts::FRAC_PI_4 + lat / 2.0).tan().ln())
}

/// Like [`lonlat_to_merc`], but a longitude outside −180..180 folds into that range, so a single
/// point projects onto the world, never metres past its edge. Do not project the vertices of a
/// shape with it: an edge from 179.9° to 180.1° would become one across the whole map. A
/// non-finite longitude stays broken rather than quietly becoming the prime meridian.
pub fn lonlat_to_merc_folded(c: Coord) -> Coord {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bugs / quality (high confidence): lonlat_to_merc_folded has no callers outside its own geom test. The fold the PR title and body describe is therefore not wired into any code path, and the body's first bullet ("a finite longitude now folds… 185° projects where -175° does") describes lonlat_to_merc, which does not fold in this head. The body also cites mercator_folds_longitudes_outside_the_world, which does not exist; the test here is mercator_keeps_longitudes_outside_the_world_unless_folded. Either wire the folded variant into the single-point callers that need it, or drop it. Update the title and body to match the final commit.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The title and description now describe the final unwrapped geometry contract. The folded helper is an explicit public point-projection alternative, rather than a migration of existing geometry callers; those callers require unwrapped coordinates. The description lists the actual regressions and removes the obsolete folding claims.

Published in ffcbf7c8; full local CI, wasm build and all pre-commit checks passed.

let lon = if !c.x.is_finite() || (c.x >= -180.0 && c.x <= 180.0) { c.x } else { wrap_lon(c.x % 360.0) };
lonlat_to_merc(Coord::new(lon, c.y))
}

/// Web Mercator metres → longitude/latitude (degrees).
pub fn merc_to_lonlat(c: Coord) -> Coord {
let lon = (c.x / MERCATOR_R).to_degrees();
let lat = (2.0 * (c.y / MERCATOR_R).exp().atan() - std::f64::consts::FRAC_PI_2).to_degrees();
Coord::new(lon, lat)
}

/// Projects a lon/lat extent to Web Mercator.
/// Projects a lon/lat extent to Web Mercator, preserving unwrapped longitudes for spans below
/// 360°. A span of a full turn or more maps to the standard world bounds.
pub fn extent_to_merc(e: &Extent) -> Extent {
if e.is_empty() {
return *e;
}
Extent::from_points(lonlat_to_merc(Coord::new(e.min_x, e.min_y)), lonlat_to_merc(Coord::new(e.max_x, e.max_y)))
// Preserve an unwrapped antimeridian extent instead of folding its corners separately.
// A full turn or more covers the world, independent of the starting longitude.
let (sw, ne) = (lonlat_to_merc(Coord::new(e.min_x, e.min_y)), lonlat_to_merc(Coord::new(e.max_x, e.max_y)));
let world = MERCATOR_R * std::f64::consts::PI;
let (west, east) =
if e.max_x.is_finite() && e.min_x.is_finite() && e.max_x - e.min_x >= 360.0 { (-world, world) } else { (sw.x, ne.x) };
Extent::from_points(Coord::new(west, sw.y), Coord::new(east, ne.y))
}

/// Great-circle distance between two lon/lat points (metres); NaN for non-finite coordinates.
Expand Down Expand Up @@ -489,6 +510,55 @@ mod tests {
assert!(wgs84_distance_m(c(0.0, f64::NEG_INFINITY), c(0.0, 0.0)).is_nan());
}

#[test]
fn an_extent_across_the_antimeridian_stays_a_sliver() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test coverage (high confidence): the sliver assertions pass on main too. For spans under 360°, extent_to_merc and lonlat_to_merc are unchanged from main. lonlat_to_merc never folds, so extent_to_merc(179.9..180.1) already gives a ~22 km width on the base branch. Only the full-turn assertions (-540..540 and 0..360) guard the one production change in this PR. The same holds for an_antimeridian_ring_stays_a_sliver_through_geo in crates/analysis/src/convert.rs, which calls lonlat_to_merc. Worth either adding a base-failing case or saying in the test doc that these pin existing behaviour.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These deliberately pin the existing unwrapped projection contract selected for #940, including the earlier regression where folding each vertex widened a narrow shape across the world. The full-turn assertions exercise the changed extent behavior; the separate folded-point assertions exercise the added API and huge-longitude fix. I am retaining the contract coverage alongside those behavior-change cases.

// A geodesic buffer near 180° comes back unwrapped (179.9° to 180.1°): about 22 km wide, not
// the whole world.
let e = extent_to_merc(&Extent::new(179.9, 0.0, 180.1, 1.0));
assert!(e.width() > 20_000.0 && e.width() < 25_000.0, "{}", e.width());
// Inside the world nothing changes; a wider-than-world extent is the world.
let plain = extent_to_merc(&Extent::new(-10.0, 0.0, 10.0, 1.0));
assert!((plain.width() - 2.0 * MERCATOR_R * 10f64.to_radians()).abs() < 1e-6);
let all = extent_to_merc(&Extent::new(-540.0, 0.0, 540.0, 1.0));
assert!((all.width() - 2.0 * MERCATOR_R * std::f64::consts::PI).abs() < 1e-6);
// A full turn from Greenwich is the world too, at the world's edges, not 0 to twice the edge.
let turn = extent_to_merc(&Extent::new(0.0, 0.0, 360.0, 1.0));
let world = MERCATOR_R * std::f64::consts::PI;
assert!((turn.min_x + world).abs() < 1e-6 && (turn.max_x - world).abs() < 1e-6, "{turn:?}");
}

#[test]
fn mercator_keeps_longitudes_outside_the_world_unless_folded() {
// Unwrapped, 185° round-trips (an edit of a shape across the antimeridian stays narrow).
let past = lonlat_to_merc(Coord::new(185.0, 0.0));
assert!((merc_to_lonlat(past).x - 185.0).abs() < 1e-9);
assert!(past.x > MERCATOR_R * std::f64::consts::PI);
// Folded, 185° is -175° on the world: the same place, never past its edge.
let folded = lonlat_to_merc_folded(Coord::new(185.0, 0.0));
let there = lonlat_to_merc(Coord::new(-175.0, 0.0));
assert!((folded.x - there.x).abs() < 1e-6 && folded.y == there.y);
assert!(folded.x.abs() <= MERCATOR_R * std::f64::consts::PI, "{}", folded.x);
// Reduce the longitude before adding 180 degrees: at 2^60 that addition loses bits.
for lon in [2f64.powi(60), -2f64.powi(60), f64::MAX, -f64::MAX, -540.0, -180.0, 180.0, 540.0] {
let reduced = lon % 360.0;
let expected = if reduced > 180.0 {
reduced - 360.0
} else if reduced < -180.0 {
reduced + 360.0
} else {
reduced
};
let actual = lonlat_to_merc_folded(Coord::new(lon, 0.0));
// Either sign of 180 degrees denotes the seam.
let delta = (merc_to_lonlat(actual).x - expected).abs();
assert!(delta < 1e-9 || (delta - 360.0).abs() < 1e-9, "{lon}: {actual:?}");
assert!(actual.x.abs() <= MERCATOR_R * std::f64::consts::PI);
}
// A broken longitude stays broken, never a plausible place near Greenwich.
assert!(lonlat_to_merc_folded(Coord::new(f64::NAN, 0.0)).x.is_nan());
assert!(lonlat_to_merc_folded(Coord::new(f64::INFINITY, 0.0)).x.is_infinite());
}

#[test]
fn wgs84_near_hemisphere_rings_keep_the_spherical_side() {
// Both sides of the equator: the spherical and ellipsoidal hemisphere areas differ.
Expand Down
Loading