use mln_style::tileset::RasterEncoding;
pub const TERRAIN_RGB_MAXZOOM: u8 = 15;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DemUnpack {
pub weights: [f32; 3],
pub base: f32,
pub scale: f32,
}
impl DemUnpack {
#[must_use]
pub fn of(encoding: RasterEncoding) -> DemUnpack {
const WEIGHTS: [f32; 3] = [65536.0, 256.0, 1.0];
match encoding {
RasterEncoding::Mapbox => DemUnpack { weights: WEIGHTS, base: -100_000.0, scale: 0.1 },
RasterEncoding::Terrarium => DemUnpack { weights: WEIGHTS, base: -8_388_608.0, scale: 1.0 / 256.0 },
RasterEncoding::Custom { red_factor, green_factor, blue_factor, base_shift } => {
DemUnpack { weights: [red_factor, green_factor, blue_factor], base: -base_shift, scale: 1.0 }
}
}
}
#[must_use]
pub fn decode(&self, texel: [u8; 4]) -> f32 {
let [r, g, b, _] = texel.map(f32::from);
let [w0, w1, w2] = self.weights;
(r * w0 + g * w1 + b * w2 + self.base) * self.scale
}
#[must_use]
pub fn weights_and_base(&self) -> [f32; 4] {
let [w0, w1, w2] = self.weights;
[w0, w1, w2, self.base]
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DemCoords {
pub scale: f32,
pub offset: [f32; 2],
}
impl DemCoords {
pub const OWN: DemCoords = DemCoords { scale: 1.0, offset: [0.0, 0.0] };
}
pub fn sample(dim: u32, coords: DemCoords, uv: [f32; 2], texel: impl Fn(u32, u32) -> f32) -> f32 {
if dim == 0 {
return 0.0;
}
let last = i64::from(dim) + 1;
let tap = |at: f32| {
let floor = at.floor();
let first = (floor as i64).clamp(0, last) as u32;
let second = (floor as i64 + 1).clamp(0, last) as u32;
(first, second, at - floor)
};
let dim = dim as f32;
let (x0, x1, fx) = tap((uv[0] * coords.scale + coords.offset[0]) * dim + 0.5);
let (y0, y1, fy) = tap((uv[1] * coords.scale + coords.offset[1]) * dim + 0.5);
let mix = |a: f32, b: f32, t: f32| a * (1.0 - t) + b * t;
let top = mix(texel(x0, y0), texel(x1, y0), fx);
let bottom = mix(texel(x0, y1), texel(x1, y1), fx);
mix(top, bottom, fy)
}
#[cfg(test)]
#[path = "dem_test.rs"]
mod dem_test;