Skip to main content

mln_engine/geo/
projection.rs

1use std::f64::consts::PI;
2
3use geometry::Point;
4use mln_style::constants::{LATITUDE_MAX, LONGITUDE_MAX, TILE_SIZE_D};
5use mln_style::crs::WorldMapping;
6use mln_style::error::Error;
7use mln_style::geo::{LatLng, WrapMode};
8use mln_style::math::{clamp_f64, deg2rad, rad2deg};
9
10use crate::camera::constants::{MAX_ZOOM, MIN_ZOOM};
11use crate::geo::constants::{EARTH_RADIUS_M, M2PI};
12
13#[derive(Clone, Copy, Debug, Default, PartialEq)]
14pub struct ProjectedMeters {
15    /// Distance measured northwards.
16    northing: f64,
17    /// Distance measured eastwards.
18    easting: f64,
19}
20
21impl ProjectedMeters {
22    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a NaN
23    /// northing or easting.
24    pub fn new(n: f64, e: f64) -> Result<Self, Error> {
25        if n.is_nan() {
26            return Err(Error::invalid_argument("northing must not be NaN"));
27        }
28        if e.is_nan() {
29            return Err(Error::invalid_argument("easting must not be NaN"));
30        }
31        Ok(ProjectedMeters { northing: n, easting: e })
32    }
33
34    #[must_use]
35    pub fn northing(&self) -> f64 {
36        self.northing
37    }
38
39    #[must_use]
40    pub fn easting(&self) -> f64 {
41        self.easting
42    }
43}
44
45/// Spherical Mercator projection
46/// <https://github.com/openlayers/docs/blob/c7ab69156e17bedc1059d64d7a864b7868e354c1/library/spherical_mercator.rst>:
47/// its points and locations are Mercator's [`WorldMapping`]'s, which holds
48/// its formulas.
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    /// The point of `lat_lng` in a world `scale` times the tile size wide,
95    /// as Mercator's [`WorldMapping::project`] puts it.
96    #[must_use]
97    pub fn project(lat_lng: &LatLng, scale: f64) -> Point<f64> {
98        WorldMapping::default().project(lat_lng, scale)
99    }
100
101    /// The point of `lat_lng` on a world `2^zoom` tiles wide.
102    #[must_use]
103    pub(crate) fn project_zoom(lat_lng: &LatLng, zoom: i32) -> Point<f64> {
104        Self::project(lat_lng, 2f64.powi(zoom) / TILE_SIZE_D)
105    }
106
107    /// The location of a point in a world `scale` times the tile size wide,
108    /// as Mercator's [`WorldMapping::unproject`] finds it. Fails with the
109    /// [`LatLng::new`] error for a NaN or infinite result.
110    pub fn unproject(p: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Result<LatLng, Error> {
111        WorldMapping::default().unproject(p, scale, wrap_mode)
112    }
113}
114
115#[cfg(test)]
116#[path = "projection_test.rs"]
117mod projection_test;