geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
//! Elevation-to-RGB encodings for `raster-dem` tiles.
//!
//! Both encodings pack a signed elevation in metres into three 8-bit
//! channels. `MapLibre` selects the decoder through the `encoding` field of a
//! `raster-dem` source, so the emitted PNG must match the declared encoding
//! exactly.

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

/// Mapbox Terrain-RGB base offset in metres.
const MAPBOX_BASE: f64 = -10_000.0;

/// Mapbox Terrain-RGB quantisation interval in metres.
const MAPBOX_INTERVAL: f64 = 0.1;

/// Terrarium base offset in metres.
const TERRARIUM_BASE: f64 = 32_768.0;

/// Elevation encoding for `raster-dem` tiles.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TerrainEncoding {
    /// Mapbox Terrain-RGB: `height = -10000 + (R * 65536 + G * 256 + B) * 0.1`.
    Mapbox,
    /// Mapzen/Tilezen Terrarium: `height = R * 256 + G + B / 256 - 32768`.
    Terrarium,
}

impl TerrainEncoding {
    /// Parse the encoding from its `MapLibre` style-spec name.
    ///
    /// # Errors
    ///
    /// Returns [`GeolithError::BboxParse`] for unknown names.
    pub fn parse(name: &str) -> Result<Self> {
        match name {
            "mapbox" | "terrain-rgb" => Ok(Self::Mapbox),
            "terrarium" => Ok(Self::Terrarium),
            other => Err(GeolithError::BboxParse(format!(
                "unknown terrain encoding '{other}' — expected 'mapbox' or 'terrarium'"
            ))),
        }
    }

    /// The `MapLibre` `raster-dem` source `encoding` value for this encoding.
    #[must_use]
    pub const fn maplibre_name(&self) -> &'static str {
        match self {
            Self::Mapbox => "mapbox",
            Self::Terrarium => "terrarium",
        }
    }

    /// Encode an elevation in metres to an RGB triple.
    ///
    /// Elevations outside the representable range are clamped rather than
    /// wrapped, so out-of-range data produces a saturated surface instead of
    /// spurious cliffs.
    #[must_use]
    pub fn encode(&self, elevation: f32) -> [u8; 3] {
        match self {
            Self::Mapbox => {
                let quantised =
                    ((f64::from(elevation) - MAPBOX_BASE) / MAPBOX_INTERVAL).round() as i64;
                let clamped = quantised.clamp(0, 0x00FF_FFFF) as u32;
                [
                    ((clamped >> 16) & 0xFF) as u8,
                    ((clamped >> 8) & 0xFF) as u8,
                    (clamped & 0xFF) as u8,
                ]
            }
            Self::Terrarium => {
                let shifted = f64::from(elevation) + TERRARIUM_BASE;
                let quantised = (shifted * 256.0).round() as i64;
                let clamped = quantised.clamp(0, 0x00FF_FFFF) as u32;
                [
                    ((clamped >> 16) & 0xFF) as u8,
                    ((clamped >> 8) & 0xFF) as u8,
                    (clamped & 0xFF) as u8,
                ]
            }
        }
    }

    /// Decode an RGB triple back to metres.
    #[must_use]
    pub fn decode(&self, rgb: [u8; 3]) -> f32 {
        let (r, g, b) = (f64::from(rgb[0]), f64::from(rgb[1]), f64::from(rgb[2]));
        match self {
            Self::Mapbox => (MAPBOX_BASE + (r * 65_536.0 + g * 256.0 + b) * MAPBOX_INTERVAL) as f32,
            Self::Terrarium => (r * 256.0 + g + b / 256.0 - TERRARIUM_BASE) as f32,
        }
    }

    /// The RGB triple used for tile pixels with no elevation data.
    ///
    /// Encoding zero metres keeps voids at sea level, which reads as flat
    /// terrain rather than the extreme cliff that a raw zero byte triple
    /// would produce under either encoding.
    #[must_use]
    pub fn nodata_rgb(&self) -> [u8; 3] {
        self.encode(0.0)
    }
}

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

    #[test]
    fn parse_accepts_documented_names() {
        assert_eq!(
            TerrainEncoding::parse("mapbox").expect("valid"),
            TerrainEncoding::Mapbox
        );
        assert_eq!(
            TerrainEncoding::parse("terrain-rgb").expect("valid"),
            TerrainEncoding::Mapbox
        );
        assert_eq!(
            TerrainEncoding::parse("terrarium").expect("valid"),
            TerrainEncoding::Terrarium
        );
    }

    #[test]
    fn parse_rejects_unknown_name() {
        assert!(TerrainEncoding::parse("gizmo").is_err());
    }

    #[test]
    fn maplibre_names_match_style_spec() {
        assert_eq!(TerrainEncoding::Mapbox.maplibre_name(), "mapbox");
        assert_eq!(TerrainEncoding::Terrarium.maplibre_name(), "terrarium");
    }

    /// The Mapbox spec fixes `-10000 m` at `(1, 134, 160)`.
    #[test]
    fn mapbox_encodes_documented_reference_values() {
        assert_eq!(TerrainEncoding::Mapbox.encode(-10_000.0), [0, 0, 0]);
        assert_eq!(TerrainEncoding::Mapbox.encode(-9_999.9), [0, 0, 1]);
        assert_eq!(TerrainEncoding::Mapbox.encode(0.0), [1, 134, 160]);
    }

    #[test]
    fn terrarium_encodes_documented_reference_values() {
        assert_eq!(TerrainEncoding::Terrarium.encode(0.0), [128, 0, 0]);
        assert_eq!(TerrainEncoding::Terrarium.encode(1.0), [128, 1, 0]);
        assert_eq!(TerrainEncoding::Terrarium.encode(-1.0), [127, 255, 0]);
    }

    #[test]
    fn mapbox_roundtrip_is_within_quantisation_step() {
        let encoding = TerrainEncoding::Mapbox;
        for elevation in [-500.0_f32, 0.0, 1.5, 2_250.0, 4_808.0, 8_848.0] {
            let decoded = encoding.decode(encoding.encode(elevation));
            assert!(
                (decoded - elevation).abs() <= MAPBOX_INTERVAL as f32,
                "{elevation} -> {decoded}"
            );
        }
    }

    #[test]
    fn terrarium_roundtrip_is_within_quantisation_step() {
        let encoding = TerrainEncoding::Terrarium;
        for elevation in [-500.0_f32, 0.0, 1.5, 2_250.0, 4_808.0, 8_848.0] {
            let decoded = encoding.decode(encoding.encode(elevation));
            assert!(
                (decoded - elevation).abs() <= 1.0 / 256.0,
                "{elevation} -> {decoded}"
            );
        }
    }

    #[test]
    fn encodings_clamp_instead_of_wrapping() {
        assert_eq!(TerrainEncoding::Mapbox.encode(-20_000.0), [0, 0, 0]);
        assert_eq!(
            TerrainEncoding::Mapbox.encode(1.0e9),
            [0xFF, 0xFF, 0xFF],
            "extreme highs saturate rather than wrap to a low elevation"
        );
        assert_eq!(TerrainEncoding::Terrarium.encode(-40_000.0), [0, 0, 0]);
        assert_eq!(TerrainEncoding::Terrarium.encode(1.0e9), [0xFF, 0xFF, 0xFF]);
    }

    #[test]
    fn nodata_decodes_to_sea_level() {
        for encoding in [TerrainEncoding::Mapbox, TerrainEncoding::Terrarium] {
            let decoded = encoding.decode(encoding.nodata_rgb());
            assert!(decoded.abs() < 0.1, "{encoding:?} nodata -> {decoded}");
        }
    }
}