Skip to main content

mln_engine/camera/
transform.rs

1//! The map's camera: the commands, animations, gestures and momentum that
2//! move it within its limits.
3//!
4//! Each command is a transition whose frame function takes the state and
5//! returns the camera at the command's progress, which `apply_transitions`
6//! composes with the other commands' cameras. The transform calls no
7//! observer: it queues what happens as `TransformEvent`s, which its owner
8//! drains once the call returns, so no callback runs while the transform
9//! changes. Over terrain, the rules of `terrain` stand the camera on the
10//! ground and keep its eye above it.
11
12use std::f64::consts::PI;
13use std::rc::Rc;
14use std::sync::Arc;
15use std::time::Duration;
16
17use geometry::Point;
18use mln_style::crs::WorldMapping;
19use mln_style::error::Error;
20use mln_style::geo::{LatLng, WrapMode};
21use mln_style::size::Size;
22use mln_style::time::Instant;
23use mln_style::types::ProjectionDefinition;
24use parking_lot::Mutex;
25
26use crate::camera::{
27    AnimationOptions, CameraLimits, CameraOptions, CenterAndBearing, ConstrainMode, FreeCameraOptions,
28    NorthOrientation, ProjectionMode, TransformState, TransitionEnd, VerticalPerspectiveProjection, View,
29    ViewProjection,
30};
31use crate::geo::constants::M2PI;
32use crate::geo::{EdgeInsets, ScreenCoordinate};
33use crate::log_target;
34
35mod anchor;
36mod animation;
37mod gesture;
38mod momentum;
39mod terrain;
40mod transition;
41
42use gesture::GestureState;
43pub(crate) use terrain::{TerrainGround, lowest_ground};
44use transition::{FrameFn, JointEnd, Transition};
45
46use crate::map::events::{CameraChange, CameraChangeSource};
47
48/// A frame time older than this is stale, and counts as unset (see
49/// `Transform::set_frame_time`): longer than a frame at 10 fps, so any host
50/// that draws sets a fresh one first.
51pub(crate) const STALE_FRAME_TIME: Duration = Duration::from_millis(100);
52
53/// Converts the given angle (in radians) to be numerically close to the
54/// anchor angle, allowing it to be interpolated properly without sudden
55/// jumps.
56fn normalize_angle(mut angle: f64, anchor_angle: f64) -> f64 {
57    if angle.is_nan() || anchor_angle.is_nan() {
58        return 0.0;
59    }
60
61    angle = mln_style::math::wrap(angle, -PI, PI);
62    if angle == -PI {
63        angle = PI;
64    }
65    let diff = (angle - anchor_angle).abs();
66    if (angle - M2PI - anchor_angle).abs() < diff {
67        angle -= M2PI;
68    }
69    if (angle + M2PI - anchor_angle).abs() < diff {
70        angle += M2PI;
71    }
72
73    angle
74}
75
76/// A `LatLng` from coordinates the transform state keeps valid, saturating
77/// any that aren't (see [`LatLng::saturating`]).
78fn lat_lng(lat: f64, lon: f64) -> LatLng {
79    LatLng::saturating(lat, lon, WrapMode::Unwrapped)
80}
81
82/// An animation frame's insets, or `None` when one is NaN (infinite insets
83/// interpolate to NaN): the frame keeps the insets it has.
84fn frame_edge_insets(top: f64, left: f64, bottom: f64, right: f64) -> Option<EdgeInsets> {
85    if [top, left, bottom, right].iter().any(|value| value.is_nan()) {
86        tracing::error!(target: log_target::GENERAL, "an animation frame's insets are NaN");
87        return None;
88    }
89    Some(EdgeInsets::new(top, left, bottom, right))
90}
91
92/// An animation frame's [`WorldMapping::unproject`], or `None` (logged) for
93/// a point with no `LatLng`, such as NaN: the frame keeps the center and
94/// zoom, as [`frame_edge_insets`] does.
95fn frame_unproject(world: &WorldMapping, p: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Option<LatLng> {
96    world.unproject(p, scale, wrap_mode).map_err(|e| {
97            tracing::error!(target: log_target::GENERAL, error = %e.message, "An animation frame's point has no location");
98        })
99        .ok()
100}
101
102/// Identifies a camera command that the transform started, in the
103/// `TransformEvent::CommandEnded` that reports its end. Each command the
104/// transform starts gets its own.
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
106pub struct CameraCommandId(u64);
107
108/// How a camera command ended.
109#[derive(Clone, Copy, Debug, PartialEq)]
110pub struct CommandEnd {
111    pub command: CameraCommandId,
112    /// The command's [`AnimationOptions::transition_id`].
113    pub(crate) transition_id: Option<u64>,
114    pub end: TransitionEnd,
115}
116
117/// What the transform reports, in order, for its owner to drain with
118/// [`Transform::drain_events`].
119#[derive(Clone, Copy, Debug, PartialEq)]
120pub(crate) enum TransformEvent {
121    CameraWillChange(CameraChange),
122    CameraIsChanging,
123    CameraDidChange(CameraChange),
124    /// A command ended: every command ends exactly once, unless the
125    /// transform is dropped with the command still running (see
126    /// [`Transform::close`]).
127    CommandEnded(CommandEnd),
128}
129
130pub(crate) type ProjectionForZoomFn = Rc<dyn Fn(f64) -> ProjectionDefinition>;
131
132// The camera fields that a command sets and owns, as bits.
133const CENTER: u16 = 1 << 0;
134const ZOOM: u16 = 1 << 1;
135const BEARING: u16 = 1 << 2;
136const PITCH: u16 = 1 << 3;
137const PADDING: u16 = 1 << 4;
138const ALTITUDE: u16 = 1 << 5;
139const ROLL: u16 = 1 << 6;
140const FOV: u16 = 1 << 7;
141
142/// The fields a command sets.
143fn camera_fields(camera: &CameraOptions) -> u16 {
144    let field = |set: bool, field: u16| if set { field } else { 0 };
145    field(camera.center.is_some(), CENTER)
146        | field(camera.zoom.is_some(), ZOOM)
147        | field(camera.bearing.is_some(), BEARING)
148        | field(camera.pitch.is_some(), PITCH)
149        | field(camera.padding.is_some(), PADDING)
150        | field(camera.center_altitude.is_some(), ALTITUDE)
151        | field(camera.roll.is_some(), ROLL)
152        | field(camera.fov.is_some(), FOV)
153}
154
155/// The time of the latest frame that a map's host drew, which the map's
156/// animations sample at and its camera commands start from (see
157/// `Transform::set_frame_time`), or the time it is held at. A clone shares
158/// the clock, so the thread that draws can set it while the map lives on
159/// another.
160#[derive(Clone, Debug, Default)]
161pub struct FrameClock(Arc<Mutex<ClockTime>>);
162
163#[derive(Clone, Copy, Debug, Default)]
164enum ClockTime {
165    #[default]
166    Unset,
167    Frame(Instant),
168    Held(Instant),
169}
170
171impl FrameClock {
172    /// Sets the latest frame's time, or unsets it, unless the clock is
173    /// held.
174    pub fn set(&self, time: Option<Instant>) {
175        let mut clock = self.0.lock();
176        if !matches!(*clock, ClockTime::Held(_)) {
177            *clock = time.map_or(ClockTime::Unset, ClockTime::Frame);
178        }
179    }
180
181    /// Holds the map's time at `time`, or with `None`, lets go of it.
182    /// While held, the map takes it for the time now: its animations and
183    /// fades sample at it, its camera commands start from it, and the
184    /// changes it schedules come once the holder moves it past them. It
185    /// never goes stale, and frame times leave it as it is.
186    pub fn hold(&self, time: Option<Instant>) {
187        *self.0.lock() = time.map_or(ClockTime::Unset, ClockTime::Held);
188    }
189
190    /// The latest frame's time, or the held time.
191    #[must_use]
192    pub fn get(&self) -> Option<Instant> {
193        match *self.0.lock() {
194            ClockTime::Unset => None,
195            ClockTime::Frame(time) | ClockTime::Held(time) => Some(time),
196        }
197    }
198
199    /// The time the clock is held at.
200    #[must_use]
201    pub fn held(&self) -> Option<Instant> {
202        match *self.0.lock() {
203            ClockTime::Held(time) => Some(time),
204            _ => None,
205        }
206    }
207}
208
209pub struct Transform {
210    state: TransformState,
211
212    transitions: Vec<Transition>,
213    /// What the transform reports, for [`Self::drain_events`].
214    events: Vec<TransformEvent>,
215    /// The command being started, which the transitions it starts report
216    /// their end to (see [`Self::command`]), unless `silent`.
217    command: Option<CameraCommandId>,
218    /// Set while a command starts transitions whose ends another of its
219    /// transitions reports: a delta's changes before its momentum.
220    silent: bool,
221    next_command: u64,
222    /// The commands made of several transitions, whose end waits for the
223    /// last of them.
224    joint_ends: Vec<JointEnd>,
225    /// What the commands being started come from: a command unless a gesture
226    /// or a momentum starts them (see [`Self::with_source`]).
227    source: CameraChangeSource,
228    gesture: GestureState,
229    /// From a gesture's first change until it ends, its momentum included.
230    /// Over terrain, a gesture holds the altitude, and comes to rest on the
231    /// ground as it ends (see `terrain`).
232    gesture_in_progress: bool,
233    /// The fields that the running commands move (`CENTER`, `ZOOM`,
234    /// `BEARING`), as of the last frame.
235    moving: u16,
236    /// The host's current frame time (see [`Self::set_frame_time`]).
237    frame_time: FrameClock,
238    projection_for_zoom: Option<ProjectionForZoomFn>,
239    globe_drag_hold: Option<GlobeDragHold>,
240    /// The terrain the camera stands on ([`Self::set_terrain`]).
241    terrain: Option<TerrainGround>,
242    /// The time of the last frame that composed the commands' cameras,
243    /// from which the altitude over terrain heads on
244    /// ([`Self::ease_altitude`]).
245    last_frame: Option<Instant>,
246}
247
248/// The location a drag on the globe holds under the cursor, from the step
249/// that grabbed it. The next step carries the drag on if it starts where
250/// that one ended, at `cursor` with the camera and the view as that step
251/// left them; any other step grabs the location under where it starts.
252#[derive(Clone, Copy, Debug)]
253struct GlobeDragHold {
254    location: LatLng,
255    /// The height in meters of the sphere `location` is on.
256    height: f64,
257    cursor: ScreenCoordinate,
258    camera: CameraOptions,
259    size: Size,
260}
261
262impl Transform {
263    #[must_use]
264    pub fn new(constrain_mode: ConstrainMode) -> Self {
265        Self::from_state(TransformState::new(constrain_mode))
266    }
267
268    pub(crate) fn from_state(state: TransformState) -> Self {
269        Transform {
270            state,
271            transitions: Vec::new(),
272            events: Vec::new(),
273            command: None,
274            silent: false,
275            next_command: 0,
276            joint_ends: Vec::new(),
277            source: CameraChangeSource::Command,
278            gesture: GestureState::default(),
279            gesture_in_progress: false,
280            moving: 0,
281            frame_time: FrameClock::default(),
282            projection_for_zoom: None,
283            globe_drag_hold: None,
284            terrain: None,
285            last_frame: None,
286        }
287    }
288
289    /// Drains what the transform reported since the last call, oldest
290    /// first. The transform keeps its buffer for what it reports next.
291    pub(crate) fn drain_events(&mut self) -> std::vec::Drain<'_, TransformEvent> {
292        self.events.drain(..)
293    }
294
295    fn emit(&mut self, event: TransformEvent) {
296        self.events.push(event);
297    }
298
299    // MARK: - Map View
300
301    pub fn resize(&mut self, size: Size) -> Result<(), Error> {
302        if size.is_empty() {
303            return Err(Error::invalid_argument("failed to resize: size is empty"));
304        }
305
306        if self.state.view().size() == size {
307            return Ok(());
308        }
309
310        self.emit(TransformEvent::CameraWillChange(CameraChange::default()));
311        self.state.set_size(size);
312        let (scale, center) = self.state.constrain_screen(self.state.view().scale());
313        if let Some(center) = center {
314            // Turns out that if you resize during a transition any changes
315            // made to the state will be ignored :( So if we have to constrain
316            // because of a resize and a transition is in progress - cancel
317            // the transition!
318            if self.in_transition() {
319                self.cancel_transitions();
320            }
321
322            // Setting x and y isn't enough to change the center: Cc and Bc
323            // must change too, which `set_lat_lng_zoom` does.
324            let zoom = crate::camera::scale_zoom(scale);
325            self.state.set_lat_lng_zoom(&center, zoom);
326            self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
327
328            return Ok(());
329        }
330        self.state.constrain_position(scale);
331
332        self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
333        Ok(())
334    }
335
336    // MARK: - Camera
337
338    /// Returns the current camera options.
339    #[must_use]
340    pub(crate) fn camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
341        self.state.camera_options(padding)
342    }
343
344    /// Change any combination of center, zoom, bearing, and pitch, without a
345    /// transition. Omitted options keep their current animations.
346    pub(crate) fn jump_to(&mut self, camera: &CameraOptions) -> CameraCommandId {
347        self.command(|transform| transform.jump(camera))
348    }
349
350    fn jump(&mut self, camera: &CameraOptions) {
351        // On the globe the zoom decides how close to a pole the center can be.
352        // GL JS's jump bounds the center by the zoom it lands on, where its
353        // ease bounds it by the zoom it starts from unless given one, so the
354        // jump settles the zoom.
355        if self.state.view().is_globe()
356            && let Some(center) = camera.center
357            && camera.zoom.is_none()
358        {
359            let zoom = self.view().zoom()
360                + VerticalPerspectiveProjection::zoom_adjustment(
361                    self.view().center(WrapMode::Wrapped).latitude(),
362                    center.latitude(),
363                );
364            self.ease_to(&CameraOptions { zoom: Some(zoom), ..*camera }, &AnimationOptions::default());
365            return;
366        }
367        self.ease_to(camera, &AnimationOptions::default());
368    }
369
370    // MARK: - Position
371
372    /// Whether the globe is drawn on a sized screen, so screen points reach
373    /// it. Before the first resize, screen-point gestures are Mercator's.
374    fn globe_on_screen(&self) -> bool {
375        self.state.view().is_globe() && !self.state.view().size().is_empty()
376    }
377
378    /// Pans the map by the given amount.
379    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a NaN
380    /// or infinite offset.
381    #[cfg(test)]
382    pub(crate) fn move_by(
383        &mut self,
384        offset: &ScreenCoordinate,
385        animation: &AnimationOptions,
386    ) -> Result<CameraCommandId, Error> {
387        self.move_by_with_anchor(offset, None, animation)
388    }
389
390    /// Moves the map by `offset`. A drag on the globe turns the planet so
391    /// that the location under `anchor` follows the cursor. The ground under
392    /// the cursor before the move follows it, on the plane at that ground's
393    /// height, or on the globe the sphere: sea level on the flat map, the
394    /// drawn ground over terrain ([`Self::set_terrain`]); without an anchor,
395    /// or with one that grabs no ground, the map moves on the plane or the
396    /// sphere at the center's altitude. On the globe, with the
397    /// bearing held, steps that follow one another, each starting at the
398    /// `anchor` of the one before with the camera as it left it, hold the
399    /// location the first of them grabbed, wherever
400    /// [`VerticalPerspectiveProjection::drag_center_holding`] has a center
401    /// that does. Fails as [`move_by`](Self::move_by) does.
402    pub(crate) fn move_by_with_anchor(
403        &mut self,
404        offset: &ScreenCoordinate,
405        anchor: Option<ScreenCoordinate>,
406        animation: &AnimationOptions,
407    ) -> Result<CameraCommandId, Error> {
408        let mut moved = Ok(());
409        let command = self.command(|transform| moved = transform.move_by_now(offset, anchor, animation));
410        moved.map(|()| command)
411    }
412
413    fn move_by_now(
414        &mut self,
415        offset: &ScreenCoordinate,
416        anchor: Option<ScreenCoordinate>,
417        animation: &AnimationOptions,
418    ) -> Result<(), Error> {
419        let flipped = |state: &TransformState, point: &ScreenCoordinate| {
420            ScreenCoordinate::new(point.x, f64::from(state.view().size().height) - point.y)
421        };
422        let size = self.state.view().size();
423        let view_center = self.state.view().padding().center_in(size);
424        let fling_duration = animation.duration.filter(|duration| *duration > Duration::ZERO);
425        let globe = self.globe_on_screen();
426        if globe && (offset.x.is_nan() || offset.y.is_nan()) {
427            return Err(Error::invalid_argument("offset must not be NaN"));
428        }
429        if globe && (!offset.x.is_finite() || !offset.y.is_finite()) {
430            return Err(Error::invalid_argument("offset must not be infinite"));
431        }
432        if globe
433            && let Some(duration) = fling_duration
434            && self.state.view().globe_free_bearing()
435        {
436            // A fling with the bearing free turns the planet on about the axis
437            // the drag turned it about, so it carries on over a pole instead
438            // of spinning round it.
439            let start = CenterAndBearing {
440                center: self.view().center(WrapMode::Unwrapped),
441                bearing: -mln_style::math::rad2deg(self.view().angle()),
442            };
443            let end = VerticalPerspectiveProjection::fling_camera(
444                self.state.view(),
445                &flipped(&self.state, &view_center),
446                &ScreenCoordinate::new(offset.x, -offset.y),
447            );
448            let start_zoom = self.view().zoom();
449            let frame: FrameFn = Box::new(move |state: &TransformState, t: f64| {
450                let camera = VerticalPerspectiveProjection::interpolate_camera(&start, &end, t);
451                let center = state.constrained_center(&camera.center, state.view().zoom());
452                CameraOptions {
453                    center: Some(center),
454                    zoom: Some(
455                        start_zoom
456                            + VerticalPerspectiveProjection::zoom_adjustment(
457                                start.center.latitude(),
458                                center.latitude(),
459                            ),
460                    ),
461                    bearing: Some(camera.bearing),
462                    ..Default::default()
463                }
464            });
465            // The fling sets the center, the zoom that keeps the planet's
466            // size and the bearing.
467            let fields = CameraOptions {
468                center: Some(end.center),
469                zoom: Some(start_zoom),
470                bearing: Some(end.bearing),
471                ..Default::default()
472            };
473            self.start_transition(&fields, animation, frame, None, duration, false);
474            return Ok(());
475        }
476
477        if globe && fling_duration.is_some() {
478            // An animated move, a fling, turns the globe as GL JS's inertia
479            // does: the location under the far end of a long one can be off
480            // the planet or over a pole. It stops short of half a turn, which
481            // the ease would take the other way round.
482            let mut center = self.state.constrained_center(
483                &VerticalPerspectiveProjection::pan_center(self.state.view(), offset),
484                self.view().zoom(),
485            );
486            let longitude = self.view().center(WrapMode::Unwrapped).longitude();
487            if (center.longitude() - longitude).abs() > 180.0 {
488                center = lat_lng(center.latitude(), longitude + 179.5f64.copysign(center.longitude() - longitude));
489            }
490            self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
491            return Ok(());
492        }
493
494        if globe {
495            // A drag turns the globe as GL JS's does: one rotation that brings
496            // the location under the cursor back under it with the bearing
497            // held, around the cursor when it is on the planet and around the
498            // center otherwise. With a free bearing the rotation turns the
499            // bearing too, so the location stays under the cursor.
500            //
501            // With the bearing held, that rotation loses the turn it would
502            // give the bearing, so step after step the location slips from
503            // under the cursor. Where a center holds it there exactly, the
504            // drag takes that center instead, for the location its first step
505            // grabbed. A step the exact center isn't for doesn't hold: the
506            // step after it grabs anew, so the drag goes from one way to the
507            // other without a jump.
508            //
509            // The location is on the sphere at the height of the ground the
510            // drag grabbed, or else at the center's altitude, as the planes
511            // of a drag on Mercator are.
512            let from = anchor.map(|anchor| ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y));
513            let held = self.globe_drag_hold.take().filter(|held| {
514                from.is_some_and(|from| (held.cursor.x - from.x).hypot(held.cursor.y - from.y) < 1e-3)
515                    && !self.state.view().globe_free_bearing()
516                    && held.size == size
517                    && held.camera == self.camera_options(None)
518            });
519            let height = match (held, anchor.zip(from)) {
520                (Some(held), _) => held.height,
521                (None, Some((anchor, from))) => self.anchor_height(&from, &anchor),
522                (None, None) => self.view().center_altitude(),
523            };
524            let on_globe = |state: &TransformState, point: &ScreenCoordinate| {
525                VerticalPerspectiveProjection::screen_coordinate_hits_globe(
526                    state.view(),
527                    &flipped(state, point),
528                    height,
529                )
530            };
531            let grab = match anchor {
532                Some(anchor) if on_globe(&self.state, &anchor) => anchor,
533                _ => view_center,
534            };
535            let pan_delta = ScreenCoordinate::new(offset.x, -offset.y);
536            let mut camera = CameraOptions::default();
537            let hold = match anchor.zip(from) {
538                Some((anchor, from)) if !self.state.view().globe_free_bearing() && on_globe(&self.state, &anchor) => {
539                    let location = match held {
540                        Some(held) => Some(held.location),
541                        None if on_globe(&self.state, &from) => self
542                            .state
543                            .view()
544                            .screen_coordinate_to_lat_lng_at(&flipped(&self.state, &from), height, WrapMode::Unwrapped)
545                            .ok(),
546                        None => None,
547                    };
548                    location.and_then(|location| {
549                        VerticalPerspectiveProjection::drag_center_holding(
550                            self.state.view(),
551                            &location,
552                            &flipped(&self.state, &anchor),
553                            height,
554                        )
555                        .map(|center| (location, anchor, center))
556                    })
557                }
558                _ => None,
559            };
560            let mut center = if let Some((_, _, center)) = hold {
561                center
562            } else if self.state.view().globe_free_bearing() {
563                let drag = VerticalPerspectiveProjection::drag_camera(
564                    self.state.view(),
565                    &flipped(&self.state, &grab),
566                    &pan_delta,
567                    height,
568                );
569                camera = CameraOptions { bearing: Some(drag.bearing), ..camera };
570                drag.center
571            } else {
572                VerticalPerspectiveProjection::drag_center(
573                    self.state.view(),
574                    &flipped(&self.state, &grab),
575                    &pan_delta,
576                    height,
577                )
578            };
579            center = self.state.constrained_center(&center, self.view().zoom());
580            let zoom = self.view().zoom()
581                + VerticalPerspectiveProjection::zoom_adjustment(
582                    self.view().center(WrapMode::Wrapped).latitude(),
583                    center.latitude(),
584                );
585            self.ease_to(&CameraOptions { center: Some(center), zoom: Some(zoom), ..camera }, animation);
586            self.globe_drag_hold = hold.map(|(location, cursor, _)| GlobeDragHold {
587                location,
588                height,
589                cursor,
590                camera: self.camera_options(None),
591                size,
592            });
593            return Ok(());
594        }
595
596        let mut center_offset = *offset;
597
598        // Reduce the offset so that it never goes past the horizon. If it
599        // goes past the horizon, the pan direction is opposite of the
600        // intended direction.
601        let pitch = self.state.view().pitch();
602        let offset_length = offset.x.hypot(offset.y);
603        if pitch > 0.0 && offset_length > 0.0 {
604            let camera_to_center =
605                0.5 * f64::from(self.state.view().size().height) / (self.state.view().fov() / 2.0).tan();
606            let pixels_to_horizon = (camera_to_center / pitch.tan()).abs();
607            // must be < 1 to keep the offset short of the horizon
608            let horizon_factor = 0.75;
609            let scale = pixels_to_horizon * horizon_factor / offset_length;
610            if scale < 1.0 {
611                center_offset = ScreenCoordinate::new(offset.x * scale, offset.y * scale);
612            }
613        }
614
615        let size = self.state.view().size();
616        let center = self.state.view().padding().center_in(size);
617        let point_on_screen = ScreenCoordinate::new(center.x - center_offset.x, center.y - center_offset.y);
618        // The ground the pointer grabbed follows it, on its plane; without an
619        // anchor, the map moves on the plane at the center's altitude. Use
620        // unwrapped LatLng to carry information about the move's direction.
621        let anchored = anchor.and_then(|anchor| {
622            let grabbed = ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y);
623            Some((grabbed, anchor, self.anchor_plane(&grabbed, &anchor)?))
624        });
625        let (from, to, height) = anchored.unwrap_or((point_on_screen, center, self.view().center_altitude()));
626        let center = self.center_moving_on_plane(&from, &to, height)?;
627        self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
628        Ok(())
629    }
630
631    // MARK: - Limits
632
633    /// Sets the limits the camera moves within (see
634    /// [`TransformState::set_limits`]).
635    pub(crate) fn set_limits(&mut self, limits: CameraLimits) -> Result<(), Error> {
636        self.state.set_limits(limits)
637    }
638
639    pub(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
640        self.state.set_frustum_offset(frustum_offset);
641    }
642
643    // MARK: - Projection
644
645    /// Sets what the view draws in (see [`TransformState::set_projection`]).
646    pub(crate) fn set_projection(&mut self, projection: ViewProjection) {
647        self.state.set_projection(projection);
648    }
649
650    /// The projection the style gives at a zoom, which constrains an
651    /// animation's target as it constrains a jump.
652    pub(crate) fn set_projection_for_zoom(&mut self, projection_for_zoom: Option<ProjectionForZoomFn>) {
653        self.projection_for_zoom = projection_for_zoom;
654    }
655
656    pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
657        self.state.set_globe_free_bearing(free_bearing);
658    }
659
660    pub(crate) fn is_globe_free_bearing(&self) -> bool {
661        self.state.view().globe_free_bearing()
662    }
663
664    #[cfg(test)]
665    pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
666        self.state.view().is_location_occluded(lat_lng)
667    }
668
669    // MARK: - North Orientation
670
671    pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
672        self.state.set_north_orientation(orientation);
673        self.state.constrain_position(self.state.view().scale());
674    }
675
676    // MARK: - Constrain mode
677
678    pub(crate) fn set_constrain_mode(&mut self, mode: ConstrainMode) {
679        self.state.set_constrain_mode(mode);
680        self.state.constrain_position(self.state.view().scale());
681    }
682
683    /// Sets whether the center stands on the terrain. The map hands the
684    /// setting to [`set_terrain`](Self::set_terrain) on its next update.
685    pub(crate) fn set_center_clamped_to_ground(&mut self, clamped: bool) {
686        self.state.set_center_clamped_to_ground(clamped);
687    }
688
689    // MARK: - Projection mode
690
691    pub(crate) fn set_projection_mode(&mut self, options: &ProjectionMode) {
692        if let Some(x_skew) = options.x_skew {
693            self.state.set_x_skew(x_skew);
694        }
695        if let Some(y_skew) = options.y_skew {
696            self.state.set_y_skew(y_skew);
697        }
698        if let Some(axonometric) = options.axonometric {
699            self.state.set_axonometric(axonometric.as_bool());
700        }
701    }
702
703    // MARK: - Frame clock
704
705    /// Puts the camera's animations on the host's frame clock: commands start
706    /// at the latest frame's time rather than at `Instant::now()` when they are
707    /// made, and the map samples them at it. Each frame then shows its
708    /// animations exactly one frame further on, whenever the input or the
709    /// map's update ran, and an animation started between frames moves by
710    /// that frame's interval on the next one: no frame repeats the
711    /// camera, and none skips ahead. `None` goes back to `Instant::now()`.
712    ///
713    /// Orbis starts animations on the first frame after the call, which
714    /// keeps the camera still for that frame; a glide that continues a drag
715    /// would pause there.
716    pub(crate) fn set_frame_time(&mut self, time: Option<Instant>) {
717        self.frame_time.set(time);
718    }
719
720    /// The clock that [`set_frame_time`](Self::set_frame_time) sets.
721    pub(crate) fn frame_clock(&self) -> FrameClock {
722        self.frame_time.clone()
723    }
724
725    /// The host's frame time, unless it is stale: older than
726    /// [`STALE_FRAME_TIME`], as when the host stopped drawing frames or
727    /// forgot to set it this frame. A stale frame time would start a command
728    /// in the past, which the next frame would show already under way or
729    /// over.
730    pub(crate) fn frame_time(&self) -> Option<Instant> {
731        self.fresh_frame_time(Instant::now())
732    }
733
734    fn fresh_frame_time(&self, now: Instant) -> Option<Instant> {
735        match *self.frame_time.0.lock() {
736            ClockTime::Held(time) => Some(time),
737            ClockTime::Frame(time) => (now.saturating_duration_since(time) <= STALE_FRAME_TIME).then_some(time),
738            ClockTime::Unset => None,
739        }
740    }
741
742    /// When commands start: the frame time, or now.
743    fn now(&self) -> Instant {
744        let now = Instant::now();
745        self.fresh_frame_time(now).unwrap_or(now)
746    }
747
748    /// The map's time now, by which the changes it schedules come: the
749    /// held time, or the system's clock's.
750    pub(crate) fn clock_now(&self) -> Instant {
751        self.frame_time.held().unwrap_or_else(Instant::now)
752    }
753
754    /// Whether a gesture or a command moves the camera: the renderer draws
755    /// such frames for speed rather than crispness.
756    #[must_use]
757    pub(crate) fn is_camera_moving(&self) -> bool {
758        self.gesture_in_progress || self.moving & (CENTER | ZOOM | BEARING) != 0
759    }
760
761    // MARK: - Transform state
762
763    #[must_use]
764    pub(crate) fn state(&self) -> &TransformState {
765        &self.state
766    }
767
768    /// The view the camera shows now.
769    #[must_use]
770    pub fn view(&self) -> &View {
771        self.state.view()
772    }
773
774    #[cfg(test)]
775    pub(crate) fn is_rotating(&self) -> bool {
776        self.moving & BEARING != 0
777    }
778
779    #[cfg(test)]
780    pub(crate) fn is_scaling(&self) -> bool {
781        self.moving & ZOOM != 0
782    }
783
784    #[cfg(test)]
785    pub(crate) fn is_panning(&self) -> bool {
786        self.moving & CENTER != 0
787    }
788
789    // MARK: Conversion and projection
790
791    #[must_use]
792    pub(crate) fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
793        let mut point = self.state.view().lat_lng_to_screen_coordinate(lat_lng);
794        point.y = f64::from(self.state.view().size().height) - point.y;
795        point
796    }
797
798    /// The screen point (y down) of a place in the world square, at sea
799    /// level on the flat map.
800    pub(crate) fn world_to_screen_coordinate(&self, world: &Point<f64>) -> ScreenCoordinate {
801        let mut point = self.state.view().world_to_screen_coordinate(world);
802        point.y = f64::from(self.state.view().size().height) - point.y;
803        point
804    }
805
806    /// The location under `point`, in screen coordinates (y down).
807    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a NaN
808    /// or infinite point.
809    pub(crate) fn screen_coordinate_to_lat_lng(
810        &self,
811        point: &ScreenCoordinate,
812        wrap_mode: WrapMode,
813    ) -> Result<LatLng, Error> {
814        let mut flipped_point = *point;
815        flipped_point.y = f64::from(self.state.view().size().height) - flipped_point.y;
816        self.state.view().screen_coordinate_to_lat_lng(&flipped_point, wrap_mode)
817    }
818
819    /// Where the line of sight through `point` (y down) meets the plane
820    /// `height` meters above sea level, on which the camera's moves solve
821    /// (see `anchor`). Fails as
822    /// [`View::screen_coordinate_to_lat_lng_at`].
823    pub(crate) fn screen_coordinate_to_lat_lng_at(
824        &self,
825        point: &ScreenCoordinate,
826        height: f64,
827        wrap_mode: WrapMode,
828    ) -> Result<LatLng, Error> {
829        self.view().screen_coordinate_to_lat_lng_at(&flip_y(self.view(), point), height, wrap_mode)
830    }
831
832    pub(crate) fn set_free_camera_options(&mut self, options: &FreeCameraOptions) {
833        self.cancel_transitions();
834        self.state.set_free_camera_options(options);
835    }
836}
837
838/// `point` measured from the other edge of `view`'s height: a screen point
839/// (y down) as a view point (y up), or back.
840pub(crate) fn flip_y(view: &View, point: &ScreenCoordinate) -> ScreenCoordinate {
841    ScreenCoordinate::new(point.x, f64::from(view.size().height) - point.y)
842}
843
844/// `seconds` truncated to whole nanoseconds; `None`
845/// when negative, NaN, or too long for a `Duration` made of nanoseconds. The
846/// bound is exclusive because `u64::MAX` rounds up as a double.
847fn nanos_from_secs(seconds: f64) -> Option<Duration> {
848    (seconds >= 0.0 && seconds * 1e9 < u64::MAX as f64).then(|| Duration::from_nanos((seconds * 1e9) as u64))
849}
850
851/// The most pitch that `insets` allow without showing the horizon above the
852/// padded area's center.
853fn max_pitch_for_padding(state: &TransformState, insets: &EdgeInsets) -> f64 {
854    // As `View::center_offset`.
855    let center_offset_y = 0.5 * (insets.top - insets.bottom);
856    if center_offset_y == 0.0 {
857        return state.limits().max_pitch;
858    }
859
860    let height = state.view().size().height;
861    debug_assert!(height != 0);
862    let field_of_view = state.view().fov();
863    // Half of fov is the field of view above perspective center.
864    let tangent_of_fov_above_center_angle =
865        (0.5 + center_offset_y / f64::from(height)) * 2.0 * (field_of_view / 2.0).tan();
866    let fov_above_center = tangent_of_fov_above_center_angle.atan();
867    f64::max(state.limits().min_pitch, state.limits().max_pitch + field_of_view / 2.0 - fov_above_center)
868}
869
870#[cfg(test)]
871#[path = "transform_test.rs"]
872mod transform_test;
873
874#[cfg(test)]
875#[path = "transform_crs_test.rs"]
876mod transform_crs_test;