1use 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
21struct DrawnDem {
23 id: OverscaledTileID,
25 image: Arc<PremultipliedImage>,
27 dim: u32,
28 coords: DemCoords,
29 min: f32,
32 max: f32,
33}
34
35struct DrawnTile {
37 id: OverscaledTileID,
38 dem: Option<DrawnDem>,
39 drawn: bool,
42}
43
44pub struct TerrainElevation {
52 tiles: Vec<DrawnTile>,
55 zooms: Vec<u8>,
57 index: HashMap<CanonicalTileID, usize>,
60 copies: HashMap<UnwrappedTileID, usize>,
62 range: Option<(f64, f64)>,
64 unpack: DemUnpack,
65 exaggeration: f32,
66 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
80fn 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 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 #[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 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 pub(crate) fn draws_as(&self, other: &TerrainElevation) -> bool {
157 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 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 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 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 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 #[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 #[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 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 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 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
263pub(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#[derive(Clone, Copy, Debug)]
287pub struct TileGround<'a> {
288 ground: &'a TerrainElevation,
289 tile: UnwrappedTileID,
290}
291
292impl<'a> TileGround<'a> {
293 #[must_use]
295 pub fn new(ground: &'a TerrainElevation, tile: UnwrappedTileID) -> Self {
296 TileGround { ground, tile }
297 }
298
299 #[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 #[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 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 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 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 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 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 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 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 #[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}