Skip to main content

mln_engine/camera/transform/
terrain.rs

1//! The terrain under the camera. Every rule applies only while the map
2//! hands the transform a ground ([`TerrainGround`]):
3//!
4//! - The eye stays above the ground while anything moves the camera
5//!   ([`Transform::keep_clear_of_ground`]).
6//! - A gesture holds the altitude, from its first step to the end of its
7//!   momentum, lifted by as much as keeps the eye above the ground, which
8//!   lowers again once the ground does. A command that runs while its
9//!   fingers are up takes the altitude over, and the gesture holds it from
10//!   where the command leaves it.
11//! - Under the clamp, the center stands on the ground:
12//!   - at rest, on the ground under it, where that is known;
13//!   - while commands run and no fingers are down, the altitude eases
14//!     toward the ground under where they leave the center, and stands on
15//!     it as they end ([`Transform::ease_altitude`]);
16//!   - brought to rest off the ground, by a cancel or by the end of a
17//!     gesture or of its momentum, the center moves along the view onto the
18//!     ground, with the eye where it is, so that the picture stays
19//!     ([`Transform::come_to_rest`]).
20//!
21//! The rules are the same on the globe, where heights stand along each
22//! point's vertical above the sea-level sphere: the same heights at the
23//! center decide the altitude, and the eye, its near plane and the ground
24//! under the line of sight are the globe camera's
25//! ([`View::ground_under`]).
26//!
27//! The terrain moves a camera at rest, as ground loads or changes under it,
28//! the clamp turns on or the terrain goes, without camera events, as in GL
29//! JS: the map's snapshots show those moves. What the terrain does to a
30//! command's or a gesture's camera happens within it, before the
31//! `CameraDidChange` that ends it.
32
33use std::sync::Arc;
34
35use glam::DVec3;
36use mln_style::geo::WrapMode;
37use mln_style::time::Instant;
38
39use super::transition::Transition;
40use super::{CENTER, Transform, flip_y};
41use crate::camera::{CameraOptions, Elevation, View};
42
43/// How many times a moving camera is raised over the ground in a frame, as
44/// in GL JS: each raise can turn or move the near plane, which can bring
45/// another part of it under the ground.
46const MAX_EYE_RAISES: usize = 3;
47
48/// The terrain the camera stands on, which the map hands the transform
49/// while its style's terrain draws outside tile mode, on every projection.
50#[derive(Clone, Debug)]
51pub struct TerrainGround {
52    /// The ground the renderer last drew, or `None` before it drew any:
53    /// the eye then stays above sea level, and the ground under the center
54    /// counts as loading.
55    pub elevation: Option<Arc<dyn Elevation>>,
56    /// Whether the center stands on the ground at rest.
57    pub clamped: bool,
58}
59
60impl Transform {
61    /// Sets the terrain the camera stands on, or `None` without terrain,
62    /// which turns off every rule of the camera over terrain. Once the
63    /// terrain goes, the view fits the flat map again, a clamped center
64    /// goes to sea level, keeping its location and zoom, and a gesture
65    /// holds the altitude from where that leaves it.
66    pub fn set_terrain(&mut self, terrain: Option<TerrainGround>) {
67        let clamped = self.clamped();
68        let goes = self.terrain.is_some() && terrain.is_none();
69        self.terrain = terrain;
70        if goes {
71            self.gesture.altitude = None;
72            self.leave_ground();
73            // Also before any ground was drawn, as the ground would have
74            // overruled the altitude of a clamped center.
75            if clamped {
76                self.go_to_sea_level();
77            }
78        }
79    }
80
81    /// Fits the view's near and far planes to the flat map again, and
82    /// returns whether they fit the ground before.
83    fn leave_ground(&mut self) -> bool {
84        let fit = self.view().terrain_min_elevation().is_some();
85        if fit {
86            self.state.set_terrain_min_elevation(None);
87        }
88        fit
89    }
90
91    /// Puts the center at sea level, keeping its location and zoom.
92    fn go_to_sea_level(&mut self) {
93        if self.view().center_altitude() != 0.0 {
94            self.state.set_center_altitude(0.0);
95        }
96    }
97
98    /// Fits the view's near and far planes to the lowest ground that
99    /// `elevation` has in the tile under the center, or to sea level where it
100    /// has none.
101    fn fit_planes(&mut self, elevation: &dyn Elevation) {
102        let min_elevation = Some(lowest_ground(self.view(), elevation));
103        if min_elevation != self.view().terrain_min_elevation() {
104            self.state.set_terrain_min_elevation(min_elevation);
105        }
106    }
107
108    /// Moves the camera onto the terrain's ground. While there is ground,
109    /// the view's near and far planes fit the lowest ground of the tile
110    /// under the center, and a camera at rest whose center is clamped
111    /// stands on the ground there, unless it is still loading. A camera that
112    /// a command moves takes the altitude its frames give it, which ease
113    /// onto the ground, and a gesture that holds the altitude lifts it just
114    /// over the ground as it is now, eye and near plane. Once there is no
115    /// ground, the planes fit the flat map again, and a clamped center goes
116    /// back to sea level, once.
117    ///
118    /// At rest it reads only the height and floor at the center
119    /// ([`Elevation::at`] and [`Elevation::min_at`]), which are what the
120    /// renderer compares to tell whether a frame's camera stood on its
121    /// newest ground. The terrain moves the camera, not a command, so this
122    /// reports no camera change. Returns whether the view changed.
123    pub fn follow_terrain(&mut self) -> bool {
124        let Some(TerrainGround { elevation, clamped }) = &self.terrain else { return false };
125        let (elevation, clamped) = (elevation.clone(), *clamped);
126        let ground = |view: &View| (view.terrain_min_elevation(), view.center_altitude());
127        let before = ground(self.view());
128        match &elevation {
129            Some(elevation) => self.fit_planes(&**elevation),
130            // Once, as the planes fit the flat map from then on.
131            None => {
132                if self.leave_ground() && clamped {
133                    self.go_to_sea_level();
134                }
135            }
136        }
137        // A command of the pitch alone doesn't count as moving the camera,
138        // but its frames set the altitude too.
139        let at_rest = !self.is_camera_moving() && !self.in_transition();
140        if self.gesture_holds_altitude() {
141            self.lift(elevation.as_deref());
142        } else if clamped && at_rest {
143            self.stand_on_ground();
144        }
145        ground(self.view()) != before
146    }
147
148    /// Whether there is terrain and it clamps the center.
149    pub(super) fn clamped(&self) -> bool {
150        self.terrain.as_ref().is_some_and(|terrain| terrain.clamped)
151    }
152
153    /// Whether a gesture holds the altitude: from its first step to the end
154    /// of its momentum, except while its fingers are up and a command runs.
155    fn gesture_holds_altitude(&self) -> bool {
156        self.gesture_in_progress && (self.gesture.active || !self.transitions.iter().any(Transition::is_command))
157    }
158
159    /// Puts the center at the height of the ground under it, where that is
160    /// known.
161    pub(super) fn stand_on_ground(&mut self) {
162        let Some(TerrainGround { elevation: Some(ground), .. }) = &self.terrain else { return };
163        let view = self.view();
164        if let Some(altitude) = ground.at(view.center(WrapMode::Wrapped)).filter(|&h| h != view.center_altitude()) {
165            self.state.set_center_altitude(altitude);
166        }
167    }
168
169    /// Sets the altitude of `camera`, a frame's camera at `now` composed of
170    /// the running commands, over terrain that clamps the center: from the
171    /// altitude the camera has, toward the ground under where the commands
172    /// leave the center, by this frame's share of what is left of the way of
173    /// the command that ends last, so that it arrives as they end (GL JS's
174    /// `_startElevationEasing`, turned toward its target each frame). Where
175    /// they leave the center is where the command that owns it ends it, or
176    /// else where it is. Ground that lands, or a command that starts, ends
177    /// or hands the center over, turns the next frame toward the new target
178    /// from where the altitude is. While that ground is unknown, as at the
179    /// end of a flight past the ground the renderer drew, or a gesture holds
180    /// the altitude, it stays where it is.
181    ///
182    /// Returns whether this frame ends the commands, which then stand the
183    /// center on the ground under where they put it
184    /// ([`Self::stand_on_ground`]).
185    pub(super) fn ease_altitude(&mut self, camera: &mut CameraOptions, now: Option<Instant>) -> bool {
186        let before = std::mem::replace(&mut self.last_frame, now);
187        let Some(TerrainGround { elevation: Some(ground), clamped: true }) = &self.terrain else { return false };
188        if self.gesture_holds_altitude() {
189            return false;
190        }
191        let commands = || self.transitions.iter().filter(|transition| transition.is_command());
192        let Some(pacing) = commands().max_by_key(|transition| transition.remaining(now)) else { return false };
193        let end = match commands().find(|transition| transition.fields & CENTER != 0) {
194            Some(owner) => owner.end_center(&self.state, camera, &**ground),
195            None => self.view().center(WrapMode::Wrapped),
196        };
197        let Some(target) = ground.at(end) else { return false };
198        let altitude = self.view().center_altitude();
199        // An easing that overshoots its end, or backs up past its start,
200        // takes the altitude no farther than the target: it arrives where
201        // the share first reaches 1, and holds while the share falls back.
202        let share = pacing.share(now).clamp(0.0, 1.0);
203        let reached = before.map_or(0.0, |before| pacing.share(Some(before)).clamp(0.0, 1.0)).min(share);
204        let lands = pacing.remaining(now).is_zero();
205        camera.center_altitude = Some(if lands || reached == 1.0 {
206            target
207        } else {
208            altitude + (target - altitude) * (share - reached) / (1.0 - reached)
209        });
210        lands
211    }
212
213    /// Stands a camera that a command, a gesture or a momentum brought to
214    /// rest over terrain that clamps the center on the ground, once no
215    /// gesture or command moves it. A center off the drawn ground under it,
216    /// as a cancel or a gesture leaves it, moves along the view onto the
217    /// ground its line of sight meets, with the eye where it is
218    /// ([`TransformState::recenter_on`], GL JS's `recenterOnTerrain`); what
219    /// that leaves off the ground, or all of it where the view meets no
220    /// drawn ground or the limits refuse the move, the center takes up in
221    /// altitude. The caller reports the change. Returns whether the camera
222    /// moved.
223    ///
224    /// [`TransformState::recenter_on`]: crate::camera::TransformState::recenter_on
225    pub(super) fn come_to_rest(&mut self) -> bool {
226        let Some(TerrainGround { elevation: Some(ground), clamped: true }) = &self.terrain else { return false };
227        let view = self.view();
228        let off = ground.at(view.center(WrapMode::Wrapped)).is_some_and(|h| h != view.center_altitude());
229        if !off || self.gesture_in_progress || !self.transitions.is_empty() {
230            return false;
231        }
232        let ground = Arc::clone(ground);
233        let center = flip_y(view, &view.padding().center_in(view.size()));
234        if let Some(hit) = view.ground_under(&center, &*ground) {
235            // A refused move leaves the state as it is.
236            let _ = self.state.recenter_on(&hit);
237        }
238        self.stand_on_ground();
239        true
240    }
241
242    /// Keeps the eye of a moving camera out of the terrain: the view's near
243    /// and far planes fit the ground under the center, as at rest, and
244    /// where the eye, or the near plane over drawn ground, would be below
245    /// the ground, a gesture that holds the altitude lifts it
246    /// ([`Self::lift`]), and anything else raises the eye by pitch and zoom,
247    /// keeping its place and the center it looks at (GL JS's
248    /// `_raiseCameraByPitchAndZoom`). Before the renderer drew any ground,
249    /// the eye stays above sea level. Without terrain it does nothing.
250    pub(super) fn keep_clear_of_ground(&mut self) {
251        let Some(terrain) = &self.terrain else { return };
252        let elevation = terrain.elevation.clone();
253        // The frame's center may have moved since the planes last fit it.
254        if let Some(elevation) = &elevation {
255            self.fit_planes(&**elevation);
256        }
257        if self.gesture_holds_altitude() {
258            self.lift(elevation.as_deref());
259            return;
260        }
261        // The gesture holds the altitude again from where this leaves it.
262        self.gesture.altitude = None;
263        for _ in 0..MAX_EYE_RAISES {
264            let shortfall = eye_shortfall(self.view(), elevation.as_deref());
265            if !(shortfall > 0.0 && self.state.raise_eye(shortfall)) {
266                return;
267            }
268        }
269    }
270
271    /// Puts the center at the altitude the gesture holds, raised by as far
272    /// as the ground reaches above the eye or the near plane there, so that
273    /// the lift lowers again once the ground under them does. The gesture
274    /// holds the altitude the camera has when it first lifts it. On Mercator
275    /// a raise moves the eye and the near plane straight up over the same
276    /// ground, so one clears them; on the globe it takes up to as many as a
277    /// command's.
278    fn lift(&mut self, elevation: Option<&dyn Elevation>) {
279        let mut altitude = *self.gesture.altitude.get_or_insert(self.view().center_altitude());
280        for raise in 0..=MAX_EYE_RAISES {
281            if self.view().center_altitude() != altitude {
282                self.state.set_center_altitude(altitude);
283            }
284            let shortfall = eye_shortfall(self.view(), elevation);
285            if !(shortfall > 0.0 && raise < MAX_EYE_RAISES) {
286                return;
287            }
288            altitude += shortfall;
289        }
290    }
291}
292
293/// The lowest ground that `elevation` has in the tile under the center of
294/// `view`, or sea level where it has none, in meters: what the view's near
295/// and far planes fit while terrain draws.
296pub(crate) fn lowest_ground(view: &View, elevation: &dyn Elevation) -> f64 {
297    elevation.min_at(view.center(WrapMode::Wrapped)).unwrap_or(0.0)
298}
299
300/// How far the ground reaches above the eye of `view`, or above a point of
301/// its near plane over drawn ground, in meters, whichever is more; zero or
302/// less while all are clear. The ground under the eye is sea level where
303/// none was drawn, or before any was (`elevation` is `None`); then only the
304/// eye counts.
305fn eye_shortfall(view: &View, elevation: Option<&dyn Elevation>) -> f64 {
306    let eye = view.eye_position();
307    let above =
308        |point: DVec3| elevation.and_then(|elevation| elevation.surface_at(point.truncate())).map(|h| h - point.z);
309    let mut shortfall = above(eye).unwrap_or(-eye.z);
310    if elevation.is_some() {
311        for point in view.near_plane_points() {
312            shortfall = above(point).map_or(shortfall, |above| shortfall.max(above));
313        }
314    }
315    shortfall
316}