geolith 0.1.4

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
//! Tile ranges and Web Mercator conversions shared by the raster readers
//! and the terrain tiler.

/// Web Mercator world extent in metres, from the antimeridian to its mirror.
pub const WORLD_EXTENT: f64 = 20_037_508.342_789_244;

/// Convert a Web Mercator metre coordinate to a fractional tile index.
#[must_use]
pub fn mercator_to_tile_fraction(x: f64, y: f64, zoom: u8) -> (f64, f64) {
    let scale = f64::from(1_u32 << zoom);
    let tx = (x + WORLD_EXTENT) / (2.0 * WORLD_EXTENT) * scale;
    let ty = (WORLD_EXTENT - y) / (2.0 * WORLD_EXTENT) * scale;
    (tx, ty)
}

/// Inclusive tile index range covering a geographic bounding box at `zoom`.
#[must_use]
pub fn tile_range_for_bounds(bounds: (f64, f64, f64, f64), zoom: u8) -> (u32, u32, u32, u32) {
    let (min_lon, min_lat, max_lon, max_lat) = bounds;
    let max_index = (1_u32 << zoom) - 1;

    let (min_x, max_y_merc) = wgs84_to_mercator(min_lon, min_lat);
    let (max_x, min_y_merc) = wgs84_to_mercator(max_lon, max_lat);

    let (tx0, ty0) = mercator_to_tile_fraction(min_x, min_y_merc, zoom);
    let (tx1, ty1) = mercator_to_tile_fraction(max_x, max_y_merc, zoom);

    (
        (tx0.floor().max(0.0) as u32).min(max_index),
        (ty0.floor().max(0.0) as u32).min(max_index),
        (tx1.ceil().max(0.0) as u32).min(max_index),
        (ty1.ceil().max(0.0) as u32).min(max_index),
    )
}

/// Project WGS84 degrees to Web Mercator metres.
#[must_use]
pub fn wgs84_to_mercator(lon: f64, lat: f64) -> (f64, f64) {
    const R: f64 = 6_378_137.0;
    let x = lon.to_radians() * R;
    let clamped = lat.clamp(-85.051_128_78, 85.051_128_78).to_radians();
    let y = (std::f64::consts::FRAC_PI_4 + clamped / 2.0).tan().ln() * R;
    (x, y)
}