Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-quality/src/geo.rs

//! Web Mercator, ground resolution and the pixel grid of one view.
//!
//! A view is defined by **metres per pixel on the ground at its centre** (`res`). A zoom
//! number is derived from it only to drive today's viewer and today's `lod` wire; the
//! v3 wire takes `res` directly.

/// WGS 84 equatorial radius, the Web Mercator sphere.
pub const EARTH_R: f64 = 6_378_137.0;
/// Web Mercator latitude limit.
pub const MAX_LAT: f64 = 85.051_128_779_806_59;
/// The slippy tile size: a 256-px world is zoom 0.
pub const TILE: f64 = 256.0;

/// Mercator x in `0..1` (west to east).
#[must_use]
pub fn merc_x(lon: f64) -> f64 {
    (lon + 180.0) / 360.0
}

/// Mercator y in `0..1` (north to south).
#[must_use]
pub fn merc_y(lat: f64) -> f64 {
    let p = lat.clamp(-MAX_LAT, MAX_LAT).to_radians();
    (1.0 - (p.tan() + 1.0 / p.cos()).ln() / std::f64::consts::PI) / 2.0
}

/// Longitude of a mercator x.
#[must_use]
pub fn lon_of(mx: f64) -> f64 {
    mx * 360.0 - 180.0
}

/// Latitude of a mercator y.
#[must_use]
pub fn lat_of(my: f64) -> f64 {
    let n = std::f64::consts::PI * (1.0 - 2.0 * my);
    n.sinh().atan().to_degrees()
}

/// Ground metres per pixel at `lat` for a slippy `zoom`.
#[must_use]
pub fn res_at_zoom(zoom: f64, lat: f64) -> f64 {
    2.0 * std::f64::consts::PI * EARTH_R * lat.to_radians().cos() / (TILE * zoom.exp2())
}

/// The slippy zoom whose ground resolution at `lat` is `res` metres per pixel.
#[must_use]
pub fn zoom_for_res(res: f64, lat: f64) -> f64 {
    (2.0 * std::f64::consts::PI * EARTH_R * lat.to_radians().cos() / (TILE * res)).log2()
}

/// Ground distance in metres (equirectangular, good to well under 1 % at view sizes).
#[must_use]
pub fn ground_m(a: (f64, f64), b: (f64, f64)) -> f64 {
    let x = (b.0 - a.0).to_radians() * ((a.1 + b.1) / 2.0).to_radians().cos();
    let y = (b.1 - a.1).to_radians();
    EARTH_R * x.hypot(y)
}

/// Area of a lon/lat ring in km² (shoelace on a local equirectangular plane), signed:
/// counter-clockwise positive.
#[must_use]
pub fn ring_area_km2(ring: &[[f64; 2]]) -> f64 {
    if ring.len() < 3 {
        return 0.0;
    }
    let lat0 = ring[0][1].to_radians().cos();
    let k = (EARTH_R / 1000.0).powi(2) * (std::f64::consts::PI / 180.0).powi(2) * lat0;
    let mut s = 0.0;
    for w in ring.windows(2) {
        s += w[0][0] * w[1][1] - w[1][0] * w[0][1];
    }
    let (f, l) = (ring[0], ring[ring.len() - 1]);
    s += l[0] * f[1] - f[0] * l[1];
    s / 2.0 * k
}

/// The pixel grid of one view: lon/lat ↔ canvas pixels, exactly as a slippy viewer
/// centred on (`lon`, `lat`) at `zoom` lays out a `width`×`height` canvas.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Grid {
    pub width: u32,
    pub height: u32,
    /// Pixels per whole world (256 · 2^zoom).
    pub world_px: f64,
    /// Mercator coordinate of the canvas' top-left corner.
    pub mx0: f64,
    pub my0: f64,
}

impl Grid {
    #[must_use]
    pub fn new(lon: f64, lat: f64, zoom: f64, width: u32, height: u32) -> Self {
        let world_px = TILE * zoom.exp2();
        Self {
            width,
            height,
            world_px,
            mx0: merc_x(lon) - f64::from(width) / 2.0 / world_px,
            my0: merc_y(lat) - f64::from(height) / 2.0 / world_px,
        }
    }

    /// Canvas pixel coordinates (continuous; pixel `i` spans `i..i+1`) of a lon/lat.
    #[must_use]
    pub fn to_px(&self, lon: f64, lat: f64) -> (f64, f64) {
        (
            (merc_x(lon) - self.mx0) * self.world_px,
            (merc_y(lat) - self.my0) * self.world_px,
        )
    }

    /// Lon/lat of a continuous canvas position.
    #[must_use]
    pub fn to_lonlat(&self, x: f64, y: f64) -> (f64, f64) {
        (
            lon_of(self.mx0 + x / self.world_px),
            lat_of(self.my0 + y / self.world_px),
        )
    }

    /// `[minlon, minlat, maxlon, maxlat]` of the canvas.
    #[must_use]
    pub fn bbox(&self) -> [f64; 4] {
        let (w, h) = (f64::from(self.width), f64::from(self.height));
        let (a, b) = self.to_lonlat(0.0, h);
        let (c, d) = self.to_lonlat(w, 0.0);
        [a, b, c, d]
    }

    /// Pixel count.
    #[must_use]
    pub fn len(&self) -> usize {
        self.width as usize * self.height as usize
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn zoom_and_res_are_inverse() {
        for lat in [0.0, 55.0, 59.33, 67.86] {
            for res in [0.5, 1.6, 16.0, 160.0, 1600.0] {
                let z = zoom_for_res(res, lat);
                assert!((res_at_zoom(z, lat) - res).abs() / res < 1e-12);
            }
        }
        // The textbook number: zoom 0 at the equator is 156 543.03 m per pixel.
        assert!((res_at_zoom(0.0, 0.0) - 156_543.033_928).abs() < 1e-3);
    }

    #[test]
    fn mercator_round_trips() {
        for (lon, lat) in [
            (18.07, 59.33),
            (11.97, 57.71),
            (20.22, 67.86),
            (-10.0, -40.0),
        ] {
            assert!((lon_of(merc_x(lon)) - lon).abs() < 1e-12);
            assert!((lat_of(merc_y(lat)) - lat).abs() < 1e-9);
        }
    }

    #[test]
    fn grid_centre_is_the_view_centre_and_res_holds() {
        let (lon, lat, res) = (18.07, 59.33, 16.0);
        let g = Grid::new(lon, lat, zoom_for_res(res, lat), 1920, 1080);
        let (x, y) = g.to_px(lon, lat);
        assert!((x - 960.0).abs() < 1e-6 && (y - 540.0).abs() < 1e-6);
        // One pixel east of the centre is `res` metres away on the ground.
        let p = g.to_lonlat(961.0, 540.0);
        assert!((ground_m((lon, lat), p) - res).abs() < 0.01);
        let b = g.bbox();
        assert!(b[0] < lon && lon < b[2] && b[1] < lat && lat < b[3]);
    }

    #[test]
    fn ring_area_of_a_degree_square_at_60n() {
        let r = [
            [0.0, 60.0],
            [1.0, 60.0],
            [1.0, 61.0],
            [0.0, 61.0],
            [0.0, 60.0],
        ];
        let a = ring_area_km2(&r);
        // 111.32 km × cos60 × 111.32 km ≈ 6 196 km² (on the sphere of radius EARTH_R).
        assert!((a - 6196.0).abs() < 40.0, "{a}");
    }
}