Skip to main content

geolith_tiles_builder/terrain/
encoding.rs

1//! Elevation-to-RGB encodings for `raster-dem` tiles.
2//!
3//! Both encodings pack a signed elevation in metres into three 8-bit
4//! channels. `MapLibre` selects the decoder through the `encoding` field of a
5//! `raster-dem` source, so the emitted PNG must match the declared encoding
6//! exactly.
7
8use geolith::error::{GeolithError, Result};
9
10/// Mapbox Terrain-RGB base offset in metres.
11const MAPBOX_BASE: f64 = -10_000.0;
12
13/// Mapbox Terrain-RGB quantisation interval in metres.
14const MAPBOX_INTERVAL: f64 = 0.1;
15
16/// Terrarium base offset in metres.
17const TERRARIUM_BASE: f64 = 32_768.0;
18
19/// Elevation encoding for `raster-dem` tiles.
20#[non_exhaustive]
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum TerrainEncoding {
23    /// Mapbox Terrain-RGB: `height = -10000 + (R * 65536 + G * 256 + B) * 0.1`.
24    Mapbox,
25    /// Mapzen/Tilezen Terrarium: `height = R * 256 + G + B / 256 - 32768`.
26    Terrarium,
27}
28
29impl TerrainEncoding {
30    /// Parse the encoding from its `MapLibre` style-spec name.
31    ///
32    /// # Errors
33    ///
34    /// Returns [`GeolithError::BboxParse`] for unknown names.
35    pub fn parse(name: &str) -> Result<Self> {
36        match name {
37            "mapbox" | "terrain-rgb" => Ok(Self::Mapbox),
38            "terrarium" => Ok(Self::Terrarium),
39            other => Err(GeolithError::BboxParse(format!(
40                "unknown terrain encoding '{other}' — expected 'mapbox' or 'terrarium'"
41            ))),
42        }
43    }
44
45    /// The `MapLibre` `raster-dem` source `encoding` value for this encoding.
46    #[must_use]
47    pub const fn maplibre_name(&self) -> &'static str {
48        match self {
49            Self::Mapbox => "mapbox",
50            Self::Terrarium => "terrarium",
51        }
52    }
53
54    /// Encode an elevation in metres to an RGB triple.
55    ///
56    /// Elevations outside the representable range are clamped rather than
57    /// wrapped, so out-of-range data produces a saturated surface instead of
58    /// spurious cliffs.
59    #[must_use]
60    pub fn encode(&self, elevation: f32) -> [u8; 3] {
61        match self {
62            Self::Mapbox => {
63                let quantised =
64                    ((f64::from(elevation) - MAPBOX_BASE) / MAPBOX_INTERVAL).round() as i64;
65                let clamped = quantised.clamp(0, 0x00FF_FFFF) as u32;
66                [
67                    ((clamped >> 16) & 0xFF) as u8,
68                    ((clamped >> 8) & 0xFF) as u8,
69                    (clamped & 0xFF) as u8,
70                ]
71            }
72            Self::Terrarium => {
73                let shifted = f64::from(elevation) + TERRARIUM_BASE;
74                let quantised = (shifted * 256.0).round() as i64;
75                let clamped = quantised.clamp(0, 0x00FF_FFFF) as u32;
76                [
77                    ((clamped >> 16) & 0xFF) as u8,
78                    ((clamped >> 8) & 0xFF) as u8,
79                    (clamped & 0xFF) as u8,
80                ]
81            }
82        }
83    }
84
85    /// Decode an RGB triple back to metres.
86    #[must_use]
87    pub fn decode(&self, rgb: [u8; 3]) -> f32 {
88        let (r, g, b) = (f64::from(rgb[0]), f64::from(rgb[1]), f64::from(rgb[2]));
89        match self {
90            Self::Mapbox => (MAPBOX_BASE + (r * 65_536.0 + g * 256.0 + b) * MAPBOX_INTERVAL) as f32,
91            Self::Terrarium => (r * 256.0 + g + b / 256.0 - TERRARIUM_BASE) as f32,
92        }
93    }
94
95    /// The RGB triple used for tile pixels with no elevation data.
96    ///
97    /// Encoding zero metres keeps voids at sea level, which reads as flat
98    /// terrain rather than the extreme cliff that a raw zero byte triple
99    /// would produce under either encoding.
100    #[must_use]
101    pub fn nodata_rgb(&self) -> [u8; 3] {
102        self.encode(0.0)
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn parse_accepts_documented_names() {
112        assert_eq!(
113            TerrainEncoding::parse("mapbox").expect("valid"),
114            TerrainEncoding::Mapbox
115        );
116        assert_eq!(
117            TerrainEncoding::parse("terrain-rgb").expect("valid"),
118            TerrainEncoding::Mapbox
119        );
120        assert_eq!(
121            TerrainEncoding::parse("terrarium").expect("valid"),
122            TerrainEncoding::Terrarium
123        );
124    }
125
126    #[test]
127    fn parse_rejects_unknown_name() {
128        assert!(TerrainEncoding::parse("gizmo").is_err());
129    }
130
131    #[test]
132    fn maplibre_names_match_style_spec() {
133        assert_eq!(TerrainEncoding::Mapbox.maplibre_name(), "mapbox");
134        assert_eq!(TerrainEncoding::Terrarium.maplibre_name(), "terrarium");
135    }
136
137    /// The Mapbox spec fixes `-10000 m` at `(1, 134, 160)`.
138    #[test]
139    fn mapbox_encodes_documented_reference_values() {
140        assert_eq!(TerrainEncoding::Mapbox.encode(-10_000.0), [0, 0, 0]);
141        assert_eq!(TerrainEncoding::Mapbox.encode(-9_999.9), [0, 0, 1]);
142        assert_eq!(TerrainEncoding::Mapbox.encode(0.0), [1, 134, 160]);
143    }
144
145    #[test]
146    fn terrarium_encodes_documented_reference_values() {
147        assert_eq!(TerrainEncoding::Terrarium.encode(0.0), [128, 0, 0]);
148        assert_eq!(TerrainEncoding::Terrarium.encode(1.0), [128, 1, 0]);
149        assert_eq!(TerrainEncoding::Terrarium.encode(-1.0), [127, 255, 0]);
150    }
151
152    #[test]
153    fn mapbox_roundtrip_is_within_quantisation_step() {
154        let encoding = TerrainEncoding::Mapbox;
155        for elevation in [-500.0_f32, 0.0, 1.5, 2_250.0, 4_808.0, 8_848.0] {
156            let decoded = encoding.decode(encoding.encode(elevation));
157            assert!(
158                (decoded - elevation).abs() <= MAPBOX_INTERVAL as f32,
159                "{elevation} -> {decoded}"
160            );
161        }
162    }
163
164    #[test]
165    fn terrarium_roundtrip_is_within_quantisation_step() {
166        let encoding = TerrainEncoding::Terrarium;
167        for elevation in [-500.0_f32, 0.0, 1.5, 2_250.0, 4_808.0, 8_848.0] {
168            let decoded = encoding.decode(encoding.encode(elevation));
169            assert!(
170                (decoded - elevation).abs() <= 1.0 / 256.0,
171                "{elevation} -> {decoded}"
172            );
173        }
174    }
175
176    #[test]
177    fn encodings_clamp_instead_of_wrapping() {
178        assert_eq!(TerrainEncoding::Mapbox.encode(-20_000.0), [0, 0, 0]);
179        assert_eq!(
180            TerrainEncoding::Mapbox.encode(1.0e9),
181            [0xFF, 0xFF, 0xFF],
182            "extreme highs saturate rather than wrap to a low elevation"
183        );
184        assert_eq!(TerrainEncoding::Terrarium.encode(-40_000.0), [0, 0, 0]);
185        assert_eq!(TerrainEncoding::Terrarium.encode(1.0e9), [0xFF, 0xFF, 0xFF]);
186    }
187
188    #[test]
189    fn nodata_decodes_to_sea_level() {
190        for encoding in [TerrainEncoding::Mapbox, TerrainEncoding::Terrarium] {
191            let decoded = encoding.decode(encoding.nodata_rgb());
192            assert!(decoded.abs() < 0.1, "{encoding:?} nodata -> {decoded}");
193        }
194    }
195}