Skip to main content

mln_engine/geo/
projection.rs

1use std::f64::consts::PI;
2
3use geometry::Point;
4use mln_style::constants::{DEGREES_MAX, LATITUDE_MAX, LONGITUDE_MAX, TILE_SIZE_D};
5use mln_style::error::Error;
6use mln_style::geo::{LatLng, WrapMode};
7use mln_style::math::{clamp_f64, deg2rad, rad2deg};
8
9use crate::camera::constants::{MAX_ZOOM, MIN_ZOOM};
10use crate::geo::constants::{EARTH_RADIUS_M, M2PI};
11
12#[derive(Clone, Copy, Debug, Default, PartialEq)]
13pub struct ProjectedMeters {
14    /// Distance measured northwards.
15    northing: f64,
16    /// Distance measured eastwards.
17    easting: f64,
18}
19
20// The derived PartialEq is the C++ operator==:
21// `a._northing == b._northing && a._easting == b._easting`.
22
23impl ProjectedMeters {
24    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a NaN
25    /// northing or easting.
26    pub fn new(n: f64, e: f64) -> Result<Self, Error> {
27        if n.is_nan() {
28            return Err(Error::invalid_argument("northing must not be NaN"));
29        }
30        if e.is_nan() {
31            return Err(Error::invalid_argument("easting must not be NaN"));
32        }
33        Ok(ProjectedMeters { northing: n, easting: e })
34    }
35
36    #[must_use]
37    pub fn northing(&self) -> f64 {
38        self.northing
39    }
40
41    #[must_use]
42    pub fn easting(&self) -> f64 {
43        self.easting
44    }
45}
46
47/// Spherical Mercator projection
48/// <https://github.com/openlayers/docs/blob/c7ab69156e17bedc1059d64d7a864b7868e354c1/library/spherical_mercator.rst>
49pub struct Projection;
50
51impl Projection {
52    /// Map pixel width at given scale.
53    #[must_use]
54    pub(crate) fn world_size(scale: f64) -> f64 {
55        scale * TILE_SIZE_D
56    }
57
58    #[must_use]
59    pub fn meters_per_pixel_at_latitude(lat: f64, zoom: f64) -> f64 {
60        let constrained_zoom = clamp_f64(zoom, MIN_ZOOM, MAX_ZOOM);
61        let constrained_scale = 2.0f64.powf(constrained_zoom);
62        let constrained_latitude = clamp_f64(lat, -LATITUDE_MAX, LATITUDE_MAX);
63        deg2rad(constrained_latitude).cos() * M2PI * EARTH_RADIUS_M / Self::world_size(constrained_scale)
64    }
65
66    #[must_use]
67    pub fn projected_meters_for_lat_lng(lat_lng: &LatLng) -> ProjectedMeters {
68        let constrained_latitude = clamp_f64(lat_lng.latitude(), -LATITUDE_MAX, LATITUDE_MAX);
69        let constrained_longitude = clamp_f64(lat_lng.longitude(), -LONGITUDE_MAX, LONGITUDE_MAX);
70
71        let m = 1.0 - 1e-15;
72        let f = clamp_f64(deg2rad(constrained_latitude).sin(), -m, m);
73
74        let easting = deg2rad(EARTH_RADIUS_M * constrained_longitude);
75        let northing = 0.5 * EARTH_RADIUS_M * ((1.0 + f) / (1.0 - f)).ln();
76
77        // A valid LatLng, clamped, gives values that aren't NaN.
78        ProjectedMeters { northing, easting }
79    }
80
81    /// The clamps keep both values in range, a NaN clamping to the upper
82    /// bound.
83    #[must_use]
84    pub fn lat_lng_for_projected_meters(projected_meters: &ProjectedMeters) -> LatLng {
85        let mut latitude = rad2deg(2.0 * (projected_meters.northing() / EARTH_RADIUS_M).exp().atan() - (PI / 2.0));
86        let mut longitude = rad2deg(projected_meters.easting()) / EARTH_RADIUS_M;
87
88        latitude = clamp_f64(latitude, -LATITUDE_MAX, LATITUDE_MAX);
89        longitude = clamp_f64(longitude, -LONGITUDE_MAX, LONGITUDE_MAX);
90
91        LatLng::saturating(latitude, longitude, WrapMode::Unwrapped)
92    }
93
94    #[must_use]
95    pub fn project(lat_lng: &LatLng, scale: f64) -> Point<f64> {
96        Self::project_(lat_lng, Self::world_size(scale))
97    }
98
99    /// The point of `lat_lng` on a world `2^zoom` tiles wide.
100    #[must_use]
101    pub(crate) fn project_zoom(lat_lng: &LatLng, zoom: i32) -> Point<f64> {
102        Self::project_(lat_lng, 2f64.powi(zoom))
103    }
104
105    /// Fails with the [`LatLng::new`] error for a NaN or infinite result.
106    pub fn unproject(p: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Result<LatLng, Error> {
107        // `p * util::DEGREES_MAX / worldSize(scale)` (mapbox point operators)
108        let world_size = Self::world_size(scale);
109        let p2 = Point::new(p.x * DEGREES_MAX / world_size, p.y * DEGREES_MAX / world_size);
110        LatLng::with_mode(
111            deg2rad(LONGITUDE_MAX - p2.y).exp().atan() * DEGREES_MAX / PI - 90.0,
112            p2.x - LONGITUDE_MAX,
113            wrap_mode,
114        )
115    }
116
117    fn project_(lat_lng: &LatLng, world_size: f64) -> Point<f64> {
118        let latitude = clamp_f64(lat_lng.latitude(), -LATITUDE_MAX, LATITUDE_MAX);
119        // `Point{...} * (worldSize / util::DEGREES_MAX)`
120        let k = world_size / DEGREES_MAX;
121        Point::new(
122            (LONGITUDE_MAX + lat_lng.longitude()) * k,
123            (LONGITUDE_MAX - rad2deg((PI / 4.0 + latitude * PI / DEGREES_MAX).tan().ln())) * k,
124        )
125    }
126}
127
128#[cfg(test)]
129#[path = "projection_test.rs"]
130mod projection_test;