Skip to main content

mln_engine/camera/
camera.rs

1use std::time::Duration;
2
3use glam::{DQuat, DVec3};
4use mln_style::geo::LatLng;
5use mln_style::unitbezier::UnitBezier;
6
7use crate::geo::{EdgeInsets, ScreenCoordinate};
8
9/// Various options for describing the viewpoint of a map. All fields are
10/// optional.
11/// A partial command replaces animations of its specified fields. Omitted
12/// fields keep their original animation timing. Flights couple center and
13/// zoom; anchored commands couple center with their specified fields.
14/// Replacing any member of a coupled group stops that group.
15/// Anchor and center points are mutually exclusive, with preference for the
16/// center point when both are set.
17#[derive(Clone, Copy, Debug, Default, PartialEq)]
18pub struct CameraOptions {
19    /// Coordinate at the center of the map.
20    pub center: Option<LatLng>,
21    /// Altitude of the center of the map, in meters above sea level, which
22    /// terrain that clamps the center (the map's `center_clamped_to_ground`)
23    /// decides instead.
24    pub center_altitude: Option<f64>,
25    /// Padding around the interior of the view that affects the frame of
26    /// reference for `center`.
27    pub padding: Option<EdgeInsets>,
28    /// Point of reference for `zoom` and `angle`, assuming an origin at the
29    /// top-left corner of the view: a command keeps the location under it in
30    /// place, over terrain the ground drawn there.
31    pub anchor: Option<ScreenCoordinate>,
32    /// Zero-based zoom level. Constrained to the minimum and maximum zoom
33    /// levels.
34    pub zoom: Option<f64>,
35    /// Bearing, measured in degrees from true north. Wrapped to [0, 360).
36    pub bearing: Option<f64>,
37    /// Pitch toward the horizon measured in degrees, with 0 deg resulting in
38    /// a two-dimensional map.
39    pub pitch: Option<f64>,
40    /// Roll, measured in degrees.
41    pub roll: Option<f64>,
42    /// Field of view, measured in degrees.
43    pub fov: Option<f64>,
44}
45
46/// How a camera fits an area in the map's view.
47#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub struct CameraFitOptions {
49    /// The space to leave between the area and each edge of the padded view.
50    pub margin: EdgeInsets,
51    /// The fitted camera's padding. `None` keeps the padding that the map's
52    /// running camera changes head for, or else the map's padding.
53    pub padding: Option<EdgeInsets>,
54    /// The rotation from north, in degrees. `None` keeps the map's.
55    pub bearing: Option<f64>,
56    /// The tilt toward the horizon, in degrees. `None` keeps the map's.
57    pub pitch: Option<f64>,
58    /// The highest zoom the fit may choose. The map's zoom limits apply
59    /// either way.
60    pub max_zoom: Option<f64>,
61}
62
63/// Various options for describing a transition between viewpoints with
64/// animation. All fields are optional; the default values depend on how
65/// this struct is used.
66#[derive(Clone, Copy, Debug, Default, PartialEq)]
67pub struct AnimationOptions {
68    /// Time to animate to the viewpoint defined herein.
69    pub duration: Option<Duration>,
70    /// Average velocity of a `flyTo()` transition, measured in screenfuls per
71    /// second, assuming a linear timing curve.
72    pub velocity: Option<f64>,
73    /// Zero-based zoom level at the peak of the `flyTo()` transition's flight
74    /// path.
75    pub min_zoom: Option<f64>,
76    /// The longest a `flyTo()` transition may take, as GL JS's `maxDuration`:
77    /// a flight whose duration, set or derived from the velocity, exceeds it
78    /// jumps instead. `None` caps nothing beyond what [`Duration`] holds: a
79    /// derived duration it can't hold jumps too. Other camera commands
80    /// ignore it.
81    pub max_duration: Option<Duration>,
82    /// The easing timing curve of the transition.
83    pub easing: Option<UnitBezier>,
84    /// Caller-chosen identity of the command, which
85    /// `Map::cancel_transitions_with_id` matches. Several commands may share
86    /// one.
87    pub transition_id: Option<u64>,
88}
89
90/// How a camera command ended, as the C API's
91/// `mln_camera_transition_outcome` reports it. A command that ended in more
92/// than one way reports [`Cancelled`](Self::Cancelled) if any of it was
93/// cancelled, otherwise [`Closed`](Self::Closed) if any of it was closed,
94/// and otherwise [`Replaced`](Self::Replaced) if any of it was replaced.
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
96pub enum TransitionOutcome {
97    /// The camera finished the change.
98    #[default]
99    Completed,
100    /// `cancel_transitions` or `cancel_transitions_with_id`, a gesture's
101    /// begin or cancel phase, free camera options, or a resize that moved the
102    /// camera back inside its bounds stopped it. A command that fails before
103    /// it moves the camera also reports this.
104    Cancelled,
105    /// A later command took every field that the command (or a momentum part)
106    /// was still animating, so it stopped. A later command that takes only
107    /// some of them leaves it animating the rest.
108    Replaced,
109    /// The map closed before the change ended.
110    Closed,
111}
112
113/// How fast each part of a camera change moves, in its own unit per second.
114#[derive(Clone, Copy, Debug, Default, PartialEq)]
115pub struct CameraVelocity {
116    /// Logical pixels per second that the map's content moves on screen.
117    pub(crate) pan: ScreenCoordinate,
118    /// Zoom levels per second.
119    pub(crate) zoom: f64,
120    /// Degrees per second.
121    pub(crate) bearing: f64,
122    /// Degrees per second.
123    pub(crate) pitch: f64,
124}
125
126/// How a camera command ended, once every field of it has: completed,
127/// cancelled, replaced by later commands, or closed with the map. Other
128/// commands may still be animating. It replaces C++'s `transitionFinishFn`,
129/// which can't tell those apart; the C API reports the same outcomes.
130#[derive(Clone, Copy, Debug, Default, PartialEq)]
131pub struct TransitionEnd {
132    pub outcome: TransitionOutcome,
133    /// How fast a momentum still moved when it was cancelled, as of the last
134    /// frame that moved the camera, which the next gesture can add to its own
135    /// release. Zero for every other end.
136    pub velocity: CameraVelocity,
137    /// The generation of the first snapshot of the map that shows where the
138    /// change left the camera, as `mln_runtime`'s map handles report it. 0
139    /// when the map closed first, and from the map itself, which ends a
140    /// change before it counts the change's generation.
141    pub generation: u64,
142}
143
144impl AnimationOptions {
145    #[must_use]
146    pub fn new(d: Duration) -> Self {
147        AnimationOptions { duration: Some(d), ..Default::default() }
148    }
149}
150
151/// Various options for accessing physical properties of the underlying camera
152/// entity. A direct access to these properties allows more flexible and
153/// precise controlling of the camera while also being fully compatible and
154/// interchangeable with `CameraOptions`. All fields are optional.
155#[derive(Clone, Copy, Debug, Default, PartialEq)]
156pub struct FreeCameraOptions {
157    /// Position of the camera in slightly modified web mercator coordinates.
158    /// The size of 1 unit is the width of the projected world instead of the
159    /// "mercator meter". Coordinate [0, 0, 0] is the north-west corner and
160    /// [1, 1, 0] is the south-east corner. Z coordinate is conformal and must
161    /// respect minimum and maximum zoom values. Zoom is automatically
162    /// computed from the altitude (z).
163    pub position: Option<DVec3>,
164    /// Orientation of the camera as a unit quaternion.
165    pub orientation: Option<DQuat>,
166}
167
168/// Where a camera change stands in a gesture, as the C API's
169/// `mln_gesture_phase` defines it. `Begin` and `Update` mark a gesture in
170/// progress, and `End` and `Cancel` end it; a gesture whose end starts
171/// momentum stays in progress until the momentum ends.
172#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
173pub enum GesturePhase {
174    /// The change isn't part of a gesture: a command.
175    #[default]
176    None,
177    /// The gesture starts. This cancels every running camera animation
178    /// before the change applies.
179    Begin,
180    /// The gesture continues. To start a gesture that keeps the running
181    /// animations, start it with this phase instead of `Begin`.
182    Update,
183    /// The gesture's last change, which may carry its momentum.
184    End,
185    /// The platform cancelled the gesture. This also cancels every running
186    /// camera animation after the change applies.
187    Cancel,
188}
189
190/// A change to the camera from where it is now, as a gesture makes it
191/// (the C API's `mln_camera_delta`).
192///
193/// The pan and the anchored change are separate camera commands, because an
194/// explicit center overrides an anchor; the anchored change reads the camera
195/// after the pan. The delta's command ends once both have ended.
196#[derive(Clone, Debug, Default, PartialEq)]
197pub struct CameraDelta {
198    /// Moves the map's content this far on the screen, as a drag does.
199    pub offset: Option<ScreenCoordinate>,
200    /// Multiplies the map's scale: 2 zooms in by one level.
201    pub scale: Option<f64>,
202    /// Degrees to add to the bearing.
203    pub bearing: Option<f64>,
204    /// Degrees to add to the pitch.
205    pub pitch: Option<f64>,
206    /// The screen point that `scale`, `bearing` and `pitch` keep in place,
207    /// and that a drag's `offset` holds: on the globe the location under it
208    /// follows the drag, as the C++ globe's `moveBy(offset, anchor)` does,
209    /// and over terrain, in a delta of [`GesturePhase::None`], the ground
210    /// drawn under it does, while a flat map moves the same wherever it is
211    /// held. It needs one of them, and it combines with `offset` and one of
212    /// the others only in a delta without a duration.
213    pub anchor: Option<ScreenCoordinate>,
214    /// How the gesture keeps moving after this delta, which only a delta in
215    /// the [`GesturePhase::End`] phase carries. Its parts' snaps apply only
216    /// to the parts the gesture changed. With momentum, `animation` may set
217    /// only its transition id, and the command ends when the momentum does.
218    pub momentum: Option<crate::camera::CameraMomentum>,
219    pub animation: AnimationOptions,
220    pub phase: GesturePhase,
221}
222
223/// How [`CameraUpdate`] moves the camera.
224#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
225pub enum CameraUpdateMode {
226    /// At once; the animation's duration is ignored.
227    #[default]
228    Jump,
229    Ease,
230    Fly,
231}
232
233/// Moves the camera to absolute values, as the C API's
234/// `mln_camera_update` does: the counterpart of [`CameraDelta`] for
235/// commands and gestures that know where the camera should go.
236#[derive(Clone, Debug, Default, PartialEq)]
237pub struct CameraUpdate {
238    pub mode: CameraUpdateMode,
239    pub camera: CameraOptions,
240    pub animation: AnimationOptions,
241    pub phase: GesturePhase,
242}
243
244/// Why a [`CameraDelta`] was rejected.
245#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, thiserror::Error)]
246pub enum CameraError {
247    /// An offset, anchor, bearing or pitch isn't finite.
248    #[error("camera delta offset, anchor, bearing and pitch must be finite")]
249    NotFinite,
250    /// The scale isn't finite and positive.
251    #[error("camera delta scale must be finite and positive")]
252    InvalidScale,
253    /// An anchor needs an offset, scale, bearing or pitch to hold in place.
254    #[error("a camera delta anchor requires scale, bearing, or pitch, or an offset to hold")]
255    AnchorWithoutChange,
256    /// Only a delta in the end phase carries momentum.
257    #[error("only a camera delta in the end phase carries momentum")]
258    MomentumOutsideEnd,
259    /// A delta with momentum sets only its animation's transition id: the
260    /// momentum, not an animation, moves the camera.
261    #[error("a camera delta with momentum sets only the transition ID of its animation")]
262    MomentumWithAnimation,
263    /// An anchor combines with an offset and a scale, bearing or pitch only
264    /// in an immediate delta: an anchored ease couples the center with its
265    /// fields, so it would replace an animated pan.
266    #[error("a camera delta anchor combines with offset only in an immediate delta")]
267    AnimatedAnchoredOffset,
268}
269
270impl CameraDelta {
271    /// Checks the delta. An anchor with only an offset is the point a drag
272    /// holds, which the globe needs.
273    pub fn validate(&self) -> Result<(), CameraError> {
274        let finite_point = |p: Option<ScreenCoordinate>| p.is_none_or(|p| p.x.is_finite() && p.y.is_finite());
275        if !finite_point(self.offset)
276            || !finite_point(self.anchor)
277            || !self.bearing.is_none_or(f64::is_finite)
278            || !self.pitch.is_none_or(f64::is_finite)
279        {
280            return Err(CameraError::NotFinite);
281        }
282        if self.scale.is_some_and(|scale| !scale.is_finite() || scale <= 0.0) {
283            return Err(CameraError::InvalidScale);
284        }
285        let anchored = self.scale.is_some() || self.bearing.is_some() || self.pitch.is_some();
286        if self.anchor.is_some() && !anchored && self.offset.is_none() {
287            return Err(CameraError::AnchorWithoutChange);
288        }
289        if self.momentum.is_some() {
290            if self.phase != GesturePhase::End {
291                return Err(CameraError::MomentumOutsideEnd);
292            }
293            let a = &self.animation;
294            if a.duration.is_some()
295                || a.velocity.is_some()
296                || a.min_zoom.is_some()
297                || a.max_duration.is_some()
298                || a.easing.is_some()
299            {
300                return Err(CameraError::MomentumWithAnimation);
301            }
302        }
303        if self.offset.is_some()
304            && self.anchor.is_some()
305            && anchored
306            && self.animation.duration.is_some_and(|duration| duration > Duration::ZERO)
307        {
308            return Err(CameraError::AnimatedAnchoredOffset);
309        }
310        Ok(())
311    }
312}