1use std::f64::consts::PI;
13use std::rc::Rc;
14use std::sync::Arc;
15use std::time::Duration;
16
17use geometry::Point;
18use mln_map_types::{
19 AnimationOptions, CameraLimits, CameraOptions, CenterAndBearing, ConstrainMode, FreeCameraOptions,
20 NorthOrientation, ProjectionMode, TransformState, TransitionEnd, VerticalPerspectiveProjection, View, ViewportMode,
21};
22use mln_style::types::ProjectionDefinition;
23use mln_util::constants::M2PI;
24use mln_util::error::Error;
25use mln_util::geo::{EdgeInsets, LatLng, ScreenCoordinate, WrapMode};
26use mln_util::projection::Projection;
27use mln_util::size::Size;
28use mln_util::time::Instant;
29use parking_lot::Mutex;
30
31use crate::log_target;
32
33mod anchor;
34mod animation;
35mod gesture;
36mod momentum;
37mod terrain;
38mod transition;
39
40use gesture::GestureState;
41pub use terrain::TerrainGround;
42pub(crate) use terrain::lowest_ground;
43use transition::{FrameFn, JointEnd, Transition};
44
45use crate::map_event::{CameraChange, CameraChangeSource};
46
47pub const STALE_FRAME_TIME: Duration = Duration::from_millis(100);
51
52fn normalize_angle(mut angle: f64, anchor_angle: f64) -> f64 {
56 if angle.is_nan() || anchor_angle.is_nan() {
57 return 0.0;
58 }
59
60 angle = mln_math::wrap(angle, -PI, PI);
61 if angle == -PI {
62 angle = PI;
63 }
64 let diff = (angle - anchor_angle).abs();
65 if (angle - M2PI - anchor_angle).abs() < diff {
66 angle -= M2PI;
67 }
68 if (angle + M2PI - anchor_angle).abs() < diff {
69 angle += M2PI;
70 }
71
72 angle
73}
74
75fn lat_lng(lat: f64, lon: f64) -> LatLng {
78 LatLng::saturating(lat, lon, WrapMode::Unwrapped)
79}
80
81fn frame_edge_insets(top: f64, left: f64, bottom: f64, right: f64) -> Option<EdgeInsets> {
84 if [top, left, bottom, right].iter().any(|value| value.is_nan()) {
85 log::error!(target: log_target::GENERAL, "an animation frame's insets are NaN");
86 return None;
87 }
88 Some(EdgeInsets::new(top, left, bottom, right))
89}
90
91fn frame_unproject(p: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Option<LatLng> {
95 Projection::unproject(p, scale, wrap_mode)
96 .map_err(|e| log::error!(target: log_target::GENERAL, "{}", e.message))
97 .ok()
98}
99
100#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
104pub struct CameraCommandId(u64);
105
106#[derive(Clone, Copy, Debug, PartialEq)]
108pub struct CommandEnd {
109 pub command: CameraCommandId,
110 pub transition_id: Option<u64>,
112 pub end: TransitionEnd,
113}
114
115#[derive(Clone, Copy, Debug, PartialEq)]
118pub enum TransformEvent {
119 CameraWillChange(CameraChange),
120 CameraIsChanging,
121 CameraDidChange(CameraChange),
122 CommandEnded(CommandEnd),
126}
127
128pub(crate) type ProjectionForZoomFn = Rc<dyn Fn(f64) -> ProjectionDefinition>;
129
130const CENTER: u16 = 1 << 0;
132const ZOOM: u16 = 1 << 1;
133const BEARING: u16 = 1 << 2;
134const PITCH: u16 = 1 << 3;
135const PADDING: u16 = 1 << 4;
136const ALTITUDE: u16 = 1 << 5;
137const ROLL: u16 = 1 << 6;
138const FOV: u16 = 1 << 7;
139
140fn camera_fields(camera: &CameraOptions) -> u16 {
142 let field = |set: bool, field: u16| if set { field } else { 0 };
143 field(camera.center.is_some(), CENTER)
144 | field(camera.zoom.is_some(), ZOOM)
145 | field(camera.bearing.is_some(), BEARING)
146 | field(camera.pitch.is_some(), PITCH)
147 | field(camera.padding.is_some(), PADDING)
148 | field(camera.center_altitude.is_some(), ALTITUDE)
149 | field(camera.roll.is_some(), ROLL)
150 | field(camera.fov.is_some(), FOV)
151}
152
153#[derive(Clone, Debug, Default)]
158pub struct FrameClock(Arc<Mutex<Option<Instant>>>);
159
160impl FrameClock {
161 pub fn set(&self, time: Option<Instant>) {
162 *self.0.lock() = time;
163 }
164
165 #[must_use]
166 pub fn get(&self) -> Option<Instant> {
167 *self.0.lock()
168 }
169}
170
171pub struct Transform {
172 state: TransformState,
173
174 transitions: Vec<Transition>,
175 events: Vec<TransformEvent>,
177 command: Option<CameraCommandId>,
180 silent: bool,
183 next_command: u64,
184 joint_ends: Vec<JointEnd>,
187 source: CameraChangeSource,
190 gesture: GestureState,
191 gesture_in_progress: bool,
195 moving: u16,
198 frame_time: FrameClock,
200 projection_for_zoom: Option<ProjectionForZoomFn>,
201 globe_drag_hold: Option<GlobeDragHold>,
202 terrain: Option<TerrainGround>,
204 last_frame: Option<Instant>,
208}
209
210#[derive(Clone, Copy, Debug)]
215struct GlobeDragHold {
216 location: LatLng,
217 height: f64,
219 cursor: ScreenCoordinate,
220 camera: CameraOptions,
221 size: Size,
222}
223
224impl Transform {
225 #[must_use]
226 pub fn new(constrain_mode: ConstrainMode, viewport_mode: ViewportMode) -> Self {
227 Self::from_state(TransformState::new(constrain_mode, viewport_mode))
228 }
229
230 pub(crate) fn from_state(state: TransformState) -> Self {
231 Transform {
232 state,
233 transitions: Vec::new(),
234 events: Vec::new(),
235 command: None,
236 silent: false,
237 next_command: 0,
238 joint_ends: Vec::new(),
239 source: CameraChangeSource::Command,
240 gesture: GestureState::default(),
241 gesture_in_progress: false,
242 moving: 0,
243 frame_time: FrameClock::default(),
244 projection_for_zoom: None,
245 globe_drag_hold: None,
246 terrain: None,
247 last_frame: None,
248 }
249 }
250
251 pub fn drain_events(&mut self) -> std::vec::Drain<'_, TransformEvent> {
254 self.events.drain(..)
255 }
256
257 #[must_use]
260 pub fn has_events(&self) -> bool {
261 !self.events.is_empty()
262 }
263
264 fn emit(&mut self, event: TransformEvent) {
265 self.events.push(event);
266 }
267
268 pub fn resize(&mut self, size: Size) -> Result<(), Error> {
271 if size.is_empty() {
272 return Err(Error::invalid_argument("failed to resize: size is empty"));
273 }
274
275 if self.state.view().size() == size {
276 return Ok(());
277 }
278
279 self.emit(TransformEvent::CameraWillChange(CameraChange::default()));
280 self.state.set_size(size);
281 let (scale, center) = self.state.constrain_screen(self.state.view().scale());
282 if let Some(center) = center {
283 if self.in_transition() {
288 self.cancel_transitions();
289 }
290
291 let zoom = mln_map_types::scale_zoom(scale);
294 self.state.set_lat_lng_zoom(¢er, zoom);
295 self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
296
297 return Ok(());
298 }
299 self.state.constrain_position(scale);
300
301 self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
302 Ok(())
303 }
304
305 #[must_use]
309 pub fn camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
310 self.state.camera_options(padding)
311 }
312
313 pub fn jump_to(&mut self, camera: &CameraOptions) -> CameraCommandId {
316 self.command(|transform| transform.jump(camera))
317 }
318
319 fn jump(&mut self, camera: &CameraOptions) {
320 if self.state.view().is_globe()
325 && let Some(center) = camera.center
326 && camera.zoom.is_none()
327 {
328 let zoom = self.view().zoom()
329 + VerticalPerspectiveProjection::zoom_adjustment(
330 self.view().center(WrapMode::Wrapped).latitude(),
331 center.latitude(),
332 );
333 self.ease_to(&CameraOptions { zoom: Some(zoom), ..*camera }, &AnimationOptions::default());
334 return;
335 }
336 self.ease_to(camera, &AnimationOptions::default());
337 }
338
339 fn globe_on_screen(&self) -> bool {
344 self.state.view().is_globe() && !self.state.view().size().is_empty()
345 }
346
347 pub fn move_by(
351 &mut self,
352 offset: &ScreenCoordinate,
353 animation: &AnimationOptions,
354 ) -> Result<CameraCommandId, Error> {
355 self.move_by_with_anchor(offset, None, animation)
356 }
357
358 pub fn move_by_with_anchor(
371 &mut self,
372 offset: &ScreenCoordinate,
373 anchor: Option<ScreenCoordinate>,
374 animation: &AnimationOptions,
375 ) -> Result<CameraCommandId, Error> {
376 let mut moved = Ok(());
377 let command = self.command(|transform| moved = transform.move_by_now(offset, anchor, animation));
378 moved.map(|()| command)
379 }
380
381 fn move_by_now(
382 &mut self,
383 offset: &ScreenCoordinate,
384 anchor: Option<ScreenCoordinate>,
385 animation: &AnimationOptions,
386 ) -> Result<(), Error> {
387 let flipped = |state: &TransformState, point: &ScreenCoordinate| {
388 ScreenCoordinate::new(point.x, f64::from(state.view().size().height) - point.y)
389 };
390 let size = self.state.view().size();
391 let view_center = self.state.view().padding().center_in(size);
392 let fling_duration = animation.duration.filter(|duration| *duration > Duration::ZERO);
393 let globe = self.globe_on_screen();
394 if globe && (offset.x.is_nan() || offset.y.is_nan()) {
395 return Err(Error::invalid_argument("offset must not be NaN"));
396 }
397 if globe && (!offset.x.is_finite() || !offset.y.is_finite()) {
398 return Err(Error::invalid_argument("offset must not be infinite"));
399 }
400 if globe
401 && let Some(duration) = fling_duration
402 && self.state.view().globe_free_bearing()
403 {
404 let start = CenterAndBearing {
408 center: self.view().center(WrapMode::Unwrapped),
409 bearing: -mln_math::rad2deg(self.view().angle()),
410 };
411 let end = VerticalPerspectiveProjection::fling_camera(
412 self.state.view(),
413 &flipped(&self.state, &view_center),
414 &ScreenCoordinate::new(offset.x, -offset.y),
415 );
416 let start_zoom = self.view().zoom();
417 let frame: FrameFn = Box::new(move |state: &TransformState, t: f64| {
418 let camera = VerticalPerspectiveProjection::interpolate_camera(&start, &end, t);
419 let center = state.constrained_center(&camera.center, state.view().zoom());
420 CameraOptions {
421 center: Some(center),
422 zoom: Some(
423 start_zoom
424 + VerticalPerspectiveProjection::zoom_adjustment(
425 start.center.latitude(),
426 center.latitude(),
427 ),
428 ),
429 bearing: Some(camera.bearing),
430 ..Default::default()
431 }
432 });
433 let fields = CameraOptions {
436 center: Some(end.center),
437 zoom: Some(start_zoom),
438 bearing: Some(end.bearing),
439 ..Default::default()
440 };
441 self.start_transition(&fields, animation, frame, None, duration, false);
442 return Ok(());
443 }
444
445 if globe && fling_duration.is_some() {
446 let mut center = self.state.constrained_center(
451 &VerticalPerspectiveProjection::pan_center(self.state.view(), offset),
452 self.view().zoom(),
453 );
454 let longitude = self.view().center(WrapMode::Unwrapped).longitude();
455 if (center.longitude() - longitude).abs() > 180.0 {
456 center = lat_lng(center.latitude(), longitude + 179.5f64.copysign(center.longitude() - longitude));
457 }
458 self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
459 return Ok(());
460 }
461
462 if globe {
463 let from = anchor.map(|anchor| ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y));
481 let held = self.globe_drag_hold.take().filter(|held| {
482 from.is_some_and(|from| (held.cursor.x - from.x).hypot(held.cursor.y - from.y) < 1e-3)
483 && !self.state.view().globe_free_bearing()
484 && held.size == size
485 && held.camera == self.camera_options(None)
486 });
487 let height = match (held, anchor.zip(from)) {
488 (Some(held), _) => held.height,
489 (None, Some((anchor, from))) => self.anchor_height(&from, &anchor),
490 (None, None) => self.view().center_altitude(),
491 };
492 let on_globe = |state: &TransformState, point: &ScreenCoordinate| {
493 VerticalPerspectiveProjection::screen_coordinate_hits_globe(
494 state.view(),
495 &flipped(state, point),
496 height,
497 )
498 };
499 let grab = match anchor {
500 Some(anchor) if on_globe(&self.state, &anchor) => anchor,
501 _ => view_center,
502 };
503 let pan_delta = ScreenCoordinate::new(offset.x, -offset.y);
504 let mut camera = CameraOptions::default();
505 let hold = match anchor.zip(from) {
506 Some((anchor, from)) if !self.state.view().globe_free_bearing() && on_globe(&self.state, &anchor) => {
507 let location = match held {
508 Some(held) => Some(held.location),
509 None if on_globe(&self.state, &from) => self
510 .state
511 .view()
512 .screen_coordinate_to_lat_lng_at(&flipped(&self.state, &from), height, WrapMode::Unwrapped)
513 .ok(),
514 None => None,
515 };
516 location.and_then(|location| {
517 VerticalPerspectiveProjection::drag_center_holding(
518 self.state.view(),
519 &location,
520 &flipped(&self.state, &anchor),
521 height,
522 )
523 .map(|center| (location, anchor, center))
524 })
525 }
526 _ => None,
527 };
528 let mut center = if let Some((_, _, center)) = hold {
529 center
530 } else if self.state.view().globe_free_bearing() {
531 let drag = VerticalPerspectiveProjection::drag_camera(
532 self.state.view(),
533 &flipped(&self.state, &grab),
534 &pan_delta,
535 height,
536 );
537 camera = CameraOptions { bearing: Some(drag.bearing), ..camera };
538 drag.center
539 } else {
540 VerticalPerspectiveProjection::drag_center(
541 self.state.view(),
542 &flipped(&self.state, &grab),
543 &pan_delta,
544 height,
545 )
546 };
547 center = self.state.constrained_center(¢er, self.view().zoom());
548 let zoom = self.view().zoom()
549 + VerticalPerspectiveProjection::zoom_adjustment(
550 self.view().center(WrapMode::Wrapped).latitude(),
551 center.latitude(),
552 );
553 self.ease_to(&CameraOptions { center: Some(center), zoom: Some(zoom), ..camera }, animation);
554 self.globe_drag_hold = hold.map(|(location, cursor, _)| GlobeDragHold {
555 location,
556 height,
557 cursor,
558 camera: self.camera_options(None),
559 size,
560 });
561 return Ok(());
562 }
563
564 let mut center_offset = *offset;
565
566 let pitch = self.state.view().pitch();
570 let offset_length = offset.x.hypot(offset.y);
571 if pitch > 0.0 && offset_length > 0.0 {
572 let camera_to_center =
573 0.5 * f64::from(self.state.view().size().height) / (self.state.view().fov() / 2.0).tan();
574 let pixels_to_horizon = (camera_to_center / pitch.tan()).abs();
575 let horizon_factor = 0.75;
577 let scale = pixels_to_horizon * horizon_factor / offset_length;
578 if scale < 1.0 {
579 center_offset = ScreenCoordinate::new(offset.x * scale, offset.y * scale);
580 }
581 }
582
583 let size = self.state.view().size();
584 let center = self.state.view().padding().center_in(size);
585 let point_on_screen = ScreenCoordinate::new(center.x - center_offset.x, center.y - center_offset.y);
586 let anchored = anchor.and_then(|anchor| {
590 let grabbed = ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y);
591 Some((grabbed, anchor, self.anchor_plane(&grabbed, &anchor)?))
592 });
593 let (from, to, height) = anchored.unwrap_or((point_on_screen, center, self.view().center_altitude()));
594 let center = self.center_moving_on_plane(&from, &to, height)?;
595 self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
596 Ok(())
597 }
598
599 pub fn set_limits(&mut self, limits: CameraLimits) -> Result<(), Error> {
604 self.state.set_limits(limits)
605 }
606
607 pub(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
608 self.state.set_frustum_offset(frustum_offset);
609 }
610
611 pub fn set_projection_definition(&mut self, definition: &ProjectionDefinition) {
614 self.state.set_projection_definition(definition);
615 }
616
617 pub(crate) fn set_projection_for_zoom(&mut self, projection_for_zoom: Option<ProjectionForZoomFn>) {
620 self.projection_for_zoom = projection_for_zoom;
621 }
622
623 pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
624 self.state.set_globe_free_bearing(free_bearing);
625 }
626
627 pub(crate) fn is_globe_free_bearing(&self) -> bool {
628 self.state.view().globe_free_bearing()
629 }
630
631 #[cfg(test)]
632 pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
633 self.state.view().is_location_occluded(lat_lng)
634 }
635
636 pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
639 self.state.set_north_orientation(orientation);
640 self.state.constrain_position(self.state.view().scale());
641 }
642
643 pub fn set_constrain_mode(&mut self, mode: ConstrainMode) {
646 self.state.set_constrain_mode(mode);
647 self.state.constrain_position(self.state.view().scale());
648 }
649
650 pub fn set_viewport_mode(&mut self, mode: ViewportMode) {
653 self.state.set_viewport_mode(mode);
654 }
655
656 pub fn set_center_clamped_to_ground(&mut self, clamped: bool) {
659 self.state.set_center_clamped_to_ground(clamped);
660 }
661
662 pub(crate) fn set_projection_mode(&mut self, options: &ProjectionMode) {
665 if let Some(x_skew) = options.x_skew {
666 self.state.set_x_skew(x_skew);
667 }
668 if let Some(y_skew) = options.y_skew {
669 self.state.set_y_skew(y_skew);
670 }
671 if let Some(axonometric) = options.axonometric {
672 self.state.set_axonometric(axonometric.as_bool());
673 }
674 }
675
676 pub fn set_frame_time(&mut self, time: Option<Instant>) {
690 self.frame_time.set(time);
691 }
692
693 pub(crate) fn frame_clock(&self) -> FrameClock {
695 self.frame_time.clone()
696 }
697
698 pub(crate) fn frame_time(&self) -> Option<Instant> {
704 self.fresh_frame_time(Instant::now())
705 }
706
707 fn fresh_frame_time(&self, now: Instant) -> Option<Instant> {
708 self.frame_time.get().filter(|&time| now.saturating_duration_since(time) <= STALE_FRAME_TIME)
709 }
710
711 fn now(&self) -> Instant {
713 let now = Instant::now();
714 self.fresh_frame_time(now).unwrap_or(now)
715 }
716
717 #[must_use]
720 pub fn is_camera_moving(&self) -> bool {
721 self.gesture_in_progress || self.moving & (CENTER | ZOOM | BEARING) != 0
722 }
723
724 #[must_use]
727 pub fn state(&self) -> &TransformState {
728 &self.state
729 }
730
731 #[must_use]
733 pub fn view(&self) -> &View {
734 self.state.view()
735 }
736
737 #[cfg(test)]
738 pub(crate) fn is_rotating(&self) -> bool {
739 self.moving & BEARING != 0
740 }
741
742 #[cfg(test)]
743 pub(crate) fn is_scaling(&self) -> bool {
744 self.moving & ZOOM != 0
745 }
746
747 #[cfg(test)]
748 pub(crate) fn is_panning(&self) -> bool {
749 self.moving & CENTER != 0
750 }
751
752 #[must_use]
755 pub fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
756 let mut point = self.state.view().lat_lng_to_screen_coordinate(lat_lng);
757 point.y = f64::from(self.state.view().size().height) - point.y;
758 point
759 }
760
761 pub fn screen_coordinate_to_lat_lng(&self, point: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
765 let mut flipped_point = *point;
766 flipped_point.y = f64::from(self.state.view().size().height) - flipped_point.y;
767 self.state.view().screen_coordinate_to_lat_lng(&flipped_point, wrap_mode)
768 }
769
770 pub(crate) fn screen_coordinate_to_lat_lng_at(
775 &self,
776 point: &ScreenCoordinate,
777 height: f64,
778 wrap_mode: WrapMode,
779 ) -> Result<LatLng, Error> {
780 self.view().screen_coordinate_to_lat_lng_at(&flip_y(self.view(), point), height, wrap_mode)
781 }
782
783 pub(crate) fn set_free_camera_options(&mut self, options: &FreeCameraOptions) {
784 self.cancel_transitions();
785 self.state.set_free_camera_options(options);
786 }
787}
788
789pub(crate) fn flip_y(view: &View, point: &ScreenCoordinate) -> ScreenCoordinate {
792 ScreenCoordinate::new(point.x, f64::from(view.size().height) - point.y)
793}
794
795fn nanos_from_secs(seconds: f64) -> Option<Duration> {
799 (seconds >= 0.0 && seconds * 1e9 < u64::MAX as f64).then(|| Duration::from_nanos((seconds * 1e9) as u64))
800}
801
802fn max_pitch_for_padding(state: &TransformState, insets: &EdgeInsets) -> f64 {
805 let center_offset_y = 0.5 * (insets.top - insets.bottom);
807 if center_offset_y == 0.0 {
808 return state.limits().max_pitch;
809 }
810
811 let height = state.view().size().height;
812 debug_assert!(height != 0);
813 let field_of_view = state.view().fov();
814 let tangent_of_fov_above_center_angle =
816 (0.5 + center_offset_y / f64::from(height)) * 2.0 * (field_of_view / 2.0).tan();
817 let fov_above_center = tangent_of_fov_above_center_angle.atan();
818 f64::max(state.limits().min_pitch, state.limits().max_pitch + field_of_view / 2.0 - fov_above_center)
819}
820
821#[cfg(test)]
822#[path = "transform_test.rs"]
823mod transform_test;