Repository navigation
fix(geom): preserve unwrapped Mercator geometry and bound world extents #1001
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
686a381
94b6d92
4e94638
5f5fcdc
eb349c0
2a72752
511c75b
f02b08f
45a901a
7131b54
6698418
56d579c
c9f8d88
6914c37
2f6db78
9f95071
ffcbf7c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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() { | ||
| 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, ¶ms).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); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bugs / quality (high confidence):
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. | ||
|
|
@@ -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() { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Test coverage (high confidence): the sliver assertions pass on
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. | ||
|
|
||
There was a problem hiding this comment.
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 incrates/geom/src/lib.rs), andlonlat_to_mercandextent_to_mercfor sub-360° spans are unchanged frommain. Soedit.move,edit.rotateandedit.scaleon 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 onmain.There was a problem hiding this comment.
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.