geolith 0.2.1

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Coordinate reference system transforms for DEM reprojection.
//!
//! Supports the CRS families produced by drone photogrammetry toolchains:
//! geographic WGS84 (EPSG:4326), Web Mercator (EPSG:3857), and the UTM
//! zone grids (EPSG:326xx north / 327xx south) that `OpenDroneMap` emits by
//! default. Transforms are pure Rust with no PROJ dependency.

use crate::error::{GeolithError, Result};

/// WGS84 semi-major axis in metres.
const WGS84_A: f64 = 6_378_137.0;

/// WGS84 inverse flattening.
const WGS84_INV_F: f64 = 298.257_223_563;

/// UTM central scale factor.
const UTM_K0: f64 = 0.9996;

/// UTM false easting in metres.
const UTM_FALSE_EASTING: f64 = 500_000.0;

/// UTM false northing applied in the southern hemisphere, in metres.
const UTM_FALSE_NORTHING_SOUTH: f64 = 10_000_000.0;

/// A supported coordinate reference system.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Crs {
    /// Geographic coordinates on the WGS84 datum (EPSG:4326), in degrees.
    Wgs84,
    /// Spherical Web Mercator (EPSG:3857), in metres.
    WebMercator,
    /// Universal Transverse Mercator on the WGS84 datum.
    Utm {
        /// UTM zone number, 1 through 60.
        zone: u8,
        /// Whether the zone is in the northern hemisphere.
        north: bool,
    },
}

impl Crs {
    /// Resolve a CRS from its EPSG code.
    ///
    /// UTM grids on ETRS89 (25828–25838), RDN2008 (7791–7793) and NAD83
    /// (26901–26923) datums are mapped to WGS84 UTM: those datums agree with
    /// WGS84 to well under a metre, far below raster tile resolution.
    ///
    /// # Errors
    ///
    /// Returns [`GeolithError::Crs`] when the code is outside the supported
    /// set of 4326, 3857, and the UTM zone families.
    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)"
            ))),
        }
    }

    /// The EPSG code for this CRS.
    #[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)
            }
        }
    }

    /// Convert a projected coordinate in this CRS to WGS84 lon/lat degrees.
    #[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),
        }
    }

    /// Convert WGS84 lon/lat degrees to a projected coordinate in this CRS.
    #[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),
        }
    }
}

/// Square eccentricity of the WGS84 ellipsoid.
#[must_use]
fn e_squared() -> f64 {
    let f = 1.0 / WGS84_INV_F;
    f * (2.0 - f)
}

/// Convert Web Mercator metres to WGS84 lon/lat degrees.
#[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)
}

/// Convert WGS84 lon/lat degrees to Web Mercator metres.
#[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)
}

/// Central meridian of a UTM zone, in degrees.
#[must_use]
fn utm_central_meridian(zone: u8) -> f64 {
    f64::from(zone) * 6.0 - 183.0
}

/// Inverse UTM projection using the Snyder series (USGS Professional Paper 1395).
#[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())
}

/// Forward UTM projection using the Snyder series (USGS Professional Paper 1395).
#[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(_)));
    }

    /// EPSG:7791 (RDN2008 / UTM 32N) is what the Belvedere Glacier UAV DSMs
    /// carry; the RDN2008 datum matches WGS84 within centimetres.
    #[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);
    }

    /// Belvedere Glacier sits in UTM zone 32N; the reference easting/northing
    /// come from projecting its published WGS84 centre with PROJ.
    #[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}");
    }
}