Skip to main content

mln_engine/camera/
camera_momentum.rs

1// The `PAN`, `ZOOM`, `BEARING` and `PITCH` constants are each part's default,
2// so that every host and the gesture recognizer start from the same glide.
3
4use std::time::Duration;
5
6use crate::geo::ScreenCoordinate;
7
8/// A unit cubic Bézier, from (0, 0) to (1, 1), with these control points.
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct MomentumEasing {
11    pub x1: f64,
12    pub y1: f64,
13    pub x2: f64,
14    pub y2: f64,
15}
16
17impl MomentumEasing {
18    /// The curve that camera animations ease along by default.
19    pub const DEFAULT: MomentumEasing = MomentumEasing { x1: 0.0, y1: 0.0, x2: 0.25, y2: 1.0 };
20    /// The curve that Android's scroll fling follows.
21    pub const ANDROID_FLING: MomentumEasing = MomentumEasing { x1: 0.175, y1: 0.5, x2: 0.35, y2: 1.0 };
22}
23
24impl Default for MomentumEasing {
25    fn default() -> Self {
26        MomentumEasing::DEFAULT
27    }
28}
29
30/// How a glide unfolds from its release speed.
31#[derive(Clone, Copy, Debug, PartialEq)]
32pub enum MomentumDecayModel {
33    /// The speed halves every `half_life`, until it drops to `stop_speed`.
34    /// `UIScrollView`'s normal deceleration is a half-life of 346 ms, and its
35    /// fast deceleration 69 ms.
36    Friction { half_life: Duration, stop_speed: f64 },
37    /// The glide lasts `duration` × (speed / `reference_speed`)^`exponent`
38    /// and follows `easing`, starting at the release speed: it covers the
39    /// speed × its duration ÷ the curve's starting slope, `y1` / `x1`.
40    /// `exponent` is above -1, so a faster release glides farther.
41    /// [`MomentumDecay::ANDROID_FLING`] is Android's `OverScroller`.
42    Curve { reference_speed: f64, duration: Duration, exponent: f64, easing: MomentumEasing },
43}
44
45/// How one part of a release glides, in the part's unit: logical pixels for
46/// pan, zoom levels for zoom, and degrees for bearing and pitch, with speeds
47/// per second.
48///
49/// Each part has a default (`PAN`, `ZOOM`, `BEARING` and `PITCH`), which
50/// struct update starts from.
51#[derive(Clone, Copy, Debug, PartialEq)]
52pub struct MomentumDecay {
53    pub model: MomentumDecayModel,
54    /// A slower release doesn't glide.
55    pub min_speed: f64,
56    /// A faster release counts as this speed.
57    pub max_speed: f64,
58    /// The farthest the part glides. A release that would glide farther
59    /// counts as the speed that glides this far.
60    pub max_distance: f64,
61}
62
63impl MomentumDecay {
64    /// Friction with a 140 ms half-life, stopping at 1 unit per second, with
65    /// no limits.
66    pub const DEFAULT: MomentumDecay = MomentumDecay {
67        model: MomentumDecayModel::Friction { half_life: Duration::from_millis(140), stop_speed: 1.0 },
68        min_speed: 0.0,
69        max_speed: f64::INFINITY,
70        max_distance: f64::INFINITY,
71    };
72    /// Stops at 10 px/s, needs a release of at least 200 px/s, and counts one
73    /// faster than 10 000 px/s as 10 000.
74    pub const PAN: MomentumDecay = MomentumDecay {
75        model: MomentumDecayModel::Friction { half_life: Duration::from_millis(140), stop_speed: 10.0 },
76        min_speed: 200.0,
77        max_speed: 10_000.0,
78        ..MomentumDecay::DEFAULT
79    };
80    /// Stops at 0.01 levels/s and glides at most 2.5 levels.
81    pub const ZOOM: MomentumDecay = MomentumDecay {
82        model: MomentumDecayModel::Friction { half_life: Duration::from_millis(140), stop_speed: 0.01 },
83        max_distance: 2.5,
84        ..MomentumDecay::DEFAULT
85    };
86    /// Stops at 1°/s and needs at least 60°/s.
87    pub const BEARING: MomentumDecay = MomentumDecay { min_speed: 60.0, ..MomentumDecay::DEFAULT };
88    /// Stops at 1°/s and needs at least 5°/s.
89    pub const PITCH: MomentumDecay = MomentumDecay { min_speed: 5.0, ..MomentumDecay::DEFAULT };
90    /// Android's scroll fling, in its density-independent pixels, which are
91    /// logical pixels: its `OverScroller` glides a 1000 dp/s fling about
92    /// 194 dp over 555 ms, longer as `speed^0.736`. It needs Android's
93    /// minimum fling of 50 dp/s and caps it at Android's maximum, 8000.
94    pub const ANDROID_FLING: MomentumDecay = MomentumDecay {
95        model: MomentumDecayModel::Curve {
96            reference_speed: 1000.0,
97            duration: Duration::from_micros(555_182),
98            exponent: 0.736_267_6,
99            easing: MomentumEasing::ANDROID_FLING,
100        },
101        min_speed: 50.0,
102        max_speed: 8000.0,
103        max_distance: f64::INFINITY,
104    };
105
106    /// Checks that every number is in range: speeds, distances and durations
107    /// positive (`min_speed` may be 0, and the maximums infinite), and a
108    /// curve's control points within [0, 1] with a rising start.
109    pub fn validate(&self) -> Result<(), InvalidMomentum> {
110        let positive = |value: f64| value.is_finite() && value > 0.0;
111        let limits =
112            self.min_speed.is_finite() && self.min_speed >= 0.0 && self.max_speed > 0.0 && self.max_distance > 0.0;
113        let model = match self.model {
114            MomentumDecayModel::Friction { half_life, stop_speed } => !half_life.is_zero() && positive(stop_speed),
115            MomentumDecayModel::Curve { reference_speed, duration, exponent, easing } => {
116                let MomentumEasing { x1, y1, x2, y2 } = easing;
117                positive(reference_speed)
118                    && !duration.is_zero()
119                    && exponent.is_finite()
120                    && exponent > -1.0
121                    && [x1, y1, x2, y2].iter().all(|value| (0.0..=1.0).contains(value))
122                    && x1 > 0.0
123                    && y1 > 0.0
124            }
125        };
126        if limits && model {
127            Ok(())
128        } else {
129            Err(InvalidMomentum(
130                "a momentum decay needs positive speeds, distances and durations, a minimum speed that isn't \
131                 negative, and a curve within [0, 1] that starts rising",
132            ))
133        }
134    }
135}
136
137impl Default for MomentumDecay {
138    fn default() -> Self {
139        MomentumDecay::DEFAULT
140    }
141}
142
143/// Why a momentum setting is out of range.
144#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
145#[error("{0}")]
146pub struct InvalidMomentum(pub &'static str);
147
148/// Where a part settles once its glide ends: on the nearest of the targets
149/// every `spacing` from `offset`, when it is within `tolerance` of one.
150/// Bearing targets lie within one turn from `offset`, and the bearing takes
151/// the shorter way around to the nearest.
152#[derive(Clone, Copy, Debug, PartialEq)]
153pub struct MomentumSnap {
154    pub spacing: f64,
155    pub offset: f64,
156    pub tolerance: f64,
157    /// Zero settles at once.
158    pub duration: Duration,
159}
160
161impl MomentumSnap {
162    /// The nearest whole level, over 300 ms.
163    pub const ZOOM: MomentumSnap =
164        MomentumSnap { spacing: 1.0, offset: 0.0, tolerance: 0.5, duration: Duration::from_millis(300) };
165    /// North, within 7°, over 300 ms.
166    pub const BEARING: MomentumSnap =
167        MomentumSnap { spacing: 360.0, offset: 0.0, tolerance: 7.0, duration: Duration::from_millis(300) };
168    /// Flat, within 7°, over 300 ms.
169    pub const PITCH: MomentumSnap =
170        MomentumSnap { spacing: 90.0, offset: 0.0, tolerance: 7.0, duration: Duration::from_millis(300) };
171
172    /// Checks for a positive spacing, a finite offset, and a tolerance that
173    /// isn't negative.
174    pub fn validate(&self) -> Result<(), InvalidMomentum> {
175        if self.spacing.is_finite()
176            && self.spacing > 0.0
177            && self.offset.is_finite()
178            && self.tolerance.is_finite()
179            && self.tolerance >= 0.0
180        {
181            Ok(())
182        } else {
183            Err(InvalidMomentum(
184                "a momentum snap needs a positive spacing, a finite offset, and a tolerance that isn't negative",
185            ))
186        }
187    }
188}
189
190/// How one part glides after release: from `velocity`, per second, by
191/// `decay`. A pan's decay applies to its speed.
192#[derive(Clone, Copy, Debug, PartialEq)]
193pub struct MomentumGlide<T> {
194    pub velocity: T,
195    pub decay: MomentumDecay,
196}
197
198/// How a gesture's zoom, bearing or pitch keeps changing after release.
199#[derive(Clone, Copy, Debug, Default, PartialEq)]
200pub struct AnchoredMomentum {
201    /// Without one, the part stops where the gesture leaves it.
202    pub glide: Option<MomentumGlide<f64>>,
203    /// The screen point that the change keeps in place; without one, the
204    /// center of the view.
205    pub anchor: Option<ScreenCoordinate>,
206    /// Where the part settles; without one, it stays where the gesture and
207    /// its glide leave it.
208    pub snap: Option<MomentumSnap>,
209}
210
211/// Camera motion that continues a gesture after its last contact lifts.
212///
213/// Each part glides on its own, applied every frame relative to the camera
214/// as it stands, so other commands can change the fields that the momentum
215/// leaves alone. A command that sets a field stops the parts that move it.
216/// On a tilted map, pan moves the map's content the same distance on screen
217/// in every direction. [`Default`] glides and settles nothing.
218///
219/// The momentum's command ends when the momentum does, with a
220/// [`TransitionEnd`](crate::camera::TransitionEnd) whose velocity says how fast a
221/// cancelled momentum still moved.
222#[derive(Clone, Copy, Debug, Default, PartialEq)]
223pub struct CameraMomentum {
224    /// Without one, the pan stops where the gesture leaves it.
225    pub pan: Option<MomentumGlide<ScreenCoordinate>>,
226    pub zoom: AnchoredMomentum,
227    pub bearing: AnchoredMomentum,
228    pub pitch: AnchoredMomentum,
229}