Skip to main content

mln_engine/render/terrain/
elevation.rs

1//! The ground a frame drew, as the map's camera reads it.
2
3use std::fmt;
4use std::sync::Arc;
5
6use glam::DVec2;
7use mln_style::bitmap::PremultipliedImage;
8use mln_style::geo::LatLng;
9use mln_style::hash::HashMap;
10use mln_style::tile_id::CanonicalTileID;
11
12use crate::camera::{Elevation, TileCoordinate};
13use crate::render::terrain::cover::{TerrainCover, dem_contents, place_in, world_copy};
14use crate::tile::dem::{self, DemCoords, DemUnpack};
15use crate::tile::{OverscaledTileID, UnwrappedTileID};
16use crate::tile_store::source_tiles::SourceTiles;
17
18/// The DEM a terrain tile drew with.
19struct DrawnDem {
20    /// The DEM tile it read.
21    id: OverscaledTileID,
22    /// The DEM tile's bordered image, `dim + 2` texels a side.
23    image: Arc<PremultipliedImage>,
24    dim: u32,
25    coords: DemCoords,
26    /// The lowest and highest heights of the DEM tile's own pixels, in
27    /// meters, not exaggerated.
28    min: f32,
29    max: f32,
30}
31
32/// A terrain tile as a frame drew it.
33struct DrawnTile {
34    id: OverscaledTileID,
35    dem: Option<DrawnDem>,
36    /// Whether the frame drew it: all but the tile under the center that
37    /// the cover keeps undrawn ([`TerrainCover::center`]).
38    drawn: bool,
39}
40
41/// The terrain's tiles as a frame drew them, with the DEM data each read: the
42/// map's camera samples it by the height rule the shaders follow, so it
43/// stands on the surface that drew. It shares the DEM tiles' images, which
44/// don't change once shared.
45///
46/// Outside the engine it is a read-only height lookup: through
47/// [`Elevation`], or under a tile's points ([`TileGround`]).
48pub struct TerrainElevation {
49    /// Nearest the center first, then the tile under the center when none
50    /// drew there ([`TerrainCover::center`]).
51    tiles: Vec<DrawnTile>,
52    /// The zoom levels of the drawn tiles, finest first.
53    zooms: Vec<u8>,
54    /// Where each drawn tile is in `tiles`, the first of its world copies,
55    /// which all read the same DEM.
56    index: HashMap<CanonicalTileID, usize>,
57    /// Where each drawn tile is in `tiles`, by its world copy.
58    copies: HashMap<UnwrappedTileID, usize>,
59    /// [`Elevation::range`]'s.
60    range: Option<(f64, f64)>,
61    unpack: DemUnpack,
62    exaggeration: f32,
63}
64
65impl fmt::Debug for TerrainElevation {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.debug_struct("TerrainElevation")
68            .field("tiles", &self.tiles.len())
69            .field("unpack", &self.unpack)
70            .field("exaggeration", &self.exaggeration)
71            .finish_non_exhaustive()
72    }
73}
74
75/// The DEM that a tile of `cover` bound, as `dem`, the terrain source's
76/// tiles, hold it.
77fn drawn_dem(dem: Option<&SourceTiles>, bound: Option<(OverscaledTileID, DemCoords)>) -> Option<DrawnDem> {
78    let (id, coords) = bound?;
79    let data = dem_contents(dem?.tile(&id)?)?.dem();
80    let dim = u32::try_from(data.dim).ok()?;
81    let (min, max) = data.range();
82    Some(DrawnDem { id, image: Arc::clone(data.shared_image()), dim, coords, min, max })
83}
84
85impl TerrainElevation {
86    /// The ground of the tiles of `cover`, as they bound their DEM from
87    /// `dem`, the terrain source's tiles, decoded by `unpack` and raised by
88    /// `exaggeration`.
89    pub(crate) fn new(
90        cover: &TerrainCover,
91        dem: Option<&SourceTiles>,
92        unpack: DemUnpack,
93        exaggeration: f32,
94    ) -> TerrainElevation {
95        let drawn = cover.tiles.iter().map(|tile| (tile, true));
96        let tiles: Vec<DrawnTile> = drawn
97            .chain(cover.center.iter().map(|tile| (tile, false)))
98            .map(|(tile, drawn)| DrawnTile { id: tile.id, dem: drawn_dem(dem, tile.dem), drawn })
99            .collect();
100        TerrainElevation::of_drawn(tiles, unpack, exaggeration)
101    }
102
103    /// The ground of a frame that drew `tile` alone, over `dem`, the DEM
104    /// of `dem_id`, the tile or one of its ancestors, raised by
105    /// `exaggeration`.
106    #[cfg(feature = "bench")]
107    pub(crate) fn of_tile(
108        tile: OverscaledTileID,
109        dem_id: OverscaledTileID,
110        dem: &crate::tile::dem_data::DEMData,
111        exaggeration: f32,
112    ) -> Self {
113        let (min, max) = dem.range();
114        let image = Arc::clone(dem.shared_image());
115        let dim = u32::try_from(dem.dim).unwrap_or(0);
116        let dz = tile.canonical.z.saturating_sub(dem_id.canonical.z);
117        let (tiles, mask) = ((1u32 << dz) as f32, (1u32 << dz) - 1);
118        let (x, y) = ((tile.canonical.x & mask) as f32, (tile.canonical.y & mask) as f32);
119        let coords = DemCoords { scale: 1.0 / tiles, offset: [x / tiles, y / tiles] };
120        let dem_tile = DrawnDem { id: dem_id, image, dim, coords, min, max };
121        let tiles = vec![DrawnTile { id: tile, dem: Some(dem_tile), drawn: true }];
122        TerrainElevation::of_drawn(tiles, DemUnpack::of(dem.encoding), exaggeration)
123    }
124
125    /// The ground of `tiles`, nearest the center first, decoded by `unpack`
126    /// and raised by `exaggeration`.
127    fn of_drawn(tiles: Vec<DrawnTile>, unpack: DemUnpack, exaggeration: f32) -> TerrainElevation {
128        let mut index = HashMap::default();
129        let mut copies = HashMap::default();
130        let mut zooms = Vec::new();
131        let mut range: Option<(f64, f64)> = None;
132        for (at, tile) in tiles.iter().enumerate().filter(|(_, tile)| tile.drawn) {
133            index.entry(tile.id.canonical).or_insert(at);
134            copies.insert(tile.id.to_unwrapped(), at);
135            if !zooms.contains(&tile.id.canonical.z) {
136                zooms.push(tile.id.canonical.z);
137            }
138            let (min, max) = tile.dem.as_ref().map_or((0.0, 0.0), |dem| {
139                let (min, max) = (f64::from(dem.min * exaggeration), f64::from(dem.max * exaggeration));
140                (min.min(max), min.max(max))
141            });
142            range = Some(range.map_or((min, max), |(low, high)| (low.min(min), high.max(max))));
143        }
144        zooms.sort_unstable_by(|a, b| b.cmp(a));
145        TerrainElevation { tiles, zooms, index, copies, range, unpack, exaggeration }
146    }
147
148    /// Whether `other` is the same ground: the same tiles, drawn or kept
149    /// under the center, reading the same DEM images in the same places,
150    /// decoded and raised alike.
151    pub(crate) fn draws_as(&self, other: &TerrainElevation) -> bool {
152        // A DEM image this holds can't be freed and its address reused, and
153        // one that changes after it is shared is copied first, so equal
154        // addresses are equal images.
155        let same_dem =
156            |a: &DrawnDem, b: &DrawnDem| a.id == b.id && a.coords == b.coords && Arc::ptr_eq(&a.image, &b.image);
157        let same_tile = |a: &DrawnTile, b: &DrawnTile| {
158            a.id == b.id
159                && a.drawn == b.drawn
160                && match (&a.dem, &b.dem) {
161                    (None, None) => true,
162                    (Some(a), Some(b)) => same_dem(a, b),
163                    _ => false,
164                }
165        };
166        self.unpack == other.unpack
167            && self.exaggeration == other.exaggeration
168            && self.tiles.len() == other.tiles.len()
169            && self.tiles.iter().zip(&other.tiles).all(|(a, b)| same_tile(a, b))
170    }
171
172    /// The drawn tile at `world`, a Web Mercator point at zoom 0 whose y is
173    /// within the world, and where in it, from 0 to 1 across, y down: the
174    /// finest that has it ([`place_in`]'s, which puts a point on an edge
175    /// between tiles in one of them). In `world`'s copy (`in_copy`), else in
176    /// any copy: every world copy of a tile reads the same DEM.
177    fn drawn_tile_at(&self, world: DVec2, in_copy: bool) -> Option<(&DrawnTile, [f32; 2])> {
178        if !world.x.is_finite() {
179            return None;
180        }
181        let (copy, x) = world_copy(world.x);
182        // No tile is in a copy past the range of the wraps.
183        let wrap = if in_copy { Some(i16::try_from(copy as i64).ok()?) } else { None };
184        self.zooms.iter().find_map(|&z| {
185            let tiles = f64::from(1u32 << z);
186            let (u, v) = (x * tiles, world.y * tiles);
187            // The world's bottom edge is in the last row's tiles.
188            let (column, row) = (u.floor(), v.floor().min(tiles - 1.0));
189            let canonical = CanonicalTileID::new(z, column as u32, row as u32);
190            let at = match wrap {
191                Some(wrap) => self.copies.get(&UnwrappedTileID::with_wrap(wrap, canonical)),
192                None => self.index.get(&canonical),
193            };
194            Some((&self.tiles[*at?], [(u - column) as f32, (v - row) as f32]))
195        })
196    }
197
198    /// The tile at `location`, and where in it: a drawn one, else the tile
199    /// the cover keeps under the center.
200    fn tile_at_location(&self, location: LatLng) -> Option<(&DrawnTile, [f32; 2])> {
201        let world = TileCoordinate::from_lat_lng(0.0, &location).p;
202        let world = DVec2::new(world.x, world.y.clamp(0.0, 1.0));
203        self.drawn_tile_at(world, false).or_else(|| {
204            let center = self.tiles.last().filter(|tile| !tile.drawn)?;
205            let [u, v] = place_in(center.id.canonical, [world.x, world.y])?;
206            Some((center, [u as f32, v as f32]))
207        })
208    }
209
210    /// [`Elevation::at`] and [`Elevation::min_at`] as the tiles, scanned in
211    /// order, give them, which the index must agree with.
212    #[cfg(test)]
213    pub(crate) fn scanned(&self, location: LatLng) -> (Option<f64>, Option<f64>) {
214        let world = TileCoordinate::from_lat_lng(0.0, &location).p;
215        let found = self.tiles.iter().find_map(|tile| {
216            let [u, v] = place_in(tile.id.canonical, [world.x, world.y])?;
217            Some((tile, [u as f32, v as f32]))
218        });
219        found.map_or((None, None), |(tile, uv)| (Some(self.height_of(tile, uv)), Some(self.min_of(tile))))
220    }
221
222    /// [`Elevation::surface_at`] as the drawn tiles of `world`'s copy,
223    /// scanned in order, give it, which the index must agree with.
224    #[cfg(test)]
225    pub(crate) fn scanned_surface(&self, world: DVec2) -> Option<f64> {
226        let copy = world_copy(world.x).0;
227        let found = self.tiles.iter().filter(|tile| tile.drawn && f64::from(tile.id.wrap) == copy).find_map(|tile| {
228            let [u, v] = place_in(tile.id.canonical, [world.x, world.y])?;
229            Some((tile, [u as f32, v as f32]))
230        });
231        let (tile, uv) = found?;
232        Some(self.height_of(tile, uv))
233    }
234
235    /// The height `tile` draws at `uv`: its DEM's, or sea level where it
236    /// draws flat.
237    fn height_of(&self, tile: &DrawnTile, uv: [f32; 2]) -> f64 {
238        tile.dem.as_ref().map_or(0.0, |dem| self.height(dem, uv))
239    }
240
241    /// The lowest height of the DEM `tile` reads, 0 for none.
242    fn min_of(&self, tile: &DrawnTile) -> f64 {
243        tile.dem.as_ref().map_or(0.0, |dem| f64::from(dem.min * self.exaggeration))
244    }
245
246    /// The height that `dem` gives at `uv` by the height rule, in meters with
247    /// the exaggeration.
248    fn height(&self, dem: &DrawnDem, uv: [f32; 2]) -> f64 {
249        dem_height(&dem.image, dem.dim, dem.coords, uv, self.unpack, self.exaggeration)
250    }
251}
252
253/// The height, in meters raised by `exaggeration`, that the DEM of `dim`
254/// pixels a side whose bordered image is `image` gives at `uv` through
255/// `coords`, decoded by `unpack`: the height rule of `crate::tile::dem`, which
256/// the shaders follow.
257pub(crate) fn dem_height(
258    image: &PremultipliedImage,
259    dim: u32,
260    coords: DemCoords,
261    uv: [f32; 2],
262    unpack: DemUnpack,
263    exaggeration: f32,
264) -> f64 {
265    let stride = dim as usize + 2;
266    let texel = |x: u32, y: u32| {
267        let start = (y as usize * stride + x as usize) * 4;
268        let texel: [u8; 4] = image.data[start..start + 4].try_into().unwrap_or_default();
269        unpack.decode(texel)
270    };
271    f64::from(dem::sample(dim, coords, uv, texel) * exaggeration)
272}
273
274/// The ground under a tile's points, as a frame drew it: what the layers
275/// whose points the CPU places, as symbols, stand on.
276#[derive(Clone, Copy, Debug)]
277pub struct TileGround<'a> {
278    ground: &'a TerrainElevation,
279    tile: UnwrappedTileID,
280}
281
282impl<'a> TileGround<'a> {
283    /// The ground of `ground` under the points of `tile`.
284    #[must_use]
285    pub fn new(ground: &'a TerrainElevation, tile: UnwrappedTileID) -> Self {
286        TileGround { ground, tile }
287    }
288
289    /// The height of the surface the frame drew at `point`, in `EXTENT`
290    /// units of the tile, in meters with the exaggeration
291    /// ([`Elevation::surface_at`]); 0 where none drew, as on flat ground. A
292    /// point past the tile's edges reads the ground there.
293    #[must_use]
294    pub fn height(&self, point: glam::Vec2) -> f32 {
295        let tiles = f64::from(1u32 << self.tile.canonical.z);
296        let extent = f64::from(mln_style::constants::EXTENT);
297        let tile = DVec2::new(f64::from(self.tile.canonical.x), f64::from(self.tile.canonical.y));
298        let world = (tile + point.as_dvec2() / extent) / tiles + DVec2::new(f64::from(self.tile.wrap), 0.0);
299        self.ground.surface_at(world).unwrap_or(0.0) as f32
300    }
301}
302
303impl Elevation for TerrainElevation {
304    fn at(&self, location: LatLng) -> Option<f64> {
305        let (tile, uv) = self.tile_at_location(location)?;
306        Some(self.height_of(tile, uv))
307    }
308
309    fn min_at(&self, location: LatLng) -> Option<f64> {
310        let (tile, _) = self.tile_at_location(location)?;
311        Some(self.min_of(tile))
312    }
313
314    fn surface_at(&self, world: DVec2) -> Option<f64> {
315        if !(0.0..=1.0).contains(&world.y) {
316            return None;
317        }
318        let (tile, uv) = self.drawn_tile_at(world, true)?;
319        Some(self.height_of(tile, uv))
320    }
321
322    fn range(&self) -> Option<(f64, f64)> {
323        self.range
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use mln_style::tileset::RasterEncoding;
330
331    use super::*;
332    use crate::render::terrain::cover::{ElevationRanges, TerrainTile};
333
334    /// A point in a world copy past the range of the tiles' wraps has no
335    /// surface, though a tile of the last copy in range drew: no copy of
336    /// the point's stands in for it.
337    #[test]
338    fn a_point_in_a_copy_past_the_wraps_has_no_surface() {
339        let tile =
340            |wrap: i16| TerrainTile { id: OverscaledTileID::new(0, wrap, CanonicalTileID::new(0, 0, 0)), dem: None };
341        let cover = TerrainCover {
342            source_id: "dem".to_owned(),
343            tile_size: 512,
344            tiles: vec![tile(i16::MAX), tile(i16::MIN)],
345            center: None,
346            dem_tiles: Vec::new(),
347            ranges: ElevationRanges::default(),
348        };
349        let ground = TerrainElevation::new(&cover, None, DemUnpack::of(RasterEncoding::Terrarium), 1.0);
350        for copy in [i16::MAX, i16::MIN] {
351            assert_eq!(Some(0.0), ground.surface_at(DVec2::new(f64::from(copy) + 0.5, 0.5)), "copy {copy}");
352        }
353        for x in [f64::from(i16::MAX) + 1.5, 1e12, f64::from(i16::MIN) - 0.5, -1e12] {
354            assert_eq!(None, ground.surface_at(DVec2::new(x, 0.5)), "x {x}");
355        }
356    }
357}