Skip to main content

mln_engine/camera/transform/
gesture.rs

1//! Gestures: camera deltas and updates relative to where the camera is.
2
3use super::{BEARING, CameraCommandId, PITCH, Transform, TransformEvent, ZOOM};
4use crate::camera::{
5    AnimationOptions, CameraDelta, CameraError, CameraMomentum, CameraOptions, CameraUpdate, CameraUpdateMode,
6    GesturePhase, TransitionOutcome,
7};
8use crate::map::events::{CameraChange, CameraChangeMode, CameraChangeSource};
9
10/// The gesture that camera deltas and updates with a phase make.
11#[derive(Clone, Copy, Debug, Default)]
12pub(super) struct GestureState {
13    /// Between its first `Begin` or `Update` and its `End` or `Cancel`.
14    pub(super) active: bool,
15    /// Counts gestures, so that an earlier gesture's momentum doesn't end a
16    /// later gesture.
17    serial: u64,
18    /// The fields the gesture changed (`ZOOM`, `BEARING`, `PITCH`), which
19    /// alone may settle.
20    changed: u16,
21    /// The altitude the gesture holds over terrain, once it took it
22    /// (see `terrain`).
23    pub(super) altitude: Option<f64>,
24}
25
26impl GestureState {
27    /// Records the fields a gesture's change moves.
28    fn change(&mut self, zoom: bool, bearing: bool, pitch: bool) {
29        self.changed |=
30            (if zoom { ZOOM } else { 0 }) | (if bearing { BEARING } else { 0 }) | (if pitch { PITCH } else { 0 });
31    }
32
33    /// Drops the snaps of the parts the gesture didn't change: only what it
34    /// changed settles.
35    fn mask_snaps(&self, momentum: &mut CameraMomentum) {
36        for (part, field) in
37            [(&mut momentum.zoom, ZOOM), (&mut momentum.bearing, BEARING), (&mut momentum.pitch, PITCH)]
38        {
39            if self.changed & field == 0 {
40                part.snap = None;
41            }
42        }
43    }
44}
45
46fn gesture_source(phase: GesturePhase) -> CameraChangeSource {
47    if phase == GesturePhase::None { CameraChangeSource::Command } else { CameraChangeSource::Gesture }
48}
49
50impl Transform {
51    /// Moves the camera relative to where it is, as a gesture does
52    /// (the C API's `mln_map_apply_camera_delta`). See
53    /// [`CameraDelta`].
54    pub fn apply_camera_delta(&mut self, delta: &CameraDelta) -> Result<CameraCommandId, CameraError> {
55        delta.validate()?;
56        Ok(self.command(|transform| transform.apply_camera_delta_now(delta)))
57    }
58
59    fn apply_camera_delta_now(&mut self, delta: &CameraDelta) {
60        let source = gesture_source(delta.phase);
61        let pans = delta.offset.is_some();
62        let eases = delta.scale.is_some() || delta.bearing.is_some() || delta.pitch.is_some();
63        // With momentum, the command's end is the momentum's, and the delta's
64        // own changes, which can't animate, apply before it starts.
65        // Otherwise the pan and the ease end the command together.
66        let parts = match delta.momentum {
67            Some(_) => AnimationOptions::default(),
68            None => delta.animation,
69        };
70        self.silent = delta.momentum.is_some();
71        self.join_ends(u32::from(pans) + u32::from(eases));
72        self.gesture_phase_before(delta.phase);
73        if delta.phase != GesturePhase::None {
74            self.gesture.change(
75                delta.scale.is_some_and(|scale| scale != 1.0),
76                delta.bearing.is_some_and(|bearing| bearing != 0.0),
77                delta.pitch.is_some_and(|pitch| pitch != 0.0),
78            );
79        }
80        self.with_source(source, |transform| {
81            if let Some(offset) = delta.offset {
82                // Validation keeps the offset finite, so it has a LatLng. The
83                // anchor is the point the drag holds, which the globe keeps
84                // under it.
85                let _ = transform.move_by_with_anchor(&offset, delta.anchor, &parts);
86            }
87            if eases {
88                let current = transform.camera_options(None);
89                let target = CameraOptions {
90                    zoom: delta.scale.map(|scale| current.zoom.unwrap_or(0.0) + scale.log2()),
91                    bearing: delta.bearing.map(|bearing| current.bearing.unwrap_or(0.0) + bearing),
92                    pitch: delta.pitch.map(|pitch| current.pitch.unwrap_or(0.0) + pitch),
93                    anchor: delta.anchor,
94                    ..CameraOptions::default()
95                };
96                transform.ease_to(&target, &parts);
97            }
98        });
99        self.silent = false;
100        match delta.momentum {
101            Some(mut momentum) => {
102                self.gesture.mask_snaps(&mut momentum);
103                // The gesture ends as its momentum starts, rather than in
104                // `gesture_phase_after`, so that a momentum with nothing to
105                // move, which ends at once, ends it too.
106                self.gesture.active = false;
107                let serial = self.gesture.serial;
108                self.with_source(CameraChangeSource::Momentum, |transform| {
109                    transform.start_momentum_now(&momentum, &delta.animation, Some(serial));
110                });
111            }
112            None if !pans && !eases => self.end_unstarted(&delta.animation, TransitionOutcome::Completed),
113            None => {}
114        }
115        self.gesture_phase_after(delta.phase, delta.momentum.is_some());
116    }
117
118    /// Moves the camera to absolute values, as a command or a gesture
119    /// (the C API's `mln_map_update_camera`). See [`CameraUpdate`].
120    pub fn update_camera(&mut self, update: &CameraUpdate) -> CameraCommandId {
121        self.command(|transform| transform.update_camera_now(update))
122    }
123
124    fn update_camera_now(&mut self, update: &CameraUpdate) {
125        self.gesture_phase_before(update.phase);
126        if update.phase != GesturePhase::None {
127            // A gesture's update can repeat a field it doesn't change.
128            let current = self.camera_options(None);
129            let changes = |value: Option<f64>, now: Option<f64>| value.is_some() && value != now;
130            self.gesture.change(
131                changes(update.camera.zoom, current.zoom),
132                changes(update.camera.bearing, current.bearing),
133                changes(update.camera.pitch, current.pitch),
134            );
135        }
136        self.with_source(gesture_source(update.phase), |transform| match update.mode {
137            CameraUpdateMode::Jump => {
138                transform.ease(&update.camera, &AnimationOptions { duration: None, ..update.animation });
139            }
140            CameraUpdateMode::Ease => transform.ease(&update.camera, &update.animation),
141            CameraUpdateMode::Fly => transform.fly(&update.camera, &update.animation, false),
142        });
143        self.gesture_phase_after(update.phase, false);
144    }
145
146    /// `Begin` cancels the running commands, and `Begin` and `Update` mark
147    /// the gesture, before its change applies, so that the change follows
148    /// the gesture rules (an ease doesn't fly, and wraps the longitude as a
149    /// drag). The first phase after a gesture ended starts a new one, which
150    /// an earlier gesture's momentum no longer ends.
151    fn gesture_phase_before(&mut self, phase: GesturePhase) {
152        if phase != GesturePhase::None && (phase == GesturePhase::Begin || !self.gesture.active) {
153            self.gesture = GestureState { serial: self.gesture.serial.wrapping_add(1), ..GestureState::default() };
154        }
155        if phase == GesturePhase::Begin {
156            self.cancel_transitions();
157        }
158        if matches!(phase, GesturePhase::Begin | GesturePhase::Update) {
159            self.gesture.active = true;
160            self.gesture_in_progress = true;
161        }
162    }
163
164    /// `Cancel` cancels the running commands after its change applies, and
165    /// `End` and `Cancel` end the gesture: at once, or when its momentum
166    /// ends. A gesture that ends at once comes to rest
167    /// ([`Self::come_to_rest`]), and reports the camera's change if that
168    /// moves it, though the picture stays.
169    fn gesture_phase_after(&mut self, phase: GesturePhase, momentum: bool) {
170        if phase == GesturePhase::Cancel {
171            self.cancel_transitions();
172        }
173        if matches!(phase, GesturePhase::End | GesturePhase::Cancel) {
174            self.gesture.active = false;
175            if !momentum {
176                self.gesture_in_progress = false;
177                if self.come_to_rest() {
178                    let change =
179                        CameraChange { mode: CameraChangeMode::Immediate, source: CameraChangeSource::Gesture };
180                    self.emit(TransformEvent::CameraWillChange(change));
181                    self.emit(TransformEvent::CameraDidChange(change));
182                }
183            }
184        }
185    }
186
187    /// The end of a gesture's momentum ends the gesture, unless another
188    /// gesture started since. The caller brings the camera to rest.
189    pub(super) fn end_gesture_momentum(&mut self, gesture: Option<u64>) {
190        if gesture == Some(self.gesture.serial) && !self.gesture.active {
191            self.gesture_in_progress = false;
192        }
193    }
194
195    #[cfg(test)]
196    pub(crate) fn set_gesture_in_progress(&mut self, in_progress: bool) {
197        self.gesture_in_progress = in_progress;
198    }
199
200    #[must_use]
201    pub fn is_gesture_in_progress(&self) -> bool {
202        self.gesture_in_progress
203    }
204}