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