1use std::f64::consts::PI;
13use std::rc::Rc;
14use std::sync::Arc;
15use std::time::Duration;
16
17use geometry::Point;
18use mln_style::crs::WorldMapping;
19use mln_style::error::Error;
20use mln_style::geo::{LatLng, WrapMode};
21use mln_style::size::Size;
22use mln_style::time::Instant;
23use mln_style::types::ProjectionDefinition;
24use parking_lot::Mutex;
25
26use crate::camera::{
27 AnimationOptions, CameraLimits, CameraOptions, CenterAndBearing, ConstrainMode, FreeCameraOptions,
28 NorthOrientation, ProjectionMode, TransformState, TransitionEnd, VerticalPerspectiveProjection, View,
29 ViewProjection,
30};
31use crate::geo::constants::M2PI;
32use crate::geo::{EdgeInsets, ScreenCoordinate};
33use crate::log_target;
34
35mod anchor;
36mod animation;
37mod gesture;
38mod momentum;
39mod terrain;
40mod transition;
41
42use gesture::GestureState;
43pub(crate) use terrain::{TerrainGround, lowest_ground};
44use transition::{FrameFn, JointEnd, Transition};
45
46use crate::map::events::{CameraChange, CameraChangeSource};
47
48pub(crate) const STALE_FRAME_TIME: Duration = Duration::from_millis(100);
52
53fn normalize_angle(mut angle: f64, anchor_angle: f64) -> f64 {
57 if angle.is_nan() || anchor_angle.is_nan() {
58 return 0.0;
59 }
60
61 angle = mln_style::math::wrap(angle, -PI, PI);
62 if angle == -PI {
63 angle = PI;
64 }
65 let diff = (angle - anchor_angle).abs();
66 if (angle - M2PI - anchor_angle).abs() < diff {
67 angle -= M2PI;
68 }
69 if (angle + M2PI - anchor_angle).abs() < diff {
70 angle += M2PI;
71 }
72
73 angle
74}
75
76fn lat_lng(lat: f64, lon: f64) -> LatLng {
79 LatLng::saturating(lat, lon, WrapMode::Unwrapped)
80}
81
82fn frame_edge_insets(top: f64, left: f64, bottom: f64, right: f64) -> Option<EdgeInsets> {
85 if [top, left, bottom, right].iter().any(|value| value.is_nan()) {
86 tracing::error!(target: log_target::GENERAL, "an animation frame's insets are NaN");
87 return None;
88 }
89 Some(EdgeInsets::new(top, left, bottom, right))
90}
91
92fn frame_unproject(world: &WorldMapping, p: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Option<LatLng> {
96 world.unproject(p, scale, wrap_mode).map_err(|e| {
97 tracing::error!(target: log_target::GENERAL, error = %e.message, "An animation frame's point has no location");
98 })
99 .ok()
100}
101
102#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
106pub struct CameraCommandId(u64);
107
108#[derive(Clone, Copy, Debug, PartialEq)]
110pub struct CommandEnd {
111 pub command: CameraCommandId,
112 pub(crate) transition_id: Option<u64>,
114 pub end: TransitionEnd,
115}
116
117#[derive(Clone, Copy, Debug, PartialEq)]
120pub(crate) enum TransformEvent {
121 CameraWillChange(CameraChange),
122 CameraIsChanging,
123 CameraDidChange(CameraChange),
124 CommandEnded(CommandEnd),
128}
129
130pub(crate) type ProjectionForZoomFn = Rc<dyn Fn(f64) -> ProjectionDefinition>;
131
132const CENTER: u16 = 1 << 0;
134const ZOOM: u16 = 1 << 1;
135const BEARING: u16 = 1 << 2;
136const PITCH: u16 = 1 << 3;
137const PADDING: u16 = 1 << 4;
138const ALTITUDE: u16 = 1 << 5;
139const ROLL: u16 = 1 << 6;
140const FOV: u16 = 1 << 7;
141
142fn camera_fields(camera: &CameraOptions) -> u16 {
144 let field = |set: bool, field: u16| if set { field } else { 0 };
145 field(camera.center.is_some(), CENTER)
146 | field(camera.zoom.is_some(), ZOOM)
147 | field(camera.bearing.is_some(), BEARING)
148 | field(camera.pitch.is_some(), PITCH)
149 | field(camera.padding.is_some(), PADDING)
150 | field(camera.center_altitude.is_some(), ALTITUDE)
151 | field(camera.roll.is_some(), ROLL)
152 | field(camera.fov.is_some(), FOV)
153}
154
155#[derive(Clone, Debug, Default)]
161pub struct FrameClock(Arc<Mutex<ClockTime>>);
162
163#[derive(Clone, Copy, Debug, Default)]
164enum ClockTime {
165 #[default]
166 Unset,
167 Frame(Instant),
168 Held(Instant),
169}
170
171impl FrameClock {
172 pub fn set(&self, time: Option<Instant>) {
175 let mut clock = self.0.lock();
176 if !matches!(*clock, ClockTime::Held(_)) {
177 *clock = time.map_or(ClockTime::Unset, ClockTime::Frame);
178 }
179 }
180
181 pub fn hold(&self, time: Option<Instant>) {
187 *self.0.lock() = time.map_or(ClockTime::Unset, ClockTime::Held);
188 }
189
190 #[must_use]
192 pub fn get(&self) -> Option<Instant> {
193 match *self.0.lock() {
194 ClockTime::Unset => None,
195 ClockTime::Frame(time) | ClockTime::Held(time) => Some(time),
196 }
197 }
198
199 #[must_use]
201 pub fn held(&self) -> Option<Instant> {
202 match *self.0.lock() {
203 ClockTime::Held(time) => Some(time),
204 _ => None,
205 }
206 }
207}
208
209pub struct Transform {
210 state: TransformState,
211
212 transitions: Vec<Transition>,
213 events: Vec<TransformEvent>,
215 command: Option<CameraCommandId>,
218 silent: bool,
221 next_command: u64,
222 joint_ends: Vec<JointEnd>,
225 source: CameraChangeSource,
228 gesture: GestureState,
229 gesture_in_progress: bool,
233 moving: u16,
236 frame_time: FrameClock,
238 projection_for_zoom: Option<ProjectionForZoomFn>,
239 globe_drag_hold: Option<GlobeDragHold>,
240 terrain: Option<TerrainGround>,
242 last_frame: Option<Instant>,
246}
247
248#[derive(Clone, Copy, Debug)]
253struct GlobeDragHold {
254 location: LatLng,
255 height: f64,
257 cursor: ScreenCoordinate,
258 camera: CameraOptions,
259 size: Size,
260}
261
262impl Transform {
263 #[must_use]
264 pub fn new(constrain_mode: ConstrainMode) -> Self {
265 Self::from_state(TransformState::new(constrain_mode))
266 }
267
268 pub(crate) fn from_state(state: TransformState) -> Self {
269 Transform {
270 state,
271 transitions: Vec::new(),
272 events: Vec::new(),
273 command: None,
274 silent: false,
275 next_command: 0,
276 joint_ends: Vec::new(),
277 source: CameraChangeSource::Command,
278 gesture: GestureState::default(),
279 gesture_in_progress: false,
280 moving: 0,
281 frame_time: FrameClock::default(),
282 projection_for_zoom: None,
283 globe_drag_hold: None,
284 terrain: None,
285 last_frame: None,
286 }
287 }
288
289 pub(crate) fn drain_events(&mut self) -> std::vec::Drain<'_, TransformEvent> {
292 self.events.drain(..)
293 }
294
295 fn emit(&mut self, event: TransformEvent) {
296 self.events.push(event);
297 }
298
299 pub fn resize(&mut self, size: Size) -> Result<(), Error> {
302 if size.is_empty() {
303 return Err(Error::invalid_argument("failed to resize: size is empty"));
304 }
305
306 if self.state.view().size() == size {
307 return Ok(());
308 }
309
310 self.emit(TransformEvent::CameraWillChange(CameraChange::default()));
311 self.state.set_size(size);
312 let (scale, center) = self.state.constrain_screen(self.state.view().scale());
313 if let Some(center) = center {
314 if self.in_transition() {
319 self.cancel_transitions();
320 }
321
322 let zoom = crate::camera::scale_zoom(scale);
325 self.state.set_lat_lng_zoom(¢er, zoom);
326 self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
327
328 return Ok(());
329 }
330 self.state.constrain_position(scale);
331
332 self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
333 Ok(())
334 }
335
336 #[must_use]
340 pub(crate) fn camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
341 self.state.camera_options(padding)
342 }
343
344 pub(crate) fn jump_to(&mut self, camera: &CameraOptions) -> CameraCommandId {
347 self.command(|transform| transform.jump(camera))
348 }
349
350 fn jump(&mut self, camera: &CameraOptions) {
351 if self.state.view().is_globe()
356 && let Some(center) = camera.center
357 && camera.zoom.is_none()
358 {
359 let zoom = self.view().zoom()
360 + VerticalPerspectiveProjection::zoom_adjustment(
361 self.view().center(WrapMode::Wrapped).latitude(),
362 center.latitude(),
363 );
364 self.ease_to(&CameraOptions { zoom: Some(zoom), ..*camera }, &AnimationOptions::default());
365 return;
366 }
367 self.ease_to(camera, &AnimationOptions::default());
368 }
369
370 fn globe_on_screen(&self) -> bool {
375 self.state.view().is_globe() && !self.state.view().size().is_empty()
376 }
377
378 #[cfg(test)]
382 pub(crate) fn move_by(
383 &mut self,
384 offset: &ScreenCoordinate,
385 animation: &AnimationOptions,
386 ) -> Result<CameraCommandId, Error> {
387 self.move_by_with_anchor(offset, None, animation)
388 }
389
390 pub(crate) fn move_by_with_anchor(
403 &mut self,
404 offset: &ScreenCoordinate,
405 anchor: Option<ScreenCoordinate>,
406 animation: &AnimationOptions,
407 ) -> Result<CameraCommandId, Error> {
408 let mut moved = Ok(());
409 let command = self.command(|transform| moved = transform.move_by_now(offset, anchor, animation));
410 moved.map(|()| command)
411 }
412
413 fn move_by_now(
414 &mut self,
415 offset: &ScreenCoordinate,
416 anchor: Option<ScreenCoordinate>,
417 animation: &AnimationOptions,
418 ) -> Result<(), Error> {
419 let flipped = |state: &TransformState, point: &ScreenCoordinate| {
420 ScreenCoordinate::new(point.x, f64::from(state.view().size().height) - point.y)
421 };
422 let size = self.state.view().size();
423 let view_center = self.state.view().padding().center_in(size);
424 let fling_duration = animation.duration.filter(|duration| *duration > Duration::ZERO);
425 let globe = self.globe_on_screen();
426 if globe && (offset.x.is_nan() || offset.y.is_nan()) {
427 return Err(Error::invalid_argument("offset must not be NaN"));
428 }
429 if globe && (!offset.x.is_finite() || !offset.y.is_finite()) {
430 return Err(Error::invalid_argument("offset must not be infinite"));
431 }
432 if globe
433 && let Some(duration) = fling_duration
434 && self.state.view().globe_free_bearing()
435 {
436 let start = CenterAndBearing {
440 center: self.view().center(WrapMode::Unwrapped),
441 bearing: -mln_style::math::rad2deg(self.view().angle()),
442 };
443 let end = VerticalPerspectiveProjection::fling_camera(
444 self.state.view(),
445 &flipped(&self.state, &view_center),
446 &ScreenCoordinate::new(offset.x, -offset.y),
447 );
448 let start_zoom = self.view().zoom();
449 let frame: FrameFn = Box::new(move |state: &TransformState, t: f64| {
450 let camera = VerticalPerspectiveProjection::interpolate_camera(&start, &end, t);
451 let center = state.constrained_center(&camera.center, state.view().zoom());
452 CameraOptions {
453 center: Some(center),
454 zoom: Some(
455 start_zoom
456 + VerticalPerspectiveProjection::zoom_adjustment(
457 start.center.latitude(),
458 center.latitude(),
459 ),
460 ),
461 bearing: Some(camera.bearing),
462 ..Default::default()
463 }
464 });
465 let fields = CameraOptions {
468 center: Some(end.center),
469 zoom: Some(start_zoom),
470 bearing: Some(end.bearing),
471 ..Default::default()
472 };
473 self.start_transition(&fields, animation, frame, None, duration, false);
474 return Ok(());
475 }
476
477 if globe && fling_duration.is_some() {
478 let mut center = self.state.constrained_center(
483 &VerticalPerspectiveProjection::pan_center(self.state.view(), offset),
484 self.view().zoom(),
485 );
486 let longitude = self.view().center(WrapMode::Unwrapped).longitude();
487 if (center.longitude() - longitude).abs() > 180.0 {
488 center = lat_lng(center.latitude(), longitude + 179.5f64.copysign(center.longitude() - longitude));
489 }
490 self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
491 return Ok(());
492 }
493
494 if globe {
495 let from = anchor.map(|anchor| ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y));
513 let held = self.globe_drag_hold.take().filter(|held| {
514 from.is_some_and(|from| (held.cursor.x - from.x).hypot(held.cursor.y - from.y) < 1e-3)
515 && !self.state.view().globe_free_bearing()
516 && held.size == size
517 && held.camera == self.camera_options(None)
518 });
519 let height = match (held, anchor.zip(from)) {
520 (Some(held), _) => held.height,
521 (None, Some((anchor, from))) => self.anchor_height(&from, &anchor),
522 (None, None) => self.view().center_altitude(),
523 };
524 let on_globe = |state: &TransformState, point: &ScreenCoordinate| {
525 VerticalPerspectiveProjection::screen_coordinate_hits_globe(
526 state.view(),
527 &flipped(state, point),
528 height,
529 )
530 };
531 let grab = match anchor {
532 Some(anchor) if on_globe(&self.state, &anchor) => anchor,
533 _ => view_center,
534 };
535 let pan_delta = ScreenCoordinate::new(offset.x, -offset.y);
536 let mut camera = CameraOptions::default();
537 let hold = match anchor.zip(from) {
538 Some((anchor, from)) if !self.state.view().globe_free_bearing() && on_globe(&self.state, &anchor) => {
539 let location = match held {
540 Some(held) => Some(held.location),
541 None if on_globe(&self.state, &from) => self
542 .state
543 .view()
544 .screen_coordinate_to_lat_lng_at(&flipped(&self.state, &from), height, WrapMode::Unwrapped)
545 .ok(),
546 None => None,
547 };
548 location.and_then(|location| {
549 VerticalPerspectiveProjection::drag_center_holding(
550 self.state.view(),
551 &location,
552 &flipped(&self.state, &anchor),
553 height,
554 )
555 .map(|center| (location, anchor, center))
556 })
557 }
558 _ => None,
559 };
560 let mut center = if let Some((_, _, center)) = hold {
561 center
562 } else if self.state.view().globe_free_bearing() {
563 let drag = VerticalPerspectiveProjection::drag_camera(
564 self.state.view(),
565 &flipped(&self.state, &grab),
566 &pan_delta,
567 height,
568 );
569 camera = CameraOptions { bearing: Some(drag.bearing), ..camera };
570 drag.center
571 } else {
572 VerticalPerspectiveProjection::drag_center(
573 self.state.view(),
574 &flipped(&self.state, &grab),
575 &pan_delta,
576 height,
577 )
578 };
579 center = self.state.constrained_center(¢er, self.view().zoom());
580 let zoom = self.view().zoom()
581 + VerticalPerspectiveProjection::zoom_adjustment(
582 self.view().center(WrapMode::Wrapped).latitude(),
583 center.latitude(),
584 );
585 self.ease_to(&CameraOptions { center: Some(center), zoom: Some(zoom), ..camera }, animation);
586 self.globe_drag_hold = hold.map(|(location, cursor, _)| GlobeDragHold {
587 location,
588 height,
589 cursor,
590 camera: self.camera_options(None),
591 size,
592 });
593 return Ok(());
594 }
595
596 let mut center_offset = *offset;
597
598 let pitch = self.state.view().pitch();
602 let offset_length = offset.x.hypot(offset.y);
603 if pitch > 0.0 && offset_length > 0.0 {
604 let camera_to_center =
605 0.5 * f64::from(self.state.view().size().height) / (self.state.view().fov() / 2.0).tan();
606 let pixels_to_horizon = (camera_to_center / pitch.tan()).abs();
607 let horizon_factor = 0.75;
609 let scale = pixels_to_horizon * horizon_factor / offset_length;
610 if scale < 1.0 {
611 center_offset = ScreenCoordinate::new(offset.x * scale, offset.y * scale);
612 }
613 }
614
615 let size = self.state.view().size();
616 let center = self.state.view().padding().center_in(size);
617 let point_on_screen = ScreenCoordinate::new(center.x - center_offset.x, center.y - center_offset.y);
618 let anchored = anchor.and_then(|anchor| {
622 let grabbed = ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y);
623 Some((grabbed, anchor, self.anchor_plane(&grabbed, &anchor)?))
624 });
625 let (from, to, height) = anchored.unwrap_or((point_on_screen, center, self.view().center_altitude()));
626 let center = self.center_moving_on_plane(&from, &to, height)?;
627 self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
628 Ok(())
629 }
630
631 pub(crate) fn set_limits(&mut self, limits: CameraLimits) -> Result<(), Error> {
636 self.state.set_limits(limits)
637 }
638
639 pub(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
640 self.state.set_frustum_offset(frustum_offset);
641 }
642
643 pub(crate) fn set_projection(&mut self, projection: ViewProjection) {
647 self.state.set_projection(projection);
648 }
649
650 pub(crate) fn set_projection_for_zoom(&mut self, projection_for_zoom: Option<ProjectionForZoomFn>) {
653 self.projection_for_zoom = projection_for_zoom;
654 }
655
656 pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
657 self.state.set_globe_free_bearing(free_bearing);
658 }
659
660 pub(crate) fn is_globe_free_bearing(&self) -> bool {
661 self.state.view().globe_free_bearing()
662 }
663
664 #[cfg(test)]
665 pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
666 self.state.view().is_location_occluded(lat_lng)
667 }
668
669 pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
672 self.state.set_north_orientation(orientation);
673 self.state.constrain_position(self.state.view().scale());
674 }
675
676 pub(crate) fn set_constrain_mode(&mut self, mode: ConstrainMode) {
679 self.state.set_constrain_mode(mode);
680 self.state.constrain_position(self.state.view().scale());
681 }
682
683 pub(crate) fn set_center_clamped_to_ground(&mut self, clamped: bool) {
686 self.state.set_center_clamped_to_ground(clamped);
687 }
688
689 pub(crate) fn set_projection_mode(&mut self, options: &ProjectionMode) {
692 if let Some(x_skew) = options.x_skew {
693 self.state.set_x_skew(x_skew);
694 }
695 if let Some(y_skew) = options.y_skew {
696 self.state.set_y_skew(y_skew);
697 }
698 if let Some(axonometric) = options.axonometric {
699 self.state.set_axonometric(axonometric.as_bool());
700 }
701 }
702
703 pub(crate) fn set_frame_time(&mut self, time: Option<Instant>) {
717 self.frame_time.set(time);
718 }
719
720 pub(crate) fn frame_clock(&self) -> FrameClock {
722 self.frame_time.clone()
723 }
724
725 pub(crate) fn frame_time(&self) -> Option<Instant> {
731 self.fresh_frame_time(Instant::now())
732 }
733
734 fn fresh_frame_time(&self, now: Instant) -> Option<Instant> {
735 match *self.frame_time.0.lock() {
736 ClockTime::Held(time) => Some(time),
737 ClockTime::Frame(time) => (now.saturating_duration_since(time) <= STALE_FRAME_TIME).then_some(time),
738 ClockTime::Unset => None,
739 }
740 }
741
742 fn now(&self) -> Instant {
744 let now = Instant::now();
745 self.fresh_frame_time(now).unwrap_or(now)
746 }
747
748 pub(crate) fn clock_now(&self) -> Instant {
751 self.frame_time.held().unwrap_or_else(Instant::now)
752 }
753
754 #[must_use]
757 pub(crate) fn is_camera_moving(&self) -> bool {
758 self.gesture_in_progress || self.moving & (CENTER | ZOOM | BEARING) != 0
759 }
760
761 #[must_use]
764 pub(crate) fn state(&self) -> &TransformState {
765 &self.state
766 }
767
768 #[must_use]
770 pub fn view(&self) -> &View {
771 self.state.view()
772 }
773
774 #[cfg(test)]
775 pub(crate) fn is_rotating(&self) -> bool {
776 self.moving & BEARING != 0
777 }
778
779 #[cfg(test)]
780 pub(crate) fn is_scaling(&self) -> bool {
781 self.moving & ZOOM != 0
782 }
783
784 #[cfg(test)]
785 pub(crate) fn is_panning(&self) -> bool {
786 self.moving & CENTER != 0
787 }
788
789 #[must_use]
792 pub(crate) fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
793 let mut point = self.state.view().lat_lng_to_screen_coordinate(lat_lng);
794 point.y = f64::from(self.state.view().size().height) - point.y;
795 point
796 }
797
798 pub(crate) fn world_to_screen_coordinate(&self, world: &Point<f64>) -> ScreenCoordinate {
801 let mut point = self.state.view().world_to_screen_coordinate(world);
802 point.y = f64::from(self.state.view().size().height) - point.y;
803 point
804 }
805
806 pub(crate) fn screen_coordinate_to_lat_lng(
810 &self,
811 point: &ScreenCoordinate,
812 wrap_mode: WrapMode,
813 ) -> Result<LatLng, Error> {
814 let mut flipped_point = *point;
815 flipped_point.y = f64::from(self.state.view().size().height) - flipped_point.y;
816 self.state.view().screen_coordinate_to_lat_lng(&flipped_point, wrap_mode)
817 }
818
819 pub(crate) fn screen_coordinate_to_lat_lng_at(
824 &self,
825 point: &ScreenCoordinate,
826 height: f64,
827 wrap_mode: WrapMode,
828 ) -> Result<LatLng, Error> {
829 self.view().screen_coordinate_to_lat_lng_at(&flip_y(self.view(), point), height, wrap_mode)
830 }
831
832 pub(crate) fn set_free_camera_options(&mut self, options: &FreeCameraOptions) {
833 self.cancel_transitions();
834 self.state.set_free_camera_options(options);
835 }
836}
837
838pub(crate) fn flip_y(view: &View, point: &ScreenCoordinate) -> ScreenCoordinate {
841 ScreenCoordinate::new(point.x, f64::from(view.size().height) - point.y)
842}
843
844fn nanos_from_secs(seconds: f64) -> Option<Duration> {
848 (seconds >= 0.0 && seconds * 1e9 < u64::MAX as f64).then(|| Duration::from_nanos((seconds * 1e9) as u64))
849}
850
851fn max_pitch_for_padding(state: &TransformState, insets: &EdgeInsets) -> f64 {
854 let center_offset_y = 0.5 * (insets.top - insets.bottom);
856 if center_offset_y == 0.0 {
857 return state.limits().max_pitch;
858 }
859
860 let height = state.view().size().height;
861 debug_assert!(height != 0);
862 let field_of_view = state.view().fov();
863 let tangent_of_fov_above_center_angle =
865 (0.5 + center_offset_y / f64::from(height)) * 2.0 * (field_of_view / 2.0).tan();
866 let fov_above_center = tangent_of_fov_above_center_angle.atan();
867 f64::max(state.limits().min_pitch, state.limits().max_pitch + field_of_view / 2.0 - fov_above_center)
868}
869
870#[cfg(test)]
871#[path = "transform_test.rs"]
872mod transform_test;
873
874#[cfg(test)]
875#[path = "transform_crs_test.rs"]
876mod transform_crs_test;