From 6e5616ce8c98013aeb63b11a65c31f23e1f53ef0 Mon Sep 17 00:00:00 2001 From: Josh Date: Wed, 11 Nov 2026 02:05:47 -0700 Subject: [PATCH 1/3] fix(data): read Natural Earth, Winkel Tripel and Eckert IV from WKT (#1701) RustGIS draws maps in these three projections and writes them as WKT, but couldn't read them back. read_wkt had no arm for their names, and every custom system is checked through proj4rs, which doesn't define natearth, wintri or eck4. So a file in one of them, and the ESRI codes 54077, 53077, 54012 and 53012, was read as longitude/latitude with a note. The formulas move from rustgis-map's world module to rustgis_geom::world, as Sinusoidal is. They gain the false easting and northing and Winkel Tripel's standard parallel. World::new gives what the map computed before, and rustgis-map re-exports the module, so the map draws as it did. crs.rs gets a transformer kind for the three, built like the ellipsoidal equidistant cylindrical one: the projection on a sphere of the datum's semi-major axis (or +R), as PROJ computes these, and the datum applied on longitude/latitude by proj4rs. Axes other than east and north, +over, a scale other than 1 and a standard parallel at a pole are refused. wkt.rs reads Natural_Earth, Winkel_Tripel and Eckert_IV (and WKT2's and Esri's names for them). Winkel Tripel's parallel is the file's, else Winkel's own, acos(2/pi), as the map draws a definition without one. The writer's comment called that PROJ's default; PROJ 9.8.1 takes 0, so the comment is corrected. --- crates/data/src/raster/crs.rs | 101 +++++++++++- crates/data/src/raster/wkt.rs | 111 +++++++++++-- crates/geom/src/lib.rs | 1 + crates/geom/src/world.rs | 289 ++++++++++++++++++++++++++++++++++ crates/map/src/projection.rs | 2 +- crates/map/src/world.rs | 242 +--------------------------- docs/user-guide/data.md | 6 +- 7 files changed, 502 insertions(+), 250 deletions(-) create mode 100644 crates/geom/src/world.rs diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index 2707790be5..9140e3b63a 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -206,8 +206,9 @@ pub(crate) fn proj_key_refused(key: &str, val: &str) -> bool { impl Crs { /// A file's own coordinate system: checked (its PROJ definition must parse, or be a - /// projection RustGIS computes: a sinusoidal one, or an equidistant cylindrical one on an - /// ellipsoid) and added to the run's table, once per definition. + /// projection RustGIS computes: a sinusoidal one, an equidistant cylindrical one on an + /// ellipsoid, or Natural Earth, Winkel Tripel or Eckert IV) and added to the run's table, once + /// per definition. pub fn custom(def: CustomCrs) -> Result { Crs::register(def, false) } @@ -418,6 +419,9 @@ pub(crate) fn transformer_of(def: &str) -> Result { if let Some(eqc) = ellipsoidal_eqc(def) { return eqc; } + if let Some(world) = WorldProjection::from_proj4(def) { + return world.and_then(|w| Ok(Transformer { kind: Kind::World { world: Box::new(w), wgs84: Box::new(wgs84()?) } })); + } let native = proj4rs::Proj::from_proj_string(def).map_err(|e| e.to_string())?; let geographic = def.contains("+proj=longlat"); Ok(Transformer { kind: Kind::Proj { native: Box::new(native), wgs84: Box::new(wgs84()?), geographic } }) @@ -576,6 +580,95 @@ impl EllipsoidalEqc { } } +/// A world projection proj4rs lacks (Natural Earth, Winkel Tripel, Eckert IV), computed by +/// `rustgis_geom::world` on a sphere of its datum's semi-major axis (or `+R`), as PROJ does for +/// these spherical projections. Its datum (ellipsoid, shift to WGS 84, prime meridian) is kept for +/// the datum transformation on longitude/latitude, as for [`EllipsoidalEqc`] (#1701). +#[derive(Clone)] +struct WorldProjection { + world: rustgis_geom::world::World, + /// Longitude/latitude on the projection's own datum and prime meridian. + geo: proj4rs::Proj, + /// Metres per unit of its coordinates. + to_meter: f64, +} + +impl WorldProjection { + /// The projection a PROJ definition describes when it is `+proj=natearth`, `wintri` or + /// `eck4`: `None` for any other; an error for one it can't compute (axes other than east and + /// north, `+over`, a scale other than 1, a standard parallel that isn't a latitude short of a + /// pole). Winkel Tripel's parallel is `+lat_1`, else Winkel's own + /// ([`rustgis_geom::world::winkel_parallel`]), as the map draws it. + fn from_proj4(def: &str) -> Option> { + use rustgis_geom::world::Kind as W; + let tokens: Vec<(&str, &str)> = + def.split_whitespace().map(|t| t.trim_start_matches('+')).map(|t| t.split_once('=').unwrap_or((t, ""))).collect(); + let name = tokens.iter().find(|(k, _)| *k == "proj").map(|(_, v)| *v)?; + let kind = match name { + "natearth" => W::NaturalEarth, + "wintri" => W::WinkelTripel, + "eck4" => W::EckertIV, + _ => return None, + }; + Some((|| { + if tokens.iter().any(|(k, v)| (*k == "k" || *k == "k_0") && v.parse::().ok() != Some(1.0)) { + return Err("a world projection with a scale other than 1 isn't supported".to_string()); + } + let lat1 = match tokens.iter().find(|(k, _)| *k == "lat_1") { + Some((_, v)) => v + .parse::() + .ok() + .filter(|v| v.is_finite() && v.abs() < 90.0) + .ok_or_else(|| format!("+lat_1={v} isn't a latitude short of a pole"))?, + None => rustgis_geom::world::winkel_parallel(), + }; + // proj4rs reads what every projection shares (centre, offsets, unit, axes, datum) from + // the same definition with a projection it has, the equidistant cylindrical, in place. + let stand_in: Vec = def + .split_whitespace() + .filter(|t| !t.trim_start_matches('+').starts_with("lat_1=")) + .map(|t| if t.trim_start_matches('+') == format!("proj={name}") { "+proj=eqc".to_string() } else { t.to_string() }) + .collect(); + let stand_in = stand_in.join(" "); + let native = proj4rs::Proj::from_proj_string(&stand_in).map_err(|e| e.to_string())?; + if !native.is_normalized_axis() || tokens.iter().any(|(k, _)| *k == "over") { + return Err("a world projection takes axes east and north only, with no +over".to_string()); + } + let geo = eqc_geographic(&stand_in)?; + let (a, _) = geo.ellipse_parameters(); + let to_meter = native.to_meter(); + if !(a.is_finite() && a > 0.0 && to_meter.is_finite() && to_meter > 0.0) { + return Err("its earth or unit isn't usable".to_string()); + } + let world = rustgis_geom::world::World { + kind, + lon0: native.longitude_of_origin().to_degrees(), + radius: a, + x0: native.false_easting(), + y0: native.false_northing(), + lat1, + }; + Ok(WorldProjection { world, geo, to_meter }) + })()) + } + + /// Its coordinates to longitude/latitude on its datum, then to WGS 84. + fn unproject(&self, wgs84: &proj4rs::Proj, c: Coord) -> Option { + let own = self.world.inverse(Coord::new(c.x * self.to_meter, c.y * self.to_meter))?; + let mut p = (own.x.to_radians(), own.y.to_radians(), 0.0); + proj4rs::transform::transform(&self.geo, wgs84, &mut p).ok()?; + Some(Coord::new(p.0.to_degrees(), p.1.to_degrees())) + } + + /// WGS 84 longitude/latitude to its datum's, then to its coordinates. + fn project(&self, wgs84: &proj4rs::Proj, c: Coord) -> Option { + let mut p = (c.x.to_radians(), c.y.to_radians(), 0.0); + proj4rs::transform::transform(wgs84, &self.geo, &mut p).ok()?; + let m = self.world.forward(Coord::new(p.0.to_degrees(), p.1.to_degrees()))?; + Some(Coord::new(m.x / self.to_meter, m.y / self.to_meter)) + } +} + #[derive(Clone)] enum Kind { LonLat, @@ -583,6 +676,7 @@ enum Kind { Proj { native: Box, wgs84: Box, geographic: bool }, Sinusoidal(rustgis_geom::Sinusoidal), Eqc { eqc: Box, wgs84: Box }, + World { world: Box, wgs84: Box }, } /// Converts between a raster's coordinates and WGS 84 longitude/latitude. @@ -599,6 +693,7 @@ impl std::fmt::Debug for Transformer { Kind::Proj { .. } => "proj", Kind::Sinusoidal(_) => "sinusoidal", Kind::Eqc { .. } => "eqc", + Kind::World { .. } => "world", }; write!(f, "Transformer({k})") } @@ -617,6 +712,7 @@ impl Transformer { } Kind::Sinusoidal(s) => s.inverse(c)?, Kind::Eqc { eqc, wgs84 } => eqc.unproject(wgs84, c)?, + Kind::World { world, wgs84 } => world.unproject(wgs84, c)?, }; out.is_finite().then_some(out) } @@ -644,6 +740,7 @@ impl Transformer { } Kind::Sinusoidal(s) => s.forward(c)?, Kind::Eqc { eqc, wgs84 } => eqc.project(wgs84, c)?, + Kind::World { world, wgs84 } => world.project(wgs84, c)?, }; out.is_finite().then_some(out) } diff --git a/crates/data/src/raster/wkt.rs b/crates/data/src/raster/wkt.rs index 1898f07741..3b2b66845f 100644 --- a/crates/data/src/raster/wkt.rs +++ b/crates/data/src/raster/wkt.rs @@ -1351,6 +1351,12 @@ fn custom(p: &Node, method: &str) -> Result { // from Robinson's table, on a sphere of the semi-major axis as in PROJ. "SINUSOIDAL" => format!("+proj=sinu {at}"), "ROBINSON" => format!("+proj=robin {at}"), + // Computed by RustGIS too (`rustgis_geom::world`), on a sphere of the semi-major axis as in + // PROJ (#1701). Winkel Tripel's standard parallel is the file's (GDAL and PROJ always + // write one), else Winkel's own, as RustGIS draws and writes it. + "NATURAL_EARTH" => format!("+proj=natearth {at}"), + "ECKERT_IV" => format!("+proj=eck4 {at}"), + "WINKEL_TRIPEL" => format!("+proj=wintri +lat_1={} {at}", lat1.unwrap_or_else(rustgis_geom::world::winkel_parallel)), // EPSG's method 9840, on the ellipsoid (proj4rs follows the EPSG Guidance Note 7-2). Esri's // Orthographic is a spherical one: on a sphere they agree, on an ellipsoid they don't, and // which one an Esri file means can't be told, so that is refused rather than guessed. @@ -1375,9 +1381,15 @@ fn custom(p: &Node, method: &str) -> Result { flip = Some("wsu"); } let axis = match flip { - // The projections RustGIS computes itself (sinusoidal, and equidistant cylindrical on an - // ellipsoid) don't take `+axis`, and `Crs::custom` would refuse their definition. - Some(_) if proj.starts_with("+proj=sinu") || (proj.starts_with("+proj=eqc") && !sphere) => return Err(REVERSED_AXES.into()), + // The projections RustGIS computes itself (sinusoidal, the world projections proj4rs lacks, + // and equidistant cylindrical on an ellipsoid) don't take `+axis`, and `Crs::custom` would + // refuse their definition. + Some(_) + if ["+proj=sinu", "+proj=natearth", "+proj=wintri", "+proj=eck4"].iter().any(|p| proj.starts_with(p)) + || (proj.starts_with("+proj=eqc") && !sphere) => + { + return Err(REVERSED_AXES.into()); + } flip => flip.map(|a| format!(" +axis={a}")).unwrap_or_default(), }; let label = match p.title().trim() { @@ -1666,9 +1678,9 @@ pub fn proj4_to_wkt(def: &str, name: &str) -> Option { /// A PROJ definition as WKT1, with `code` as its EPSG authority. fn def_wkt(def: &str, name: &str, code: Option) -> Option { - // proj4rs doesn't project the world projections RustGIS computes itself (rustgis-map's - // `world`): their ellipsoid, prime meridian and unit are read from the definition as a - // geographic one. + // proj4rs doesn't project the world projections RustGIS computes itself + // (`rustgis_geom::world`): their ellipsoid, prime meridian and unit are read from the + // definition as a geographic one. let proj = proj4rs::Proj::from_proj_string(def).ok().or_else(|| { let kind = def.split_whitespace().find_map(|t| t.strip_prefix("+proj="))?; if !matches!(kind, "natearth" | "wintri" | "eck4") { @@ -1925,10 +1937,11 @@ fn def_wkt(def: &str, name: &str, code: Option) -> Option { ps = vec![("central_meridian", lon0)]; "Eckert_IV" } - // Its standard parallel is PROJ's default, Aitoff's and Hammer's parallel of acos(2/π) - // (about 50.46°), unless the definition gives one. + // Its standard parallel is the definition's, else Winkel's own of acos(2/π) (about + // 50.46°), the one the map draws a definition without one in. PROJ 9.8.1 takes 0 there, + // so it is always written. "wintri" => { - let lat1 = get("lat_1").unwrap_or_else(|| std::f64::consts::FRAC_2_PI.acos().to_degrees()); + let lat1 = get("lat_1").unwrap_or_else(rustgis_geom::world::winkel_parallel); ps = vec![("standard_parallel_1", lat1), ("central_meridian", lon0)]; "Winkel_Tripel" } @@ -2124,6 +2137,86 @@ pub(crate) mod tests { assert_eq!(proj4_to_wkt("+proj=nosuch +datum=WGS84 +units=m +no_defs", "X"), None); } + /// The world projections RustGIS computes itself are read from WKT as GDAL (WKT1), Esri and + /// PROJ (WKT2) write them, and from their ESRI codes (a FileGDB feature class's), not as + /// longitude/latitude: each places a point where PROJ 9.8.1 does, within a millimetre, and + /// back, with Winkel Tripel's standard parallel the file's. RustGIS's own WKT for its presets + /// reads back to the system it was written from (#1701). + #[test] + fn world_projections_are_read() { + let places = |crs: Crs, what: &str, points: &[((f64, f64), (f64, f64))]| { + let t = crs.transformer().unwrap_or_else(|e| panic!("{what}: {e}")); + for &((lon, lat), (x, y)) in points { + let m = t.from_lonlat(Coord::new(lon, lat)).unwrap(); + assert!((m.x - x).abs() < 1e-3 && (m.y - y).abs() < 1e-3, "{what} {lon},{lat}: {m:?}"); + let back = t.to_lonlat(Coord::new(x, y)).unwrap(); + assert!((back.x - lon).abs() < 1e-8 && (back.y - lat).abs() < 1e-8, "{what} {x},{y}: {back:?}"); + } + }; + // Centred on 60°W, offset by 100 m and -200 m; Winkel Tripel's parallel at 40°N. + for (wkt1, esri, wkt2, points) in [ + ( + r#"PROJCS["unknown",GEOGCS["unknown",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]]],PROJECTION["Natural_Earth"],PARAMETER["central_meridian",-60],PARAMETER["false_easting",100],PARAMETER["false_northing",-200],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH]]"#, + r#"PROJCS["unknown",GEOGCS["GCS_unknown",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Natural_Earth"],PARAMETER["False_Easting",100.0],PARAMETER["False_Northing",-200.0],PARAMETER["Central_Meridian",-60.0],UNIT["Meter",1.0]]"#, + r#"PROJCRS["unknown",BASEGEOGCRS["unknown",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]],ID["EPSG",6326]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8901]]],CONVERSION["unknown",METHOD["Natural Earth"],PARAMETER["Longitude of natural origin",-60,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8802]],PARAMETER["False easting",100,LENGTHUNIT["metre",1],ID["EPSG",8806]],PARAMETER["False northing",-200,LENGTHUNIT["metre",1],ID["EPSG",8807]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1,ID["EPSG",9001]]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1,ID["EPSG",9001]]]]"#, + [((10.0, 50.0), (5944996.452900967, 5606224.7555508325)), ((-120.0, -35.0), (-5473849.827720951, -3939478.50735193))], + ), + ( + r#"PROJCS["unknown",GEOGCS["unknown",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]]],PROJECTION["Eckert_IV"],PARAMETER["central_meridian",-60],PARAMETER["false_easting",100],PARAMETER["false_northing",-200],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH]]"#, + r#"PROJCS["unknown",GEOGCS["GCS_unknown",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Eckert_IV"],PARAMETER["False_Easting",100.0],PARAMETER["False_Northing",-200.0],PARAMETER["Central_Meridian",-60.0],UNIT["Meter",1.0]]"#, + r#"PROJCRS["unknown",BASEGEOGCRS["unknown",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]],ID["EPSG",6326]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8901]]],CONVERSION["unknown",METHOD["Eckert IV"],PARAMETER["Longitude of natural origin",-60,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8802]],PARAMETER["False easting",100,LENGTHUNIT["metre",1],ID["EPSG",8806]],PARAMETER["False northing",-200,LENGTHUNIT["metre",1],ID["EPSG",8807]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1,ID["EPSG",9001]]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1,ID["EPSG",9001]]]]"#, + [((10.0, 50.0), (5581773.315127191, 6071282.405990218)), ((-120.0, -35.0), (-5221045.868366751, -4438772.808673019))], + ), + ( + r#"PROJCS["unknown",GEOGCS["unknown",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]]],PROJECTION["Winkel_Tripel"],PARAMETER["central_meridian",-60],PARAMETER["standard_parallel_1",40],PARAMETER["false_easting",100],PARAMETER["false_northing",-200],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH]]"#, + r#"PROJCS["unknown",GEOGCS["GCS_unknown",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Winkel_Tripel"],PARAMETER["False_Easting",100.0],PARAMETER["False_Northing",-200.0],PARAMETER["Central_Meridian",-60.0],PARAMETER["Standard_Parallel_1",40.0],UNIT["Meter",1.0]]"#, + r#"PROJCRS["unknown",BASEGEOGCRS["unknown",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]],ID["EPSG",6326]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8901]]],CONVERSION["unknown",METHOD["Winkel Tripel"],PARAMETER["Longitude of natural origin",-60,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8802]],PARAMETER["Latitude of 1st standard parallel",40,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8823]],PARAMETER["False easting",100,LENGTHUNIT["metre",1],ID["EPSG",8806]],PARAMETER["False northing",-200,LENGTHUNIT["metre",1],ID["EPSG",8807]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1,ID["EPSG",9001]]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1,ID["EPSG",9001]]]]"#, + [((10.0, 50.0), (5795783.3284553625, 5703113.4871610105)), ((-120.0, -35.0), (-5457165.906327649, -3978189.6516721374))], + ), + ] { + for wkt in [wkt1, esri, wkt2] { + let crs = crs_from_wkt(wkt).unwrap_or_else(|e| panic!("{e}: {wkt}")); + assert!(matches!(crs, Crs::Custom(_)), "{wkt}"); + places(crs, wkt, &points); + } + } + // World Natural Earth and Eckert IV on WGS 84, and on the spheres ESRI gives them. + for (code, points) in [ + (54077, [((10.0, 50.0), (849270.9218429951, 5606424.7555508325)), ((-120.0, -35.0), (-10947899.655441903, -3939278.50735193))]), + (54012, [((10.0, 50.0), (797381.9021610274, 6071482.405990218)), ((-120.0, -35.0), (-10442291.736733502, -4438572.808673019))]), + ( + 53077, + [((10.0, 50.0), (848321.7736396515, 5600158.995300423)), ((-120.0, -35.0), (-10935664.243842268, -3934875.9556790087))], + ), + ( + 53012, + [((10.0, 50.0), (796489.6487278191, 6064688.5459756795)), ((-120.0, -35.0), (-10430607.033798292, -4433606.139858049))], + ), + ] { + let crs = crate::filegdb::crs_of_code(code).unwrap_or_else(|| panic!("ESRI:{code}")); + places(crs, &format!("ESRI:{code}"), &points); + } + // The presets' WKT reads back to the presets: Winkel Tripel at Winkel's own parallel. + for def in [ + "+proj=natearth +lon_0=0 +datum=WGS84 +units=m +no_defs", + "+proj=wintri +lon_0=0 +datum=WGS84 +units=m +no_defs", + "+proj=eck4 +lon_0=0 +datum=WGS84 +units=m +no_defs", + ] { + let back = crs_from_wkt(&proj4_to_wkt(def, "World").unwrap()).unwrap().transformer().unwrap(); + let direct = crate::raster::crs::transformer_of(def).unwrap(); + for (lon, lat) in [(10.0, 50.0), (-120.0, -35.0), (179.0, 80.0)] { + let (a, b) = (back.from_lonlat(Coord::new(lon, lat)).unwrap(), direct.from_lonlat(Coord::new(lon, lat)).unwrap()); + assert!((a.x - b.x).abs() < 1e-6 && (a.y - b.y).abs() < 1e-6, "{def} {lon},{lat}: {a:?} {b:?}"); + } + } + // Axes pointing west aren't read, as for the other projections RustGIS computes; a + // standard parallel at a pole isn't a Winkel Tripel. + let wkt1 = r#"PROJCS["unknown",GEOGCS["unknown",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]]],PROJECTION["Natural_Earth"],PARAMETER["central_meridian",-60],PARAMETER["false_easting",100],PARAMETER["false_northing",-200],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH]]"#; + assert_eq!(crs_from_wkt(&wkt1.replace(r#"AXIS["Easting",EAST]"#, r#"AXIS["Easting",WEST]"#)), Err(REVERSED_AXES.into())); + let wintri = r#"PROJCS["unknown",GEOGCS["unknown",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]]],PROJECTION["Winkel_Tripel"],PARAMETER["central_meridian",-60],PARAMETER["standard_parallel_1",40],PARAMETER["false_easting",100],PARAMETER["false_northing",-200],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH]]"#; + assert!(crs_from_wkt(&wintri.replace(r#""standard_parallel_1",40"#, r#""standard_parallel_1",90"#)).is_err()); + } + #[test] fn epsg_authority() { let wkt = r#"PROJCS["anything",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["central_meridian",-81],UNIT["metre",1],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","32617"]]"#; diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 366bed0974..100dc87cd1 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -11,6 +11,7 @@ pub mod eqc; pub mod sinusoidal; pub mod triangulate; pub mod utm; +pub mod world; pub use body::{BODIES, Body}; pub use eqc::EquidistantCylindrical; diff --git a/crates/geom/src/world.rs b/crates/geom/src/world.rs new file mode 100644 index 0000000000..9464831587 --- /dev/null +++ b/crates/geom/src/world.rs @@ -0,0 +1,289 @@ +//! World map projections computed here, on a sphere: Robinson, Equal Earth, Natural Earth, Winkel +//! Tripel and Eckert IV. The map draws in them (rustgis-map's `Projector`, on a sphere of the WGS +//! 84 equatorial radius unless the definition gives `+R`), and a file's coordinate system in the +//! three proj4rs lacks (Natural Earth, Winkel Tripel, Eckert IV) is read with them, on a sphere of +//! its datum's semi-major axis as in PROJ (opengeos/RustGIS#1701). +//! +//! The forward formulas follow the projections' published definitions. Inverses use Newton's +//! method on the forward formula, which also rejects points outside the map's outline (no +//! longitude/latitude maps to them). + +use crate::Coord; + +/// A world projection (PROJ names: `robin`, `eqearth`, `natearth`, `wintri`, `eck4`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Robinson, + EqualEarth, + NaturalEarth, + WinkelTripel, + EckertIV, +} + +impl Kind { + pub fn from_proj_name(name: &str) -> Option { + Some(match name { + "robin" => Kind::Robinson, + "eqearth" => Kind::EqualEarth, + "natearth" => Kind::NaturalEarth, + "wintri" => Kind::WinkelTripel, + "eck4" => Kind::EckertIV, + _ => return None, + }) + } + + pub fn proj_name(self) -> &'static str { + match self { + Kind::Robinson => "robin", + Kind::EqualEarth => "eqearth", + Kind::NaturalEarth => "natearth", + Kind::WinkelTripel => "wintri", + Kind::EckertIV => "eck4", + } + } +} + +/// Winkel's own standard parallel for his Tripel, acos(2/π) (about 50.46°, degrees): the one the +/// map draws a Winkel Tripel without one in, and RustGIS writes for it. PROJ 9.8.1 takes 0 for a +/// definition without `+lat_1`; GDAL and PROJ always write the parallel in WKT, so a file says +/// which. +pub fn winkel_parallel() -> f64 { + std::f64::consts::FRAC_2_PI.acos().to_degrees() +} + +/// Robinson's table: (X, Y) every 5° of latitude from 0° to 90°. +const ROBINSON: [(f64, f64); 19] = [ + (1.0000, 0.0000), + (0.9986, 0.0620), + (0.9954, 0.1240), + (0.9900, 0.1860), + (0.9822, 0.2480), + (0.9730, 0.3100), + (0.9600, 0.3720), + (0.9427, 0.4340), + (0.9216, 0.4958), + (0.8962, 0.5571), + (0.8679, 0.6176), + (0.8350, 0.6769), + (0.7986, 0.7346), + (0.7597, 0.7903), + (0.7186, 0.8435), + (0.6732, 0.8936), + (0.6213, 0.9394), + (0.5722, 0.9761), + (0.5322, 1.0000), +]; + +/// Robinson's X and Y at |latitude| in degrees, by cubic (Catmull-Rom) interpolation. +fn robinson_xy(lat_deg: f64) -> (f64, f64) { + let t = (lat_deg.abs() / 5.0).clamp(0.0, 18.0); + let i = (t.floor() as usize).min(17); + let f = t - i as f64; + let at = |k: isize| { + // Mirror at the equator and extend linearly past the pole. + let k = k.clamp(-1, 19); + match k { + -1 => (ROBINSON[1].0, -ROBINSON[1].1), + 19 => (2.0 * ROBINSON[18].0 - ROBINSON[17].0, 2.0 * ROBINSON[18].1 - ROBINSON[17].1), + k => ROBINSON[k as usize], + } + }; + let (p0, p1, p2, p3) = (at(i as isize - 1), at(i as isize), at(i as isize + 1), at(i as isize + 2)); + let cr = |a: f64, b: f64, c: f64, d: f64| { + 0.5 * (2.0 * b + (-a + c) * f + (2.0 * a - 5.0 * b + 4.0 * c - d) * f * f + (-a + 3.0 * b - 3.0 * c + d) * f * f * f) + }; + (cr(p0.0, p1.0, p2.0, p3.0), cr(p0.1, p1.1, p2.1, p3.1)) +} + +/// Forward projection of (λ, φ) in radians, as multiples of the radius. `cos_phi1` is the cosine +/// of Winkel Tripel's standard parallel; the others don't use it. +fn unit_forward(kind: Kind, lam: f64, phi: f64, cos_phi1: f64) -> (f64, f64) { + match kind { + Kind::Robinson => { + let (x, y) = robinson_xy(phi.to_degrees()); + (0.8487 * x * lam, 1.3523 * y * phi.signum()) + } + Kind::EqualEarth => { + const A1: f64 = 1.340264; + const A2: f64 = -0.081106; + const A3: f64 = 0.000893; + const A4: f64 = 0.003796; + let m = 3.0_f64.sqrt() / 2.0; + let th = (m * phi.sin()).asin(); + let (t2, t6, t8) = (th * th, th.powi(6), th.powi(8)); + let x = 2.0 * 3.0_f64.sqrt() * lam * th.cos() / (3.0 * (9.0 * A4 * t8 + 7.0 * A3 * t6 + 3.0 * A2 * t2 + A1)); + let y = th * (A4 * t8 + A3 * t6 + A2 * t2 + A1); + (x, y) + } + Kind::NaturalEarth => { + let p2 = phi * phi; + let p4 = p2 * p2; + let x = lam * (0.8707 - 0.131979 * p2 + p4 * (-0.013791 + p4 * p2 * (0.003971 - 0.001529 * p2))); + let y = phi * (1.007226 + p2 * (0.015085 + p4 * (-0.044475 + 0.028874 * p2 - 0.005916 * p4))); + (x, y) + } + Kind::WinkelTripel => { + let alpha = (phi.cos() * (lam / 2.0).cos()).clamp(-1.0, 1.0).acos(); + let sinc = if alpha.abs() < 1e-12 { 1.0 } else { alpha.sin() / alpha }; + let x = 0.5 * (lam * cos_phi1 + 2.0 * phi.cos() * (lam / 2.0).sin() / sinc); + let y = 0.5 * (phi + phi.sin() / sinc); + (x, y) + } + Kind::EckertIV => { + // θ + sinθ·cosθ + 2·sinθ = (2 + π/2)·sinφ, by Newton. + let k = (2.0 + std::f64::consts::FRAC_PI_2) * phi.sin(); + let mut th = phi / 2.0; + for _ in 0..30 { + let f = th + th.sin() * th.cos() + 2.0 * th.sin() - k; + let d = 1.0 + (2.0 * th).cos() + 2.0 * th.cos(); + if d.abs() < 1e-12 { + break; + } + let step = f / d; + th -= step; + if step.abs() < 1e-14 { + break; + } + } + let pi = std::f64::consts::PI; + let x = 2.0 / (pi * (4.0 + pi)).sqrt() * lam * (1.0 + th.cos()); + let y = 2.0 * (pi / (4.0 + pi)).sqrt() * th.sin(); + (x, y) + } + } +} + +/// A world projection on a sphere, with a central meridian, false easting and northing, and +/// (Winkel Tripel only) a standard parallel. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct World { + pub kind: Kind, + /// Central meridian, degrees. + pub lon0: f64, + /// The sphere's radius, metres. + pub radius: f64, + /// False easting and northing, metres. + pub x0: f64, + pub y0: f64, + /// Winkel Tripel's standard parallel, degrees ([`winkel_parallel`] unless a definition gives + /// one); the other projections have none. + pub lat1: f64, +} + +impl World { + /// A projection without false easting or northing, Winkel Tripel at Winkel's own parallel. + pub fn new(kind: Kind, lon0: f64, radius: f64) -> World { + World { kind, lon0, radius, x0: 0.0, y0: 0.0, lat1: winkel_parallel() } + } + + pub fn forward(&self, c: Coord) -> Option { + if !c.is_finite() { + return None; + } + // Keep ±180° (and points a rounding error past it) on their own side, so rings along the + // map's edge don't jump across the whole map. + let d = c.x - self.lon0; + let d = if d.abs() <= 180.0 + 1e-6 { d.clamp(-180.0, 180.0) } else { (d + 540.0).rem_euclid(360.0) - 180.0 }; + let lam = d.to_radians(); + let phi = c.y.clamp(-90.0, 90.0).to_radians(); + let (x, y) = unit_forward(self.kind, lam, phi, self.lat1.to_radians().cos()); + let out = Coord::new(x * self.radius + self.x0, y * self.radius + self.y0); + out.is_finite().then_some(out) + } + + /// Newton's method from a starting guess; `None` when no point maps to `m`. + pub fn inverse(&self, m: Coord) -> Option { + if !m.is_finite() { + return None; + } + let (tx, ty) = ((m.x - self.x0) / self.radius, (m.y - self.y0) / self.radius); + let cos_phi1 = self.lat1.to_radians().cos(); + let forward = |lam: f64, phi: f64| unit_forward(self.kind, lam, phi, cos_phi1); + let (pi, half) = (std::f64::consts::PI, std::f64::consts::FRAC_PI_2); + let (mut lam, mut phi) = ((tx / 0.85).clamp(-pi, pi), (ty / 1.2).clamp(-half, half)); + let h = 1e-7; + for _ in 0..40 { + let (fx, fy) = forward(lam, phi); + let (ex, ey) = (fx - tx, fy - ty); + if ex.abs() + ey.abs() < 1e-12 { + break; + } + // Numerical Jacobian, stepping inward near the edges. + let dl = if lam + h > pi { -h } else { h }; + let dp = if phi + h > half { -h } else { h }; + let (ax, ay) = forward(lam + dl, phi); + let (bx, by) = forward(lam, phi + dp); + let (j11, j21) = ((ax - fx) / dl, (ay - fy) / dl); + let (j12, j22) = ((bx - fx) / dp, (by - fy) / dp); + let det = j11 * j22 - j12 * j21; + if !det.is_finite() || det.abs() < 1e-15 { + break; + } + lam = (lam - (j22 * ex - j12 * ey) / det).clamp(-pi, pi); + phi = (phi - (-j21 * ex + j11 * ey) / det).clamp(-half, half); + } + let (fx, fy) = forward(lam, phi); + // Off the outline Newton settles at the clamp, short of the target. + if (fx - tx).abs() + (fy - ty).abs() > 1e-9 { + return None; + } + let lon = (lam.to_degrees() + self.lon0 + 540.0).rem_euclid(360.0) - 180.0; + Some(Coord::new(lon, phi.to_degrees())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::MERCATOR_R; + + #[test] + fn round_trips_and_outlines() { + for kind in [Kind::Robinson, Kind::EqualEarth, Kind::NaturalEarth, Kind::WinkelTripel, Kind::EckertIV] { + for w in + [World::new(kind, 0.0, MERCATOR_R), World { x0: 1_000.0, y0: -2_000.0, lat1: 0.0, ..World::new(kind, 30.0, MERCATOR_R) }] + { + for (lon, lat) in [(0.0, 0.0), (10.0, 50.0), (-120.0, -35.0), (179.0, 80.0), (-60.0, 10.0)] { + let m = w.forward(Coord::new(lon, lat)).unwrap(); + let back = w.inverse(m).unwrap_or_else(|| panic!("{w:?} {lon},{lat}")); + let dl = ((back.x - lon + 540.0).rem_euclid(360.0) - 180.0).abs(); + assert!(dl < 1e-6 && (back.y - lat).abs() < 1e-6, "{w:?} {lon},{lat}: {back:?}"); + } + // Beyond the outline: nothing maps there. + let (e, n) = (w.forward(Coord::new(w.lon0 + 180.0, 0.0)).unwrap(), w.forward(Coord::new(w.lon0, 90.0)).unwrap()); + let corner = Coord::new(w.x0 + 0.99 * (e.x - w.x0), w.y0 + 0.99 * (n.y - w.y0)); + assert!(w.inverse(corner).is_none(), "{w:?} corner"); + assert!(w.inverse(Coord::new(f64::NAN, 0.0)).is_none()); + } + } + // Robinson's published scale: the equator is 0.8487·2πR long. + let r = World::new(Kind::Robinson, 0.0, MERCATOR_R); + let x = r.forward(Coord::new(180.0, 0.0)).unwrap().x; + assert!((x / (0.8487 * std::f64::consts::PI * MERCATOR_R) - 1.0).abs() < 1e-9); + // A central meridian shifts the map. + let shifted = World::new(Kind::EqualEarth, 150.0, MERCATOR_R); + assert!(shifted.forward(Coord::new(150.0, 0.0)).unwrap().x.abs() < 1e-6); + } + + /// Against pyproj 3.8.0 (PROJ 9.8.1): 10°E 50°N and 120°W 35°S, on PROJ's unit sphere. + #[test] + fn against_proj() { + let unit = |kind: Kind, lat1: f64| World { lat1, ..World::new(kind, 0.0, 1.0) }; + let (natearth, eck4) = (unit(Kind::NaturalEarth, 0.0), unit(Kind::EckertIV, 0.0)); + // PROJ's bare `+proj=wintri` (`+lat_1=0`), and Winkel's parallel. + let (wintri0, wintri) = (unit(Kind::WinkelTripel, 0.0), unit(Kind::WinkelTripel, winkel_parallel())); + for (w, at, want) in [ + (natearth, (10.0, 50.0), (0.133_153_446_193_299_88, 0.879_006_637_134_140_1)), + (natearth, (-120.0, -35.0), (-1.716_472_953_691_948_3, -0.617_622_121_844_032_2)), + (eck4, (10.0, 50.0), (0.125_017_995_405_402_45, 0.951_920_977_236_804_1)), + (eck4, (-120.0, -35.0), (-1.637_200_915_680_158_8, -0.695_904_275_601_640_1)), + (wintri0, (10.0, 50.0), (0.151_149_075_678_650_05, 0.873_092_595_459_548_4)), + (wintri0, (-120.0, -35.0), (-1.940_535_950_688_134_1, -0.666_578_076_704_930_9)), + (wintri, (10.0, 50.0), (0.119_438_168_634_489_14, 0.873_092_595_459_548_4)), + (wintri, (-120.0, -35.0), (-1.560_005_066_158_203_2, -0.666_578_076_704_930_9)), + ] { + let m = w.forward(Coord::new(at.0, at.1)).unwrap(); + assert!((m.x - want.0).abs() < 1e-9 && (m.y - want.1).abs() < 1e-9, "{w:?}: {m:?}"); + } + } +} diff --git a/crates/map/src/projection.rs b/crates/map/src/projection.rs index 73f226382c..a16ab2a88c 100644 --- a/crates/map/src/projection.rs +++ b/crates/map/src/projection.rs @@ -616,7 +616,7 @@ impl Projector { .find_map(|t| t.strip_prefix("+R=")?.parse::().ok()) .filter(|r| r.is_finite() && *r > 0.0) .unwrap_or(rustgis_geom::MERCATOR_R); - let engine = Engine::World(crate::world::World { kind, lon0, radius }); + let engine = Engine::World(crate::world::World::new(kind, lon0, radius)); return Ok(Projector { engine, to_meter: 1.0, domain, lon0, edge: std::sync::OnceLock::new() }); } let native = proj4rs::Proj::from_proj_string(&def).map_err(|e| match e { diff --git a/crates/map/src/world.rs b/crates/map/src/world.rs index 4071f2b822..b6d30b4d77 100644 --- a/crates/map/src/world.rs +++ b/crates/map/src/world.rs @@ -1,238 +1,6 @@ -//! World map projections computed here, on a sphere (of the WGS 84 equatorial radius unless the -//! definition gives `+R`): Robinson, Equal Earth, Natural Earth, Winkel Tripel and Eckert IV. -//! -//! The forward formulas follow the projections' published definitions. Inverses use Newton's -//! method on the forward formula, which also rejects points outside the map's outline (no -//! longitude/latitude maps to them). +//! World map projections the map draws in: Robinson, Equal Earth, Natural Earth, Winkel Tripel +//! and Eckert IV, on a sphere of the WGS 84 equatorial radius unless the definition gives `+R`. +//! They are computed in `rustgis_geom::world`, where a file's coordinate system in one of them is +//! read with the same formulas (opengeos/RustGIS#1701). -use rustgis_geom::Coord; - -/// A world projection (PROJ names: `robin`, `eqearth`, `natearth`, `wintri`, `eck4`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Kind { - Robinson, - EqualEarth, - NaturalEarth, - WinkelTripel, - EckertIV, -} - -impl Kind { - pub fn from_proj_name(name: &str) -> Option { - Some(match name { - "robin" => Kind::Robinson, - "eqearth" => Kind::EqualEarth, - "natearth" => Kind::NaturalEarth, - "wintri" => Kind::WinkelTripel, - "eck4" => Kind::EckertIV, - _ => return None, - }) - } - - pub fn proj_name(self) -> &'static str { - match self { - Kind::Robinson => "robin", - Kind::EqualEarth => "eqearth", - Kind::NaturalEarth => "natearth", - Kind::WinkelTripel => "wintri", - Kind::EckertIV => "eck4", - } - } -} - -/// Robinson's table: (X, Y) every 5° of latitude from 0° to 90°. -const ROBINSON: [(f64, f64); 19] = [ - (1.0000, 0.0000), - (0.9986, 0.0620), - (0.9954, 0.1240), - (0.9900, 0.1860), - (0.9822, 0.2480), - (0.9730, 0.3100), - (0.9600, 0.3720), - (0.9427, 0.4340), - (0.9216, 0.4958), - (0.8962, 0.5571), - (0.8679, 0.6176), - (0.8350, 0.6769), - (0.7986, 0.7346), - (0.7597, 0.7903), - (0.7186, 0.8435), - (0.6732, 0.8936), - (0.6213, 0.9394), - (0.5722, 0.9761), - (0.5322, 1.0000), -]; - -/// Robinson's X and Y at |latitude| in degrees, by cubic (Catmull-Rom) interpolation. -fn robinson_xy(lat_deg: f64) -> (f64, f64) { - let t = (lat_deg.abs() / 5.0).clamp(0.0, 18.0); - let i = (t.floor() as usize).min(17); - let f = t - i as f64; - let at = |k: isize| { - // Mirror at the equator and extend linearly past the pole. - let k = k.clamp(-1, 19); - match k { - -1 => (ROBINSON[1].0, -ROBINSON[1].1), - 19 => (2.0 * ROBINSON[18].0 - ROBINSON[17].0, 2.0 * ROBINSON[18].1 - ROBINSON[17].1), - k => ROBINSON[k as usize], - } - }; - let (p0, p1, p2, p3) = (at(i as isize - 1), at(i as isize), at(i as isize + 1), at(i as isize + 2)); - let cr = |a: f64, b: f64, c: f64, d: f64| { - 0.5 * (2.0 * b + (-a + c) * f + (2.0 * a - 5.0 * b + 4.0 * c - d) * f * f + (-a + 3.0 * b - 3.0 * c + d) * f * f * f) - }; - (cr(p0.0, p1.0, p2.0, p3.0), cr(p0.1, p1.1, p2.1, p3.1)) -} - -/// Forward projection of (λ, φ) in radians, as multiples of the radius. -fn unit_forward(kind: Kind, lam: f64, phi: f64) -> (f64, f64) { - match kind { - Kind::Robinson => { - let (x, y) = robinson_xy(phi.to_degrees()); - (0.8487 * x * lam, 1.3523 * y * phi.signum()) - } - Kind::EqualEarth => { - const A1: f64 = 1.340264; - const A2: f64 = -0.081106; - const A3: f64 = 0.000893; - const A4: f64 = 0.003796; - let m = 3.0_f64.sqrt() / 2.0; - let th = (m * phi.sin()).asin(); - let (t2, t6, t8) = (th * th, th.powi(6), th.powi(8)); - let x = 2.0 * 3.0_f64.sqrt() * lam * th.cos() / (3.0 * (9.0 * A4 * t8 + 7.0 * A3 * t6 + 3.0 * A2 * t2 + A1)); - let y = th * (A4 * t8 + A3 * t6 + A2 * t2 + A1); - (x, y) - } - Kind::NaturalEarth => { - let p2 = phi * phi; - let p4 = p2 * p2; - let x = lam * (0.8707 - 0.131979 * p2 + p4 * (-0.013791 + p4 * p2 * (0.003971 - 0.001529 * p2))); - let y = phi * (1.007226 + p2 * (0.015085 + p4 * (-0.044475 + 0.028874 * p2 - 0.005916 * p4))); - (x, y) - } - Kind::WinkelTripel => { - let phi1 = (2.0 / std::f64::consts::PI).acos(); - let alpha = (phi.cos() * (lam / 2.0).cos()).clamp(-1.0, 1.0).acos(); - let sinc = if alpha.abs() < 1e-12 { 1.0 } else { alpha.sin() / alpha }; - let x = 0.5 * (lam * phi1.cos() + 2.0 * phi.cos() * (lam / 2.0).sin() / sinc); - let y = 0.5 * (phi + phi.sin() / sinc); - (x, y) - } - Kind::EckertIV => { - // θ + sinθ·cosθ + 2·sinθ = (2 + π/2)·sinφ, by Newton. - let k = (2.0 + std::f64::consts::FRAC_PI_2) * phi.sin(); - let mut th = phi / 2.0; - for _ in 0..30 { - let f = th + th.sin() * th.cos() + 2.0 * th.sin() - k; - let d = 1.0 + (2.0 * th).cos() + 2.0 * th.cos(); - if d.abs() < 1e-12 { - break; - } - let step = f / d; - th -= step; - if step.abs() < 1e-14 { - break; - } - } - let pi = std::f64::consts::PI; - let x = 2.0 / (pi * (4.0 + pi)).sqrt() * lam * (1.0 + th.cos()); - let y = 2.0 * (pi / (4.0 + pi)).sqrt() * th.sin(); - (x, y) - } - } -} - -/// A built-in world projection with a central meridian. -#[derive(Clone, Copy, Debug)] -pub struct World { - pub kind: Kind, - /// Central meridian, degrees. - pub lon0: f64, - /// The sphere's radius, metres. - pub radius: f64, -} - -impl World { - pub fn forward(&self, c: Coord) -> Option { - if !c.is_finite() { - return None; - } - // Keep ±180° (and points a rounding error past it) on their own side, so rings along the - // map's edge don't jump across the whole map. - let d = c.x - self.lon0; - let d = if d.abs() <= 180.0 + 1e-6 { d.clamp(-180.0, 180.0) } else { (d + 540.0).rem_euclid(360.0) - 180.0 }; - let lam = d.to_radians(); - let phi = c.y.clamp(-90.0, 90.0).to_radians(); - let (x, y) = unit_forward(self.kind, lam, phi); - let out = Coord::new(x * self.radius, y * self.radius); - out.is_finite().then_some(out) - } - - /// Newton's method from a starting guess; `None` when no point maps to `m`. - pub fn inverse(&self, m: Coord) -> Option { - if !m.is_finite() { - return None; - } - let (tx, ty) = (m.x / self.radius, m.y / self.radius); - let (pi, half) = (std::f64::consts::PI, std::f64::consts::FRAC_PI_2); - let (mut lam, mut phi) = ((tx / 0.85).clamp(-pi, pi), (ty / 1.2).clamp(-half, half)); - let h = 1e-7; - for _ in 0..40 { - let (fx, fy) = unit_forward(self.kind, lam, phi); - let (ex, ey) = (fx - tx, fy - ty); - if ex.abs() + ey.abs() < 1e-12 { - break; - } - // Numerical Jacobian, stepping inward near the edges. - let dl = if lam + h > pi { -h } else { h }; - let dp = if phi + h > half { -h } else { h }; - let (ax, ay) = unit_forward(self.kind, lam + dl, phi); - let (bx, by) = unit_forward(self.kind, lam, phi + dp); - let (j11, j21) = ((ax - fx) / dl, (ay - fy) / dl); - let (j12, j22) = ((bx - fx) / dp, (by - fy) / dp); - let det = j11 * j22 - j12 * j21; - if !det.is_finite() || det.abs() < 1e-15 { - break; - } - lam = (lam - (j22 * ex - j12 * ey) / det).clamp(-pi, pi); - phi = (phi - (-j21 * ex + j11 * ey) / det).clamp(-half, half); - } - let (fx, fy) = unit_forward(self.kind, lam, phi); - // Off the outline Newton settles at the clamp, short of the target. - if (fx - tx).abs() + (fy - ty).abs() > 1e-9 { - return None; - } - let lon = (lam.to_degrees() + self.lon0 + 540.0).rem_euclid(360.0) - 180.0; - Some(Coord::new(lon, phi.to_degrees())) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use rustgis_geom::MERCATOR_R; - - #[test] - fn round_trips_and_outlines() { - for kind in [Kind::Robinson, Kind::EqualEarth, Kind::NaturalEarth, Kind::WinkelTripel, Kind::EckertIV] { - let w = World { kind, lon0: 0.0, radius: MERCATOR_R }; - for (lon, lat) in [(0.0, 0.0), (10.0, 50.0), (-120.0, -35.0), (179.0, 80.0), (-60.0, 10.0)] { - let m = w.forward(Coord::new(lon, lat)).unwrap(); - let back = w.inverse(m).unwrap_or_else(|| panic!("{kind:?} {lon},{lat}")); - assert!((back.x - lon).abs() < 1e-6 && (back.y - lat).abs() < 1e-6, "{kind:?} {lon},{lat}: {back:?}"); - } - // Beyond the outline: nothing maps there. - let corner = - Coord::new(0.99 * w.forward(Coord::new(180.0, 0.0)).unwrap().x, 0.99 * w.forward(Coord::new(0.0, 90.0)).unwrap().y); - assert!(w.inverse(corner).is_none(), "{kind:?} corner"); - assert!(w.inverse(Coord::new(f64::NAN, 0.0)).is_none()); - } - // Robinson's published scale: the equator is 0.8487·2πR long. - let r = World { kind: Kind::Robinson, lon0: 0.0, radius: MERCATOR_R }; - let x = r.forward(Coord::new(180.0, 0.0)).unwrap().x; - assert!((x / (0.8487 * std::f64::consts::PI * MERCATOR_R) - 1.0).abs() < 1e-9); - // A central meridian shifts the map. - let shifted = World { kind: Kind::EqualEarth, lon0: 150.0, radius: MERCATOR_R }; - assert!(shifted.forward(Coord::new(150.0, 0.0)).unwrap().x.abs() < 1e-6); - } -} +pub use rustgis_geom::world::{Kind, World}; diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index ae2fe6bbe9..407cd03dc8 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -132,7 +132,11 @@ produces a notice when no transformation is available. Swiss oblique Mercator, t Krovak East/North variant, the oblique Mercator in its azimuth forms (the two-point form, with no azimuth, is refused), and the Cassini-Soldner, polyconic and Equal Earth methods are supported from their parameters, as are sinusoidal (MODIS), Robinson, orthographic and Mercator -(variant A), in `.prj` files and in GeoTIFF keys. Esri's orthographic is a spherical projection: +(variant A), in `.prj` files and in GeoTIFF keys. Natural Earth, Winkel Tripel and Eckert IV are +read from WKT as GDAL, Esri and PROJ write it, and by their ESRI codes (World and Sphere Natural Earth and Eckert IV, `ESRI:54077`, `53077`, `54012`, +`53012`). They're computed on a sphere of the datum's semi-major axis, as PROJ computes them. Winkel Tripel's standard parallel is the file's; a +definition without one takes Winkel's own, acos(2/π) (about 50.46°), as the map draws its Winkel +Tripel, where PROJ takes 0. Esri's orthographic is a spherical projection: on an ellipsoid it is refused, with a notice, rather than computed as EPSG's ellipsoidal one. The equidistant cylindrical projection (EPSG:4087, World Equidistant Cylindrical) uses a sphere of its datum's semi-major axis, matching legacy PROJ/GDAL coordinates (verified with PROJ 9.7.1), both for data From 9f64ef02a6f5be16e9c6db3fef8df40e1f2a72ca Mon Sep 17 00:00:00 2001 From: Josh Date: Wed, 11 Nov 2026 08:39:34 -0700 Subject: [PATCH 2/3] fix(data, map): Winkel Tripel without a parallel is at PROJ's 0; whole-world extents (#1701) A Winkel Tripel definition or WKT without a standard parallel is read and written at 0, as PROJ 9.8.1 takes it, instead of Winkel's own. The map's preset now gives Winkel's parallel as its +lat_1, and the map reads +lat_1 from the definition, so it draws as before and agrees with the reader. A world projection's parameter that isn't a finite number is refused, as for Web Mercator, rather than taken as not given. World::inverse keeps a whole world's east edge at 180 degrees, and a raster's extent in one of these projections reaches the antimeridian and the poles when they are in the grid, which the edge samples miss. --- crates/data/src/raster/crs.rs | 12 +++++-- crates/data/src/raster/esri.rs | 5 +-- crates/data/src/raster/mod.rs | 62 ++++++++++++++++++++++++++++++++++ crates/data/src/raster/wkt.rs | 61 ++++++++++++++++++++++++++++----- crates/geom/src/world.rs | 21 ++++++++---- crates/map/src/projection.rs | 35 +++++++++++++++++-- docs/user-guide/data.md | 5 +-- 7 files changed, 177 insertions(+), 24 deletions(-) diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index 9140e3b63a..840bb62bc6 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -597,8 +597,8 @@ impl WorldProjection { /// The projection a PROJ definition describes when it is `+proj=natearth`, `wintri` or /// `eck4`: `None` for any other; an error for one it can't compute (axes other than east and /// north, `+over`, a scale other than 1, a standard parallel that isn't a latitude short of a - /// pole). Winkel Tripel's parallel is `+lat_1`, else Winkel's own - /// ([`rustgis_geom::world::winkel_parallel`]), as the map draws it. + /// pole). Winkel Tripel's parallel is `+lat_1`, else 0, as PROJ 9.8.1 takes it (the map's + /// preset gives Winkel's own, [`rustgis_geom::world::winkel_parallel`]). fn from_proj4(def: &str) -> Option> { use rustgis_geom::world::Kind as W; let tokens: Vec<(&str, &str)> = @@ -620,7 +620,7 @@ impl WorldProjection { .ok() .filter(|v| v.is_finite() && v.abs() < 90.0) .ok_or_else(|| format!("+lat_1={v} isn't a latitude short of a pole"))?, - None => rustgis_geom::world::winkel_parallel(), + None => 0.0, }; // proj4rs reads what every projection shares (centre, offsets, unit, axes, datum) from // the same definition with a projection it has, the equidistant cylindrical, in place. @@ -750,6 +750,12 @@ impl Transformer { matches!(self.kind, Kind::LonLat | Kind::Proj { geographic: true, .. }) } + /// Whether its projection is a world projection RustGIS computes (Natural Earth, Winkel + /// Tripel, Eckert IV), whose outline is widest at the equator (#1701). + pub(super) fn is_world_projection(&self) -> bool { + matches!(self.kind, Kind::World { .. }) + } + /// Web Mercator to native coordinates (the renderer's direction). pub fn from_merc(&self, c: Coord) -> Option { match &self.kind { diff --git a/crates/data/src/raster/esri.rs b/crates/data/src/raster/esri.rs index baceede8f6..aa5854ad6a 100644 --- a/crates/data/src/raster/esri.rs +++ b/crates/data/src/raster/esri.rs @@ -18,8 +18,9 @@ //! systems are candidates to add), and the NAD27 ones whose grids proj4rs can't load: 167; //! - six world systems RustGIS computes on a sphere where PROJ uses the ellipsoid or other //! parameters, kilometres apart: World Miller (54003), the WGS 84 Equal Earths (54035–54037) -//! and the Winkel Tripel NGS pair (53042, 54042), whose `lat_1` RustGIS doesn't read. The -//! presets, and EPSG:8857, stay the way to draw these; +//! and the Winkel Tripel NGS pair (53042, 54042), whose `lat_1` the map didn't read then (it +//! does since #1701, so they are candidates to add). The presets, and EPSG:8857, stay the way +//! to draw these; //! - 44 systems whose datum PROJ shifts to WGS 84 by something other than one Helmert step //! (Molodensky–Badekas for Korean 1985, a chain of operations for NGO 1948 …), and the 11 //! planetary ones (Moon, Mars), whose bodies the map can't hold; diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index e533fd7a96..672926afd4 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -890,6 +890,31 @@ impl Raster { let (lo, hi) = (e.min_x - shift, e.max_x - shift); (e.min_x, e.max_x) = if lo >= -180.0 && hi <= 180.0 { (lo, hi) } else { (-180.0, 180.0) }; } + // A whole world in a world projection RustGIS computes reaches the antimeridian and the + // poles at its outline's edge, which samples miss when the grid's edges are a little past + // it (its corners are off the outline): whatever of them is in the grid is in its extent + // (#1701). + if !e.is_empty() && self.transformer.is_world_projection() { + let inside = |lon: f64, lat: f64| { + self.transformer.from_lonlat(Coord::new(lon, lat)).is_some_and(|m| { + let (col, row) = self.transform.to_pixel(m); + (-1e-6..=w + 1e-6).contains(&col) && (-1e-6..=h + 1e-6).contains(&row) + }) + }; + let along = |i: usize| -180.0 + 360.0 * i as f64 / steps as f64; + if (0..=steps).any(|i| inside(180.0, along(i) / 2.0)) { + e.max_x = 180.0; + } + if (0..=steps).any(|i| inside(-180.0, along(i) / 2.0)) { + e.min_x = -180.0; + } + if (0..=steps).any(|i| inside(along(i), 90.0)) { + e.max_y = 90.0; + } + if (0..=steps).any(|i| inside(along(i), -90.0)) { + e.min_y = -90.0; + } + } e } @@ -1783,6 +1808,43 @@ pub(crate) mod tests { assert!(e.contains(Coord::new(179.9, 0.0)) && e.contains(Coord::new(-179.9, 0.0))); } + /// A whole world in Natural Earth, Winkel Tripel or Eckert IV reaches both sides of the + /// antimeridian and both poles, with its edges on the outline or a little past it, as a warp + /// leaves them; its east half reaches 180° and not -180°, and Europe stays Europe (#1701). + #[test] + fn a_whole_world_in_a_world_projection_has_a_world_wide_extent() { + for def in [ + "+proj=natearth +lon_0=0 +datum=WGS84 +units=m +no_defs", + "+proj=wintri +lon_0=0 +lat_1=50.459776252189805 +datum=WGS84 +units=m +no_defs", + "+proj=eck4 +lon_0=0 +datum=WGS84 +units=m +no_defs", + ] { + let crs = Crs::parse(def).unwrap(); + let t = crs.transformer().unwrap(); + let at = |lon: f64, lat: f64| t.from_lonlat(Coord::new(lon, lat)).unwrap(); + let (east, north) = (at(180.0, 0.0).x, at(0.0, 90.0).y); + let raster = |(west, south, east, north): (f64, f64, f64, f64)| { + let (w, h) = (64, 32); + let gt = GeoTransform { + origin_x: west, + origin_y: north, + pixel_width: (east - west) / w as f64, + pixel_height: (south - north) / h as f64, + }; + Raster::new("w", w, h, vec![vec![1.0; (w * h) as usize]], gt, crs, None, ColorHint::Gray, "Float32").unwrap() + }; + for past in [1.0, 1.001, 1.01] { + let e = raster((-east * past, -north * past, east * past, north * past)).extent(); + assert_eq!((e.min_x, e.max_x, e.min_y, e.max_y), (-180.0, 180.0, -90.0, 90.0), "{def} {past}: {e:?}"); + // The east half: 0° to 180°. + let e = raster((0.0, -north * past, east * past, north * past)).extent(); + assert!(e.min_x.abs() < 1e-6 && e.max_x == 180.0, "{def} {past}: {e:?}"); + } + let (sw, ne) = (at(-10.0, 35.0), at(30.0, 70.0)); + let e = raster((sw.x, sw.y, ne.x, ne.y)).extent(); + assert!(e.min_x > -40.0 && e.max_x < 60.0 && e.min_y > 30.0 && e.max_y < 75.0, "{def}: {e:?}"); + } + } + #[test] fn rejects_bad_shapes() { let gt = GeoTransform { origin_x: 0.0, origin_y: 0.0, pixel_width: 1.0, pixel_height: -1.0 }; diff --git a/crates/data/src/raster/wkt.rs b/crates/data/src/raster/wkt.rs index 3b2b66845f..14d00935d7 100644 --- a/crates/data/src/raster/wkt.rs +++ b/crates/data/src/raster/wkt.rs @@ -1353,10 +1353,20 @@ fn custom(p: &Node, method: &str) -> Result { "ROBINSON" => format!("+proj=robin {at}"), // Computed by RustGIS too (`rustgis_geom::world`), on a sphere of the semi-major axis as in // PROJ (#1701). Winkel Tripel's standard parallel is the file's (GDAL and PROJ always - // write one), else Winkel's own, as RustGIS draws and writes it. + // write one), else 0, as PROJ reads WKT without one. A parameter that isn't a finite + // number (`1e400`, which `parameters` leaves out) is refused rather than taken as not + // given, as for Web Mercator: a parallel given so would be read as 0. + "NATURAL_EARTH" | "ECKERT_IV" | "WINKEL_TRIPEL" + if p.nodes().any(|n| n.name.eq_ignore_ascii_case("PARAMETER") && n.num(0).is_none()) => + { + return Err(format!( + "the {} projection with a parameter that isn't a finite number isn't supported", + p.child("PROJECTION").map_or("", Node::title) + )); + } "NATURAL_EARTH" => format!("+proj=natearth {at}"), "ECKERT_IV" => format!("+proj=eck4 {at}"), - "WINKEL_TRIPEL" => format!("+proj=wintri +lat_1={} {at}", lat1.unwrap_or_else(rustgis_geom::world::winkel_parallel)), + "WINKEL_TRIPEL" => format!("+proj=wintri +lat_1={} {at}", lat1.unwrap_or(0.0)), // EPSG's method 9840, on the ellipsoid (proj4rs follows the EPSG Guidance Note 7-2). Esri's // Orthographic is a spherical one: on a sphere they agree, on an ellipsoid they don't, and // which one an Esri file means can't be told, so that is refused rather than guessed. @@ -1937,11 +1947,10 @@ fn def_wkt(def: &str, name: &str, code: Option) -> Option { ps = vec![("central_meridian", lon0)]; "Eckert_IV" } - // Its standard parallel is the definition's, else Winkel's own of acos(2/π) (about - // 50.46°), the one the map draws a definition without one in. PROJ 9.8.1 takes 0 there, - // so it is always written. + // Its standard parallel is the definition's, else 0, as PROJ 9.8.1 takes and writes it + // (the map's preset gives Winkel's own, acos(2/π), about 50.46°). "wintri" => { - let lat1 = get("lat_1").unwrap_or_else(rustgis_geom::world::winkel_parallel); + let lat1 = get("lat_1").unwrap_or(0.0); ps = vec![("standard_parallel_1", lat1), ("central_meridian", lon0)]; "Winkel_Tripel" } @@ -2131,8 +2140,12 @@ pub(crate) mod tests { assert!(wkt.contains("PARAMETER[\"central_meridian\",-60]") && wkt.contains("PARAMETER[\"false_easting\",100]"), "{wkt}"); assert!(wkt.contains("SPHEROID[\"WGS 84\",6378137,298.257223563"), "{wkt}"); } + // Winkel Tripel's standard parallel: the definition's (the map's preset gives Winkel's + // own), else 0, as PROJ 9.8.1 writes a definition without one. + let wkt = proj4_to_wkt("+proj=wintri +lon_0=0 +lat_1=50.459776252189805 +datum=WGS84 +units=m +no_defs", "W").unwrap(); + assert!(wkt.contains("PARAMETER[\"standard_parallel_1\",50.459776252189805]"), "{wkt}"); let wkt = proj4_to_wkt("+proj=wintri +lon_0=0 +datum=WGS84 +units=m +no_defs", "W").unwrap(); - assert!(wkt.contains("PARAMETER[\"standard_parallel_1\",50.4597"), "{wkt}"); + assert!(wkt.contains("PARAMETER[\"standard_parallel_1\",0]"), "{wkt}"); // Another projection proj4rs can't read still has none. assert_eq!(proj4_to_wkt("+proj=nosuch +datum=WGS84 +units=m +no_defs", "X"), None); } @@ -2196,10 +2209,20 @@ pub(crate) mod tests { let crs = crate::filegdb::crs_of_code(code).unwrap_or_else(|| panic!("ESRI:{code}")); places(crs, &format!("ESRI:{code}"), &points); } - // The presets' WKT reads back to the presets: Winkel Tripel at Winkel's own parallel. + // A Winkel Tripel without a standard parallel is at 0, as PROJ 9.8.1 takes it: its + // definition, WKT1 without the parameter, and the WKT written from the definition. + let bare = "+proj=wintri +lon_0=-60 +x_0=100 +y_0=-200 +datum=WGS84 +units=m +no_defs"; + let at_0 = [((10.0, 50.0), (6707316.7995641865, 5703113.4871610105)), ((-120.0, -35.0), (-6238480.310135213, -3978189.6516721374))]; + places(Crs::parse(bare).unwrap(), bare, &at_0); + let no_parallel = r#"PROJCS["unknown",GEOGCS["unknown",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]]],PROJECTION["Winkel_Tripel"],PARAMETER["central_meridian",-60],PARAMETER["false_easting",100],PARAMETER["false_northing",-200],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH]]"#; + places(crs_from_wkt(no_parallel).unwrap(), no_parallel, &at_0); + let written = proj4_to_wkt(bare, "W").unwrap(); + places(crs_from_wkt(&written).unwrap(), &written, &at_0); + // The presets' WKT reads back to the presets: Winkel Tripel at Winkel's own parallel, + // which its preset gives. for def in [ "+proj=natearth +lon_0=0 +datum=WGS84 +units=m +no_defs", - "+proj=wintri +lon_0=0 +datum=WGS84 +units=m +no_defs", + "+proj=wintri +lon_0=0 +lat_1=50.459776252189805 +datum=WGS84 +units=m +no_defs", "+proj=eck4 +lon_0=0 +datum=WGS84 +units=m +no_defs", ] { let back = crs_from_wkt(&proj4_to_wkt(def, "World").unwrap()).unwrap().transformer().unwrap(); @@ -2217,6 +2240,26 @@ pub(crate) mod tests { assert!(crs_from_wkt(&wintri.replace(r#""standard_parallel_1",40"#, r#""standard_parallel_1",90"#)).is_err()); } + /// A world projection's parameter that isn't a finite number (`1e400`, which the reader + /// leaves out) isn't taken as not given, a parallel of 0 or a centre of 0°, in WKT1 and WKT2 + /// (#1701). + #[test] + fn world_projections_refuse_a_parameter_that_isnt_a_number() { + let wintri = r#"PROJCS["unknown",GEOGCS["unknown",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]]],PROJECTION["Winkel_Tripel"],PARAMETER["central_meridian",-60],PARAMETER["standard_parallel_1",40],PARAMETER["false_easting",100],PARAMETER["false_northing",-200],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH]]"#; + let natearth = wintri.replace("Winkel_Tripel", "Natural_Earth").replace(r#"PARAMETER["standard_parallel_1",40],"#, ""); + assert!(crs_from_wkt(wintri).is_ok() && crs_from_wkt(&natearth).is_ok()); + let unusable = [ + wintri.replace(r#""standard_parallel_1",40"#, r#""standard_parallel_1",1e400"#), + wintri.replace(r#""central_meridian",-60"#, r#""central_meridian",1e400"#), + natearth.replace(r#""central_meridian",-60"#, r#""central_meridian",-1e400"#), + r#"PROJCRS["unknown",BASEGEOGCRS["unknown",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]],ID["EPSG",6326]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8901]]],CONVERSION["unknown",METHOD["Winkel Tripel"],PARAMETER["Longitude of natural origin",-60,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8802]],PARAMETER["Latitude of 1st standard parallel",1e400,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8823]],PARAMETER["False easting",100,LENGTHUNIT["metre",1],ID["EPSG",8806]],PARAMETER["False northing",-200,LENGTHUNIT["metre",1],ID["EPSG",8807]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1,ID["EPSG",9001]]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1,ID["EPSG",9001]]]]"#.to_string(), + ]; + for wkt in unusable { + let e = crs_from_wkt(&wkt).unwrap_err(); + assert!(e.contains("isn't a finite number"), "{e}: {wkt}"); + } + } + #[test] fn epsg_authority() { let wkt = r#"PROJCS["anything",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["central_meridian",-81],UNIT["metre",1],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","32617"]]"#; diff --git a/crates/geom/src/world.rs b/crates/geom/src/world.rs index 9464831587..7c70c50aa9 100644 --- a/crates/geom/src/world.rs +++ b/crates/geom/src/world.rs @@ -44,9 +44,8 @@ impl Kind { } /// Winkel's own standard parallel for his Tripel, acos(2/π) (about 50.46°, degrees): the one the -/// map draws a Winkel Tripel without one in, and RustGIS writes for it. PROJ 9.8.1 takes 0 for a -/// definition without `+lat_1`; GDAL and PROJ always write the parallel in WKT, so a file says -/// which. +/// map's Winkel Tripel preset gives as its `+lat_1`. A definition or WKT without one is at 0, as +/// PROJ 9.8.1 takes it; GDAL and PROJ always write the parallel in WKT, so a file says which. pub fn winkel_parallel() -> f64 { std::f64::consts::FRAC_2_PI.acos().to_degrees() } @@ -165,8 +164,8 @@ pub struct World { /// False easting and northing, metres. pub x0: f64, pub y0: f64, - /// Winkel Tripel's standard parallel, degrees ([`winkel_parallel`] unless a definition gives - /// one); the other projections have none. + /// Winkel Tripel's standard parallel, degrees (a definition's `+lat_1`, 0 without one, as in + /// PROJ); the other projections have none. pub lat1: f64, } @@ -227,7 +226,10 @@ impl World { if (fx - tx).abs() + (fy - ty).abs() > 1e-9 { return None; } - let lon = (lam.to_degrees() + self.lon0 + 540.0).rem_euclid(360.0) - 180.0; + // Within ±180° as PROJ gives it, as `Sinusoidal` and `Eqc` do: a whole world's east edge + // is 180°, not -180° (a rounding error past it too, as in `forward`). + let lon = lam.to_degrees() + self.lon0; + let lon = if lon.abs() <= 180.0 + 1e-9 { lon.clamp(-180.0, 180.0) } else { (lon + 540.0).rem_euclid(360.0) - 180.0 }; Some(Coord::new(lon, phi.to_degrees())) } } @@ -255,6 +257,13 @@ mod tests { assert!(w.inverse(corner).is_none(), "{w:?} corner"); assert!(w.inverse(Coord::new(f64::NAN, 0.0)).is_none()); } + // The edges come back on their own side, as PROJ gives them: centred on 0°, the east + // edge is 180° and the west -180°; centred on 30°, both are -150° (#1701). + for (lon0, east, west) in [(0.0, 180.0, -180.0), (30.0, -150.0, -150.0)] { + let w = World::new(kind, lon0, MERCATOR_R); + let edge = |dir: f64| w.inverse(w.forward(Coord::new(lon0 + dir * 180.0, 0.0)).unwrap()).unwrap().x; + assert!((edge(1.0) - east).abs() < 1e-9 && (edge(-1.0) - west).abs() < 1e-9, "{w:?}: {} {}", edge(1.0), edge(-1.0)); + } } // Robinson's published scale: the equator is 0.8487·2πR long. let r = World::new(Kind::Robinson, 0.0, MERCATOR_R); diff --git a/crates/map/src/projection.rs b/crates/map/src/projection.rs index a16ab2a88c..fb42ee49f9 100644 --- a/crates/map/src/projection.rs +++ b/crates/map/src/projection.rs @@ -18,7 +18,9 @@ pub const PRESETS: &[(&str, &str, &str)] = &[ ("robinson", "Robinson", "+proj=robin +lon_0=0 +datum=WGS84 +units=m +no_defs"), ("equalEarth", "Equal Earth", "+proj=eqearth +lon_0=0 +datum=WGS84 +units=m +no_defs"), ("naturalEarth", "Natural Earth", "+proj=natearth +lon_0=0 +datum=WGS84 +units=m +no_defs"), - ("winkelTripel", "Winkel Tripel", "+proj=wintri +lon_0=0 +datum=WGS84 +units=m +no_defs"), + // At Winkel's own standard parallel, acos(2/π) (`rustgis_geom::world::winkel_parallel`): + // PROJ, and RustGIS's readers, take 0 for a definition without one. + ("winkelTripel", "Winkel Tripel", "+proj=wintri +lon_0=0 +lat_1=50.459776252189805 +datum=WGS84 +units=m +no_defs"), ("eckertIV", "Eckert IV (equal-area world)", "+proj=eck4 +lon_0=0 +datum=WGS84 +units=m +no_defs"), ("northPolar", "North Polar Stereographic", "+proj=stere +lat_0=90 +lat_ts=70 +lon_0=0 +datum=WGS84 +units=m +no_defs"), ("southPolar", "South Polar Stereographic", "+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +datum=WGS84 +units=m +no_defs"), @@ -616,7 +618,18 @@ impl Projector { .find_map(|t| t.strip_prefix("+R=")?.parse::().ok()) .filter(|r| r.is_finite() && *r > 0.0) .unwrap_or(rustgis_geom::MERCATOR_R); - let engine = Engine::World(crate::world::World::new(kind, lon0, radius)); + // Winkel Tripel's standard parallel as the definition gives it (the preset gives + // Winkel's own), else 0, as PROJ and RustGIS's readers take it, so the map draws a + // definition where its data is read. + let lat1 = match def.split_whitespace().find_map(|t| t.strip_prefix("+lat_1=")) { + Some(v) => v + .parse::() + .ok() + .filter(|v| v.is_finite() && v.abs() < 90.0) + .ok_or_else(|| format!("{code}: +lat_1={v} isn't a latitude short of a pole"))?, + None => 0.0, + }; + let engine = Engine::World(crate::world::World { lat1, ..crate::world::World::new(kind, lon0, radius) }); return Ok(Projector { engine, to_meter: 1.0, domain, lon0, edge: std::sync::OnceLock::new() }); } let native = proj4rs::Proj::from_proj_string(&def).map_err(|e| match e { @@ -1356,6 +1369,24 @@ mod tests { assert!(checked >= 31, "only {checked} world projections checked"); } + /// The world presets RustGIS computes draw where its readers place their definitions (a map + /// exported in one, say): Winkel Tripel at Winkel's own parallel, which its preset gives, as + /// PROJ 9.8.1 places it (#1701). + #[test] + fn world_presets_draw_where_their_definitions_are_read() { + for code in ["naturalEarth", "winkelTripel", "eckertIV", "winkelTripel +lon_0=150"] { + let (def, _) = lookup(code).unwrap(); + let p = Projector::new(code).unwrap(); + let t = rustgis_data::raster::Crs::parse(&def).unwrap().transformer().unwrap(); + for (lon, lat) in [(10.0, 50.0), (-120.0, -35.0), (179.0, 80.0)] { + let (a, b) = (p.forward(Coord::new(lon, lat)).unwrap(), t.from_lonlat(Coord::new(lon, lat)).unwrap()); + assert!((a.x - b.x).abs() < 1e-3 && (a.y - b.y).abs() < 1e-3, "{code} {lon},{lat}: {a:?} {b:?}"); + } + } + let m = Projector::new("winkelTripel").unwrap().forward(Coord::new(10.0, 50.0)).unwrap(); + assert!((m.x - 761_793.002_579_874_7).abs() < 1e-3 && (m.y - 5_568_704.187_526_578).abs() < 1e-3, "{m:?}"); + } + #[test] fn unfound_edges_get_their_neighbours_stray() { let lats: Vec = (0..EDGE_SAMPLES).map(|i| (-90.0 + EDGE_STEP * i as f64).clamp(-89.9, 89.9)).collect(); diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 407cd03dc8..1eff9fe410 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -135,8 +135,9 @@ supported from their parameters, as are sinusoidal (MODIS), Robinson, orthograph (variant A), in `.prj` files and in GeoTIFF keys. Natural Earth, Winkel Tripel and Eckert IV are read from WKT as GDAL, Esri and PROJ write it, and by their ESRI codes (World and Sphere Natural Earth and Eckert IV, `ESRI:54077`, `53077`, `54012`, `53012`). They're computed on a sphere of the datum's semi-major axis, as PROJ computes them. Winkel Tripel's standard parallel is the file's; a -definition without one takes Winkel's own, acos(2/π) (about 50.46°), as the map draws its Winkel -Tripel, where PROJ takes 0. Esri's orthographic is a spherical projection: +definition or WKT without one is at 0, as PROJ takes it. The map's Winkel Tripel is at Winkel's +own, acos(2/π) (about 50.46°), and its definition and WKT say so. A parameter that isn't a +finite number is refused rather than taken as not given. Esri's orthographic is a spherical projection: on an ellipsoid it is refused, with a notice, rather than computed as EPSG's ellipsoidal one. The equidistant cylindrical projection (EPSG:4087, World Equidistant Cylindrical) uses a sphere of its datum's semi-major axis, matching legacy PROJ/GDAL coordinates (verified with PROJ 9.7.1), both for data From 7ea026c8af6fee2b843691a7e079faa8c025dc95 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 11 Nov 2026 21:52:27 -0500 Subject: [PATCH 3/3] fix(data): world projections from review: edge meridian, +geoc, offsets From the reviews of #1781: - A raster in Natural Earth, Winkel Tripel or Eckert IV centred elsewhere than on 0 degrees has its outline's edges on the meridian opposite its centre, not the antimeridian. Its extent now reaches that meridian when the edge is in the grid: centred on 150E, a west half a little past the outline reached only 26.6W, not 30W. - +geoc is kept from the datum's longitude/latitude. proj4rs applied it there, which moved 10E 45N by 21 km; PROJ computes these on a sphere, where it changes nothing. - An offset that isn't a number (+x_0=inf) is refused; every point of such a system was nowhere. - +lat_1 is checked for Winkel Tripel only; Natural Earth and Eckert IV ignore it, as PROJ does. - WKT with a scale factor other than 1 is refused, as +k is in a definition, rather than read without it. - The comments and the data guide say that 0 is PROJ's parallel for a Winkel Tripel coordinate system without one (cs2cs, GDAL, WKT), and that the proj program takes acos(2/pi) for the bare projection. --- crates/data/src/raster/crs.rs | 31 ++++++++++++++++++-------- crates/data/src/raster/mod.rs | 30 ++++++++++++++++++++++++- crates/data/src/raster/wkt.rs | 41 ++++++++++++++++++++++++++++++++--- crates/geom/src/world.rs | 10 +++++---- docs/user-guide/data.md | 13 ++++++----- 5 files changed, 103 insertions(+), 22 deletions(-) diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index 320374ce81..ba38485cd1 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -623,9 +623,13 @@ struct WorldProjection { impl WorldProjection { /// The projection a PROJ definition describes when it is `+proj=natearth`, `wintri` or /// `eck4`: `None` for any other; an error for one it can't compute (axes other than east and - /// north, `+over`, a scale other than 1, a standard parallel that isn't a latitude short of a - /// pole). Winkel Tripel's parallel is `+lat_1`, else 0, as PROJ 9.8.1 takes it (the map's - /// preset gives Winkel's own, [`rustgis_geom::world::winkel_parallel`]). + /// north, `+over`, a scale other than 1, an offset that isn't a number, a Winkel Tripel + /// standard parallel that isn't a latitude short of a pole). Winkel Tripel's parallel is + /// `+lat_1`, else 0, as PROJ takes a definition used as a coordinate system (`cs2cs`, GDAL, + /// and WKT without the parameter; verified with PROJ 9.8.1 and 9.9.0). The `proj` program, + /// which runs the bare projection, takes Winkel's own, acos(2/π), for one without `+lat_1`; + /// the map's preset gives that one ([`rustgis_geom::world::winkel_parallel`]). Natural Earth + /// and Eckert IV have no standard parallel: a `+lat_1` is ignored, as in PROJ. fn from_proj4(def: &str) -> Option> { use rustgis_geom::world::Kind as W; let tokens: Vec<(&str, &str)> = @@ -641,7 +645,7 @@ impl WorldProjection { if tokens.iter().any(|(k, v)| (*k == "k" || *k == "k_0") && v.parse::().ok() != Some(1.0)) { return Err("a world projection with a scale other than 1 isn't supported".to_string()); } - let lat1 = match tokens.iter().find(|(k, _)| *k == "lat_1") { + let lat1 = match tokens.iter().find(|(k, _)| *k == "lat_1").filter(|_| kind == W::WinkelTripel) { Some((_, v)) => v .parse::() .ok() @@ -651,9 +655,11 @@ impl WorldProjection { }; // proj4rs reads what every projection shares (centre, offsets, unit, axes, datum) from // the same definition with a projection it has, the equidistant cylindrical, in place. + // `+geoc` (latitudes counted from the earth's centre) changes nothing on the sphere + // these are computed on, in PROJ too, so it is kept from the datum's longitude/latitude. let stand_in: Vec = def .split_whitespace() - .filter(|t| !t.trim_start_matches('+').starts_with("lat_1=")) + .filter(|t| !t.trim_start_matches('+').starts_with("lat_1=") && t.trim_start_matches('+') != "geoc") .map(|t| if t.trim_start_matches('+') == format!("proj={name}") { "+proj=eqc".to_string() } else { t.to_string() }) .collect(); let stand_in = stand_in.join(" "); @@ -675,6 +681,10 @@ impl WorldProjection { y0: native.false_northing(), lat1, }; + // `+x_0=inf` parses: every point of such a system would be nowhere. + if !(world.lon0.is_finite() && world.x0.is_finite() && world.y0.is_finite()) { + return Err("its centre or offset isn't a number".to_string()); + } Ok(WorldProjection { world, geo, to_meter }) })()) } @@ -777,10 +787,13 @@ impl Transformer { matches!(self.kind, Kind::LonLat | Kind::Proj { geographic: true, .. }) } - /// Whether its projection is a world projection RustGIS computes (Natural Earth, Winkel - /// Tripel, Eckert IV), whose outline is widest at the equator (#1701). - pub(super) fn is_world_projection(&self) -> bool { - matches!(self.kind, Kind::World { .. }) + /// The WGS 84 longitude of its central meridian, when its projection is a world projection + /// RustGIS computes (Natural Earth, Winkel Tripel, Eckert IV): its outline's east and west + /// edges are the meridian opposite (#1701). + pub(super) fn world_central_meridian(&self) -> Option { + let Kind::World { world, wgs84 } = &self.kind else { return None }; + let centre = Coord::new(world.world.x0 / world.to_meter, world.world.y0 / world.to_meter); + world.unproject(wgs84, centre).map(|c| c.x).filter(|lon| lon.is_finite()) } /// Web Mercator to native coordinates (the renderer's direction). diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 672926afd4..8a85754fa1 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -894,7 +894,7 @@ impl Raster { // poles at its outline's edge, which samples miss when the grid's edges are a little past // it (its corners are off the outline): whatever of them is in the grid is in its extent // (#1701). - if !e.is_empty() && self.transformer.is_world_projection() { + if let Some(centre) = self.transformer.world_central_meridian().filter(|_| !e.is_empty()) { let inside = |lon: f64, lat: f64| { self.transformer.from_lonlat(Coord::new(lon, lat)).is_some_and(|m| { let (col, row) = self.transform.to_pixel(m); @@ -914,6 +914,12 @@ impl Raster { if (0..=steps).any(|i| inside(along(i), -90.0)) { e.min_y = -90.0; } + // Centred elsewhere than on 0°, the outline's edges are another meridian than the + // antimeridian: the one opposite its centre, on either side of it. + let edge = (centre + 360.0).rem_euclid(360.0) - 180.0; + if edge.abs() < 180.0 - 1e-6 && (0..=steps).any(|i| [-1e-9, 1e-9].iter().any(|d| inside(edge + d, along(i) / 2.0))) { + (e.min_x, e.max_x) = (e.min_x.min(edge), e.max_x.max(edge)); + } } e } @@ -1842,6 +1848,28 @@ pub(crate) mod tests { let (sw, ne) = (at(-10.0, 35.0), at(30.0, 70.0)); let e = raster((sw.x, sw.y, ne.x, ne.y)).extent(); assert!(e.min_x > -40.0 && e.max_x < 60.0 && e.min_y > 30.0 && e.max_y < 75.0, "{def}: {e:?}"); + // Centred on 150°E, the outline's edges are 30°W: the west half is 30°W to 150°E, a + // whole world all of it, and the east half, across the antimeridian, all of it too. + let crs = Crs::parse(&def.replace("+lon_0=0", "+lon_0=150")).unwrap(); + let raster = |(west, south, east, north): (f64, f64, f64, f64)| { + let (w, h) = (64, 32); + let gt = GeoTransform { + origin_x: west, + origin_y: north, + pixel_width: (east - west) / w as f64, + pixel_height: (south - north) / h as f64, + }; + Raster::new("w", w, h, vec![vec![1.0; (w * h) as usize]], gt, crs, None, ColorHint::Gray, "Float32").unwrap() + }; + for past in [1.0, 1.001, 1.01] { + let e = raster((-east * past, -north * past, 0.0, north * past)).extent(); + assert!((e.min_x + 30.0).abs() < 1e-6 && (e.max_x - 150.0).abs() < 1e-6, "{def} at 150°E, west half, {past}: {e:?}"); + assert_eq!((e.min_y, e.max_y), (-90.0, 90.0), "{def} at 150°E, west half, {past}: {e:?}"); + for west in [-east * past, 0.0] { + let e = raster((west, -north * past, east * past, north * past)).extent(); + assert_eq!((e.min_x, e.max_x), (-180.0, 180.0), "{def} at 150°E from {west}, {past}: {e:?}"); + } + } } } diff --git a/crates/data/src/raster/wkt.rs b/crates/data/src/raster/wkt.rs index 14d00935d7..b352bfbc94 100644 --- a/crates/data/src/raster/wkt.rs +++ b/crates/data/src/raster/wkt.rs @@ -1353,7 +1353,8 @@ fn custom(p: &Node, method: &str) -> Result { "ROBINSON" => format!("+proj=robin {at}"), // Computed by RustGIS too (`rustgis_geom::world`), on a sphere of the semi-major axis as in // PROJ (#1701). Winkel Tripel's standard parallel is the file's (GDAL and PROJ always - // write one), else 0, as PROJ reads WKT without one. A parameter that isn't a finite + // write one), else 0, as PROJ reads WKT without one (and a bare `+proj=wintri` used as a + // coordinate system; the `proj` program takes acos(2/π)). A parameter that isn't a finite // number (`1e400`, which `parameters` leaves out) is refused rather than taken as not // given, as for Web Mercator: a parallel given so would be read as 0. "NATURAL_EARTH" | "ECKERT_IV" | "WINKEL_TRIPEL" @@ -1364,6 +1365,15 @@ fn custom(p: &Node, method: &str) -> Result { p.child("PROJECTION").map_or("", Node::title) )); } + // None of the three has a scale factor, and PROJ ignores one. A definition with a scale + // other than 1 is refused (`WorldProjection::from_proj4`), so WKT with one is too, rather + // than read without it. + "NATURAL_EARTH" | "ECKERT_IV" | "WINKEL_TRIPEL" if k0 != 1.0 => { + return Err(format!( + "the {} projection with a scale factor other than 1 isn't supported", + p.child("PROJECTION").map_or("", Node::title) + )); + } "NATURAL_EARTH" => format!("+proj=natearth {at}"), "ECKERT_IV" => format!("+proj=eck4 {at}"), "WINKEL_TRIPEL" => format!("+proj=wintri +lat_1={} {at}", lat1.unwrap_or(0.0)), @@ -1947,8 +1957,9 @@ fn def_wkt(def: &str, name: &str, code: Option) -> Option { ps = vec![("central_meridian", lon0)]; "Eckert_IV" } - // Its standard parallel is the definition's, else 0, as PROJ 9.8.1 takes and writes it - // (the map's preset gives Winkel's own, acos(2/π), about 50.46°). + // Its standard parallel is the definition's, else 0, as PROJ takes a definition used as a + // coordinate system and writes it (the map's preset gives Winkel's own, acos(2/π), about + // 50.46°, which is also what the `proj` program takes for the bare projection). "wintri" => { let lat1 = get("lat_1").unwrap_or(0.0); ps = vec![("standard_parallel_1", lat1), ("central_meridian", lon0)]; @@ -2238,6 +2249,30 @@ pub(crate) mod tests { assert_eq!(crs_from_wkt(&wkt1.replace(r#"AXIS["Easting",EAST]"#, r#"AXIS["Easting",WEST]"#)), Err(REVERSED_AXES.into())); let wintri = r#"PROJCS["unknown",GEOGCS["unknown",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]]],PROJECTION["Winkel_Tripel"],PARAMETER["central_meridian",-60],PARAMETER["standard_parallel_1",40],PARAMETER["false_easting",100],PARAMETER["false_northing",-200],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH]]"#; assert!(crs_from_wkt(&wintri.replace(r#""standard_parallel_1",40"#, r#""standard_parallel_1",90"#)).is_err()); + // None has a scale factor: one other than 1 is refused in WKT, as `+k` is in a definition. + let scaled = + wkt1.replace(r#"PARAMETER["central_meridian",-60],"#, r#"PARAMETER["central_meridian",-60],PARAMETER["scale_factor",0.5],"#); + assert!(crs_from_wkt(&scaled).unwrap_err().contains("scale factor other than 1")); + assert!(crs_from_wkt(&scaled.replace("0.5]", "1]")).is_ok()); + assert!(Crs::parse("+proj=natearth +k=0.5 +datum=WGS84 +units=m +no_defs").is_err()); + // Natural Earth and Eckert IV have no standard parallel: a `+lat_1` is ignored, as in PROJ, + // where Winkel Tripel refuses one at a pole. `+geoc` changes nothing on their sphere (PROJ + // 9.9.0's `proj` gives the same position with and without it). + for name in ["natearth", "eck4"] { + let plain = Crs::parse(&format!("+proj={name} +lon_0=-60 +datum=WGS84 +units=m +no_defs")).unwrap().transformer().unwrap(); + for extra in ["+lat_1=95", "+geoc"] { + let def = format!("+proj={name} +lon_0=-60 {extra} +datum=WGS84 +units=m +no_defs"); + let t = Crs::parse(&def).unwrap_or_else(|e| panic!("{def}: {e}")).transformer().unwrap(); + let (a, b) = (t.from_lonlat(Coord::new(10.0, 45.0)).unwrap(), plain.from_lonlat(Coord::new(10.0, 45.0)).unwrap()); + assert!((a.x - b.x).abs() < 1e-6 && (a.y - b.y).abs() < 1e-6, "{def}: {a:?} {b:?}"); + } + } + assert!(Crs::parse("+proj=wintri +lat_1=95 +datum=WGS84 +units=m +no_defs").is_err()); + // An offset that isn't a number would place every point nowhere. + for bad in ["+x_0=inf", "+y_0=NaN", "+x_0=-inf"] { + let def = format!("+proj=natearth {bad} +datum=WGS84 +units=m +no_defs"); + assert!(Crs::parse(&def).is_err(), "{def}"); + } } /// A world projection's parameter that isn't a finite number (`1e400`, which the reader diff --git a/crates/geom/src/world.rs b/crates/geom/src/world.rs index 7c70c50aa9..38268f43dc 100644 --- a/crates/geom/src/world.rs +++ b/crates/geom/src/world.rs @@ -44,8 +44,10 @@ impl Kind { } /// Winkel's own standard parallel for his Tripel, acos(2/π) (about 50.46°, degrees): the one the -/// map's Winkel Tripel preset gives as its `+lat_1`. A definition or WKT without one is at 0, as -/// PROJ 9.8.1 takes it; GDAL and PROJ always write the parallel in WKT, so a file says which. +/// map's Winkel Tripel preset gives as its `+lat_1`, and the one the `proj` program takes for a +/// bare `+proj=wintri`. A definition used as a coordinate system, or WKT, without one is at 0, as +/// PROJ takes those (`cs2cs`, GDAL); GDAL and PROJ always write the parallel in WKT, so a file +/// says which. pub fn winkel_parallel() -> f64 { std::f64::consts::FRAC_2_PI.acos().to_degrees() } @@ -164,8 +166,8 @@ pub struct World { /// False easting and northing, metres. pub x0: f64, pub y0: f64, - /// Winkel Tripel's standard parallel, degrees (a definition's `+lat_1`, 0 without one, as in - /// PROJ); the other projections have none. + /// Winkel Tripel's standard parallel, degrees (a definition's `+lat_1`, 0 without one, as + /// PROJ takes a coordinate system's); the other projections have none. pub lat1: f64, } diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index ab23c91d40..992a0656c3 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -133,11 +133,14 @@ Krovak East/North variant, the oblique Mercator in its azimuth forms (the two-po no azimuth, is refused), and the Cassini-Soldner, polyconic and Equal Earth methods are supported from their parameters, as are sinusoidal (MODIS), Robinson, orthographic and Mercator (variant A), in `.prj` files and in GeoTIFF keys. Natural Earth, Winkel Tripel and Eckert IV are -read from WKT as GDAL, Esri and PROJ write it, and by their ESRI codes (World and Sphere Natural Earth and Eckert IV, `ESRI:54077`, `53077`, `54012`, -`53012`). They're computed on a sphere of the datum's semi-major axis, as PROJ computes them. Winkel Tripel's standard parallel is the file's; a -definition or WKT without one is at 0, as PROJ takes it. The map's Winkel Tripel is at Winkel's -own, acos(2/π) (about 50.46°), and its definition and WKT say so. A parameter that isn't a -finite number is refused rather than taken as not given. Esri's orthographic is a spherical projection: +read from WKT as GDAL, Esri and PROJ write it, and by their ESRI codes (Natural Earth and Eckert +IV, on WGS 84 and on a sphere: `ESRI:54077`, `53077`, `54012`, `53012`). They're computed on a +sphere of the datum's semi-major axis, as PROJ computes them. Winkel Tripel's standard parallel +is the file's; a definition or WKT without one is at 0, as PROJ and GDAL take a coordinate +system without one (PROJ's `proj` program, which runs the bare projection, takes Winkel's own +instead). The map's Winkel Tripel is at Winkel's own, acos(2/π) (about 50.46°), and its +definition and WKT say so. A parameter that isn't a finite number, or a scale factor other than +1, is refused rather than left out. Esri's orthographic is a spherical projection: on an ellipsoid it is refused, with a notice, rather than computed as EPSG's ellipsoidal one. The equidistant cylindrical projection (EPSG:4087, World Equidistant Cylindrical) uses a sphere of its datum's semi-major axis, matching legacy PROJ/GDAL coordinates (verified with PROJ 9.7.1), both for data