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 geometry::Point;
7use glam::{DVec2, DVec3, Vec2};
8use mln_style::bitmap::PremultipliedImage;
9use mln_style::crs::WorldMapping;
10use mln_style::geo::{LatLng, WrapMode};
11use mln_style::hash::HashMap;
12use mln_style::tile_id::CanonicalTileID;
13
14use crate::camera::{Elevation, TileCoordinate, TileProjector, VerticalPerspectiveProjection, View};
15use crate::geo::ScreenCoordinate;
16use crate::render::terrain::cover::{TerrainCover, dem_contents, place_in, world_copy};
17use crate::tile::dem::{self, DemCoords, DemUnpack};
18use crate::tile::{OverscaledTileID, UnwrappedTileID};
19use crate::tile_store::source_tiles::SourceTiles;
20
21/// The DEM a terrain tile drew with.
22struct DrawnDem {
23    /// The DEM tile it read.
24    id: OverscaledTileID,
25    /// The DEM tile's bordered image, `dim + 2` texels a side.
26    image: Arc<PremultipliedImage>,
27    dim: u32,
28    coords: DemCoords,
29    /// The lowest and highest heights of the DEM tile's own pixels, in
30    /// meters, not exaggerated.
31    min: f32,
32    max: f32,
33}
34
35/// A terrain tile as a frame drew it.
36struct DrawnTile {
37    id: OverscaledTileID,
38    dem: Option<DrawnDem>,
39    /// Whether the frame drew it: all but the tile under the center that
40    /// the cover keeps undrawn ([`TerrainCover::center`]).
41    drawn: bool,
42}
43
44/// The terrain's tiles as a frame drew them, with the DEM data each read: the
45/// map's camera samples it by the height rule the shaders follow, so it
46/// stands on the surface that drew. It shares the DEM tiles' images, which
47/// don't change once shared.
48///
49/// Outside the engine it is a read-only height lookup: through
50/// [`Elevation`], or under a tile's points ([`TileGround`]).
51pub struct TerrainElevation {
52    /// Nearest the center first, then the tile under the center when none
53    /// drew there ([`TerrainCover::center`]).
54    tiles: Vec<DrawnTile>,
55    /// The zoom levels of the drawn tiles, finest first.
56    zooms: Vec<u8>,
57    /// Where each drawn tile is in `tiles`, the first of its world copies,
58    /// which all read the same DEM.
59    index: HashMap<CanonicalTileID, usize>,
60    /// Where each drawn tile is in `tiles`, by its world copy.
61    copies: HashMap<UnwrappedTileID, usize>,
62    /// [`Elevation::range`]'s.
63    range: Option<(f64, f64)>,
64    unpack: DemUnpack,
65    exaggeration: f32,
66    /// How the map's lng/lat maps to the world square the tiles are in.
67    world: WorldMapping,
68}
69
70impl fmt::Debug for TerrainElevation {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.debug_struct("TerrainElevation")
73            .field("tiles", &self.tiles.len())
74            .field("unpack", &self.unpack)
75            .field("exaggeration", &self.exaggeration)
76            .finish_non_exhaustive()
77    }
78}
79
80/// The DEM that a tile of `cover` bound, as `dem`, the terrain source's
81/// tiles, hold it.
82fn drawn_dem(dem: Option<&SourceTiles>, bound: Option<(OverscaledTileID, DemCoords)>) -> Option<DrawnDem> {
83    let (id, coords) = bound?;
84    let data = dem_contents(dem?.tile(&id)?)?.dem();
85    let dim = u32::try_from(data.dim).ok()?;
86    let (min, max) = data.range();
87    Some(DrawnDem { id, image: Arc::clone(data.shared_image()), dim, coords, min, max })
88}
89
90impl TerrainElevation {
91    /// The ground of the tiles of `cover`, as they bound their DEM from
92    /// `dem`, the terrain source's tiles, decoded by `unpack` and raised by
93    /// `exaggeration`.
94    pub(crate) fn new(
95        cover: &TerrainCover,
96        dem: Option<&SourceTiles>,
97        unpack: DemUnpack,
98        exaggeration: f32,
99    ) -> TerrainElevation {
100        let drawn = cover.tiles.iter().map(|tile| (tile, true));
101        let tiles: Vec<DrawnTile> = drawn
102            .chain(cover.center.iter().map(|tile| (tile, false)))
103            .map(|(tile, drawn)| DrawnTile { id: tile.id, dem: drawn_dem(dem, tile.dem), drawn })
104            .collect();
105        TerrainElevation::of_drawn(tiles, unpack, exaggeration, cover.world.clone())
106    }
107
108    /// The ground of a frame that drew `tile` alone, over `dem`, the DEM
109    /// of `dem_id`, the tile or one of its ancestors, raised by
110    /// `exaggeration`.
111    #[cfg(feature = "bench")]
112    pub(crate) fn of_tile(
113        tile: OverscaledTileID,
114        dem_id: OverscaledTileID,
115        dem: &crate::tile::dem_data::DEMData,
116        exaggeration: f32,
117    ) -> Self {
118        let (min, max) = dem.range();
119        let image = Arc::clone(dem.shared_image());
120        let dim = u32::try_from(dem.dim).unwrap_or(0);
121        let dz = tile.canonical.z.saturating_sub(dem_id.canonical.z);
122        let (tiles, mask) = ((1u32 << dz) as f32, (1u32 << dz) - 1);
123        let (x, y) = ((tile.canonical.x & mask) as f32, (tile.canonical.y & mask) as f32);
124        let coords = DemCoords { scale: 1.0 / tiles, offset: [x / tiles, y / tiles] };
125        let dem_tile = DrawnDem { id: dem_id, image, dim, coords, min, max };
126        let tiles = vec![DrawnTile { id: tile, dem: Some(dem_tile), drawn: true }];
127        TerrainElevation::of_drawn(tiles, DemUnpack::of(dem.encoding), exaggeration, WorldMapping::default())
128    }
129
130    /// The ground of `tiles`, nearest the center first, decoded by `unpack`
131    /// and raised by `exaggeration`, in the world square of `world`.
132    fn of_drawn(tiles: Vec<DrawnTile>, unpack: DemUnpack, exaggeration: f32, world: WorldMapping) -> TerrainElevation {
133        let mut index = HashMap::default();
134        let mut copies = HashMap::default();
135        let mut zooms = Vec::new();
136        let mut range: Option<(f64, f64)> = None;
137        for (at, tile) in tiles.iter().enumerate().filter(|(_, tile)| tile.drawn) {
138            index.entry(tile.id.canonical).or_insert(at);
139            copies.insert(tile.id.to_unwrapped(), at);
140            if !zooms.contains(&tile.id.canonical.z) {
141                zooms.push(tile.id.canonical.z);
142            }
143            let (min, max) = tile.dem.as_ref().map_or((0.0, 0.0), |dem| {
144                let (min, max) = (f64::from(dem.min * exaggeration), f64::from(dem.max * exaggeration));
145                (min.min(max), min.max(max))
146            });
147            range = Some(range.map_or((min, max), |(low, high)| (low.min(min), high.max(max))));
148        }
149        zooms.sort_unstable_by(|a, b| b.cmp(a));
150        TerrainElevation { tiles, zooms, index, copies, range, unpack, exaggeration, world }
151    }
152
153    /// Whether `other` is the same ground: the same tiles, drawn or kept
154    /// under the center, reading the same DEM images in the same places,
155    /// decoded and raised alike.
156    pub(crate) fn draws_as(&self, other: &TerrainElevation) -> bool {
157        // A DEM image this holds can't be freed and its address reused, and
158        // one that changes after it is shared is copied first, so equal
159        // addresses are equal images.
160        let same_dem =
161            |a: &DrawnDem, b: &DrawnDem| a.id == b.id && a.coords == b.coords && Arc::ptr_eq(&a.image, &b.image);
162        let same_tile = |a: &DrawnTile, b: &DrawnTile| {
163            a.id == b.id
164                && a.drawn == b.drawn
165                && match (&a.dem, &b.dem) {
166                    (None, None) => true,
167                    (Some(a), Some(b)) => same_dem(a, b),
168                    _ => false,
169                }
170        };
171        self.unpack == other.unpack
172            && self.exaggeration == other.exaggeration
173            && self.world == other.world
174            && self.tiles.len() == other.tiles.len()
175            && self.tiles.iter().zip(&other.tiles).all(|(a, b)| same_tile(a, b))
176    }
177
178    /// The drawn tile at `world`, a Web Mercator point at zoom 0 whose y is
179    /// within the world, and where in it, from 0 to 1 across, y down: the
180    /// finest that has it ([`place_in`]'s, which puts a point on an edge
181    /// between tiles in one of them). In `world`'s copy (`in_copy`), else in
182    /// any copy: every world copy of a tile reads the same DEM.
183    fn drawn_tile_at(&self, world: DVec2, in_copy: bool) -> Option<(&DrawnTile, [f32; 2])> {
184        if !world.x.is_finite() {
185            return None;
186        }
187        let (copy, x) = world_copy(world.x);
188        // No tile is in a copy past the range of the wraps.
189        let wrap = if in_copy { Some(i16::try_from(copy as i64).ok()?) } else { None };
190        self.zooms.iter().find_map(|&z| {
191            let tiles = f64::from(1u32 << z);
192            let (u, v) = (x * tiles, world.y * tiles);
193            // The world's bottom edge is in the last row's tiles.
194            let (column, row) = (u.floor(), v.floor().min(tiles - 1.0));
195            let canonical = CanonicalTileID::new(z, column as u32, row as u32);
196            let at = match wrap {
197                Some(wrap) => self.copies.get(&UnwrappedTileID::with_wrap(wrap, canonical)),
198                None => self.index.get(&canonical),
199            };
200            Some((&self.tiles[*at?], [(u - column) as f32, (v - row) as f32]))
201        })
202    }
203
204    /// The tile at `location`, and where in it: a drawn one, else the tile
205    /// the cover keeps under the center. A world that doesn't wrap has no
206    /// copies, and no ground outside its square.
207    fn tile_at_location(&self, location: LatLng) -> Option<(&DrawnTile, [f32; 2])> {
208        let world = self.world.world_from_lat_lng(&location);
209        if !self.world.wraps() && (!(0.0..1.0).contains(&world.x) || !(0.0..=1.0).contains(&world.y)) {
210            return None;
211        }
212        let world = DVec2::new(world.x, world.y.clamp(0.0, 1.0));
213        self.drawn_tile_at(world, false).or_else(|| {
214            let center = self.tiles.last().filter(|tile| !tile.drawn)?;
215            let [u, v] = place_in(center.id.canonical, [world.x, world.y])?;
216            Some((center, [u as f32, v as f32]))
217        })
218    }
219
220    /// [`Elevation::at`] and [`Elevation::min_at`] as the tiles, scanned in
221    /// order, give them, which the index must agree with.
222    #[cfg(test)]
223    pub(crate) fn scanned(&self, location: LatLng) -> (Option<f64>, Option<f64>) {
224        let world = TileCoordinate::from_lat_lng(0.0, &location).p;
225        let found = self.tiles.iter().find_map(|tile| {
226            let [u, v] = place_in(tile.id.canonical, [world.x, world.y])?;
227            Some((tile, [u as f32, v as f32]))
228        });
229        found.map_or((None, None), |(tile, uv)| (Some(self.height_of(tile, uv)), Some(self.min_of(tile))))
230    }
231
232    /// [`Elevation::surface_at`] as the drawn tiles of `world`'s copy,
233    /// scanned in order, give it, which the index must agree with.
234    #[cfg(test)]
235    pub(crate) fn scanned_surface(&self, world: DVec2) -> Option<f64> {
236        let copy = world_copy(world.x).0;
237        let found = self.tiles.iter().filter(|tile| tile.drawn && f64::from(tile.id.wrap) == copy).find_map(|tile| {
238            let [u, v] = place_in(tile.id.canonical, [world.x, world.y])?;
239            Some((tile, [u as f32, v as f32]))
240        });
241        let (tile, uv) = found?;
242        Some(self.height_of(tile, uv))
243    }
244
245    /// The height `tile` draws at `uv`: its DEM's, or sea level where it
246    /// draws flat.
247    fn height_of(&self, tile: &DrawnTile, uv: [f32; 2]) -> f64 {
248        tile.dem.as_ref().map_or(0.0, |dem| self.height(dem, uv))
249    }
250
251    /// The lowest height of the DEM `tile` reads, 0 for none.
252    fn min_of(&self, tile: &DrawnTile) -> f64 {
253        tile.dem.as_ref().map_or(0.0, |dem| f64::from(dem.min * self.exaggeration))
254    }
255
256    /// The height that `dem` gives at `uv` by the height rule, in meters with
257    /// the exaggeration.
258    fn height(&self, dem: &DrawnDem, uv: [f32; 2]) -> f64 {
259        dem_height(&dem.image, dem.dim, dem.coords, uv, self.unpack, self.exaggeration)
260    }
261}
262
263/// The height, in meters raised by `exaggeration`, that the DEM of `dim`
264/// pixels a side whose bordered image is `image` gives at `uv` through
265/// `coords`, decoded by `unpack`: the height rule of `crate::tile::dem`, which
266/// the shaders follow.
267pub(crate) fn dem_height(
268    image: &PremultipliedImage,
269    dim: u32,
270    coords: DemCoords,
271    uv: [f32; 2],
272    unpack: DemUnpack,
273    exaggeration: f32,
274) -> f64 {
275    let stride = dim as usize + 2;
276    let texel = |x: u32, y: u32| {
277        let start = (y as usize * stride + x as usize) * 4;
278        let texel: [u8; 4] = image.data[start..start + 4].try_into().unwrap_or_default();
279        unpack.decode(texel)
280    };
281    f64::from(dem::sample(dim, coords, uv, texel) * exaggeration)
282}
283
284/// The ground under a tile's points, as a frame drew it: what the layers
285/// whose points the CPU places, as symbols, stand on.
286#[derive(Clone, Copy, Debug)]
287pub struct TileGround<'a> {
288    ground: &'a TerrainElevation,
289    tile: UnwrappedTileID,
290}
291
292impl<'a> TileGround<'a> {
293    /// The ground of `ground` under the points of `tile`.
294    #[must_use]
295    pub fn new(ground: &'a TerrainElevation, tile: UnwrappedTileID) -> Self {
296        TileGround { ground, tile }
297    }
298
299    /// The height of the surface the frame drew at `point`, in `EXTENT`
300    /// units of the tile, in meters with the exaggeration
301    /// ([`Elevation::surface_at`]); 0 where none drew, as on flat ground. A
302    /// point past the tile's edges reads the ground there.
303    #[must_use]
304    pub fn height(&self, point: Vec2) -> f32 {
305        let tiles = f64::from(1u32 << self.tile.canonical.z);
306        let extent = f64::from(mln_style::constants::EXTENT);
307        let tile = DVec2::new(f64::from(self.tile.canonical.x), f64::from(self.tile.canonical.y));
308        let world = (tile + point.as_dvec2() / extent) / tiles + DVec2::new(f64::from(self.tile.wrap), 0.0);
309        self.ground.surface_at(world).unwrap_or(0.0) as f32
310    }
311
312    /// How much of what stands at `point`, in `EXTENT` units of the tile,
313    /// `elevation` meters up, the ground in front of it leaves in `view`, as
314    /// the shaders' `ground_visibility` fades it: 1 where it doesn't show,
315    /// where no ground nearer the camera shows at its screen point, or where
316    /// that point is outside the view, down to 0 where the nearest ground
317    /// there is in front of it by GL JS's ramp of depth; where that leaves
318    /// less than 0.95, averaged with the same test of the screen point 0.01
319    /// clip units above. The line of sight is sampled every 4 pixels across
320    /// the ground, at most 512 times, and the ground it first passes under
321    /// found by bisection.
322    #[must_use]
323    pub fn visibility(&self, view: &View, point: Point<f64>, elevation: f64) -> f64 {
324        let tile = self.tile;
325        let projector = TileProjector::new(view, &tile);
326        let drawn = projector.project_as_drawn(&point, elevation);
327        let size = view.size();
328        let (width, view_height) = (f64::from(size.width), f64::from(size.height));
329        // Where the point draws on the screen, from its top left; clip
330        // space's y goes up.
331        let screen =
332            ScreenCoordinate::new((drawn.point.x + 1.0) * width * 0.5, (1.0 - drawn.point.y) * view_height * 0.5);
333        if drawn.occluded
334            || drawn.signed_distance_from_camera <= 0.0
335            || !(0.0..=width).contains(&screen.x)
336            || !(0.0..=view_height).contains(&screen.y)
337        {
338            return 1.0;
339        }
340
341        // The line of sight, as a line from the point to the eye, or to where
342        // the near plane cuts it, through Mercator's tile units and meters, or
343        // through the globe's unit-sphere space; and its point at `t`, from 0
344        // at the point to 1, as a point of the tile and a height.
345        let extent = f64::from(mln_style::constants::EXTENT);
346        let tiles = f64::from(1u32 << tile.canonical.z);
347        let to_tile = |x: f64, y: f64| {
348            [
349                ((x - f64::from(tile.wrap)) * tiles - f64::from(tile.canonical.x)) * extent,
350                (y * tiles - f64::from(tile.canonical.y)) * extent,
351            ]
352        };
353        let point_x = (f64::from(tile.canonical.x) + point.x / extent) / tiles + f64::from(tile.wrap);
354        let globe = view.is_globe();
355        let (start, end) = if globe {
356            let surface = VerticalPerspectiveProjection::tile_coordinates_to_sphere(&point, &tile);
357            (
358                surface * (1.0 + elevation / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS),
359                view.globe_camera_position(),
360            )
361        } else {
362            let Some((near, _)) = view.line_of_sight(&ScreenCoordinate::new(screen.x, view_height - screen.y)) else {
363                return 1.0;
364            };
365            let [x, y] = to_tile(near.x, near.y);
366            (DVec3::new(point.x, point.y, elevation), DVec3::new(x, y, near.z))
367        };
368        let at = |t: f64| {
369            let q = start.lerp(end, t);
370            if !globe {
371                return ([q.x, q.y], q.z);
372            }
373            let (radius, n) = (q.length(), q.normalize());
374            let location =
375                LatLng::saturating(n.y.asin().to_degrees(), n.x.atan2(n.z).to_degrees(), WrapMode::Unwrapped);
376            let p = TileCoordinate::from_lat_lng(0.0, &location).p;
377            // In the world copy of the point.
378            let x = p.x + (point_x - p.x).round();
379            (to_tile(x, p.y), (radius - 1.0) * VerticalPerspectiveProjection::GLOBE_RADIUS_METERS)
380        };
381        let under = |t: f64| {
382            let (point, ray) = at(t);
383            f64::from(self.height(Vec2::new(point[0] as f32, point[1] as f32))) > ray
384        };
385
386        // The tile units that a logical pixel spans at the point.
387        let pixels_to_tile_units = extent
388            / (mln_style::constants::TILE_SIZE * 2f64.powf(view.zoom() - f64::from(tile.canonical.z)))
389            * projector.map_aligned_scale_at(&point);
390        let (eye, _) = at(1.0);
391        let across = (eye[0] - point.x).hypot(eye[1] - point.y) / pixels_to_tile_units;
392        let steps = (across / 4.0).ceil().clamp(1.0, 512.0) as u32;
393        let Some(step) = (1..=steps).find(|&i| under(1.0 - f64::from(i) / f64::from(steps))) else {
394            return 1.0;
395        };
396        let (mut above, mut below) =
397            (1.0 - f64::from(step - 1) / f64::from(steps), 1.0 - f64::from(step) / f64::from(steps));
398        for _ in 0..24 {
399            let mid = f64::midpoint(above, below);
400            if under(mid) { below = mid } else { above = mid }
401        }
402        let (ground, ray) = at(below);
403        let ground = projector.project_as_drawn(&Point::new(ground[0], ground[1]), ray);
404
405        // GL JS's `depthOpacity` against the ground `distance` from the
406        // camera, with its ramp's scale.
407        let depth_opacity = |distance: f64| {
408            let d = view_height / 25.0 * (1.0 / drawn.signed_distance_from_camera - 1.0 / distance) + 0.0001;
409            1.0 - (-500.0 * d).clamp(0.0, 1.0)
410        };
411        let visibility = depth_opacity(ground.signed_distance_from_camera);
412        if visibility > 0.95 {
413            return 1.0;
414        }
415        // Partly hidden, averaged with the screen point 0.01 clip units
416        // above, where the line of sight meets the nearest ground the frame
417        // drew; 1 where that point is outside the view or meets none.
418        let above = ScreenCoordinate::new(screen.x, view_height - screen.y + 0.005 * view_height);
419        let hit = if above.y <= view_height { view.ground_under(&above, self.ground) } else { None };
420        let above = match hit {
421            Some(hit) => {
422                // On the globe, in the world copy of the point.
423                let x = if globe { hit.world.x + (point_x - hit.world.x).round() } else { hit.world.x };
424                let [x, y] = to_tile(x, hit.world.y);
425                depth_opacity(projector.project_as_drawn(&Point::new(x, y), hit.height).signed_distance_from_camera)
426            }
427            None => 1.0,
428        };
429        f64::midpoint(visibility, above)
430    }
431}
432
433impl Elevation for TerrainElevation {
434    fn at(&self, location: LatLng) -> Option<f64> {
435        let (tile, uv) = self.tile_at_location(location)?;
436        Some(self.height_of(tile, uv))
437    }
438
439    fn min_at(&self, location: LatLng) -> Option<f64> {
440        let (tile, _) = self.tile_at_location(location)?;
441        Some(self.min_of(tile))
442    }
443
444    fn surface_at(&self, world: DVec2) -> Option<f64> {
445        if !(0.0..=1.0).contains(&world.y) {
446            return None;
447        }
448        let (tile, uv) = self.drawn_tile_at(world, true)?;
449        Some(self.height_of(tile, uv))
450    }
451
452    fn range(&self) -> Option<(f64, f64)> {
453        self.range
454    }
455}
456
457#[cfg(test)]
458mod tests {
459    use mln_style::tileset::RasterEncoding;
460
461    use super::*;
462    use crate::render::terrain::cover::{ElevationRanges, TerrainTile};
463
464    /// A point in a world copy past the range of the tiles' wraps has no
465    /// surface, though a tile of the last copy in range drew: no copy of
466    /// the point's stands in for it.
467    #[test]
468    fn a_point_in_a_copy_past_the_wraps_has_no_surface() {
469        let tile =
470            |wrap: i16| TerrainTile { id: OverscaledTileID::new(0, wrap, CanonicalTileID::new(0, 0, 0)), dem: None };
471        let cover = TerrainCover {
472            source_id: "dem".to_owned(),
473            tile_size: 512,
474            tiles: vec![tile(i16::MAX), tile(i16::MIN)],
475            center: None,
476            dem_tiles: Vec::new(),
477            ranges: ElevationRanges::default(),
478            world: WorldMapping::default(),
479        };
480        let ground = TerrainElevation::new(&cover, None, DemUnpack::of(RasterEncoding::Terrarium), 1.0);
481        for copy in [i16::MAX, i16::MIN] {
482            assert_eq!(Some(0.0), ground.surface_at(DVec2::new(f64::from(copy) + 0.5, 0.5)), "copy {copy}");
483        }
484        for x in [f64::from(i16::MAX) + 1.5, 1e12, f64::from(i16::MIN) - 0.5, -1e12] {
485            assert_eq!(None, ground.surface_at(DVec2::new(x, 0.5)), "x {x}");
486        }
487    }
488}