1use std::time::Duration;
5
6use glam::DVec3;
7use mln_map_types::{
8 AnimationOptions, CameraOptions, CameraVelocity, Elevation, TransformState, TransitionEnd, TransitionOutcome,
9 VerticalPerspectiveProjection,
10};
11use mln_util::constants::{DEFAULT_TRANSITION_EASE, TILE_SIZE_D};
12use mln_util::geo::{LatLng, ScreenCoordinate, WrapMode};
13use mln_util::projection::Projection;
14use mln_util::time::Instant;
15
16use super::anchor::sees_plane;
17use super::momentum::MomentumState;
18use super::{
19 ALTITUDE, BEARING, CENTER, CameraCommandId, CommandEnd, FOV, PADDING, PITCH, ROLL, Transform, TransformEvent, ZOOM,
20 camera_fields, max_pitch_for_padding,
21};
22use crate::log_target;
23use crate::map_event::{CameraChange, CameraChangeMode, CameraChangeSource};
24
25pub(super) type FrameFn = Box<dyn Fn(&TransformState, f64) -> CameraOptions>;
29
30pub(super) type AlongFn = Box<dyn Fn(f64) -> f64>;
33
34pub(super) struct Transition {
36 pub(super) fields: u16,
39 coupled_fields: u16,
41 pub(super) moving_fields: u16,
45 start: Instant,
46 pub(super) duration: Duration,
48 animation: AnimationOptions,
49 frame: FrameFn,
50 along: Option<AlongFn>,
53 anchor: Option<ScreenCoordinate>,
54 anchor_lat_lng: LatLng,
55 anchor_height: f64,
58 pub(super) momentum: Option<MomentumState>,
61 stopped: Option<TransitionOutcome>,
65 source: CameraChangeSource,
67 pub(super) command: Option<CameraCommandId>,
69 pub(super) gesture: Option<u64>,
72}
73
74impl Transition {
75 pub(super) fn new(
78 fields: u16,
79 moving_fields: u16,
80 start: Instant,
81 duration: Duration,
82 animation: &AnimationOptions,
83 frame: FrameFn,
84 source: CameraChangeSource,
85 ) -> Transition {
86 Transition {
87 fields,
88 coupled_fields: 0,
89 moving_fields,
90 start,
91 duration,
92 animation: *animation,
93 frame,
94 along: None,
95 anchor: None,
96 anchor_lat_lng: LatLng::default(),
97 anchor_height: 0.0,
98 momentum: None,
99 stopped: None,
100 source,
101 command: None,
102 gesture: None,
103 }
104 }
105
106 pub(super) fn is_command(&self) -> bool {
109 self.source == CameraChangeSource::Command && self.momentum.is_none()
110 }
111
112 pub(super) fn end_center(&self, state: &TransformState, frame: &CameraOptions, ground: &dyn Elevation) -> LatLng {
117 let end = (self.frame)(state, 1.0);
118 match self.anchor {
119 Some(anchor) => {
120 let mut camera = *frame;
121 compose(&mut camera, &end, self.fields);
122 anchored_end(state, &camera, &anchor, &self.anchor_lat_lng, self.anchor_height, ground)
123 }
124 None => end.center.or(frame.center).unwrap_or_else(|| state.view().center(WrapMode::Unwrapped)).wrapped(),
125 }
126 }
127
128 fn mode(&self) -> CameraChangeMode {
129 if self.duration == Duration::ZERO { CameraChangeMode::Immediate } else { CameraChangeMode::Animated }
130 }
131
132 fn ended_by(&mut self, outcome: TransitionOutcome) {
136 if self.stopped != Some(TransitionOutcome::Cancelled) {
137 self.stopped = Some(outcome);
138 }
139 }
140
141 fn end(&self) -> TransitionEnd {
145 let (velocity, momentum_replaced) =
146 self.momentum.as_ref().map_or((CameraVelocity::default(), false), MomentumState::end);
147 let outcome = self.stopped.unwrap_or(if momentum_replaced {
148 TransitionOutcome::Replaced
149 } else {
150 TransitionOutcome::Completed
151 });
152 TransitionEnd { outcome, velocity, generation: 0 }
153 }
154
155 fn progress(&self, now: Option<Instant>) -> f64 {
158 let duration = self.duration;
159 match now {
160 Some(now) if !duration.is_zero() => {
161 mln_math::clamp_f64(now.saturating_duration_since(self.start).div_duration_f64(duration), 0.0, 1.0)
162 }
163 _ => 1.0,
164 }
165 }
166
167 fn eased_progress(&self, now: Option<Instant>) -> f64 {
170 let t = self.progress(now);
171 let ease = self.animation.easing.unwrap_or(DEFAULT_TRANSITION_EASE);
172 if t == 1.0 { 1.0 } else { ease.solve(t, 0.001) }
173 }
174
175 pub(super) fn share(&self, now: Option<Instant>) -> f64 {
178 let k = self.eased_progress(now);
179 match &self.along {
180 Some(along) if k < 1.0 => along(k),
181 _ => k,
182 }
183 }
184
185 pub(super) fn remaining(&self, now: Option<Instant>) -> Duration {
187 self.duration.saturating_sub(self.elapsed(now))
188 }
189
190 pub(super) fn elapsed(&self, now: Option<Instant>) -> Duration {
193 now.map_or(Duration::MAX, |now| now.saturating_duration_since(self.start))
194 }
195
196 fn has_run_out(&self, now: Option<Instant>) -> bool {
198 now.is_none_or(|now| now >= self.start && self.elapsed(Some(now)) >= self.duration)
199 }
200}
201
202fn compose(camera: &mut CameraOptions, value: &CameraOptions, fields: u16) {
205 if fields & CENTER != 0 && value.center.is_some() {
206 camera.center = value.center;
207 }
208 if fields & ZOOM != 0 {
209 camera.zoom = value.zoom;
210 }
211 if fields & BEARING != 0 {
212 camera.bearing = value.bearing;
213 }
214 if fields & PITCH != 0 {
215 camera.pitch = value.pitch;
216 }
217 if fields & PADDING != 0 && value.padding.is_some() {
218 camera.padding = value.padding;
219 }
220 if fields & ALTITUDE != 0 {
221 camera.center_altitude = value.center_altitude;
222 }
223 if fields & ROLL != 0 {
224 camera.roll = value.roll;
225 }
226 if fields & FOV != 0 {
227 camera.fov = value.fov;
228 }
229}
230
231fn place(state: &mut TransformState, current: &CameraOptions, camera: &mut CameraOptions) {
239 let padding = camera.padding.unwrap_or_default();
240 state.set_padding(&padding);
241 if let Some(fov) = camera.fov.filter(|_| camera.fov != current.fov) {
242 state.set_fov(mln_math::deg2rad(fov));
243 }
244 if let Some(bearing) = camera.bearing.filter(|_| camera.bearing != current.bearing) {
245 state.set_angle(mln_math::deg2rad(-bearing));
246 }
247 if let Some(roll) = camera.roll.filter(|_| camera.roll != current.roll) {
248 state.set_roll(mln_math::deg2rad(roll));
249 }
250 let pitch = match camera.pitch.filter(|_| camera.pitch != current.pitch) {
251 Some(pitch) => mln_math::deg2rad(pitch),
252 None => state.view().pitch(),
253 };
254 state.set_pitch(f64::min(max_pitch_for_padding(state, &padding), pitch));
255 state.set_center_altitude(camera.center_altitude.unwrap_or_default());
257 let mut zoom = camera.zoom.unwrap_or_default();
258 state.constrain_camera_and_zoom_to_bounds(camera, &mut zoom);
259 state.set_lat_lng_zoom(&camera.center.unwrap_or_default(), zoom);
260}
261
262fn anchored_end(
274 state: &TransformState,
275 camera: &CameraOptions,
276 anchor: &ScreenCoordinate,
277 location: &LatLng,
278 height: f64,
279 ground: &dyn Elevation,
280) -> LatLng {
281 let mut state = state.clone();
282 let current = state.camera_options(None);
283 let altitude = current.center_altitude;
284 place(&mut state, ¤t, &mut CameraOptions { center_altitude: altitude, ..*camera });
285 if state.view().is_globe() || !sees_plane(state.view(), anchor, height) {
286 return state.view().center(WrapMode::Wrapped);
287 }
288 let _ = state.move_lat_lng_at(location, anchor, height);
290 let view = state.view();
291 let center = view.center(WrapMode::Unwrapped);
292 let on_ground = view.line_of_sight(anchor).and_then(|(near, far)| {
293 let world = Projection::project(¢er, 1.0 / TILE_SIZE_D);
294 let at = DVec3::new(world.x, world.y, view.center_altitude());
295 view.ground_along(at - (far - near), at + (far - near), ground)
296 });
297 on_ground.map_or(center, |hit| hit.location(WrapMode::Unwrapped)).wrapped()
298}
299
300pub(super) struct JointEnd {
304 command: CameraCommandId,
305 remaining: u32,
306 outcome: TransitionOutcome,
307}
308
309impl Transform {
310 pub(super) fn start_transition(
320 &mut self,
321 camera: &CameraOptions,
322 animation: &AnimationOptions,
323 frame: FrameFn,
324 along: Option<AlongFn>,
325 duration: Duration,
326 flight: bool,
327 ) {
328 let mut fields = camera_fields(camera);
329 if self.clamped() {
330 fields &= !ALTITUDE;
331 }
332 let mut coupled_fields = if flight { CENTER | ZOOM } else { 0 };
333 fields |= coupled_fields;
334
335 let mut anchor = if camera.center.is_some() { None } else { camera.anchor };
338 let mut anchor_lat_lng = LatLng::default();
339 let mut anchor_height = 0.0;
340 if let Some(a) = anchor.as_mut() {
341 anchor_height = self.anchor_height(a, a);
342 a.y = f64::from(self.state.view().size().height) - a.y;
343 match self.state.view().screen_coordinate_to_lat_lng_at(a, anchor_height, WrapMode::Unwrapped) {
346 Ok(lat_lng) => {
347 anchor_lat_lng = lat_lng;
348 fields |= CENTER;
349 coupled_fields = fields;
350 }
351 Err(e) => {
352 log::error!(target: log_target::GENERAL, "{}", e.message);
353 anchor = None;
354 }
355 }
356 }
357
358 let target = frame(&self.state, 1.0);
359 let panning = flight || anchor.is_some() || camera.center != Some(self.view().center(WrapMode::Unwrapped));
360 let scaling = flight || target.zoom != Some(self.view().zoom());
361 let rotating = target.bearing != Some(-mln_math::rad2deg(self.view().angle()));
362 let moving_fields = (if panning { CENTER } else { 0 })
363 | (if scaling { ZOOM } else { 0 })
364 | (if rotating { BEARING } else { 0 });
365
366 let start = self.now();
367 let duration = if fields != 0 { duration } else { Duration::ZERO };
368 let transition = Transition {
369 coupled_fields,
370 along,
371 anchor,
372 anchor_lat_lng,
373 anchor_height,
374 command: self.reporting(),
375 ..Transition::new(fields, moving_fields, start, duration, animation, frame, self.source)
376 };
377 let mode = transition.mode();
378
379 let finished = self.release_fields(fields);
380 self.transitions.push(transition);
381 self.update_movement_flags();
382 self.finish_transitions(finished);
383
384 self.emit(TransformEvent::CameraWillChange(CameraChange { mode, source: self.source }));
385
386 if duration == Duration::ZERO {
387 let index = self.transitions.len() - 1;
388 self.apply_transitions(Some(index), Some(start));
389 let transition = self.transitions.remove(index);
390 self.update_movement_flags();
391 self.finish_transitions(vec![transition]);
392 }
393 }
394
395 fn apply_transitions(&mut self, only: Option<usize>, now: Option<Instant>) {
399 let current = self.state.camera_options(None);
402 let mut camera = current;
403
404 let active = match only {
405 Some(index) => &self.transitions[index..=index],
406 None => &self.transitions[..],
407 };
408 for transition in active.iter().filter(|transition| transition.momentum.is_none()) {
409 let k = transition.eased_progress(now);
410 compose(&mut camera, &(transition.frame)(&self.state, k), transition.fields);
411 }
412 let lands = self.ease_altitude(&mut camera, now);
413
414 let anchored = self.transitions.iter().enumerate().rev().find_map(|(index, transition)| {
417 let anchor = transition.anchor.filter(|_| transition.fields & CENTER != 0)?;
418 Some((anchor, transition.anchor_lat_lng, transition.anchor_height, index))
419 });
420
421 let globe_zoom_around = match anchored {
427 Some((anchor, anchor_lat_lng, height, _)) if self.globe_on_screen() => {
428 let location = self
429 .state
430 .view()
431 .screen_coordinate_to_lat_lng_at(&anchor, height, WrapMode::Unwrapped)
432 .unwrap_or_else(|e| {
433 log::error!(target: log_target::GENERAL, "{}", e.message);
434 anchor_lat_lng
435 });
436 Some((location, self.state.view().zoom()))
437 }
438 _ => None,
439 };
440
441 place(&mut self.state, ¤t, &mut camera);
444 if let Some((anchor, anchor_lat_lng, height, index)) = anchored {
445 match globe_zoom_around {
446 Some((location, zoom_before)) if self.state.view().zoom() != zoom_before => {
447 let zoom_delta = self.state.view().zoom() - zoom_before;
448 let free_bearing = self.state.view().globe_free_bearing();
449 VerticalPerspectiveProjection::zoom_around_point(
450 &mut self.state,
451 &anchor,
452 &location,
453 height,
454 zoom_delta,
455 free_bearing,
456 );
457 }
458 _ => self.hold_anchor(&anchor_lat_lng, &anchor, height, ¤t, index),
459 }
460 }
461 if lands {
462 self.stand_on_ground();
463 }
464 self.keep_clear_of_ground();
466 }
467
468 fn hold_anchor(
479 &mut self,
480 location: &LatLng,
481 anchor: &ScreenCoordinate,
482 height: f64,
483 before: &CameraOptions,
484 index: usize,
485 ) {
486 if !self.view().is_globe() && !sees_plane(self.view(), anchor, height) {
487 let zoom = self.view().zoom();
488 self.state.set_lat_lng_zoom(&before.center.unwrap_or_default(), zoom);
489 let transition = &mut self.transitions[index];
490 transition.anchor = None;
491 transition.fields &= !CENTER;
492 return;
493 }
494 if let Err(e) = self.state.move_lat_lng_at(location, anchor, height) {
495 log::error!(target: log_target::GENERAL, "{}", e.message);
496 }
497 }
498
499 pub(super) fn update_movement_flags(&mut self) {
501 self.moving = self.transitions.iter().fold(0, |moving, t| moving | (t.fields & t.moving_fields));
502 }
503
504 pub(super) fn finish_transitions(&mut self, finished: Vec<Transition>) {
508 for transition in &finished {
509 self.end_gesture_momentum(transition.gesture);
510 }
511 if !finished.is_empty() {
512 self.come_to_rest();
513 }
514 for transition in finished {
515 self.report_end(transition.command, transition.animation.transition_id, transition.end());
516 let change = CameraChange { mode: transition.mode(), source: transition.source };
519 self.emit(TransformEvent::CameraDidChange(change));
520 }
521 }
522
523 #[must_use]
525 pub fn in_transition(&self) -> bool {
526 !self.transitions.is_empty()
527 }
528
529 pub fn update_transitions(&mut self, now: Option<Instant>) {
532 if self.transitions.is_empty() {
533 return;
534 }
535
536 if self.transitions.iter().any(|t| t.momentum.is_none()) {
537 self.apply_transitions(None, now);
538 }
539 for index in 0..self.transitions.len() {
540 self.advance_momentum(index, now);
541 }
542 if self.transitions.iter().any(|t| t.momentum.is_some()) {
543 self.keep_clear_of_ground();
544 }
545
546 let finished: Vec<_> = self.transitions.extract_if(.., |t| t.has_run_out(now) || t.fields == 0).collect();
547 self.update_movement_flags();
548 if !self.transitions.is_empty() {
549 self.emit(TransformEvent::CameraIsChanging);
550 }
551
552 self.finish_transitions(finished);
553 }
554
555 pub(super) fn release_fields(&mut self, fields: u16) -> Vec<Transition> {
558 for active in &mut self.transitions {
559 let mut replaced = fields;
560 let coupled = active.coupled_fields & active.fields;
563 if coupled & replaced != 0 {
564 replaced |= coupled;
565 }
566 active.fields &= !replaced;
567 if let Some(momentum) = &mut active.momentum {
568 active.fields = momentum.retain(active.fields);
569 }
570 if active.fields == 0 {
571 active.ended_by(TransitionOutcome::Replaced);
572 }
573 }
574 self.transitions.extract_if(.., |active| active.fields == 0).collect()
575 }
576
577 pub(super) fn command(&mut self, start: impl FnOnce(&mut Self)) -> CameraCommandId {
582 if let Some(command) = self.command {
583 start(self);
584 return command;
585 }
586 let command = CameraCommandId(self.next_command);
587 self.next_command += 1;
588 self.command = Some(command);
589 start(self);
590 self.command = None;
591 command
592 }
593
594 pub(super) fn reporting(&self) -> Option<CameraCommandId> {
596 self.command.filter(|_| !self.silent)
597 }
598
599 pub(super) fn join_ends(&mut self, count: u32) {
602 if let Some(command) = self.reporting().filter(|_| count > 1) {
603 self.joint_ends.push(JointEnd { command, remaining: count, outcome: TransitionOutcome::Completed });
604 }
605 }
606
607 fn report_end(&mut self, command: Option<CameraCommandId>, transition_id: Option<u64>, mut end: TransitionEnd) {
610 let Some(command) = command else { return };
611 if let Some(index) = self.joint_ends.iter().position(|joint| joint.command == command) {
612 let joint = &mut self.joint_ends[index];
613 joint.remaining -= 1;
614 joint.outcome = match (joint.outcome, end.outcome) {
615 (TransitionOutcome::Cancelled, _) | (_, TransitionOutcome::Cancelled) => TransitionOutcome::Cancelled,
616 (TransitionOutcome::Closed, _) | (_, TransitionOutcome::Closed) => TransitionOutcome::Closed,
617 (TransitionOutcome::Replaced, _) | (_, TransitionOutcome::Replaced) => TransitionOutcome::Replaced,
618 _ => TransitionOutcome::Completed,
619 };
620 if joint.remaining > 0 {
621 return;
622 }
623 end.outcome = joint.outcome;
624 self.joint_ends.swap_remove(index);
625 }
626 self.emit(TransformEvent::CommandEnded(CommandEnd { command, transition_id, end }));
627 }
628
629 pub(super) fn end_unstarted(&mut self, animation: &AnimationOptions, outcome: TransitionOutcome) {
632 self.report_end(
633 self.reporting(),
634 animation.transition_id,
635 TransitionEnd { outcome, ..TransitionEnd::default() },
636 );
637 }
638
639 pub(crate) fn cancel_transitions(&mut self) {
640 let mut finished = std::mem::take(&mut self.transitions);
641 for transition in &mut finished {
642 transition.ended_by(TransitionOutcome::Cancelled);
643 }
644 self.update_movement_flags();
645 self.finish_transitions(finished);
646 }
647
648 pub fn cancel_transitions_with_id(&mut self, transition_id: u64) -> bool {
652 let mut finished: Vec<_> = self
653 .transitions
654 .extract_if(.., |transition| transition.animation.transition_id == Some(transition_id))
655 .collect();
656 if finished.is_empty() {
657 return false;
658 }
659 for transition in &mut finished {
660 transition.ended_by(TransitionOutcome::Cancelled);
661 }
662 self.update_movement_flags();
663 self.finish_transitions(finished);
664 true
665 }
666
667 pub fn close(&mut self) {
671 for transition in std::mem::take(&mut self.transitions) {
672 let end = TransitionEnd { outcome: TransitionOutcome::Closed, ..transition.end() };
673 self.report_end(transition.command, transition.animation.transition_id, end);
674 }
675 self.update_movement_flags();
676 }
677}