use crate::error::{GeolithError, Result};
const WGS84_A: f64 = 6_378_137.0;
const WGS84_INV_F: f64 = 298.257_223_563;
const UTM_K0: f64 = 0.9996;
const UTM_FALSE_EASTING: f64 = 500_000.0;
const UTM_FALSE_NORTHING_SOUTH: f64 = 10_000_000.0;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Crs {
Wgs84,
WebMercator,
Utm {
zone: u8,
north: bool,
},
}
impl Crs {
pub fn from_epsg(code: u32) -> Result<Self> {
match code {
4326 => Ok(Self::Wgs84),
3857 | 900_913 | 3785 => Ok(Self::WebMercator),
32_601..=32_660 => Ok(Self::Utm {
zone: (code - 32_600) as u8,
north: true,
}),
32_701..=32_760 => Ok(Self::Utm {
zone: (code - 32_700) as u8,
north: false,
}),
25_828..=25_838 => Ok(Self::Utm {
zone: (code - 25_800) as u8,
north: true,
}),
7_791..=7_793 => Ok(Self::Utm {
zone: (code - 7_759) as u8,
north: true,
}),
26_901..=26_923 => Ok(Self::Utm {
zone: (code - 26_900) as u8,
north: true,
}),
other => Err(GeolithError::Crs(format!(
"unsupported EPSG:{other} — supported: 4326, 3857, UTM zones \
(326xx/327xx WGS84, 258xx ETRS89, 7791-7793 RDN2008, 269xx NAD83)"
))),
}
}
#[must_use]
pub fn epsg(&self) -> u32 {
match *self {
Self::Wgs84 => 4326,
Self::WebMercator => 3857,
Self::Utm { zone, north } => {
let base = if north { 32_600 } else { 32_700 };
base + u32::from(zone)
}
}
}
#[must_use]
pub fn to_wgs84(&self, x: f64, y: f64) -> (f64, f64) {
match *self {
Self::Wgs84 => (x, y),
Self::WebMercator => web_mercator_to_wgs84(x, y),
Self::Utm { zone, north } => utm_to_wgs84(x, y, zone, north),
}
}
#[must_use]
pub fn from_wgs84(&self, lon: f64, lat: f64) -> (f64, f64) {
match *self {
Self::Wgs84 => (lon, lat),
Self::WebMercator => wgs84_to_web_mercator(lon, lat),
Self::Utm { zone, north } => wgs84_to_utm(lon, lat, zone, north),
}
}
}
#[must_use]
fn e_squared() -> f64 {
let f = 1.0 / WGS84_INV_F;
f * (2.0 - f)
}
#[must_use]
fn web_mercator_to_wgs84(x: f64, y: f64) -> (f64, f64) {
let lon = (x / WGS84_A).to_degrees();
let lat = ((y / WGS84_A).exp().atan() * 2.0 - std::f64::consts::FRAC_PI_2).to_degrees();
(lon, lat)
}
#[must_use]
fn wgs84_to_web_mercator(lon: f64, lat: f64) -> (f64, f64) {
let x = lon.to_radians() * WGS84_A;
let clamped = lat.clamp(-89.999_999, 89.999_999).to_radians();
let y = (std::f64::consts::FRAC_PI_4 + clamped / 2.0).tan().ln() * WGS84_A;
(x, y)
}
#[must_use]
fn utm_central_meridian(zone: u8) -> f64 {
f64::from(zone) * 6.0 - 183.0
}
#[must_use]
fn utm_to_wgs84(easting: f64, northing: f64, zone: u8, north: bool) -> (f64, f64) {
let e2 = e_squared();
let ep2 = e2 / (1.0 - e2);
let x = easting - UTM_FALSE_EASTING;
let y = if north {
northing
} else {
northing - UTM_FALSE_NORTHING_SOUTH
};
let m = y / UTM_K0;
let mu = m / (WGS84_A * (1.0 - e2 / 4.0 - 3.0 * e2 * e2 / 64.0 - 5.0 * e2.powi(3) / 256.0));
let sqrt_1_e2 = (1.0 - e2).sqrt();
let e1 = (1.0 - sqrt_1_e2) / (1.0 + sqrt_1_e2);
let phi1 = mu
+ (3.0 * e1 / 2.0 - 27.0 * e1.powi(3) / 32.0) * (2.0 * mu).sin()
+ (21.0 * e1 * e1 / 16.0 - 55.0 * e1.powi(4) / 32.0) * (4.0 * mu).sin()
+ (151.0 * e1.powi(3) / 96.0) * (6.0 * mu).sin()
+ (1097.0 * e1.powi(4) / 512.0) * (8.0 * mu).sin();
let (sin_phi1, cos_phi1) = phi1.sin_cos();
let tan_phi1 = sin_phi1 / cos_phi1;
let c1 = ep2 * cos_phi1 * cos_phi1;
let t1 = tan_phi1 * tan_phi1;
let denom = 1.0 - e2 * sin_phi1 * sin_phi1;
let n1 = WGS84_A / denom.sqrt();
let r1 = WGS84_A * (1.0 - e2) / denom.powf(1.5);
let d = x / (n1 * UTM_K0);
let d2 = d * d;
let d4 = d2 * d2;
let d6 = d4 * d2;
let lat = phi1
- (n1 * tan_phi1 / r1)
* (d2 / 2.0 - (5.0 + 3.0 * t1 + 10.0 * c1 - 4.0 * c1 * c1 - 9.0 * ep2) * d4 / 24.0
+ (61.0 + 90.0 * t1 + 298.0 * c1 + 45.0 * t1 * t1 - 252.0 * ep2 - 3.0 * c1 * c1)
* d6
/ 720.0);
let lon = utm_central_meridian(zone).to_radians()
+ (d - (1.0 + 2.0 * t1 + c1) * d2 * d / 6.0
+ (5.0 - 2.0 * c1 + 28.0 * t1 - 3.0 * c1 * c1 + 8.0 * ep2 + 24.0 * t1 * t1) * d4 * d
/ 120.0)
/ cos_phi1;
(lon.to_degrees(), lat.to_degrees())
}
#[must_use]
fn wgs84_to_utm(lon: f64, lat: f64, zone: u8, north: bool) -> (f64, f64) {
let e2 = e_squared();
let ep2 = e2 / (1.0 - e2);
let phi = lat.to_radians();
let lambda = lon.to_radians();
let lambda0 = utm_central_meridian(zone).to_radians();
let (sin_phi, cos_phi) = phi.sin_cos();
let tan_phi = sin_phi / cos_phi;
let n = WGS84_A / (1.0 - e2 * sin_phi * sin_phi).sqrt();
let t = tan_phi * tan_phi;
let c = ep2 * cos_phi * cos_phi;
let a_term = cos_phi * (lambda - lambda0);
let m = WGS84_A
* ((1.0 - e2 / 4.0 - 3.0 * e2 * e2 / 64.0 - 5.0 * e2.powi(3) / 256.0) * phi
- (3.0 * e2 / 8.0 + 3.0 * e2 * e2 / 32.0 + 45.0 * e2.powi(3) / 1024.0)
* (2.0 * phi).sin()
+ (15.0 * e2 * e2 / 256.0 + 45.0 * e2.powi(3) / 1024.0) * (4.0 * phi).sin()
- (35.0 * e2.powi(3) / 3072.0) * (6.0 * phi).sin());
let a2 = a_term * a_term;
let a3 = a2 * a_term;
let a4 = a2 * a2;
let a5 = a4 * a_term;
let a6 = a4 * a2;
let easting = UTM_K0
* n
* (a_term
+ (1.0 - t + c) * a3 / 6.0
+ (5.0 - 18.0 * t + t * t + 72.0 * c - 58.0 * ep2) * a5 / 120.0)
+ UTM_FALSE_EASTING;
let mut northing = UTM_K0
* (m + n
* tan_phi
* (a2 / 2.0
+ (5.0 - t + 9.0 * c + 4.0 * c * c) * a4 / 24.0
+ (61.0 - 58.0 * t + t * t + 600.0 * c - 330.0 * ep2) * a6 / 720.0));
if !north {
northing += UTM_FALSE_NORTHING_SOUTH;
}
(easting, northing)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn epsg_roundtrip_for_supported_codes() {
for code in [4326_u32, 3857, 32_632, 32_701, 32_760] {
let crs = Crs::from_epsg(code).expect("supported code");
assert_eq!(crs.epsg(), code);
}
}
#[test]
fn epsg_aliases_map_to_web_mercator() {
assert_eq!(
Crs::from_epsg(900_913).expect("alias"),
Crs::WebMercator,
"900913 is the legacy Web Mercator alias"
);
assert_eq!(Crs::from_epsg(3785).expect("alias"), Crs::WebMercator);
}
#[test]
fn unsupported_epsg_is_rejected() {
let err = Crs::from_epsg(27_700).expect_err("OSGB is unsupported");
assert!(matches!(err, GeolithError::Crs(_)));
}
#[test]
fn utm_compatible_datums_map_to_wgs84_zones() {
assert_eq!(
Crs::from_epsg(7_791).expect("RDN2008 32N"),
Crs::Utm {
zone: 32,
north: true
}
);
assert_eq!(
Crs::from_epsg(25_832).expect("ETRS89 32N"),
Crs::Utm {
zone: 32,
north: true
}
);
assert_eq!(
Crs::from_epsg(26_910).expect("NAD83 10N"),
Crs::Utm {
zone: 10,
north: true
}
);
assert!(
Crs::from_epsg(7_794).is_err(),
"RDN2008 / Italy zone is not a UTM zone and must be rejected"
);
}
#[test]
fn wgs84_is_identity() {
let crs = Crs::Wgs84;
let (lon, lat) = crs.to_wgs84(7.9797, 45.9756);
assert!((lon - 7.9797).abs() < 1e-12);
assert!((lat - 45.9756).abs() < 1e-12);
}
#[test]
fn web_mercator_roundtrip() {
let crs = Crs::WebMercator;
let (x, y) = crs.from_wgs84(7.9797, 45.9756);
let (lon, lat) = crs.to_wgs84(x, y);
assert!((lon - 7.9797).abs() < 1e-9, "lon roundtrip: {lon}");
assert!((lat - 45.9756).abs() < 1e-9, "lat roundtrip: {lat}");
}
#[test]
fn web_mercator_origin_is_zero() {
let (x, y) = Crs::WebMercator.from_wgs84(0.0, 0.0);
assert!(x.abs() < 1e-9);
assert!(y.abs() < 1e-9);
}
#[test]
fn utm_north_roundtrip_belvedere() {
let crs = Crs::Utm {
zone: 32,
north: true,
};
let (lon0, lat0) = (7.9097, 45.9256);
let (e, n) = crs.from_wgs84(lon0, lat0);
assert!(
(400_000.0..=600_000.0).contains(&e),
"easting near central meridian: {e}"
);
assert!(
(5_000_000.0..=5_200_000.0).contains(&n),
"northing for 45.9N: {n}"
);
let (lon, lat) = crs.to_wgs84(e, n);
assert!((lon - lon0).abs() < 1e-7, "lon roundtrip: {lon}");
assert!((lat - lat0).abs() < 1e-7, "lat roundtrip: {lat}");
}
#[test]
fn utm_central_meridian_matches_zone_definition() {
assert!((utm_central_meridian(1) + 177.0).abs() < 1e-12);
assert!((utm_central_meridian(31) - 3.0).abs() < 1e-12);
assert!((utm_central_meridian(60) - 177.0).abs() < 1e-12);
}
#[test]
fn utm_central_meridian_has_false_easting_exactly() {
let crs = Crs::Utm {
zone: 32,
north: true,
};
let (e, _) = crs.from_wgs84(utm_central_meridian(32), 45.0);
assert!(
(e - UTM_FALSE_EASTING).abs() < 1e-6,
"central meridian maps to false easting: {e}"
);
}
#[test]
fn utm_south_roundtrip_applies_false_northing() {
let crs = Crs::Utm {
zone: 55,
north: false,
};
let (lon0, lat0) = (147.0, -42.0);
let (e, n) = crs.from_wgs84(lon0, lat0);
assert!(
n > 5_000_000.0,
"southern northing carries the false offset: {n}"
);
let (lon, lat) = crs.to_wgs84(e, n);
assert!((lon - lon0).abs() < 1e-7, "lon roundtrip: {lon}");
assert!((lat - lat0).abs() < 1e-7, "lat roundtrip: {lat}");
}
#[test]
fn utm_equator_northing_is_zero_in_north() {
let crs = Crs::Utm {
zone: 32,
north: true,
};
let (_, n) = crs.from_wgs84(9.0, 0.0);
assert!(n.abs() < 1e-6, "equator northing in north zone: {n}");
}
}