Skip to main content

mln_engine/render/terrain/
mod.rs

1//! 3D terrain: the style's `terrain` drawn as a surface raised by a
2//! raster-dem source, with the layers that drape over it drawn into
3//! textures that the surface samples.
4//!
5//! Terrain draws once the style's terrain names a raster-dem source whose
6//! tileset has loaded, outside tile mode, on every projection, on a backend
7//! that makes its shader ([`RenderTerrain::make_shader`]). A frame without
8//! terrain takes none of the steps below, which [`RenderTerrain`] runs for
9//! each frame:
10//!
11//! 1. **Update**, before the sources update ([`RenderTerrain::update`]):
12//!    terrain tiles cover the view ([`TerrainCover`]), culled by the DEM's
13//!    elevation ranges ([`ElevationRanges`]), and the terrain's source keeps
14//!    the DEM tiles they read loaded. Every source covers the view the same
15//!    way.
16//! 2. **Bind**, once the sources have updated ([`RenderTerrain::bind`]):
17//!    each tile binds its DEM, and the ground the tiles draw
18//!    ([`TerrainElevation`]) goes to the map, whose camera stands on it.
19//! 3. **Encode**: the layers that drape draw nothing into the frame, but
20//!    into the drapes of their stack ([`DrapeStacks`], [`Drapes`]); the
21//!    surface makes a draw per tile and stack, which reads the DEM textures
22//!    ([`RenderTerrain::update_dems`], [`RenderTerrain::update_draws`]).
23//!    The layers that stand on terrain stand on the frame's ground
24//!    ([`FrameGround`], [`RenderTerrain::update_ground`]): their points'
25//!    heights are the ground's under them ([`TileGround`]).
26//! 4. **Ground**: before the frame's passes, where layers hide behind the
27//!    ground, the surface draws its depth into the ground's depth texture
28//!    ([`RenderTerrain::render_ground`]), which they read.
29//! 5. **Drapes**: before the frame's pass, the drapes whose layers draw
30//!    from something new draw into their textures; the others keep theirs
31//!    ([`RenderTerrain::render_drapes`]).
32//! 6. **Surface**: the frame's pass draws each stack's surface where the
33//!    stack's first layer draws, and between the stacks the layers that
34//!    don't drape, flat ([`RenderTerrain::render`]). The surface of a
35//!    hillshade's own stack shades its slopes with the frame's lights
36//!    ([`SurfaceLight`]), and the sky's fog covers it ([`terrain_fog`]).
37
38mod cover;
39mod dem_textures;
40mod drapes;
41mod draws;
42mod elevation;
43mod fog;
44pub(crate) mod glsl;
45mod ground;
46mod mesh;
47pub(crate) mod msl;
48pub mod programs;
49mod stacks;
50pub mod ubo;
51pub(crate) mod wgsl;
52
53use std::rc::Rc;
54use std::sync::Arc;
55
56pub(crate) use cover::{ElevationRanges, TerrainCover};
57#[cfg(test)]
58pub(crate) use cover::{REMEMBERED_RANGES, TerrainTile};
59pub(crate) use drapes::{DrapeRepaint, Drapes};
60pub use elevation::{TerrainElevation, TileGround};
61pub(crate) use fog::terrain_fog;
62pub use ground::{FrameGround, GroundHeights, StandingDraw, height_binding, point_center};
63use mln_gfx::gpu::Gpu;
64use mln_style::crs::WorldMapping;
65use mln_style::hash::HashMap;
66use mln_style::layer::SourceKind;
67use mln_style::tile_id::CanonicalTileID;
68use mln_style::tileset::RasterEncoding;
69pub(crate) use stacks::{DrapeStacks, Draped};
70
71use crate::draw::context::Context;
72use crate::draw::store::Texture;
73use crate::layer::layer_drawing::ChangedBuckets;
74use crate::map::{MapMode, TerrainSkirtLength};
75use crate::render::events::RendererEvent;
76use crate::render::paint_parameters::PaintParameters;
77use crate::render::terrain::cover::dem_contents;
78use crate::render::terrain::dem_textures::DemTextures;
79use crate::render::terrain::draws::TerrainDraws;
80use crate::render::terrain::ground::GroundDepth;
81use crate::render::terrain::ubo::{HillshadeEvaluatedPropsUBO, HillshadeTilePropsUBO, TerrainFog, TerrainProps};
82use crate::render::update_parameters::UpdateParameters;
83use crate::tile::OverscaledTileID;
84use crate::tile::dem::DemUnpack;
85use crate::tile_store::source_tiles::SourceTiles;
86
87/// How far the skirts of terrain tiles reach down at `zoom` in `world`, in
88/// meters, or `None` for no skirts. `Auto` is a fifth of a tile's width,
89/// of a tile of the world's tile matrix set, its units taken as meters,
90/// which for Mercator is the tile's width at the equator.
91fn skirt_length(length: TerrainSkirtLength, zoom: f64, world: &WorldMapping) -> Option<f64> {
92    let world_width = world.tile_matrix_set().extent_at_zoom0;
93    match length {
94        TerrainSkirtLength::Auto => Some(world_width / zoom.max(0.0).exp2() / 5.0),
95        TerrainSkirtLength::None => None,
96    }
97}
98
99/// How the terrain's surface draws in a frame: how its DEM decodes, its
100/// exaggeration and its skirts.
101#[derive(Clone, Copy, Debug, Default, PartialEq)]
102pub(crate) struct Surface {
103    /// How the surface stands, the first members of its uniform block.
104    pub(crate) props: TerrainProps,
105    /// Whether the tiles have skirts.
106    pub(crate) skirts: bool,
107}
108
109impl Surface {
110    /// The surface of a DEM of `encoding`, raised by `exaggeration`, with
111    /// skirts of `skirt_length` meters, or none.
112    fn new(encoding: RasterEncoding, exaggeration: f32, skirt_length: Option<f64>) -> Surface {
113        let unpack = DemUnpack::of(encoding);
114        let props = TerrainProps {
115            unpack: unpack.weights_and_base(),
116            unpack_scale: unpack.scale,
117            exaggeration,
118            skirt_length: skirt_length.unwrap_or(0.0) as f32,
119        };
120        Surface { props, skirts: skirt_length.is_some() }
121    }
122
123    /// How the DEM decodes.
124    fn unpack(&self) -> DemUnpack {
125        let [r, g, b, base] = self.props.unpack;
126        DemUnpack { weights: [r, g, b], base, scale: self.props.unpack_scale }
127    }
128}
129
130/// The shading that the surface adds to a stack's drapes, which hold a
131/// hillshade's slopes, as the hillshade's own draws would shade them: so
132/// that a hillshade lit from the viewport keeps its drapes as the map
133/// turns, while its light stays where the viewport puts it.
134#[derive(Clone, Copy, Debug, Default, PartialEq)]
135pub struct SurfaceLight {
136    /// The hillshade's lights, turned by the frame's bearing.
137    pub props: HillshadeEvaluatedPropsUBO,
138    /// The hillshade's values of a tile, but for its latitudes, which are
139    /// each terrain tile's.
140    pub tile: HillshadeTilePropsUBO,
141}
142
143/// The textures of the DEM tiles that the frame's terrain tiles read, which
144/// their draws bind.
145pub(crate) struct DemBindings {
146    /// The texture of each DEM tile, with its width in pixels.
147    textures: HashMap<CanonicalTileID, (Texture, u32)>,
148    /// A transparent 1×1 texture, of flat ground and of a drape that holds
149    /// nothing.
150    flat: Texture,
151}
152
153impl DemBindings {
154    /// The texture of the DEM tile `dem`, with its width in pixels, if a
155    /// tile reads it.
156    pub(crate) fn dem(&self, dem: &OverscaledTileID) -> Option<(&Texture, u32)> {
157        self.textures.get(&dem.canonical).map(|(texture, dim)| (texture, *dim))
158    }
159
160    /// A transparent 1×1 texture.
161    pub(crate) fn flat(&self) -> &Texture {
162        &self.flat
163    }
164}
165
166/// The terrain of the frames the renderer draws: whether it draws, the
167/// tiles that cover the view, their drapes and their draws.
168#[derive(Default)]
169pub(crate) struct RenderTerrain {
170    cover: Option<TerrainCover>,
171    /// How the surface of the cover draws.
172    surface: Surface,
173    drapes: Drapes,
174    draws: TerrainDraws,
175    /// The ground the last update's cover drew, as the renderer last told
176    /// the map; `None` while terrain doesn't draw.
177    elevation: Option<Arc<TerrainElevation>>,
178    /// The textures of the DEM tiles the frame's draws read.
179    dem_textures: DemTextures,
180    /// What the frame's draws bind of them; `None` without terrain.
181    dems: Option<DemBindings>,
182    /// The texture of the ground's depth, while the frame draws it.
183    ground_depth: GroundDepth,
184    /// The most bytes the drapes hold, the map's
185    /// [`TerrainOptions::drape_memory_limit`], or `None` for no limit.
186    ///
187    /// [`TerrainOptions::drape_memory_limit`]: crate::map::TerrainOptions::drape_memory_limit
188    drape_memory_limit: Option<u64>,
189}
190
191impl RenderTerrain {
192    /// Brings the terrain to `parameters`, before the sources update: checks
193    /// whether it draws, takes in the elevation ranges of the DEM tiles that
194    /// have loaded, which the last cover's ranges remember, covers the view
195    /// with its tiles and lists the DEM tiles they read. `dem` finds the
196    /// tiles of a source by its id. Returns the cover while terrain draws;
197    /// its tiles bind their DEM in [`bind`]. While terrain doesn't draw, it
198    /// remembers no ranges. Terrain doesn't draw on a backend that failed to
199    /// make its shader ([`make_shader`]): the map draws flat.
200    ///
201    /// [`bind`]: Self::bind
202    /// [`make_shader`]: Self::make_shader
203    pub(crate) fn update<'a>(
204        &mut self,
205        parameters: &UpdateParameters,
206        dem: impl FnOnce(&str) -> Option<&'a SourceTiles>,
207    ) -> Option<&TerrainCover> {
208        let mut ranges = self.cover.take().map(|cover| cover.ranges).unwrap_or_default();
209        let style = &parameters.style;
210        let terrain = style.terrain()?;
211        if parameters.mode == MapMode::Tile || self.draws.failed() {
212            return None;
213        }
214        // Terrain draws only once its source's tiles have a cover, and not
215        // at all from a source whose tiles aren't raster-dem.
216        let dem = dem(&terrain.source).filter(|dem| dem.info.kind == SourceKind::RasterDem)?;
217        let cover = dem.info.cover?;
218
219        let skirt_length =
220            skirt_length(parameters.terrain.skirt_length, parameters.view.zoom(), parameters.view.world());
221        self.surface = Surface::new(dem.info.dem_encoding, terrain.exaggeration, skirt_length);
222        self.drape_memory_limit = parameters.terrain.drape_memory_limit;
223
224        let dem_zooms = cover.zoom_range;
225        ranges.update(dem, dem_zooms, f64::from(terrain.exaggeration));
226        let tile_size = cover.tile_size;
227        let view = &parameters.view;
228        self.cover = Some(TerrainCover::new(view, &terrain.source, tile_size, dem_zooms, ranges));
229        self.cover.as_ref()
230    }
231
232    /// Makes the surface's shader on `gpu` in `context` for the update of
233    /// `parameters`, before [`update`], if its style has terrain. A backend
234    /// that fails to make it draws no terrain until the shaders are made
235    /// again ([`release_shaders`]).
236    ///
237    /// [`update`]: Self::update
238    /// [`release_shaders`]: Self::release_shaders
239    pub(crate) fn make_shader(&mut self, gpu: &mut dyn Gpu, context: &mut Context, parameters: &UpdateParameters) {
240        if parameters.style.terrain().is_some() && parameters.mode != MapMode::Tile {
241            self.draws.shaders(gpu, context, &parameters.view);
242        }
243    }
244
245    /// Binds each terrain tile's DEM, once the sources have updated, from
246    /// the tiles of the terrain's source that `dem` finds by its id. A
247    /// frame's bindings are of the DEM tiles it has, so that a frame that
248    /// has loaded draws each tile with its own.
249    ///
250    /// Returns whether the frame is grounded: whether the update
251    /// ([`UpdateParameters::elevation`]) carries the ground the tiles now
252    /// draw, the same `Arc`, or neither has one, as while terrain doesn't
253    /// draw. Otherwise it tells the map of its current ground in `events`
254    /// ([`RendererEvent::TerrainElevation`]), before the frame finishes.
255    /// The ground keeps its `Arc` while the tiles, the DEM data they read and
256    /// how it decodes stay the same.
257    pub(crate) fn bind<'a>(
258        &mut self,
259        dem: impl FnOnce(&str) -> Option<&'a SourceTiles>,
260        parameters: &UpdateParameters,
261        events: &mut Vec<RendererEvent>,
262    ) -> bool {
263        let seen = parameters.elevation.as_deref();
264        let Some(cover) = &mut self.cover else {
265            if self.elevation.take().is_some() || seen.is_some() {
266                events.push(RendererEvent::TerrainElevation(None));
267            }
268            return seen.is_none();
269        };
270        let tiles = dem(&cover.source_id);
271        cover.bind(tiles);
272        let ground = TerrainElevation::new(cover, tiles, self.surface.unpack(), self.surface.props.exaggeration);
273        let drawn = match &mut self.elevation {
274            Some(drawn) if drawn.draws_as(&ground) => drawn,
275            slot => slot.insert(Arc::new(ground.with_clearance(tiles))),
276        };
277        let grounded = seen.is_some_and(|seen| std::ptr::addr_eq(seen, Arc::as_ptr(drawn)));
278        if !grounded {
279            events.push(RendererEvent::TerrainElevation(Some(Arc::<TerrainElevation>::clone(drawn))));
280        }
281        grounded
282    }
283
284    /// The ground the last update's cover drew, while terrain draws.
285    pub(crate) fn ground(&self) -> Option<&Arc<TerrainElevation>> {
286        self.elevation.as_ref()
287    }
288
289    /// The ground of the frame of the last update, where it has terrain and
290    /// a layer `stands` on it: the ground its cover drew ([`ground`]), and,
291    /// where a layer `hides` behind it, the texture of its depth, which the
292    /// frame draws first ([`render_ground`]). Drops the ground's depth
293    /// otherwise.
294    ///
295    /// [`ground`]: Self::ground
296    /// [`render_ground`]: Self::render_ground
297    pub(crate) fn update_ground(
298        &mut self,
299        parameters: &mut PaintParameters<'_>,
300        stands: bool,
301        hides: bool,
302    ) -> Option<Rc<FrameGround>> {
303        let elevation = self.elevation.clone().filter(|_| stands && self.cover.is_some());
304        let depth = elevation
305            .as_ref()
306            .filter(|_| hides)
307            .map(|_| self.ground_depth.texture(parameters.context, parameters.renderable_size));
308        if depth.is_none() {
309            self.ground_depth.clear();
310        }
311        Some(Rc::new(FrameGround::new(elevation?, depth)))
312    }
313
314    /// The drapes of the last frame.
315    #[cfg(test)]
316    pub(crate) fn drapes(&self) -> &Drapes {
317        &self.drapes
318    }
319
320    /// How the surface of the last update's cover draws.
321    #[cfg(test)]
322    pub(crate) fn surface(&self) -> Surface {
323        self.surface
324    }
325
326    /// The cover of the last update, while terrain draws: [`update`]'s.
327    ///
328    /// [`update`]: Self::update
329    pub(crate) fn cover(&self) -> Option<&TerrainCover> {
330        self.cover.as_ref()
331    }
332
333    /// Makes, in the encode, the textures of the DEM tiles of the terrain's
334    /// source, which `dem` finds by its id, that the tiles of the last
335    /// update's cover read, for the surface's draws; drops them in a frame
336    /// without terrain.
337    pub(crate) fn update_dems<'a>(
338        &mut self,
339        parameters: &mut PaintParameters<'_>,
340        dem: impl FnOnce(&str) -> Option<&'a SourceTiles>,
341    ) {
342        let Some(cover) = &self.cover else {
343            self.dem_textures = DemTextures::default();
344            self.dems = None;
345            return;
346        };
347        let context = &mut *parameters.context;
348        let tiles = dem(&cover.source_id);
349        let mut textures = HashMap::default();
350        for (id, _) in cover.tiles.iter().filter_map(|tile| tile.dem) {
351            if textures.contains_key(&id.canonical) {
352                continue;
353            }
354            if let Some(dem) = tiles.and_then(|tiles| dem_contents(tiles.tile(&id)?)) {
355                let dim = u32::try_from(dem.dem().dim).unwrap_or(0);
356                textures.insert(id.canonical, (self.dem_textures.texture(context, dem), dim));
357            }
358        }
359        self.dem_textures.finish_frame();
360        let flat = self.dem_textures.flat(context);
361        self.dems = Some(DemBindings { textures, flat });
362    }
363
364    /// Starts the encode's update of the drapes of the frame of the last
365    /// update, of `stacks` stacks of draped layers, whose layers then make
366    /// their draws in them ([`Drapes::update_layer`]); `None`, dropping the
367    /// drapes, for a frame that doesn't draw terrain or no stack.
368    pub(crate) fn begin_drapes(&mut self, parameters: &mut PaintParameters<'_>, stacks: usize) -> Option<&mut Drapes> {
369        let Some(cover) = self.cover.as_ref().filter(|_| stacks > 0) else {
370            self.drapes = Drapes::default();
371            return None;
372        };
373        let max_texture_size = parameters.context.caps().max_texture_size;
374        self.drapes.begin(
375            parameters.view,
376            cover,
377            stacks,
378            (self.drape_memory_limit.unwrap_or(u64::MAX), max_texture_size),
379        );
380        Some(&mut self.drapes)
381    }
382
383    /// Makes the draws of the frame of the last update, a set for each stack
384    /// of the drapes the encode began ([`begin_drapes`]), which read the DEM
385    /// textures of the frame ([`update_dems`]), sample their stack's drapes,
386    /// shade them with the stack's light of `stacks`, if it has one, and
387    /// cover them with `fog`, and, if `depth_first`, draws of the surface's
388    /// depth alone ([`render_depth`]), and, if `ground`, draws of the
389    /// ground's depth into its texture ([`render_ground`]). Without either,
390    /// which a frame without terrain has neither of, it makes no draws, and
391    /// drops what the draws hold.
392    ///
393    /// [`begin_drapes`]: Self::begin_drapes
394    /// [`update_dems`]: Self::update_dems
395    /// [`render_depth`]: Self::render_depth
396    /// [`render_ground`]: Self::render_ground
397    pub(crate) fn update_draws(
398        &mut self,
399        gpu: &mut dyn Gpu,
400        parameters: &mut PaintParameters<'_>,
401        stacks: &DrapeStacks,
402        fog: TerrainFog,
403        (depth_first, ground): (bool, bool),
404    ) {
405        let cover = self.cover.as_ref().zip(self.dems.as_ref());
406        self.draws.update(gpu, parameters, cover, (self.surface, fog), (&self.drapes, stacks), (depth_first, ground));
407    }
408
409    /// Follow-up repaint needed for any deferred drapes from the last frame.
410    pub(crate) fn drape_repaint(&self) -> DrapeRepaint {
411        self.drapes.repaint()
412    }
413
414    /// Makes the drapes that show the buckets in `changed`, which changed,
415    /// draw again.
416    pub(crate) fn mark_changed(&mut self, changed: &ChangedBuckets) {
417        self.drapes.mark_changed(changed);
418    }
419
420    /// Makes every drape draw again in the next frame, for a change that
421    /// their keys don't tell: the style's images, or a frame that failed.
422    pub(crate) fn redraw_drapes(&mut self) {
423        self.drapes.redraw();
424    }
425
426    /// Drops the drapes once the map's center crossed the antimeridian: the
427    /// tiles are the same ones under new ids, and the next frame draws their
428    /// drapes again.
429    pub(crate) fn handle_wrap_jump(&mut self) {
430        self.drapes = Drapes::default();
431    }
432
433    /// Uploads the GPU objects of the frame's draws.
434    pub(crate) fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) {
435        self.draws.upload(gpu, context);
436    }
437
438    /// Uploads the drapes' draws and makes what they draw with, through
439    /// `gpu`, the context of `parameters`, the frame's.
440    pub(crate) fn upload_drapes(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
441        self.drapes.upload(gpu, parameters);
442    }
443
444    /// Draws the drapes into their textures, outside any pass, before the
445    /// frame's passes, whose surface samples them.
446    pub(crate) fn render_drapes(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
447        self.drapes.render(gpu, parameters);
448    }
449
450    /// Counts in the rendering stats of `context` what the drapes hold once
451    /// a frame has drawn ([`Drapes::count`]).
452    pub(crate) fn count(&self, context: &mut Context) {
453        self.drapes.count(context);
454    }
455
456    /// Draws the surface of `stack`, which samples the stack's drapes, into
457    /// the open pass of `gpu`, the context's.
458    pub(crate) fn render(&mut self, stack: usize, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
459        self.draws.render(stack, gpu, parameters);
460    }
461
462    /// Draws the ground's depth, where the frame has a ground that a layer
463    /// hides behind ([`update_ground`]), in a pass of its own before the
464    /// frame's passes, into its texture.
465    ///
466    /// [`update_ground`]: Self::update_ground
467    pub(crate) fn render_ground(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
468        if !self.draws.draws_ground() {
469            return;
470        }
471        let Some(pass) = self.ground_depth.pass(gpu, parameters.context) else {
472            return;
473        };
474        if let Err(error) = parameters.begin_pass(gpu, pass) {
475            parameters.context.fail(format!("Beginning the ground's pass failed: {error}"));
476            return;
477        }
478        self.draws.render_ground(gpu, parameters);
479        if let Err(error) = parameters.end_pass(gpu) {
480            parameters.context.fail(format!("Ending the ground's pass failed: {error}"));
481        }
482    }
483
484    /// Draws the surface's depth alone into the open pass of `gpu`, the
485    /// context's, where the frame's draws have it, so that the 3D layers
486    /// that draw before the first stack's surface stand behind the ground.
487    pub(crate) fn render_depth(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
488        self.draws.render_depth(gpu, parameters);
489    }
490
491    /// Drops all it made from the map's data, for the renderer's
492    /// `clear_data`: the cover and the elevation ranges it remembers, the
493    /// drapes and the layers' drawings in them, the draws and the DEM
494    /// textures. If it had told the map of the ground, it tells it in
495    /// `events` that the ground is gone.
496    pub(crate) fn clear_data(&mut self, events: &mut Vec<RendererEvent>) {
497        if self.elevation.is_some() {
498            events.push(RendererEvent::TerrainElevation(None));
499        }
500        *self = RenderTerrain::default();
501    }
502
503    /// Drops the draws and the drapes, which hold the renderer's shaders,
504    /// and the DEM textures; the next frame makes them again.
505    pub(crate) fn release_shaders(&mut self) {
506        self.drapes = Drapes::default();
507        self.draws = TerrainDraws::default();
508        self.dem_textures = DemTextures::default();
509        self.dems = None;
510        self.ground_depth.clear();
511    }
512}