1use std::f64::consts::PI;
11use std::rc::Rc;
12use std::sync::Arc;
13use std::time::Duration;
14
15use geometry::Point;
16use mln_map_types::{
17 AnimationOptions, CameraDelta, CameraError, CameraMomentum, CameraOptions, CameraUpdate, CameraUpdateMode,
18 CameraVelocity, CenterAndBearing, ConstrainMode, FreeCameraOptions, GesturePhase, MomentumDecay,
19 MomentumDecayModel, MomentumEasing, MomentumSnap, NorthOrientation, ProjectionMode, TransformState, TransitionEnd,
20 TransitionOutcome, VerticalPerspectiveProjection, ViewportMode,
21};
22use mln_style_types::ProjectionDefinition;
23use mln_util::UnitBezier;
24use mln_util::constants::{DEFAULT_TRANSITION_EASE, M2PI, PITCH_MAX};
25use mln_util::error::Error;
26use mln_util::geo::{EdgeInsets, LatLng, LatLngBounds, ScreenCoordinate, WrapMode};
27use mln_util::interpolate::interpolate;
28use mln_util::logging::{Event, Log};
29use mln_util::projection::Projection;
30use mln_util::size::Size;
31use mln_util::time::Instant;
32use parking_lot::Mutex;
33
34use crate::map_event::{CameraChange, CameraChangeMode, CameraChangeSource};
35
36pub(crate) const STALE_FRAME_TIME: Duration = Duration::from_millis(100);
40
41fn normalize_angle(mut angle: f64, anchor_angle: f64) -> f64 {
45 if angle.is_nan() || anchor_angle.is_nan() {
46 return 0.0;
47 }
48
49 angle = mln_math::wrap(angle, -PI, PI);
50 if angle == -PI {
51 angle = PI;
52 }
53 let diff = (angle - anchor_angle).abs();
54 if (angle - M2PI - anchor_angle).abs() < diff {
55 angle -= M2PI;
56 }
57 if (angle + M2PI - anchor_angle).abs() < diff {
58 angle += M2PI;
59 }
60
61 angle
62}
63
64fn lat_lng(lat: f64, lon: f64) -> LatLng {
65 LatLng::new(lat, lon).unwrap_or_else(|e| panic!("{e}"))
67}
68
69fn frame_edge_insets(top: f64, left: f64, bottom: f64, right: f64) -> Option<EdgeInsets> {
74 EdgeInsets::new(top, left, bottom, right).map_err(|e| Log::error(Event::General, &e.message)).ok()
75}
76
77fn frame_unproject(p: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Option<LatLng> {
81 Projection::unproject(p, scale, wrap_mode).map_err(|e| Log::error(Event::General, &e.message)).ok()
82}
83
84fn std_to_string(value: f64) -> String {
86 format!("{value:.6}")
87}
88
89#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
93pub struct CameraCommandId(u64);
94
95#[derive(Clone, Copy, Debug, PartialEq)]
97pub struct CommandEnd {
98 pub command: CameraCommandId,
99 pub transition_id: Option<u64>,
101 pub end: TransitionEnd,
102}
103
104#[derive(Clone, Copy, Debug, PartialEq)]
107pub enum TransformEvent {
108 CameraWillChange(CameraChange),
109 CameraIsChanging,
110 CameraDidChange(CameraChange),
111 CommandEnded(CommandEnd),
115}
116
117type FrameFn = Box<dyn Fn(&TransformState, f64) -> CameraOptions>;
121pub(crate) type ProjectionForZoomFn = Rc<dyn Fn(f64) -> ProjectionDefinition>;
122
123const CENTER: u16 = 1 << 0;
125const ZOOM: u16 = 1 << 1;
126const BEARING: u16 = 1 << 2;
127const PITCH: u16 = 1 << 3;
128const PADDING: u16 = 1 << 4;
129const ALTITUDE: u16 = 1 << 5;
130const ROLL: u16 = 1 << 6;
131const FOV: u16 = 1 << 7;
132
133fn camera_fields(camera: &CameraOptions) -> u16 {
135 let field = |set: bool, field: u16| if set { field } else { 0 };
136 field(camera.center.is_some(), CENTER)
137 | field(camera.zoom.is_some(), ZOOM)
138 | field(camera.bearing.is_some(), BEARING)
139 | field(camera.pitch.is_some(), PITCH)
140 | field(camera.padding.is_some(), PADDING)
141 | field(camera.center_altitude.is_some(), ALTITUDE)
142 | field(camera.roll.is_some(), ROLL)
143 | field(camera.fov.is_some(), FOV)
144}
145
146struct Transition {
148 fields: u16,
151 coupled_fields: u16,
153 moving_fields: u16,
157 start: Instant,
158 duration: Duration,
160 animation: AnimationOptions,
161 frame: FrameFn,
162 anchor: Option<ScreenCoordinate>,
163 anchor_lat_lng: LatLng,
164 momentum: Option<MomentumState>,
167 stopped: Option<TransitionOutcome>,
171 source: CameraChangeSource,
173 command: Option<CameraCommandId>,
175 gesture: Option<u64>,
178}
179
180impl Transition {
181 fn new(
184 fields: u16,
185 moving_fields: u16,
186 start: Instant,
187 duration: Duration,
188 animation: &AnimationOptions,
189 frame: FrameFn,
190 source: CameraChangeSource,
191 ) -> Transition {
192 Transition {
193 fields,
194 coupled_fields: 0,
195 moving_fields,
196 start,
197 duration,
198 animation: *animation,
199 frame,
200 anchor: None,
201 anchor_lat_lng: LatLng::default(),
202 momentum: None,
203 stopped: None,
204 source,
205 command: None,
206 gesture: None,
207 }
208 }
209
210 fn mode(&self) -> CameraChangeMode {
211 if self.duration == Duration::ZERO { CameraChangeMode::Immediate } else { CameraChangeMode::Animated }
212 }
213
214 fn ended_by(&mut self, outcome: TransitionOutcome) {
218 if self.stopped != Some(TransitionOutcome::Cancelled) {
219 self.stopped = Some(outcome);
220 }
221 }
222
223 fn end(&self) -> TransitionEnd {
227 let (velocity, momentum_replaced) =
228 self.momentum.as_ref().map_or((CameraVelocity::default(), false), MomentumState::end);
229 let outcome = self.stopped.unwrap_or(if momentum_replaced {
230 TransitionOutcome::Replaced
231 } else {
232 TransitionOutcome::Completed
233 });
234 TransitionEnd { outcome, velocity, generation: 0 }
235 }
236
237 fn progress(&self, now: Option<Instant>) -> f64 {
240 let duration = self.duration;
241 match now {
242 Some(now) if !duration.is_zero() => {
243 mln_math::clamp_f64(now.saturating_duration_since(self.start).div_duration_f64(duration), 0.0, 1.0)
244 }
245 _ => 1.0,
246 }
247 }
248
249 fn elapsed(&self, now: Option<Instant>) -> Duration {
252 now.map_or(Duration::MAX, |now| now.saturating_duration_since(self.start))
253 }
254
255 fn has_run_out(&self, now: Option<Instant>) -> bool {
257 now.is_none_or(|now| now >= self.start && self.elapsed(Some(now)) >= self.duration)
258 }
259}
260
261fn nanos_from_secs(seconds: f64) -> Option<Duration> {
265 (seconds >= 0.0 && seconds * 1e9 < u64::MAX as f64).then(|| Duration::from_nanos((seconds * 1e9) as u64))
266}
267
268#[derive(Clone, Copy, Default)]
271struct Glide {
272 distance: f64,
273 duration: Duration,
274 rate: f64,
276 easing: Option<MomentumEasing>,
278}
279
280impl Glide {
281 fn plan(speed: f64, decay: &MomentumDecay) -> Option<Glide> {
283 if speed.is_nan() || speed <= 0.0 || speed < decay.min_speed {
284 return None;
285 }
286 let mut speed = f64::min(speed, decay.max_speed);
287 let mut glide = Glide::default();
288 let seconds;
289 match decay.model {
290 MomentumDecayModel::Friction => {
291 let half_life = decay.half_life.as_secs_f64();
292 if half_life.is_nan() || half_life <= 0.0 || decay.stop_speed.is_nan() || decay.stop_speed <= 0.0 {
293 return None;
294 }
295 glide.rate = std::f64::consts::LN_2 / half_life;
296 speed = f64::min(speed, decay.stop_speed + glide.rate * decay.max_distance);
297 if speed <= decay.stop_speed {
298 return None;
299 }
300 seconds = (speed / decay.stop_speed).ln() / glide.rate;
301 glide.distance = (speed - decay.stop_speed) / glide.rate;
302 }
303 MomentumDecayModel::Ease => {
304 glide.distance = f64::min(decay.distance, decay.max_distance);
305 seconds = decay.duration.as_secs_f64();
306 glide.easing = Some(decay.easing);
307 }
308 }
309 if glide.distance.is_nan() || glide.distance <= 0.0 {
311 return None;
312 }
313 glide.duration = nanos_from_secs(seconds).filter(|duration| !duration.is_zero())?;
314 Some(glide)
315 }
316
317 fn progress(&self, elapsed: Duration) -> f64 {
319 if elapsed >= self.duration {
320 return 1.0;
321 }
322 if elapsed.is_zero() {
323 return 0.0;
324 }
325 let t = elapsed.as_secs_f64();
326 let total = self.duration.as_secs_f64();
327 match self.easing {
328 None => (-self.rate * t).exp_m1() / (-self.rate * total).exp_m1(),
329 Some(easing) => bezier(&easing).solve(t / total, 1e-6),
330 }
331 }
332
333 fn speed(&self, elapsed: Duration) -> f64 {
335 if elapsed >= self.duration {
336 return 0.0;
337 }
338 let t = elapsed.as_secs_f64();
339 let total = self.duration.as_secs_f64();
340 let Some(easing) = self.easing else {
341 return self.rate * (-self.rate * t).exp() / -(-self.rate * total).exp_m1();
342 };
343 let ease = bezier(&easing);
346 let p = f64::max(ease.solve_curve_x(t / total, 1e-6), 1e-6);
347 let cy = 3.0 * easing.y1;
348 let by = 3.0 * (easing.y2 - easing.y1) - cy;
349 let ay = 1.0 - cy - by;
350 let dy = (3.0 * ay * p + 2.0 * by) * p + cy;
351 let dx = ease.sample_curve_derivative_x(p);
352 if dx > 0.0 { dy / dx / total } else { 0.0 }
353 }
354}
355
356fn bezier(easing: &MomentumEasing) -> UnitBezier {
357 UnitBezier::new(easing.x1, easing.y1, easing.x2, easing.y2)
358}
359
360#[derive(Clone, Copy, Default)]
362struct MomentumPart {
363 fields: u16,
365 glide: Glide,
366 applied: f64,
368 moving: bool,
369 snap: Option<MomentumSnap>,
371 snap_pending: bool,
372 snap_delta: Option<f64>,
375 snap_start: Duration,
376 snap_applied: f64,
377}
378
379impl MomentumPart {
380 fn active(&self) -> bool {
381 self.moving || self.snap_pending || self.snap_delta.is_some()
382 }
383}
384
385const MOMENTUM_ZOOM: usize = 0;
387const MOMENTUM_BEARING: usize = 1;
388const MOMENTUM_PITCH: usize = 2;
389
390struct MomentumState {
392 options: CameraMomentum,
393 pan_total: ScreenCoordinate,
395 pan: MomentumPart,
396 scalars: [MomentumPart; 3],
398 scalar_totals: [f64; 3],
399 replaced: bool,
401 elapsed: Duration,
403}
404
405impl MomentumState {
406 fn anchor(&self, part: usize) -> Option<ScreenCoordinate> {
407 match part {
408 MOMENTUM_ZOOM => self.options.zoom_anchor,
409 MOMENTUM_BEARING => self.options.bearing_anchor,
410 _ => self.options.pitch_anchor,
411 }
412 }
413
414 fn retain(&mut self, owned: u16) -> u16 {
417 let mut needed = 0;
418 let mut replaced = false;
419 for part in std::iter::once(&mut self.pan).chain(self.scalars.iter_mut()) {
420 if !part.active() {
421 continue;
422 }
423 if part.fields & owned != part.fields {
424 replaced |= part.moving || part.snap_delta.is_some();
425 part.moving = false;
426 part.snap_pending = false;
427 part.snap_delta = None;
428 continue;
429 }
430 needed |= part.fields;
431 }
432 self.replaced |= replaced;
433 needed
434 }
435
436 fn end(&self) -> (CameraVelocity, bool) {
440 let mut velocity = CameraVelocity::default();
441 if self.pan.moving {
442 let share = self.pan.glide.speed(self.elapsed);
443 velocity.pan = ScreenCoordinate::new(self.pan_total.x * share, self.pan_total.y * share);
444 }
445 let speed = |i: usize| {
446 let part = &self.scalars[i];
447 if part.moving { self.scalar_totals[i] * part.glide.speed(self.elapsed) } else { 0.0 }
448 };
449 velocity.zoom = speed(MOMENTUM_ZOOM);
450 velocity.bearing = speed(MOMENTUM_BEARING);
451 velocity.pitch = speed(MOMENTUM_PITCH);
452 (velocity, self.replaced)
453 }
454}
455
456fn snap_delta(value: f64, snap: &MomentumSnap, circular: bool) -> f64 {
460 if snap.spacing.is_nan() || snap.spacing <= 0.0 {
461 return 0.0;
462 }
463 let delta = if circular {
464 let turn = value - snap.offset - 360.0 * ((value - snap.offset) / 360.0).floor();
465 let below = (turn / snap.spacing).floor() * snap.spacing;
466 let above = f64::min(below + snap.spacing, 360.0);
467 if turn - below <= above - turn { below - turn } else { above - turn }
468 } else {
469 snap.offset + ((value - snap.offset) / snap.spacing).round() * snap.spacing - value
471 };
472 if delta.abs() <= snap.tolerance { delta } else { 0.0 }
473}
474
475fn momentum_value(state: &TransformState, part: usize) -> f64 {
477 match part {
478 MOMENTUM_ZOOM => state.get_zoom(),
479 MOMENTUM_BEARING => -mln_math::rad2deg(state.get_bearing()),
480 _ => mln_math::rad2deg(state.get_pitch()),
481 }
482}
483
484#[derive(Clone, Debug, Default)]
489pub struct FrameClock(Arc<Mutex<Option<Instant>>>);
490
491impl FrameClock {
492 pub fn set(&self, time: Option<Instant>) {
493 *self.0.lock() = time;
494 }
495
496 #[must_use]
497 pub fn get(&self) -> Option<Instant> {
498 *self.0.lock()
499 }
500}
501
502pub struct Transform {
503 state: TransformState,
504
505 transitions: Vec<Transition>,
506 events: Vec<TransformEvent>,
508 command: Option<CameraCommandId>,
511 silent: bool,
514 next_command: u64,
515 joint_ends: Vec<JointEnd>,
518 source: CameraChangeSource,
521 gesture: GestureState,
522 frame_time: FrameClock,
524 projection_for_zoom: Option<ProjectionForZoomFn>,
525 globe_free_bearing: bool,
526 globe_drag_hold: Option<GlobeDragHold>,
527}
528
529struct JointEnd {
533 command: CameraCommandId,
534 remaining: u32,
535 outcome: TransitionOutcome,
536}
537
538#[derive(Clone, Copy, Debug)]
543struct GlobeDragHold {
544 location: LatLng,
545 cursor: ScreenCoordinate,
546 camera: CameraOptions,
547 size: Size,
548}
549
550#[derive(Clone, Copy, Debug, Default)]
552struct GestureState {
553 active: bool,
555 serial: u64,
558 changed: u16,
561}
562
563impl GestureState {
564 fn change(&mut self, zoom: bool, bearing: bool, pitch: bool) {
566 self.changed |=
567 (if zoom { ZOOM } else { 0 }) | (if bearing { BEARING } else { 0 }) | (if pitch { PITCH } else { 0 });
568 }
569
570 fn mask_snaps(&self, momentum: &mut CameraMomentum) {
573 if self.changed & ZOOM == 0 {
574 momentum.zoom_snap = None;
575 }
576 if self.changed & BEARING == 0 {
577 momentum.bearing_snap = None;
578 }
579 if self.changed & PITCH == 0 {
580 momentum.pitch_snap = None;
581 }
582 }
583}
584
585impl Transform {
586 #[must_use]
587 pub fn new(constrain_mode: ConstrainMode, viewport_mode: ViewportMode) -> Self {
588 Self::from_state(TransformState::new(constrain_mode, viewport_mode))
589 }
590
591 pub(crate) fn from_state(state: TransformState) -> Self {
592 Transform {
593 state,
594 transitions: Vec::new(),
595 events: Vec::new(),
596 command: None,
597 silent: false,
598 next_command: 0,
599 joint_ends: Vec::new(),
600 source: CameraChangeSource::Command,
601 gesture: GestureState::default(),
602 frame_time: FrameClock::default(),
603 projection_for_zoom: None,
604 globe_free_bearing: false,
605 globe_drag_hold: None,
606 }
607 }
608
609 pub fn drain_events(&mut self) -> std::vec::Drain<'_, TransformEvent> {
612 self.events.drain(..)
613 }
614
615 pub fn has_events(&self) -> bool {
618 !self.events.is_empty()
619 }
620
621 fn emit(&mut self, event: TransformEvent) {
622 self.events.push(event);
623 }
624
625 pub fn resize(&mut self, size: Size) -> Result<(), Error> {
628 if size.is_empty() {
629 return Err(Error::invalid_argument("failed to resize: size is empty"));
630 }
631
632 if self.state.get_size() == size {
633 return Ok(());
634 }
635
636 self.emit(TransformEvent::CameraWillChange(CameraChange::default()));
637 self.state.set_size(size);
638 let (scale, center) = self.state.constrain_screen(self.state.get_scale());
639 if let Some(center) = center {
640 if self.in_transition() {
645 self.cancel_transitions();
646 }
647
648 let zoom = self.state.scale_zoom(scale);
651 self.state.set_lat_lng_zoom(¢er, zoom);
652 self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
653
654 return Ok(());
655 }
656 self.constrain_position(scale);
657
658 self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
659 Ok(())
660 }
661
662 pub fn get_camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
666 self.state.get_camera_options(padding)
667 }
668
669 pub fn jump_to(&mut self, camera: &CameraOptions) -> CameraCommandId {
672 self.command(|transform| transform.jump(camera))
673 }
674
675 fn jump(&mut self, camera: &CameraOptions) {
676 if self.state.is_globe_rendering()
681 && let Some(center) = camera.center
682 && camera.zoom.is_none()
683 {
684 let zoom = self.get_zoom()
685 + VerticalPerspectiveProjection::zoom_adjustment(
686 self.get_lat_lng(WrapMode::Wrapped).latitude(),
687 center.latitude(),
688 );
689 self.ease_to(&CameraOptions { zoom: Some(zoom), ..*camera }, &AnimationOptions::default());
690 return;
691 }
692 self.ease_to(camera, &AnimationOptions::default());
693 }
694
695 pub fn ease_to(&mut self, camera: &CameraOptions, animation: &AnimationOptions) -> CameraCommandId {
699 self.command(|transform| transform.ease(camera, animation))
700 }
701
702 fn ease(&mut self, input_camera: &CameraOptions, animation: &AnimationOptions) {
703 let mut camera = *input_camera;
704 let globe = self.state.is_globe_rendering();
705
706 let duration = animation.duration.unwrap_or(Duration::ZERO);
707 if !globe
708 && self.state.get_lat_lng_bounds() == LatLngBounds::default()
709 && !self.is_gesture_in_progress()
710 && duration != Duration::ZERO
711 && animation.easing.is_none()
712 {
713 self.fly_to(&camera, animation, true);
718 return;
719 }
720
721 let mut zoom = camera.zoom.unwrap_or(self.get_zoom());
722 if camera.zoom.is_none()
723 && let Some(center) = camera.center
724 && globe
725 {
726 zoom += VerticalPerspectiveProjection::zoom_adjustment(
727 self.get_lat_lng(WrapMode::Wrapped).latitude(),
728 center.latitude(),
729 );
730 }
731 self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut zoom);
732
733 let padding = camera.padding.unwrap_or(self.state.get_edge_insets());
734 let mut start_lat_lng = self.get_lat_lng(WrapMode::Unwrapped);
735 let unwrapped_lat_lng = camera.center.unwrap_or(start_lat_lng);
736 let lat_lng_end = self.state.constrained_center(
740 &if self.state.get_lat_lng_bounds() == LatLngBounds::default() {
741 unwrapped_lat_lng.wrapped()
742 } else {
743 unwrapped_lat_lng
744 },
745 if camera.zoom.is_some() { zoom } else { self.get_zoom() },
746 );
747
748 let mut bearing = match camera.bearing {
749 Some(b) => mln_math::deg2rad(-b),
750 None => self.get_bearing(),
751 };
752 let mut pitch = match camera.pitch {
753 Some(p) => mln_math::deg2rad(p),
754 None => self.get_pitch(),
755 };
756 let mut fov = match camera.fov {
757 Some(f) => mln_math::deg2rad(f),
758 None => self.get_field_of_view(),
759 };
760 let center_alt = camera.center_altitude.unwrap_or(self.state.get_center_altitude());
761 let roll = match camera.roll {
762 Some(r) => mln_math::deg2rad(r),
763 None => self.get_roll(),
764 };
765
766 if zoom.is_nan() || bearing.is_nan() || pitch.is_nan() || roll.is_nan() || fov.is_nan() {
767 self.end_unstarted(animation, TransitionOutcome::Cancelled);
768 return;
769 }
770
771 if self.state.get_lat_lng_bounds() == LatLngBounds::default() {
772 if self.is_gesture_in_progress() {
773 let wrap = unwrapped_lat_lng.longitude() - lat_lng_end.longitude();
778 start_lat_lng = lat_lng(start_lat_lng.latitude(), start_lat_lng.longitude() - wrap);
779 } else {
780 start_lat_lng.unwrap_for_shortest_path(&lat_lng_end);
782 }
783 }
784 let start_center_alt = self.state.get_center_altitude();
785
786 let start_point = Projection::project(&start_lat_lng, self.state.get_scale());
787 let end_point = Projection::project(&lat_lng_end, self.state.get_scale());
788
789 let target_globe = match &self.projection_for_zoom {
793 Some(projection_for_zoom) => projection_for_zoom(zoom).transition_state() > 0.0,
794 None => globe,
795 };
796 zoom = mln_math::clamp_f64(
797 zoom,
798 self.state.get_min_zoom_at_latitude_with(lat_lng_end.latitude(), target_globe),
799 self.state.get_max_zoom(),
800 );
801 pitch = mln_math::clamp_f64(pitch, self.state.get_min_pitch(), self.state.get_max_pitch());
802 fov = mln_math::clamp_f64(fov, self.state.get_min_field_of_view(), self.state.get_max_field_of_view());
803
804 bearing = normalize_angle(bearing, self.state.get_bearing());
806
807 let start_zoom = self.state.get_zoom();
808 let start_bearing = normalize_angle(self.state.get_bearing(), bearing);
809 let start_pitch = self.state.get_pitch();
810 let start_roll = self.state.get_roll();
811 let start_fov = f64::from(self.state.get_field_of_view());
812 let start_edge_insets = self.state.get_edge_insets();
813
814 let normalized_start_zoom = if globe {
819 start_zoom + VerticalPerspectiveProjection::zoom_adjustment(start_lat_lng.latitude(), 0.0)
820 } else {
821 start_zoom
822 };
823 let normalized_zoom = if globe {
824 zoom + VerticalPerspectiveProjection::zoom_adjustment(lat_lng_end.latitude(), 0.0)
825 } else {
826 zoom
827 };
828 let final_scale = self.state.zoom_scale(normalized_zoom - normalized_start_zoom);
829 let base = if normalized_zoom > normalized_start_zoom {
830 f64::min(2.0, final_scale)
831 } else {
832 f64::max(0.5, final_scale)
833 };
834 let delta_latitude = if globe {
835 VerticalPerspectiveProjection::difference_of_angles_degrees(
836 start_lat_lng.latitude(),
837 lat_lng_end.latitude(),
838 )
839 } else {
840 0.0
841 };
842 let delta_longitude = if globe {
843 VerticalPerspectiveProjection::difference_of_angles_degrees(
844 start_lat_lng.longitude(),
845 lat_lng_end.longitude(),
846 )
847 } else {
848 0.0
849 };
850 let moves_around_anchor = camera.anchor.is_some() && camera.center.is_none();
851
852 let frame: FrameFn = Box::new(move |state: &TransformState, t: f64| {
853 let (frame_lat_lng, frame_zoom) = if globe {
854 let mut frame_lat_lng =
858 if moves_around_anchor { state.get_lat_lng(WrapMode::Unwrapped) } else { lat_lng_end };
859 let mut frame_zoom = zoom;
860 if moves_around_anchor {
861 frame_zoom = interpolate(&normalized_start_zoom, &normalized_zoom, t)
862 + VerticalPerspectiveProjection::zoom_adjustment(0.0, frame_lat_lng.latitude());
863 } else if t < 1.0 {
864 let factor = t * base.powf(1.0 - t);
865 frame_lat_lng = VerticalPerspectiveProjection::interpolate_lat_lng(
866 &start_lat_lng,
867 delta_latitude,
868 delta_longitude,
869 factor,
870 )
871 .wrapped();
872 frame_zoom = if zoom == start_zoom {
873 start_zoom
874 } else {
875 interpolate(&normalized_start_zoom, &normalized_zoom, t)
876 + VerticalPerspectiveProjection::zoom_adjustment(0.0, frame_lat_lng.latitude())
877 };
878 }
879 (Some(frame_lat_lng), frame_zoom)
880 } else {
881 let frame_point = interpolate(&start_point, &end_point, t);
882 (
883 frame_unproject(&frame_point, state.zoom_scale(start_zoom), WrapMode::Unwrapped),
884 interpolate(&start_zoom, &zoom, t),
885 )
886 };
887 CameraOptions {
888 center: frame_lat_lng,
889 zoom: Some(frame_zoom),
890 center_altitude: Some(interpolate(&start_center_alt, ¢er_alt, t)),
891 bearing: Some(-mln_math::rad2deg(mln_math::wrap(interpolate(&start_bearing, &bearing, t), -PI, PI))),
892 padding: interpolate_edge_insets(&start_edge_insets, &padding, t),
893 pitch: Some(mln_math::rad2deg(interpolate(&start_pitch, &pitch, t))),
894 roll: Some(mln_math::rad2deg(interpolate(&start_roll, &roll, t))),
895 fov: Some(mln_math::rad2deg(interpolate(&start_fov, &fov, t))),
896 ..Default::default()
897 }
898 });
899
900 let moves_center = input_camera.center.is_some() || lat_lng_end.wrapped() != start_lat_lng.wrapped();
905 let fields = if globe && moves_around_anchor {
906 CameraOptions { zoom: Some(zoom), ..*input_camera }
907 } else if globe && moves_center {
908 CameraOptions { center: Some(lat_lng_end), zoom: Some(zoom), ..*input_camera }
909 } else {
910 *input_camera
911 };
912 self.start_transition(&fields, animation, frame, duration, false);
913 }
914
915 pub(crate) fn fly_to(
924 &mut self,
925 camera: &CameraOptions,
926 animation: &AnimationOptions,
927 linear_zoom_interpolation: bool,
928 ) -> CameraCommandId {
929 self.command(|transform| transform.fly(camera, animation, linear_zoom_interpolation))
930 }
931
932 fn fly(&mut self, input_camera: &CameraOptions, animation: &AnimationOptions, linear_zoom_interpolation: bool) {
933 let mut camera = *input_camera;
934 let globe = self.state.is_globe_rendering();
935
936 let mut zoom = camera.zoom.unwrap_or(self.get_zoom());
937 if camera.zoom.is_none()
938 && let Some(center) = camera.center
939 && globe
940 {
941 zoom += VerticalPerspectiveProjection::zoom_adjustment(
942 self.get_lat_lng(WrapMode::Wrapped).latitude(),
943 center.latitude(),
944 );
945 }
946 self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut zoom);
947
948 let padding = camera.padding.unwrap_or(self.state.get_edge_insets());
949 let lat_lng_end = self.state.constrained_center(
952 &camera.center.unwrap_or(self.get_lat_lng(WrapMode::Unwrapped)).wrapped(),
953 if camera.zoom.is_some() { zoom } else { self.get_zoom() },
954 );
955 let center_alt = camera.center_altitude.unwrap_or(self.state.get_center_altitude());
956 let mut bearing = match camera.bearing {
957 Some(b) => mln_math::deg2rad(-b),
958 None => self.get_bearing(),
959 };
960 let mut pitch = match camera.pitch {
961 Some(p) => mln_math::deg2rad(p),
962 None => self.get_pitch(),
963 };
964 let roll = match camera.roll {
965 Some(r) => mln_math::deg2rad(r),
966 None => self.get_roll(),
967 };
968 let mut fov = match camera.fov {
969 Some(f) => mln_math::deg2rad(f),
970 None => self.get_field_of_view(),
971 };
972
973 if zoom.is_nan()
974 || bearing.is_nan()
975 || pitch.is_nan()
976 || roll.is_nan()
977 || fov.is_nan()
978 || self.state.get_size().is_empty()
979 {
980 self.end_unstarted(animation, TransitionOutcome::Cancelled);
981 return;
982 }
983
984 let mut start_lat_lng = self.get_lat_lng(WrapMode::Unwrapped).wrapped();
986 start_lat_lng.unwrap_for_shortest_path(&lat_lng_end);
987 let start_center_alt = self.state.get_center_altitude();
988
989 let start_point = Projection::project(&start_lat_lng, self.state.get_scale());
990 let end_point = Projection::project(&lat_lng_end, self.state.get_scale());
991
992 let target_globe = match &self.projection_for_zoom {
996 Some(projection_for_zoom) => projection_for_zoom(zoom).transition_state() > 0.0,
997 None => globe,
998 };
999 zoom = mln_math::clamp_f64(
1000 zoom,
1001 self.state.get_min_zoom_at_latitude_with(lat_lng_end.latitude(), target_globe),
1002 self.state.get_max_zoom(),
1003 );
1004 pitch = mln_math::clamp_f64(pitch, self.state.get_min_pitch(), self.state.get_max_pitch());
1005 fov = mln_math::clamp_f64(fov, self.state.get_min_field_of_view(), self.state.get_max_field_of_view());
1006
1007 bearing = normalize_angle(bearing, self.state.get_bearing());
1009 let start_zoom = self.state.scale_zoom(self.state.get_scale());
1010 let start_bearing = normalize_angle(self.state.get_bearing(), bearing);
1011 let start_pitch = self.state.get_pitch();
1012 let start_roll = self.state.get_roll();
1013 let start_fov = f64::from(self.state.get_field_of_view());
1014
1015 let size = self.state.get_size();
1018 let w0 = f64::max(
1019 f64::from(size.width) - padding.left - padding.right,
1020 f64::from(size.height) - padding.top - padding.bottom,
1021 );
1022 let normalized_start_zoom = if globe {
1025 start_zoom + VerticalPerspectiveProjection::zoom_adjustment(start_lat_lng.latitude(), 0.0)
1026 } else {
1027 start_zoom
1028 };
1029 let normalized_zoom = if globe {
1030 zoom + VerticalPerspectiveProjection::zoom_adjustment(lat_lng_end.latitude(), 0.0)
1031 } else {
1032 zoom
1033 };
1034 let w1 = w0 / self.state.zoom_scale(normalized_zoom - normalized_start_zoom);
1037 let u1 = if globe {
1040 VerticalPerspectiveProjection::surface_distance_pixels(
1041 Projection::world_size(self.state.get_scale()),
1042 start_lat_lng.latitude(),
1043 &start_lat_lng,
1044 &lat_lng_end,
1045 )
1046 } else {
1047 (end_point.x - start_point.x).hypot(end_point.y - start_point.y)
1048 };
1049
1050 let mut rho = 1.42;
1060 if globe {
1061 let floor_zoom =
1064 f64::max(animation.min_zoom.unwrap_or(self.state.get_min_zoom()), self.state.get_min_zoom());
1065 let normalized_floor_zoom = f64::min(
1066 f64::min(
1067 floor_zoom + VerticalPerspectiveProjection::zoom_adjustment(lat_lng_end.latitude(), 0.0),
1068 normalized_start_zoom,
1069 ),
1070 normalized_zoom,
1071 );
1072 let min_zoom = mln_math::clamp_f64(
1073 normalized_floor_zoom + VerticalPerspectiveProjection::zoom_adjustment(0.0, lat_lng_end.latitude()),
1074 self.state.get_min_zoom_at_latitude(lat_lng_end.latitude()),
1075 self.state.get_max_zoom(),
1076 );
1077 let w_max = w0
1078 / self.state.zoom_scale(
1079 min_zoom + VerticalPerspectiveProjection::zoom_adjustment(lat_lng_end.latitude(), 0.0)
1080 - normalized_start_zoom,
1081 );
1082 if u1 != 0.0 {
1083 rho = f64::min(rho, (w_max / u1 * 2.0).sqrt());
1084 }
1085 } else if animation.min_zoom.is_some() || linear_zoom_interpolation {
1086 let mut min_zoom =
1088 mln_math::fmin(animation.min_zoom.unwrap_or(start_zoom), mln_math::fmin(start_zoom, zoom));
1089 min_zoom = mln_math::clamp_f64(
1090 min_zoom,
1091 self.state.get_min_zoom_at_latitude(lat_lng_end.latitude()),
1092 self.state.get_max_zoom(),
1093 );
1094 let w_max = w0 / self.state.zoom_scale(min_zoom - start_zoom);
1097 rho = if u1 == 0.0 { 1.0 } else { (w_max / u1 * 2.0).sqrt() };
1098 }
1099 let rho2 = rho * rho;
1101
1102 let r = |i: f64| -> f64 {
1106 let b = (w1 * w1 - w0 * w0 + if i == 0.0 { 1.0 } else { -1.0 } * rho2 * rho2 * u1 * u1)
1108 / (2.0 * if i == 0.0 { w0 } else { w1 } * rho2 * u1);
1109 ((b * b + 1.0).sqrt() - b).ln()
1110 };
1111
1112 let r0 = if u1 == 0.0 { f64::INFINITY } else { r(0.0) }; let r1 = if u1 == 0.0 { f64::INFINITY } else { r(1.0) };
1115
1116 let is_close = u1.abs() < 0.000_001 || !r0.is_finite() || !r1.is_finite();
1119
1120 let w = move |s: f64| -> f64 {
1125 if is_close {
1126 ((if w1 < w0 { -1.0 } else { 1.0 }) * rho * s).exp()
1127 } else {
1128 r0.cosh() / (r0 + rho * s).cosh()
1129 }
1130 };
1131 let u = move |s: f64| -> f64 {
1135 if is_close { 0.0 } else { w0 * (r0.cosh() * (r0 + rho * s).tanh() - r0.sinh()) / rho2 / u1 }
1136 };
1137 let total_s = if is_close { (w1 / w0).ln().abs() / rho } else { (r1 - r0) / rho };
1139
1140 let duration = if let Some(duration) = animation.duration {
1141 duration
1142 } else {
1143 let mut velocity = 1.2;
1145 if let Some(v) = animation.velocity {
1146 velocity = v / rho;
1147 }
1148 nanos_from_secs(total_s / velocity).unwrap_or_default()
1152 };
1153 let duration = match animation.max_duration {
1154 Some(max) if !linear_zoom_interpolation && duration > max => Duration::ZERO,
1155 _ => duration,
1156 };
1157 let start_scale = self.state.get_scale();
1158 let start_edge_insets = self.state.get_edge_insets();
1159 let delta_latitude = if globe {
1160 VerticalPerspectiveProjection::difference_of_angles_degrees(
1161 start_lat_lng.latitude(),
1162 lat_lng_end.latitude(),
1163 )
1164 } else {
1165 0.0
1166 };
1167 let delta_longitude = if globe {
1168 VerticalPerspectiveProjection::difference_of_angles_degrees(
1169 start_lat_lng.longitude(),
1170 lat_lng_end.longitude(),
1171 )
1172 } else {
1173 0.0
1174 };
1175
1176 let frame: FrameFn = Box::new(move |state: &TransformState, k: f64| {
1177 let s = k * total_s;
1180 let us = if k == 1.0 { 1.0 } else { u(s) };
1181
1182 let (frame_lat_lng, frame_zoom) = if globe {
1183 let mut frame_lat_lng = lat_lng_end;
1184 let mut frame_zoom = zoom;
1185 if k < 1.0 {
1186 frame_lat_lng = VerticalPerspectiveProjection::interpolate_lat_lng(
1187 &start_lat_lng,
1188 delta_latitude,
1189 delta_longitude,
1190 us,
1191 )
1192 .wrapped();
1193 let frame_normalized_zoom = if linear_zoom_interpolation {
1194 interpolate(&normalized_start_zoom, &normalized_zoom, k)
1195 } else {
1196 normalized_start_zoom + state.scale_zoom(1.0 / w(s))
1197 };
1198 frame_zoom = frame_normalized_zoom
1199 + VerticalPerspectiveProjection::zoom_adjustment(0.0, frame_lat_lng.latitude());
1200 if frame_zoom.is_nan() {
1201 frame_zoom = zoom;
1202 }
1203 }
1204 (Some(frame_lat_lng), frame_zoom)
1205 } else {
1206 let frame_point = interpolate(&start_point, &end_point, us);
1209 let mut frame_zoom = if linear_zoom_interpolation {
1210 interpolate(&start_zoom, &zoom, k)
1211 } else {
1212 start_zoom + state.scale_zoom(1.0 / w(s))
1213 };
1214
1215 if frame_zoom.is_nan() {
1217 frame_zoom = zoom;
1218 }
1219
1220 (frame_unproject(&frame_point, start_scale, WrapMode::Unwrapped), frame_zoom)
1222 };
1223 CameraOptions {
1224 center: frame_lat_lng,
1225 zoom: Some(frame_zoom),
1226 center_altitude: Some(interpolate(&start_center_alt, ¢er_alt, us)),
1227 bearing: Some(-mln_math::rad2deg(mln_math::wrap(interpolate(&start_bearing, &bearing, k), -PI, PI))),
1228 padding: interpolate_edge_insets(&start_edge_insets, &padding, k),
1229 pitch: Some(mln_math::rad2deg(interpolate(&start_pitch, &pitch, k))),
1230 roll: Some(mln_math::rad2deg(interpolate(&start_roll, &roll, k))),
1231 fov: Some(mln_math::rad2deg(interpolate(&start_fov, &fov, k))),
1232 ..Default::default()
1233 }
1234 });
1235
1236 self.start_transition(input_camera, animation, frame, duration, !linear_zoom_interpolation);
1237 }
1238
1239 fn globe_on_screen(&self) -> bool {
1244 self.state.is_globe_rendering() && !self.state.get_size().is_empty()
1245 }
1246
1247 pub fn move_by(
1251 &mut self,
1252 offset: &ScreenCoordinate,
1253 animation: &AnimationOptions,
1254 ) -> Result<CameraCommandId, Error> {
1255 self.move_by_with_anchor(offset, None, animation)
1256 }
1257
1258 pub fn move_by_with_anchor(
1266 &mut self,
1267 offset: &ScreenCoordinate,
1268 anchor: Option<ScreenCoordinate>,
1269 animation: &AnimationOptions,
1270 ) -> Result<CameraCommandId, Error> {
1271 let mut moved = Ok(());
1272 let command = self.command(|transform| moved = transform.move_by_now(offset, anchor, animation));
1273 moved.map(|()| command)
1274 }
1275
1276 fn move_by_now(
1277 &mut self,
1278 offset: &ScreenCoordinate,
1279 anchor: Option<ScreenCoordinate>,
1280 animation: &AnimationOptions,
1281 ) -> Result<(), Error> {
1282 let flipped = |state: &TransformState, point: &ScreenCoordinate| {
1283 ScreenCoordinate::new(point.x, f64::from(state.get_size().height) - point.y)
1284 };
1285 let size = self.state.get_size();
1286 let view_center = self.state.get_edge_insets().get_center(size.width as u16, size.height as u16);
1287 let fling_duration = animation.duration.filter(|duration| *duration > Duration::ZERO);
1288 let globe = self.globe_on_screen();
1289 if globe && (offset.x.is_nan() || offset.y.is_nan()) {
1290 return Err(Error::invalid_argument("offset must not be NaN"));
1291 }
1292 if globe && (!offset.x.is_finite() || !offset.y.is_finite()) {
1293 return Err(Error::invalid_argument("offset must not be infinite"));
1294 }
1295 if globe
1296 && let Some(duration) = fling_duration
1297 && self.globe_free_bearing
1298 {
1299 let start = CenterAndBearing {
1303 center: self.get_lat_lng(WrapMode::Unwrapped),
1304 bearing: -mln_math::rad2deg(self.get_bearing()),
1305 };
1306 let end = VerticalPerspectiveProjection::fling_camera(
1307 &self.state,
1308 &flipped(&self.state, &view_center),
1309 &ScreenCoordinate::new(offset.x, -offset.y),
1310 );
1311 let start_zoom = self.get_zoom();
1312 let frame: FrameFn = Box::new(move |state: &TransformState, t: f64| {
1313 let camera = VerticalPerspectiveProjection::interpolate_camera(&start, &end, t);
1314 let center = state.constrained_center(&camera.center, state.get_zoom());
1315 CameraOptions {
1316 center: Some(center),
1317 zoom: Some(
1318 start_zoom
1319 + VerticalPerspectiveProjection::zoom_adjustment(
1320 start.center.latitude(),
1321 center.latitude(),
1322 ),
1323 ),
1324 bearing: Some(camera.bearing),
1325 ..Default::default()
1326 }
1327 });
1328 let fields = CameraOptions {
1331 center: Some(end.center),
1332 zoom: Some(start_zoom),
1333 bearing: Some(end.bearing),
1334 ..Default::default()
1335 };
1336 self.start_transition(&fields, animation, frame, duration, false);
1337 return Ok(());
1338 }
1339
1340 if globe && fling_duration.is_some() {
1341 let mut center = self
1346 .state
1347 .constrained_center(&VerticalPerspectiveProjection::pan_center(&self.state, offset), self.get_zoom());
1348 let longitude = self.get_lat_lng(WrapMode::Unwrapped).longitude();
1349 if (center.longitude() - longitude).abs() > 180.0 {
1350 center = lat_lng(center.latitude(), longitude + 179.5f64.copysign(center.longitude() - longitude));
1351 }
1352 self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
1353 return Ok(());
1354 }
1355
1356 if globe {
1357 let on_globe = |state: &TransformState, point: &ScreenCoordinate| {
1371 VerticalPerspectiveProjection::screen_coordinate_hits_globe(state, &flipped(state, point))
1372 };
1373 let grab = match anchor {
1374 Some(anchor) if on_globe(&self.state, &anchor) => anchor,
1375 _ => view_center,
1376 };
1377 let pan_delta = ScreenCoordinate::new(offset.x, -offset.y);
1378 let mut camera = CameraOptions::default();
1379 let held = self.globe_drag_hold.take();
1380 let hold = match anchor {
1381 Some(anchor) if !self.globe_free_bearing && on_globe(&self.state, &anchor) => {
1382 let from = ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y);
1383 let location = match held {
1384 Some(held)
1385 if (held.cursor.x - from.x).hypot(held.cursor.y - from.y) < 1e-3
1386 && held.size == size
1387 && held.camera == self.get_camera_options(None) =>
1388 {
1389 Some(held.location)
1390 }
1391 _ if on_globe(&self.state, &from) => self
1392 .state
1393 .screen_coordinate_to_lat_lng(&flipped(&self.state, &from), WrapMode::Unwrapped)
1394 .ok(),
1395 _ => None,
1396 };
1397 location.and_then(|location| {
1398 VerticalPerspectiveProjection::drag_center_holding(
1399 &self.state,
1400 &location,
1401 &flipped(&self.state, &anchor),
1402 )
1403 .map(|center| (location, anchor, center))
1404 })
1405 }
1406 _ => None,
1407 };
1408 let mut center = if let Some((_, _, center)) = hold {
1409 center
1410 } else if self.globe_free_bearing {
1411 let drag =
1412 VerticalPerspectiveProjection::drag_camera(&self.state, &flipped(&self.state, &grab), &pan_delta);
1413 camera = CameraOptions { bearing: Some(drag.bearing), ..camera };
1414 drag.center
1415 } else {
1416 VerticalPerspectiveProjection::drag_center(&self.state, &flipped(&self.state, &grab), &pan_delta)
1417 };
1418 center = self.state.constrained_center(¢er, self.get_zoom());
1419 let zoom = self.get_zoom()
1420 + VerticalPerspectiveProjection::zoom_adjustment(
1421 self.get_lat_lng(WrapMode::Wrapped).latitude(),
1422 center.latitude(),
1423 );
1424 self.ease_to(&CameraOptions { center: Some(center), zoom: Some(zoom), ..camera }, animation);
1425 self.globe_drag_hold = hold.map(|(location, cursor, _)| GlobeDragHold {
1426 location,
1427 cursor,
1428 camera: self.get_camera_options(None),
1429 size,
1430 });
1431 return Ok(());
1432 }
1433
1434 let mut center_offset = *offset;
1435
1436 let pitch = self.state.get_pitch();
1440 let offset_length = offset.x.hypot(offset.y);
1441 if pitch > 0.0 && offset_length > 0.0 {
1442 let camera_to_center =
1443 0.5 * f64::from(self.state.get_size().height) / (f64::from(self.state.get_field_of_view()) / 2.0).tan();
1444 let pixels_to_horizon = (camera_to_center / pitch.tan()).abs();
1445 let horizon_factor = 0.75;
1447 let scale = pixels_to_horizon * horizon_factor / offset_length;
1448 if scale < 1.0 {
1449 center_offset = ScreenCoordinate::new(offset.x * scale, offset.y * scale);
1450 }
1451 }
1452
1453 let size = self.state.get_size();
1454 let center = self.state.get_edge_insets().get_center(size.width as u16, size.height as u16);
1455 let point_on_screen = ScreenCoordinate::new(center.x - center_offset.x, center.y - center_offset.y);
1456 let center = self.screen_coordinate_to_lat_lng(&point_on_screen, WrapMode::Unwrapped)?;
1458 self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
1459 Ok(())
1460 }
1461
1462 pub fn get_lat_lng(&self, wrap: WrapMode) -> LatLng {
1463 self.state.get_lat_lng(wrap)
1464 }
1465
1466 pub(crate) fn get_zoom(&self) -> f64 {
1469 self.state.get_zoom()
1470 }
1471
1472 pub fn set_lat_lng_bounds(&mut self, bounds: LatLngBounds) -> Result<(), Error> {
1475 if !bounds.valid() {
1476 return Err(Error::invalid_argument("failed to set bounds: bounds are invalid"));
1477 }
1478 self.state.set_lat_lng_bounds(bounds);
1479 Ok(())
1480 }
1481
1482 pub(crate) fn set_min_zoom(&mut self, min_zoom: f64) {
1483 if min_zoom.is_nan() {
1484 return;
1485 }
1486 self.state.set_min_zoom(min_zoom);
1487 }
1488
1489 pub(crate) fn set_max_zoom(&mut self, max_zoom: f64) {
1490 if max_zoom.is_nan() {
1491 return;
1492 }
1493 self.state.set_max_zoom(max_zoom);
1494 }
1495
1496 pub(crate) fn set_min_pitch(&mut self, min_pitch: f64) {
1497 if min_pitch.is_nan() {
1498 return;
1499 }
1500 if mln_math::deg2rad(min_pitch) < mln_util::constants::PITCH_MIN {
1501 Log::warning(
1502 Event::General,
1503 format!(
1504 "Trying to set minimum pitch below the limit ({} degrees), the value will be clamped.",
1505 std_to_string(mln_math::rad2deg(mln_util::constants::PITCH_MIN))
1506 ),
1507 );
1508 }
1509 self.state.set_min_pitch(mln_math::deg2rad(min_pitch));
1510 }
1511
1512 pub fn set_max_pitch(&mut self, max_pitch: f64) {
1513 if max_pitch.is_nan() {
1514 return;
1515 }
1516 if mln_math::deg2rad(max_pitch) > PITCH_MAX {
1517 Log::warning(
1518 Event::General,
1519 format!(
1520 "Trying to set maximum pitch above the limit ({} degrees), the value will be clamped.",
1521 std_to_string(mln_math::rad2deg(PITCH_MAX))
1522 ),
1523 );
1524 }
1525 self.state.set_max_pitch(mln_math::deg2rad(max_pitch));
1526 }
1527
1528 pub(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
1529 self.state.set_frustum_offset(frustum_offset);
1530 }
1531
1532 pub(crate) fn get_bearing(&self) -> f64 {
1535 self.state.get_bearing()
1536 }
1537
1538 pub fn get_pitch(&self) -> f64 {
1541 self.state.get_pitch()
1542 }
1543
1544 pub(crate) fn get_roll(&self) -> f64 {
1545 self.state.get_roll()
1546 }
1547
1548 pub(crate) fn get_field_of_view(&self) -> f64 {
1550 f64::from(self.state.get_field_of_view())
1551 }
1552
1553 pub fn set_projection_definition(&mut self, definition: &ProjectionDefinition) {
1556 self.state.set_projection_definition(definition);
1557 }
1558
1559 pub(crate) fn set_projection_for_zoom(&mut self, projection_for_zoom: Option<ProjectionForZoomFn>) {
1562 self.projection_for_zoom = projection_for_zoom;
1563 }
1564
1565 pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
1566 self.globe_free_bearing = free_bearing;
1567 }
1568
1569 pub(crate) fn is_globe_free_bearing(&self) -> bool {
1570 self.globe_free_bearing
1571 }
1572
1573 #[cfg(test)]
1574 pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
1575 self.state.is_location_occluded(lat_lng)
1576 }
1577
1578 pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
1581 self.state.set_north_orientation(orientation);
1582 self.constrain_position(self.state.get_scale());
1583 }
1584
1585 fn constrain_position(&mut self, scale: f64) {
1588 let (scale, x, y) = self.state.constrain(scale, self.state.get_x(), self.state.get_y());
1589 self.state.set_x(x);
1590 self.state.set_y(y);
1591 self.state.set_scale(scale);
1592 }
1593
1594 pub fn set_constrain_mode(&mut self, mode: ConstrainMode) {
1597 self.state.set_constrain_mode(mode);
1598 self.constrain_position(self.state.get_scale());
1599 }
1600
1601 pub fn set_viewport_mode(&mut self, mode: ViewportMode) {
1604 self.state.set_viewport_mode(mode);
1605 }
1606
1607 pub(crate) fn set_projection_mode(&mut self, options: &ProjectionMode) {
1610 if let Some(x_skew) = options.x_skew {
1611 self.state.set_x_skew(x_skew);
1612 }
1613 if let Some(y_skew) = options.y_skew {
1614 self.state.set_y_skew(y_skew);
1615 }
1616 if let Some(axonometric) = options.axonometric {
1617 self.state.set_axonometric(axonometric);
1618 }
1619 }
1620
1621 #[cfg(test)]
1622 pub(crate) fn get_projection_mode(&self) -> ProjectionMode {
1623 ProjectionMode::default()
1624 .with_axonometric(self.state.get_axonometric())
1625 .with_x_skew(self.state.get_x_skew())
1626 .with_y_skew(self.state.get_y_skew())
1627 }
1628
1629 fn start_transition(
1638 &mut self,
1639 camera: &CameraOptions,
1640 animation: &AnimationOptions,
1641 frame: FrameFn,
1642 duration: Duration,
1643 flight: bool,
1644 ) {
1645 let mut fields = camera_fields(camera);
1646 let mut coupled_fields = if flight { CENTER | ZOOM } else { 0 };
1647 fields |= coupled_fields;
1648
1649 let mut anchor = if camera.center.is_some() { None } else { camera.anchor };
1652 let mut anchor_lat_lng = LatLng::default();
1653 if let Some(a) = anchor.as_mut() {
1654 a.y = f64::from(self.state.get_size().height) - a.y;
1655 match self.state.screen_coordinate_to_lat_lng(a, WrapMode::Unwrapped) {
1659 Ok(lat_lng) => {
1660 anchor_lat_lng = lat_lng;
1661 fields |= CENTER;
1662 coupled_fields = fields;
1663 }
1664 Err(e) => {
1665 Log::error(Event::General, &e.message);
1666 anchor = None;
1667 }
1668 }
1669 }
1670
1671 let target = frame(&self.state, 1.0);
1672 let panning = flight || anchor.is_some() || camera.center != Some(self.get_lat_lng(WrapMode::Unwrapped));
1673 let scaling = flight || target.zoom != Some(self.get_zoom());
1674 let rotating = target.bearing != Some(-mln_math::rad2deg(self.get_bearing()));
1675 let moving_fields = (if panning { CENTER } else { 0 })
1676 | (if scaling { ZOOM } else { 0 })
1677 | (if rotating { BEARING } else { 0 });
1678
1679 let start = self.now();
1680 let duration = if fields != 0 { duration } else { Duration::ZERO };
1681 let transition = Transition {
1682 coupled_fields,
1683 anchor,
1684 anchor_lat_lng,
1685 command: self.reporting(),
1686 ..Transition::new(fields, moving_fields, start, duration, animation, frame, self.source)
1687 };
1688 let mode = transition.mode();
1689
1690 let finished = self.release_fields(fields);
1691 self.transitions.push(transition);
1692 self.update_movement_flags();
1693 self.finish_transitions(finished);
1694
1695 self.emit(TransformEvent::CameraWillChange(CameraChange { mode, source: self.source }));
1696
1697 if duration == Duration::ZERO {
1698 let index = self.transitions.len() - 1;
1699 self.apply_transitions(Some(index), Some(start));
1700 let transition = self.transitions.remove(index);
1701 self.update_movement_flags();
1702 self.finish_transitions(vec![transition]);
1703 }
1704 }
1705
1706 fn apply_transitions(&mut self, only: Option<usize>, now: Option<Instant>) {
1710 let current = self.state.get_camera_options(None);
1713 let mut camera = current;
1714
1715 let active = match only {
1716 Some(index) => &self.transitions[index..=index],
1717 None => &self.transitions[..],
1718 };
1719 for transition in active {
1720 if transition.momentum.is_some() {
1721 continue;
1722 }
1723 let t = transition.progress(now);
1724 let ease = transition.animation.easing.unwrap_or(DEFAULT_TRANSITION_EASE);
1725 let value = (transition.frame)(&self.state, if t == 1.0 { 1.0 } else { ease.solve(t, 0.001) });
1726 let fields = transition.fields;
1727 if fields & CENTER != 0 && value.center.is_some() {
1730 camera.center = value.center;
1731 }
1732 if fields & ZOOM != 0 {
1733 camera.zoom = value.zoom;
1734 }
1735 if fields & BEARING != 0 {
1736 camera.bearing = value.bearing;
1737 }
1738 if fields & PITCH != 0 {
1739 camera.pitch = value.pitch;
1740 }
1741 if fields & PADDING != 0 && value.padding.is_some() {
1742 camera.padding = value.padding;
1743 }
1744 if fields & ALTITUDE != 0 {
1745 camera.center_altitude = value.center_altitude;
1746 }
1747 if fields & ROLL != 0 {
1748 camera.roll = value.roll;
1749 }
1750 if fields & FOV != 0 {
1751 camera.fov = value.fov;
1752 }
1753 }
1754
1755 let anchored = self.transitions.iter().rev().find_map(|transition| {
1758 let anchor = transition.anchor.filter(|_| transition.fields & CENTER != 0)?;
1759 Some((anchor, transition.anchor_lat_lng))
1760 });
1761
1762 let globe_zoom_around = match anchored {
1768 Some((anchor, anchor_lat_lng)) if self.globe_on_screen() => {
1769 let location =
1770 self.state.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped).unwrap_or_else(|e| {
1771 Log::error(Event::General, &e.message);
1772 anchor_lat_lng
1773 });
1774 Some((location, self.state.get_zoom()))
1775 }
1776 _ => None,
1777 };
1778
1779 let padding = camera.padding.unwrap_or_default();
1788 self.state.set_edge_insets(&padding);
1789 if let Some(fov) = camera.fov.filter(|_| camera.fov != current.fov) {
1790 self.state.set_field_of_view(mln_math::deg2rad(fov));
1791 }
1792 if let Some(bearing) = camera.bearing.filter(|_| camera.bearing != current.bearing) {
1793 self.state.set_bearing(mln_math::deg2rad(-bearing));
1794 }
1795 if let Some(roll) = camera.roll.filter(|_| camera.roll != current.roll) {
1796 self.state.set_roll(mln_math::deg2rad(roll));
1797 }
1798 let pitch = match camera.pitch.filter(|_| camera.pitch != current.pitch) {
1799 Some(pitch) => mln_math::deg2rad(pitch),
1800 None => self.state.get_pitch(),
1801 };
1802 self.state.set_pitch(f64::min(get_max_pitch_for_edge_insets(&self.state, &padding), pitch));
1803 let mut zoom = camera.zoom.unwrap_or_default();
1804 self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut zoom);
1805 self.state.set_lat_lng_zoom(&camera.center.unwrap_or_default(), zoom);
1806 if let Some((anchor, anchor_lat_lng)) = anchored {
1807 match globe_zoom_around {
1808 Some((location, zoom_before)) if self.state.get_zoom() != zoom_before => {
1809 let zoom_delta = self.state.get_zoom() - zoom_before;
1810 VerticalPerspectiveProjection::zoom_around_point(
1811 &mut self.state,
1812 &anchor,
1813 &location,
1814 zoom_delta,
1815 self.globe_free_bearing,
1816 );
1817 }
1818 _ => {
1821 if let Err(e) = self.state.move_lat_lng(&anchor_lat_lng, &anchor) {
1822 Log::error(Event::General, &e.message);
1823 }
1824 }
1825 }
1826 }
1827 self.state.set_center_altitude(camera.center_altitude.unwrap_or_default());
1828 }
1829
1830 fn update_movement_flags(&mut self) {
1833 let moving = self.transitions.iter().fold(0, |moving, t| moving | (t.fields & t.moving_fields));
1834 self.state.set_panning_in_progress(moving & CENTER != 0);
1835 self.state.set_scaling_in_progress(moving & ZOOM != 0);
1836 self.state.set_rotating_in_progress(moving & BEARING != 0);
1837 }
1838
1839 fn finish_transitions(&mut self, finished: Vec<Transition>) {
1840 for transition in finished {
1841 self.end_gesture_momentum(transition.gesture);
1842 self.report_end(transition.command, transition.animation.transition_id, transition.end());
1843 let change = CameraChange { mode: transition.mode(), source: transition.source };
1846 self.emit(TransformEvent::CameraDidChange(change));
1847 }
1848 }
1849
1850 pub fn in_transition(&self) -> bool {
1852 !self.transitions.is_empty()
1853 }
1854
1855 pub fn update_transitions(&mut self, now: Option<Instant>) {
1858 if self.transitions.is_empty() {
1859 return;
1860 }
1861
1862 if self.transitions.iter().any(|t| t.momentum.is_none()) {
1863 self.apply_transitions(None, now);
1864 }
1865 for index in 0..self.transitions.len() {
1866 self.advance_momentum(index, now);
1867 }
1868
1869 let finished: Vec<_> = self.transitions.extract_if(.., |t| t.has_run_out(now) || t.fields == 0).collect();
1870 self.update_movement_flags();
1871 if !self.transitions.is_empty() {
1872 self.emit(TransformEvent::CameraIsChanging);
1873 }
1874
1875 self.finish_transitions(finished);
1876 }
1877
1878 fn release_fields(&mut self, fields: u16) -> Vec<Transition> {
1881 for active in &mut self.transitions {
1882 let mut replaced = fields;
1883 if active.coupled_fields & replaced != 0 {
1884 replaced |= active.coupled_fields;
1885 }
1886 active.fields &= !replaced;
1887 if let Some(momentum) = &mut active.momentum {
1888 active.fields = momentum.retain(active.fields);
1889 }
1890 if active.fields == 0 {
1891 active.ended_by(TransitionOutcome::Replaced);
1892 }
1893 }
1894 self.transitions.extract_if(.., |active| active.fields == 0).collect()
1895 }
1896
1897 fn command(&mut self, start: impl FnOnce(&mut Self)) -> CameraCommandId {
1904 if let Some(command) = self.command {
1905 start(self);
1906 return command;
1907 }
1908 let command = CameraCommandId(self.next_command);
1909 self.next_command += 1;
1910 self.command = Some(command);
1911 start(self);
1912 self.command = None;
1913 command
1914 }
1915
1916 fn reporting(&self) -> Option<CameraCommandId> {
1918 self.command.filter(|_| !self.silent)
1919 }
1920
1921 fn join_ends(&mut self, count: u32) {
1924 if let Some(command) = self.reporting().filter(|_| count > 1) {
1925 self.joint_ends.push(JointEnd { command, remaining: count, outcome: TransitionOutcome::Completed });
1926 }
1927 }
1928
1929 fn report_end(&mut self, command: Option<CameraCommandId>, transition_id: Option<u64>, mut end: TransitionEnd) {
1932 let Some(command) = command else { return };
1933 if let Some(index) = self.joint_ends.iter().position(|joint| joint.command == command) {
1934 let joint = &mut self.joint_ends[index];
1935 joint.remaining -= 1;
1936 joint.outcome = match (joint.outcome, end.outcome) {
1937 (TransitionOutcome::Cancelled, _) | (_, TransitionOutcome::Cancelled) => TransitionOutcome::Cancelled,
1938 (TransitionOutcome::Closed, _) | (_, TransitionOutcome::Closed) => TransitionOutcome::Closed,
1939 (TransitionOutcome::Replaced, _) | (_, TransitionOutcome::Replaced) => TransitionOutcome::Replaced,
1940 _ => TransitionOutcome::Completed,
1941 };
1942 if joint.remaining > 0 {
1943 return;
1944 }
1945 end.outcome = joint.outcome;
1946 self.joint_ends.swap_remove(index);
1947 }
1948 self.emit(TransformEvent::CommandEnded(CommandEnd { command, transition_id, end }));
1949 }
1950
1951 fn end_unstarted(&mut self, animation: &AnimationOptions, outcome: TransitionOutcome) {
1954 self.report_end(
1955 self.reporting(),
1956 animation.transition_id,
1957 TransitionEnd { outcome, ..TransitionEnd::default() },
1958 );
1959 }
1960
1961 #[cfg(test)]
1966 pub(crate) fn start_momentum(&mut self, options: &CameraMomentum, animation: &AnimationOptions) -> CameraCommandId {
1967 self.command(|transform| {
1968 transform.with_source(CameraChangeSource::Momentum, |transform| {
1969 transform.start_momentum_now(options, animation, None);
1970 });
1971 })
1972 }
1973
1974 fn start_momentum_now(&mut self, options: &CameraMomentum, animation: &AnimationOptions, gesture: Option<u64>) {
1977 let momentum_change = |mode: CameraChangeMode| CameraChange { mode, source: CameraChangeSource::Momentum };
1978 let mut momentum = MomentumState {
1979 options: *options,
1980 pan_total: ScreenCoordinate::new(0.0, 0.0),
1981 pan: MomentumPart::default(),
1982 scalars: [MomentumPart::default(); 3],
1983 scalar_totals: [0.0; 3],
1984 replaced: false,
1985 elapsed: Duration::ZERO,
1986 };
1987 let mut moving = 0;
1988 let mut settling = 0;
1989 let mut motion = Duration::ZERO;
1990 if let Some(velocity) = options.pan_velocity {
1991 let speed = velocity.x.hypot(velocity.y);
1992 if let Some(glide) = Glide::plan(speed, &options.pan_decay) {
1993 momentum.pan = MomentumPart { fields: CENTER, glide, moving: true, ..Default::default() };
1994 moving |= CENTER;
1995 motion = glide.duration;
1996 let scale = glide.distance / speed;
1997 momentum.pan_total = ScreenCoordinate::new(velocity.x * scale, velocity.y * scale);
1998 }
1999 }
2000 let scalars = [
2001 (options.zoom_velocity, &options.zoom_decay, options.zoom_anchor, options.zoom_snap, ZOOM),
2002 (options.bearing_velocity, &options.bearing_decay, options.bearing_anchor, options.bearing_snap, BEARING),
2003 (options.pitch_velocity, &options.pitch_decay, options.pitch_anchor, options.pitch_snap, PITCH),
2004 ];
2005 let mut instant = true;
2006 for (i, (velocity, decay, anchor, snap, field)) in scalars.into_iter().enumerate() {
2007 let part = &mut momentum.scalars[i];
2008 part.fields = field | if anchor.is_some() { CENTER } else { 0 };
2009 if let Some(velocity) = velocity
2010 && let Some(glide) = Glide::plan(velocity.abs(), decay)
2011 {
2012 part.glide = glide;
2013 part.moving = true;
2014 moving |= part.fields;
2015 motion = motion.max(glide.duration);
2016 momentum.scalar_totals[i] = glide.distance.copysign(velocity);
2017 }
2018 part.snap = snap;
2020 part.snap_pending = snap.is_some_and(|snap| {
2021 part.moving || snap_delta(momentum_value(&self.state, i), &snap, i == MOMENTUM_BEARING) != 0.0
2022 });
2023 if part.snap_pending {
2024 settling |= part.fields;
2025 if snap.is_some_and(|snap| snap.duration != Duration::ZERO) {
2026 instant = false;
2027 }
2028 }
2029 }
2030
2031 let start = self.now();
2032
2033 if moving == 0 && (settling == 0 || instant) {
2036 if settling != 0 {
2037 let finished = self.release_fields(settling);
2038 self.update_movement_flags();
2039 self.finish_transitions(finished);
2040 self.emit(TransformEvent::CameraWillChange(momentum_change(CameraChangeMode::Immediate)));
2041 for i in 0..momentum.scalars.len() {
2042 let part = &mut momentum.scalars[i];
2043 let Some(snap) = part.snap.filter(|_| part.snap_pending) else { continue };
2044 part.snap_pending = false;
2045 let delta = snap_delta(momentum_value(&self.state, i), &snap, i == MOMENTUM_BEARING);
2046 self.step_scalar(i, delta, momentum.anchor(i));
2047 }
2048 }
2049 self.end_gesture_momentum(gesture);
2050 self.end_unstarted(animation, TransitionOutcome::Completed);
2051 if settling != 0 {
2052 self.emit(TransformEvent::CameraDidChange(momentum_change(CameraChangeMode::Immediate)));
2053 }
2054 return;
2055 }
2056
2057 let fields = moving | settling;
2058 let transition = Transition {
2059 momentum: Some(momentum),
2060 gesture,
2061 command: self.reporting(),
2062 ..Transition::new(
2063 fields,
2064 moving,
2065 start,
2066 motion,
2067 animation,
2068 Box::new(|_, _| CameraOptions::default()),
2069 CameraChangeSource::Momentum,
2070 )
2071 };
2072 let finished = self.release_fields(fields);
2073 self.transitions.push(transition);
2074 self.update_movement_flags();
2075 self.finish_transitions(finished);
2076 self.emit(TransformEvent::CameraWillChange(momentum_change(CameraChangeMode::Animated)));
2077 }
2078
2079 fn with_source<R>(&mut self, source: CameraChangeSource, start: impl FnOnce(&mut Self) -> R) -> R {
2081 let previous = std::mem::replace(&mut self.source, source);
2082 let result = start(self);
2083 self.source = previous;
2084 result
2085 }
2086
2087 fn step_scalar(&mut self, part: usize, amount: f64, anchor: Option<ScreenCoordinate>) -> bool {
2089 match part {
2090 MOMENTUM_ZOOM => self.step_zoom(amount, anchor),
2091 MOMENTUM_BEARING => {
2092 self.step_bearing(amount, anchor);
2093 true
2094 }
2095 _ => self.step_pitch(amount, anchor),
2096 }
2097 }
2098
2099 fn advance_momentum(&mut self, index: usize, now: Option<Instant>) {
2102 let transition = &mut self.transitions[index];
2103 let Some(mut momentum) = transition.momentum.take() else { return };
2104 let elapsed = transition.elapsed(now);
2105 let (mut duration, mut moving_fields) = (transition.duration, transition.moving_fields);
2106 momentum.elapsed = elapsed;
2107
2108 let advance = |part: &mut MomentumPart| -> f64 {
2109 if !part.moving {
2110 return 0.0;
2111 }
2112 let progress = part.glide.progress(elapsed);
2113 let fraction = progress - part.applied;
2114 part.applied = progress;
2115 if progress >= 1.0 {
2116 part.moving = false;
2117 }
2118 fraction
2119 };
2120 let fraction = advance(&mut momentum.pan);
2122 if fraction != 0.0 {
2123 let total = momentum.pan_total;
2124 if !self.step_pan(ScreenCoordinate::new(total.x * fraction, total.y * fraction)) {
2125 momentum.pan.moving = false;
2126 }
2127 }
2128 for i in 0..momentum.scalars.len() {
2129 let anchor = momentum.anchor(i);
2130 let total = momentum.scalar_totals[i];
2131 let part = &mut momentum.scalars[i];
2132 let fraction = advance(part);
2133 if fraction != 0.0 && !self.step_scalar(i, total * fraction, anchor) {
2134 part.moving = false;
2135 }
2136 if part.snap_pending && !part.moving {
2139 part.snap_pending = false;
2140 let snap = part.snap.unwrap_or_default();
2141 let delta = snap_delta(momentum_value(&self.state, i), &snap, i == MOMENTUM_BEARING);
2142 if delta != 0.0 {
2143 part.snap_delta = Some(delta);
2144 part.snap_start = elapsed;
2145 duration = duration.max(elapsed.saturating_add(snap.duration));
2146 moving_fields |= part.fields;
2147 }
2148 }
2149 if let Some(delta) = part.snap_delta {
2150 let duration = part.snap.unwrap_or_default().duration;
2151 let t = if duration.is_zero() || now.is_none() {
2153 1.0
2154 } else {
2155 mln_math::clamp_f64(elapsed.saturating_sub(part.snap_start).div_duration_f64(duration), 0.0, 1.0)
2156 };
2157 let eased = if t >= 1.0 { 1.0 } else { DEFAULT_TRANSITION_EASE.solve(t, 0.001) };
2158 let fraction = eased - part.snap_applied;
2159 part.snap_applied = eased;
2160 let moved = fraction == 0.0 || self.step_scalar(i, delta * fraction, anchor);
2161 if t >= 1.0 || !moved {
2162 part.snap_delta = None;
2163 }
2164 }
2165 }
2166
2167 let transition = &mut self.transitions[index];
2169 transition.duration = duration;
2170 transition.moving_fields = moving_fields;
2171 transition.fields = momentum.retain(transition.fields);
2172 transition.momentum = Some(momentum);
2173 }
2174
2175 fn momentum_anchor(&self, anchor: Option<ScreenCoordinate>) -> Option<(ScreenCoordinate, LatLng)> {
2180 let anchor = anchor?;
2181 let point = ScreenCoordinate::new(anchor.x, f64::from(self.state.get_size().height) - anchor.y);
2182 match self.state.screen_coordinate_to_lat_lng(&point, WrapMode::Unwrapped) {
2183 Ok(lat_lng) => Some((point, lat_lng)),
2184 Err(e) => {
2185 Log::error(Event::General, &e.message);
2186 None
2187 }
2188 }
2189 }
2190
2191 fn hold_momentum_anchor(&mut self, anchor: Option<(ScreenCoordinate, LatLng)>) {
2194 let Some((point, lat_lng)) = anchor else { return };
2195 let altitude = self.state.get_center_altitude();
2196 if let Err(e) = self.state.move_lat_lng(&lat_lng, &point) {
2197 Log::error(Event::General, &e.message);
2198 }
2199 self.state.set_center_altitude(altitude);
2200 }
2201
2202 fn step_pan(&mut self, offset: ScreenCoordinate) -> bool {
2206 const MAX_STEP: f64 = 16.0;
2211 const MAX_STEPS: f64 = 100.0;
2212 let distance = offset.x.hypot(offset.y);
2213 if distance.is_nan() || distance <= 0.0 {
2214 return true;
2215 }
2216 let before = self.get_lat_lng(WrapMode::Unwrapped);
2217 let altitude = self.state.get_center_altitude();
2218 let steps = f64::min((distance / MAX_STEP).ceil(), MAX_STEPS);
2219 let step = ScreenCoordinate::new(offset.x / steps, offset.y / steps);
2220 let bounded = self.state.get_lat_lng_bounds() != LatLngBounds::default();
2221 for _ in 0..steps as u32 {
2222 if self.globe_on_screen() {
2223 self.step_globe_pan(&step);
2224 continue;
2225 }
2226 let size = self.state.get_size();
2227 let center = self.state.get_edge_insets().get_center(size.width as u16, size.height as u16);
2228 let point = ScreenCoordinate::new(center.x - step.x, center.y - step.y);
2229 let unwrapped = match self.screen_coordinate_to_lat_lng(&point, WrapMode::Unwrapped) {
2232 Ok(lat_lng) => lat_lng,
2233 Err(e) => {
2234 Log::error(Event::General, &e.message);
2235 break;
2236 }
2237 };
2238 let mut camera = CameraOptions {
2239 center: Some(if bounded { unwrapped } else { unwrapped.wrapped() }),
2240 ..Default::default()
2241 };
2242 let mut zoom = self.state.get_zoom();
2243 self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut zoom);
2244 self.state.set_lat_lng_zoom(&camera.center.unwrap_or(unwrapped), zoom);
2245 }
2246 self.state.set_center_altitude(altitude);
2247 self.get_lat_lng(WrapMode::Unwrapped) != before
2248 }
2249
2250 fn step_globe_pan(&mut self, step: &ScreenCoordinate) {
2255 let size = self.state.get_size();
2256 let view_center = self.state.get_edge_insets().get_center(size.width as u16, size.height as u16);
2257 let grab = ScreenCoordinate::new(view_center.x, f64::from(size.height) - view_center.y);
2258 let pan_delta = ScreenCoordinate::new(step.x, -step.y);
2259 let (center, bearing) = if self.globe_free_bearing {
2260 let drag = VerticalPerspectiveProjection::drag_camera(&self.state, &grab, &pan_delta);
2261 (drag.center, Some(drag.bearing))
2262 } else {
2263 (VerticalPerspectiveProjection::drag_center(&self.state, &grab, &pan_delta), None)
2264 };
2265 let center = self.state.constrained_center(¢er, self.get_zoom());
2266 let zoom = self.get_zoom()
2267 + VerticalPerspectiveProjection::zoom_adjustment(
2268 self.get_lat_lng(WrapMode::Wrapped).latitude(),
2269 center.latitude(),
2270 );
2271 if let Some(bearing) = bearing {
2272 self.state.set_bearing(mln_math::deg2rad(-bearing));
2273 }
2274 self.state.set_lat_lng_zoom(¢er, zoom);
2275 }
2276
2277 fn step_zoom(&mut self, zoom: f64, anchor: Option<ScreenCoordinate>) -> bool {
2278 let before = self.state.get_zoom();
2279 let altitude = self.state.get_center_altitude();
2280 let anchor = self.momentum_anchor(anchor);
2281 let center = self.get_lat_lng(WrapMode::Unwrapped);
2282 let mut target = mln_math::clamp_f64(
2283 before + zoom,
2284 self.state.get_min_zoom_at_latitude(center.latitude()),
2285 self.state.get_max_zoom(),
2286 );
2287 let mut camera = CameraOptions { center: Some(center), ..Default::default() };
2288 self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut target);
2289 self.state.set_lat_lng_zoom(&camera.center.unwrap_or(center), target);
2290 self.state.set_center_altitude(altitude);
2294 match anchor {
2295 Some((point, lat_lng)) if self.globe_on_screen() && self.state.get_zoom() != before => {
2298 let zoom_delta = self.state.get_zoom() - before;
2299 VerticalPerspectiveProjection::zoom_around_point(
2300 &mut self.state,
2301 &point,
2302 &lat_lng,
2303 zoom_delta,
2304 self.globe_free_bearing,
2305 );
2306 }
2307 _ => self.hold_momentum_anchor(anchor),
2308 }
2309 self.state.get_zoom() != before
2310 }
2311
2312 fn step_bearing(&mut self, bearing: f64, anchor: Option<ScreenCoordinate>) {
2313 let anchor = self.momentum_anchor(anchor);
2314 self.state.set_bearing(mln_math::wrap(self.state.get_bearing() - mln_math::deg2rad(bearing), -PI, PI));
2315 self.hold_momentum_anchor(anchor);
2316 }
2317
2318 fn step_pitch(&mut self, pitch: f64, anchor: Option<ScreenCoordinate>) -> bool {
2319 let anchor = self.momentum_anchor(anchor);
2320 let before = self.state.get_pitch();
2321 let max_pitch = get_max_pitch_for_edge_insets(&self.state, &self.state.get_edge_insets());
2322 self.state.set_pitch(mln_math::clamp_f64(
2323 before + mln_math::deg2rad(pitch),
2324 self.state.get_min_pitch(),
2325 max_pitch,
2326 ));
2327 if self.state.get_pitch() == before {
2328 return false;
2329 }
2330 self.hold_momentum_anchor(anchor);
2331 true
2332 }
2333
2334 pub fn set_frame_time(&mut self, time: Option<Instant>) {
2346 self.frame_time.set(time);
2347 }
2348
2349 pub(crate) fn frame_clock(&self) -> FrameClock {
2351 self.frame_time.clone()
2352 }
2353
2354 pub(crate) fn frame_time(&self) -> Option<Instant> {
2360 self.fresh_frame_time(Instant::now())
2361 }
2362
2363 fn fresh_frame_time(&self, now: Instant) -> Option<Instant> {
2364 self.frame_time.get().filter(|&time| now.saturating_duration_since(time) <= STALE_FRAME_TIME)
2365 }
2366
2367 fn now(&self) -> Instant {
2369 let now = Instant::now();
2370 self.fresh_frame_time(now).unwrap_or(now)
2371 }
2372
2373 pub(crate) fn cancel_transitions(&mut self) {
2374 let mut finished = std::mem::take(&mut self.transitions);
2375 for transition in &mut finished {
2376 transition.ended_by(TransitionOutcome::Cancelled);
2377 }
2378 self.update_movement_flags();
2379 self.finish_transitions(finished);
2380 }
2381
2382 pub fn cancel_transitions_with_id(&mut self, transition_id: u64) -> bool {
2386 let mut finished: Vec<_> = self
2387 .transitions
2388 .extract_if(.., |transition| transition.animation.transition_id == Some(transition_id))
2389 .collect();
2390 if finished.is_empty() {
2391 return false;
2392 }
2393 for transition in &mut finished {
2394 transition.ended_by(TransitionOutcome::Cancelled);
2395 }
2396 self.update_movement_flags();
2397 self.finish_transitions(finished);
2398 true
2399 }
2400
2401 pub fn close(&mut self) {
2405 for transition in std::mem::take(&mut self.transitions) {
2406 let end = TransitionEnd { outcome: TransitionOutcome::Closed, ..transition.end() };
2407 self.report_end(transition.command, transition.animation.transition_id, end);
2408 }
2409 self.update_movement_flags();
2410 }
2411
2412 pub fn apply_camera_delta(&mut self, delta: &CameraDelta) -> Result<CameraCommandId, CameraError> {
2418 delta.validate()?;
2419 Ok(self.command(|transform| transform.apply_camera_delta_now(delta)))
2420 }
2421
2422 fn apply_camera_delta_now(&mut self, delta: &CameraDelta) {
2423 let source = gesture_source(delta.phase);
2424 let pans = delta.offset.is_some();
2425 let eases = delta.scale.is_some() || delta.bearing.is_some() || delta.pitch.is_some();
2426 let parts = match delta.momentum {
2430 Some(_) => AnimationOptions::default(),
2431 None => delta.animation,
2432 };
2433 self.silent = delta.momentum.is_some();
2434 self.join_ends(u32::from(pans) + u32::from(eases));
2435 self.gesture_phase_before(delta.phase);
2436 if delta.phase != GesturePhase::None {
2437 self.gesture.change(
2438 delta.scale.is_some_and(|scale| scale != 1.0),
2439 delta.bearing.is_some_and(|bearing| bearing != 0.0),
2440 delta.pitch.is_some_and(|pitch| pitch != 0.0),
2441 );
2442 }
2443 self.with_source(source, |transform| {
2444 if let Some(offset) = delta.offset {
2445 let _ = transform.move_by_with_anchor(&offset, delta.anchor, &parts);
2449 }
2450 if eases {
2451 let current = transform.get_camera_options(None);
2452 let target = CameraOptions {
2453 zoom: delta.scale.map(|scale| current.zoom.unwrap_or(0.0) + scale.log2()),
2454 bearing: delta.bearing.map(|bearing| current.bearing.unwrap_or(0.0) + bearing),
2455 pitch: delta.pitch.map(|pitch| current.pitch.unwrap_or(0.0) + pitch),
2456 anchor: delta.anchor,
2457 ..CameraOptions::default()
2458 };
2459 transform.ease_to(&target, &parts);
2460 }
2461 });
2462 self.silent = false;
2463 match delta.momentum {
2464 Some(mut momentum) => {
2465 self.gesture.mask_snaps(&mut momentum);
2466 self.gesture.active = false;
2470 let serial = self.gesture.serial;
2471 self.with_source(CameraChangeSource::Momentum, |transform| {
2472 transform.start_momentum_now(&momentum, &delta.animation, Some(serial));
2473 });
2474 }
2475 None if !pans && !eases => self.end_unstarted(&delta.animation, TransitionOutcome::Completed),
2476 None => {}
2477 }
2478 self.gesture_phase_after(delta.phase, delta.momentum.is_some());
2479 }
2480
2481 pub fn update_camera(&mut self, update: &CameraUpdate) -> CameraCommandId {
2484 self.command(|transform| transform.update_camera_now(update))
2485 }
2486
2487 fn update_camera_now(&mut self, update: &CameraUpdate) {
2488 self.gesture_phase_before(update.phase);
2489 if update.phase != GesturePhase::None {
2490 let current = self.get_camera_options(None);
2492 let changes = |value: Option<f64>, now: Option<f64>| value.is_some() && value != now;
2493 self.gesture.change(
2494 changes(update.camera.zoom, current.zoom),
2495 changes(update.camera.bearing, current.bearing),
2496 changes(update.camera.pitch, current.pitch),
2497 );
2498 }
2499 self.with_source(gesture_source(update.phase), |transform| match update.mode {
2500 CameraUpdateMode::Jump => {
2501 transform.ease(&update.camera, &AnimationOptions { duration: None, ..update.animation });
2502 }
2503 CameraUpdateMode::Ease => transform.ease(&update.camera, &update.animation),
2504 CameraUpdateMode::Fly => transform.fly(&update.camera, &update.animation, false),
2505 });
2506 self.gesture_phase_after(update.phase, false);
2507 }
2508
2509 fn gesture_phase_before(&mut self, phase: GesturePhase) {
2515 if phase != GesturePhase::None && (phase == GesturePhase::Begin || !self.gesture.active) {
2516 self.gesture = GestureState { serial: self.gesture.serial.wrapping_add(1), ..GestureState::default() };
2517 }
2518 if phase == GesturePhase::Begin {
2519 self.cancel_transitions();
2520 }
2521 if matches!(phase, GesturePhase::Begin | GesturePhase::Update) {
2522 self.gesture.active = true;
2523 self.set_gesture_in_progress(true);
2524 }
2525 }
2526
2527 fn gesture_phase_after(&mut self, phase: GesturePhase, momentum: bool) {
2531 if phase == GesturePhase::Cancel {
2532 self.cancel_transitions();
2533 }
2534 if matches!(phase, GesturePhase::End | GesturePhase::Cancel) {
2535 self.gesture.active = false;
2536 if !momentum {
2537 self.set_gesture_in_progress(false);
2538 }
2539 }
2540 }
2541
2542 fn end_gesture_momentum(&mut self, gesture: Option<u64>) {
2545 if gesture == Some(self.gesture.serial) && !self.gesture.active {
2546 self.set_gesture_in_progress(false);
2547 }
2548 }
2549
2550 pub(crate) fn set_gesture_in_progress(&mut self, in_progress: bool) {
2551 self.state.set_gesture_in_progress(in_progress);
2552 }
2553
2554 pub fn is_gesture_in_progress(&self) -> bool {
2555 self.state.is_gesture_in_progress()
2556 }
2557
2558 pub fn get_state(&self) -> &TransformState {
2561 &self.state
2562 }
2563
2564 #[cfg(test)]
2565 pub(crate) fn is_rotating(&self) -> bool {
2566 self.state.is_rotating()
2567 }
2568
2569 #[cfg(test)]
2570 pub(crate) fn is_scaling(&self) -> bool {
2571 self.state.is_scaling()
2572 }
2573
2574 #[cfg(test)]
2575 pub(crate) fn is_panning(&self) -> bool {
2576 self.state.is_panning()
2577 }
2578
2579 pub fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
2582 let mut point = self.state.lat_lng_to_screen_coordinate(lat_lng);
2583 point.y = f64::from(self.state.get_size().height) - point.y;
2584 point
2585 }
2586
2587 pub fn screen_coordinate_to_lat_lng(&self, point: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
2591 let mut flipped_point = *point;
2592 flipped_point.y = f64::from(self.state.get_size().height) - flipped_point.y;
2593 self.state.screen_coordinate_to_lat_lng(&flipped_point, wrap_mode)
2594 }
2595
2596 #[cfg(test)]
2597 pub(crate) fn get_free_camera_options(&self) -> FreeCameraOptions {
2598 self.state.get_free_camera_options()
2599 }
2600
2601 pub(crate) fn set_free_camera_options(&mut self, options: &FreeCameraOptions) {
2602 self.cancel_transitions();
2603 self.state.set_free_camera_options(options);
2604 }
2605}
2606
2607fn gesture_source(phase: GesturePhase) -> CameraChangeSource {
2608 if phase == GesturePhase::None { CameraChangeSource::Command } else { CameraChangeSource::Gesture }
2609}
2610
2611fn interpolate_edge_insets(start: &EdgeInsets, end: &EdgeInsets, t: f64) -> Option<EdgeInsets> {
2616 if start == end {
2617 return Some(*end);
2618 }
2619 frame_edge_insets(
2620 interpolate(&start.top, &end.top, t),
2621 interpolate(&start.left, &end.left, t),
2622 interpolate(&start.bottom, &end.bottom, t),
2623 interpolate(&start.right, &end.right, t),
2624 )
2625}
2626
2627fn get_max_pitch_for_edge_insets(state: &TransformState, insets: &EdgeInsets) -> f64 {
2631 let center_offset_y = 0.5 * (insets.top - insets.bottom);
2633 if center_offset_y == 0.0 {
2634 return state.get_max_pitch();
2635 }
2636
2637 let height = state.get_size().height;
2638 debug_assert!(height != 0);
2639 let field_of_view = f64::from(state.get_field_of_view());
2640 let tangent_of_fov_above_center_angle =
2642 (0.5 + center_offset_y / f64::from(height)) * 2.0 * (field_of_view / 2.0).tan();
2643 let fov_above_center = tangent_of_fov_above_center_angle.atan();
2644 f64::max(state.get_min_pitch(), state.get_max_pitch() + field_of_view / 2.0 - fov_above_center)
2645}
2646
2647#[cfg(test)]
2648#[path = "transform_test.rs"]
2649mod transform_test;