Skip to main content

mln_engine/tile/
dem.rs

1//! The height rule of raster-dem sources: how a DEM texel decodes to meters,
2//! and how terrain reads a height between texels. The shaders follow it in
3//! the same `f32` operations, in the same order: hillshade's and color
4//! relief's decode texels as [`DemUnpack::decode`] does, and terrain's read
5//! heights as [`sample`] does at its mesh's vertices. So the CPU reads the
6//! heights the GPU draws at the vertices, bit for bit; between them the
7//! surface is linear across each quad, which spans a DEM tile's size / 256
8//! pixels or fewer, 2 for 512 px tiles. `mln_engine`'s conformance case
9//! `terrain_heights` checks each backend against [`sample`].
10//!
11//! A DEM tile of `dim` pixels a side is kept behind a one-texel border, so
12//! its bordered texels run from 0 to `dim + 1` and pixel `i` is texel
13//! `i + 1`. Pixel `i` describes the cell centred at `(i + 0.5) / dim` of the
14//! tile, as hillshade and color-relief read it.
15
16use mln_style::tileset::RasterEncoding;
17
18pub const TERRAIN_RGB_MAXZOOM: u8 = 15;
19
20/// How a DEM's texels decode: `(r·w0 + g·w1 + b·w2 + base) · scale`, over
21/// channels from 0 to 255.
22///
23/// For Mapbox and Terrarium the weights and base are integers and the sum is
24/// below 2^24, so the sum is exact in `f32` and the decode rounds once, the
25/// same on the CPU and the GPU.
26#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct DemUnpack {
28    pub(crate) weights: [f32; 3],
29    pub(crate) base: f32,
30    pub scale: f32,
31}
32
33impl DemUnpack {
34    /// The decode of `encoding`.
35    #[must_use]
36    pub fn of(encoding: RasterEncoding) -> DemUnpack {
37        const WEIGHTS: [f32; 3] = [65536.0, 256.0, 1.0];
38        match encoding {
39            RasterEncoding::Mapbox => DemUnpack { weights: WEIGHTS, base: -100_000.0, scale: 0.1 },
40            RasterEncoding::Terrarium => DemUnpack { weights: WEIGHTS, base: -8_388_608.0, scale: 1.0 / 256.0 },
41            RasterEncoding::Custom { red_factor, green_factor, blue_factor, base_shift } => {
42                DemUnpack { weights: [red_factor, green_factor, blue_factor], base: -base_shift, scale: 1.0 }
43            }
44        }
45    }
46
47    /// The height in meters of an RGBA `texel`; alpha is ignored.
48    #[must_use]
49    pub fn decode(&self, texel: [u8; 4]) -> f32 {
50        let [r, g, b, _] = texel.map(f32::from);
51        let [w0, w1, w2] = self.weights;
52        (r * w0 + g * w1 + b * w2 + self.base) * self.scale
53    }
54
55    /// The weights, then the base: the `unpack` of the shaders' uniform
56    /// blocks, which hold the scale beside it.
57    #[must_use]
58    pub fn weights_and_base(&self) -> [f32; 4] {
59        let [w0, w1, w2] = self.weights;
60        [w0, w1, w2, self.base]
61    }
62}
63
64/// Where a terrain tile reads its DEM: DEM uv = tile uv · `scale` +
65/// `offset`. A tile reading its own DEM tile has scale 1 and offset 0; one
66/// reading an ancestor's reads the sub-rect it covers.
67#[derive(Clone, Copy, Debug, PartialEq)]
68pub struct DemCoords {
69    pub scale: f32,
70    pub offset: [f32; 2],
71}
72
73impl DemCoords {
74    /// The whole DEM tile.
75    pub const OWN: DemCoords = DemCoords { scale: 1.0, offset: [0.0, 0.0] };
76}
77
78/// The unexaggerated height at `uv` (0 to 1 across the tile, y down) of a
79/// DEM with `dim` pixels a side, read through `coords`. `texel(x, y)`
80/// decodes the bordered texel at `x`, `y`, each in `0..=dim + 1`. A `dim` of
81/// 0 is no DEM: the height is 0.
82///
83/// The height interpolates bilinearly, in `f32`, between the four texels
84/// around the texel coordinate `(uv · scale + offset) · dim + 0.5`, each
85/// clamped to the bordered texels.
86pub fn sample(dim: u32, coords: DemCoords, uv: [f32; 2], texel: impl Fn(u32, u32) -> f32) -> f32 {
87    if dim == 0 {
88        return 0.0;
89    }
90    let last = i64::from(dim) + 1;
91    let tap = |at: f32| {
92        let floor = at.floor();
93        let first = (floor as i64).clamp(0, last) as u32;
94        let second = (floor as i64 + 1).clamp(0, last) as u32;
95        (first, second, at - floor)
96    };
97    let dim = dim as f32;
98    let (x0, x1, fx) = tap((uv[0] * coords.scale + coords.offset[0]) * dim + 0.5);
99    let (y0, y1, fy) = tap((uv[1] * coords.scale + coords.offset[1]) * dim + 0.5);
100    let mix = |a: f32, b: f32, t: f32| a * (1.0 - t) + b * t;
101    let top = mix(texel(x0, y0), texel(x1, y0), fx);
102    let bottom = mix(texel(x0, y1), texel(x1, y1), fx);
103    mix(top, bottom, fy)
104}
105
106#[cfg(test)]
107#[path = "dem_test.rs"]
108mod dem_test;