1use std::time::Duration;
5
6use glam::DVec3;
7use mln_style::constants::{DEFAULT_TRANSITION_EASE, TILE_SIZE_D};
8use mln_style::geo::{LatLng, WrapMode};
9use mln_style::time::Instant;
10
11use super::anchor::sees_plane;
12use super::momentum::MomentumState;
13use super::{
14 ALTITUDE, BEARING, CENTER, CameraCommandId, CommandEnd, FOV, PADDING, PITCH, ROLL, Transform, TransformEvent, ZOOM,
15 camera_fields, max_pitch_for_padding,
16};
17use crate::camera::{
18 AnimationOptions, CameraOptions, CameraVelocity, Elevation, TransformState, TransitionEnd, TransitionOutcome,
19 VerticalPerspectiveProjection,
20};
21use crate::geo::ScreenCoordinate;
22use crate::geo::projection::Projection;
23use crate::log_target;
24use crate::map::events::{CameraChange, CameraChangeMode, CameraChangeSource};
25
26pub(super) type FrameFn = Box<dyn Fn(&TransformState, f64) -> CameraOptions>;
30
31pub(super) type AlongFn = Box<dyn Fn(f64) -> f64>;
34
35pub(super) struct Transition {
37 pub(super) fields: u16,
40 coupled_fields: u16,
42 pub(super) moving_fields: u16,
46 start: Instant,
47 pub(super) duration: Duration,
49 animation: AnimationOptions,
50 frame: FrameFn,
51 along: Option<AlongFn>,
54 anchor: Option<ScreenCoordinate>,
55 anchor_lat_lng: LatLng,
56 anchor_height: f64,
59 pub(super) momentum: Option<MomentumState>,
62 stopped: Option<TransitionOutcome>,
66 source: CameraChangeSource,
68 pub(super) command: Option<CameraCommandId>,
70 pub(super) gesture: Option<u64>,
73}
74
75impl Transition {
76 pub(super) fn new(
79 fields: u16,
80 moving_fields: u16,
81 start: Instant,
82 duration: Duration,
83 animation: &AnimationOptions,
84 frame: FrameFn,
85 source: CameraChangeSource,
86 ) -> Transition {
87 Transition {
88 fields,
89 coupled_fields: 0,
90 moving_fields,
91 start,
92 duration,
93 animation: *animation,
94 frame,
95 along: None,
96 anchor: None,
97 anchor_lat_lng: LatLng::default(),
98 anchor_height: 0.0,
99 momentum: None,
100 stopped: None,
101 source,
102 command: None,
103 gesture: None,
104 }
105 }
106
107 pub(super) fn is_command(&self) -> bool {
110 self.source == CameraChangeSource::Command && self.momentum.is_none()
111 }
112
113 pub(super) fn end_center(&self, state: &TransformState, frame: &CameraOptions, ground: &dyn Elevation) -> LatLng {
118 let end = (self.frame)(state, 1.0);
119 match self.anchor {
120 Some(anchor) => {
121 let mut camera = *frame;
122 compose(&mut camera, &end, self.fields);
123 anchored_end(state, &camera, &anchor, &self.anchor_lat_lng, self.anchor_height, ground)
124 }
125 None => end.center.or(frame.center).unwrap_or_else(|| state.view().center(WrapMode::Unwrapped)).wrapped(),
126 }
127 }
128
129 fn mode(&self) -> CameraChangeMode {
130 if self.duration == Duration::ZERO { CameraChangeMode::Immediate } else { CameraChangeMode::Animated }
131 }
132
133 fn ended_by(&mut self, outcome: TransitionOutcome) {
137 if self.stopped != Some(TransitionOutcome::Cancelled) {
138 self.stopped = Some(outcome);
139 }
140 }
141
142 fn end(&self) -> TransitionEnd {
146 let (velocity, momentum_replaced) =
147 self.momentum.as_ref().map_or((CameraVelocity::default(), false), MomentumState::end);
148 let outcome = self.stopped.unwrap_or(if momentum_replaced {
149 TransitionOutcome::Replaced
150 } else {
151 TransitionOutcome::Completed
152 });
153 TransitionEnd { outcome, velocity, generation: 0 }
154 }
155
156 fn progress(&self, now: Option<Instant>) -> f64 {
159 let duration = self.duration;
160 match now {
161 Some(now) if !duration.is_zero() => mln_style::math::clamp_f64(
162 now.saturating_duration_since(self.start).div_duration_f64(duration),
163 0.0,
164 1.0,
165 ),
166 _ => 1.0,
167 }
168 }
169
170 fn eased_progress(&self, now: Option<Instant>) -> f64 {
173 let t = self.progress(now);
174 let ease = self.animation.easing.unwrap_or(DEFAULT_TRANSITION_EASE);
175 if t == 1.0 { 1.0 } else { ease.solve(t, 0.001) }
176 }
177
178 pub(super) fn share(&self, now: Option<Instant>) -> f64 {
181 let k = self.eased_progress(now);
182 match &self.along {
183 Some(along) if k < 1.0 => along(k),
184 _ => k,
185 }
186 }
187
188 pub(super) fn remaining(&self, now: Option<Instant>) -> Duration {
190 self.duration.saturating_sub(self.elapsed(now))
191 }
192
193 pub(super) fn elapsed(&self, now: Option<Instant>) -> Duration {
196 now.map_or(Duration::MAX, |now| now.saturating_duration_since(self.start))
197 }
198
199 fn has_run_out(&self, now: Option<Instant>) -> bool {
201 now.is_none_or(|now| now >= self.start && self.elapsed(Some(now)) >= self.duration)
202 }
203}
204
205fn compose(camera: &mut CameraOptions, value: &CameraOptions, fields: u16) {
208 if fields & CENTER != 0 && value.center.is_some() {
209 camera.center = value.center;
210 }
211 if fields & ZOOM != 0 {
212 camera.zoom = value.zoom;
213 }
214 if fields & BEARING != 0 {
215 camera.bearing = value.bearing;
216 }
217 if fields & PITCH != 0 {
218 camera.pitch = value.pitch;
219 }
220 if fields & PADDING != 0 && value.padding.is_some() {
221 camera.padding = value.padding;
222 }
223 if fields & ALTITUDE != 0 {
224 camera.center_altitude = value.center_altitude;
225 }
226 if fields & ROLL != 0 {
227 camera.roll = value.roll;
228 }
229 if fields & FOV != 0 {
230 camera.fov = value.fov;
231 }
232}
233
234fn place(state: &mut TransformState, current: &CameraOptions, camera: &mut CameraOptions) {
242 let padding = camera.padding.unwrap_or_default();
243 state.set_padding(&padding);
244 if let Some(fov) = camera.fov.filter(|_| camera.fov != current.fov) {
245 state.set_fov(mln_style::math::deg2rad(fov));
246 }
247 if let Some(bearing) = camera.bearing.filter(|_| camera.bearing != current.bearing) {
248 state.set_angle(mln_style::math::deg2rad(-bearing));
249 }
250 if let Some(roll) = camera.roll.filter(|_| camera.roll != current.roll) {
251 state.set_roll(mln_style::math::deg2rad(roll));
252 }
253 let pitch = match camera.pitch.filter(|_| camera.pitch != current.pitch) {
254 Some(pitch) => mln_style::math::deg2rad(pitch),
255 None => state.view().pitch(),
256 };
257 state.set_pitch(f64::min(max_pitch_for_padding(state, &padding), pitch));
258 state.set_center_altitude(camera.center_altitude.unwrap_or_default());
260 let mut zoom = camera.zoom.unwrap_or_default();
261 state.constrain_camera_and_zoom_to_bounds(camera, &mut zoom);
262 state.set_lat_lng_zoom(&camera.center.unwrap_or_default(), zoom);
263}
264
265fn anchored_end(
277 state: &TransformState,
278 camera: &CameraOptions,
279 anchor: &ScreenCoordinate,
280 location: &LatLng,
281 height: f64,
282 ground: &dyn Elevation,
283) -> LatLng {
284 let mut state = state.clone();
285 let current = state.camera_options(None);
286 let altitude = current.center_altitude;
287 place(&mut state, ¤t, &mut CameraOptions { center_altitude: altitude, ..*camera });
288 if state.view().is_globe() || !sees_plane(state.view(), anchor, height) {
289 return state.view().center(WrapMode::Wrapped);
290 }
291 let _ = state.move_lat_lng_at(location, anchor, height);
293 let view = state.view();
294 let center = view.center(WrapMode::Unwrapped);
295 let on_ground = view.line_of_sight(anchor).and_then(|(near, far)| {
296 let world = Projection::project(¢er, 1.0 / TILE_SIZE_D);
297 let at = DVec3::new(world.x, world.y, view.center_altitude());
298 view.ground_along(at - (far - near), at + (far - near), ground)
299 });
300 on_ground.map_or(center, |hit| hit.location(WrapMode::Unwrapped)).wrapped()
301}
302
303pub(super) struct JointEnd {
307 command: CameraCommandId,
308 remaining: u32,
309 outcome: TransitionOutcome,
310}
311
312impl Transform {
313 pub(super) fn start_transition(
323 &mut self,
324 camera: &CameraOptions,
325 animation: &AnimationOptions,
326 frame: FrameFn,
327 along: Option<AlongFn>,
328 duration: Duration,
329 flight: bool,
330 ) {
331 let mut fields = camera_fields(camera);
332 if self.clamped() {
333 fields &= !ALTITUDE;
334 }
335 let mut coupled_fields = if flight { CENTER | ZOOM } else { 0 };
336 fields |= coupled_fields;
337
338 let mut anchor = if camera.center.is_some() { None } else { camera.anchor };
341 let mut anchor_lat_lng = LatLng::default();
342 let mut anchor_height = 0.0;
343 if let Some(a) = anchor.as_mut() {
344 anchor_height = self.anchor_height(a, a);
345 a.y = f64::from(self.state.view().size().height) - a.y;
346 match self.state.view().screen_coordinate_to_lat_lng_at(a, anchor_height, WrapMode::Unwrapped) {
349 Ok(lat_lng) => {
350 anchor_lat_lng = lat_lng;
351 fields |= CENTER;
352 coupled_fields = fields;
353 }
354 Err(e) => {
355 log::error!(target: log_target::GENERAL, "{}", e.message);
356 anchor = None;
357 }
358 }
359 }
360
361 let target = frame(&self.state, 1.0);
362 let panning = flight || anchor.is_some() || camera.center != Some(self.view().center(WrapMode::Unwrapped));
363 let scaling = flight || target.zoom != Some(self.view().zoom());
364 let rotating = target.bearing != Some(-mln_style::math::rad2deg(self.view().angle()));
365 let moving_fields = (if panning { CENTER } else { 0 })
366 | (if scaling { ZOOM } else { 0 })
367 | (if rotating { BEARING } else { 0 });
368
369 let start = self.now();
370 let duration = if fields != 0 { duration } else { Duration::ZERO };
371 let transition = Transition {
372 coupled_fields,
373 along,
374 anchor,
375 anchor_lat_lng,
376 anchor_height,
377 command: self.reporting(),
378 ..Transition::new(fields, moving_fields, start, duration, animation, frame, self.source)
379 };
380 let mode = transition.mode();
381
382 let finished = self.release_fields(fields);
383 self.transitions.push(transition);
384 self.update_movement_flags();
385 self.finish_transitions(finished);
386
387 self.emit(TransformEvent::CameraWillChange(CameraChange { mode, source: self.source }));
388
389 if duration == Duration::ZERO {
390 let index = self.transitions.len() - 1;
391 self.apply_transitions(Some(index), Some(start));
392 let transition = self.transitions.remove(index);
393 self.update_movement_flags();
394 self.finish_transitions(vec![transition]);
395 }
396 }
397
398 fn apply_transitions(&mut self, only: Option<usize>, now: Option<Instant>) {
402 let current = self.state.camera_options(None);
405 let mut camera = current;
406
407 let active = match only {
408 Some(index) => &self.transitions[index..=index],
409 None => &self.transitions[..],
410 };
411 for transition in active.iter().filter(|transition| transition.momentum.is_none()) {
412 let k = transition.eased_progress(now);
413 compose(&mut camera, &(transition.frame)(&self.state, k), transition.fields);
414 }
415 let lands = self.ease_altitude(&mut camera, now);
416
417 let anchored = self.transitions.iter().enumerate().rev().find_map(|(index, transition)| {
420 let anchor = transition.anchor.filter(|_| transition.fields & CENTER != 0)?;
421 Some((anchor, transition.anchor_lat_lng, transition.anchor_height, index))
422 });
423
424 let globe_zoom_around = match anchored {
430 Some((anchor, anchor_lat_lng, height, _)) if self.globe_on_screen() => {
431 let location = self
432 .state
433 .view()
434 .screen_coordinate_to_lat_lng_at(&anchor, height, WrapMode::Unwrapped)
435 .unwrap_or_else(|e| {
436 log::error!(target: log_target::GENERAL, "{}", e.message);
437 anchor_lat_lng
438 });
439 Some((location, self.state.view().zoom()))
440 }
441 _ => None,
442 };
443
444 place(&mut self.state, ¤t, &mut camera);
447 if let Some((anchor, anchor_lat_lng, height, index)) = anchored {
448 match globe_zoom_around {
449 Some((location, zoom_before)) if self.state.view().zoom() != zoom_before => {
450 let zoom_delta = self.state.view().zoom() - zoom_before;
451 let free_bearing = self.state.view().globe_free_bearing();
452 VerticalPerspectiveProjection::zoom_around_point(
453 &mut self.state,
454 &anchor,
455 &location,
456 height,
457 zoom_delta,
458 free_bearing,
459 );
460 }
461 _ => self.hold_anchor(&anchor_lat_lng, &anchor, height, ¤t, index),
462 }
463 }
464 if lands {
465 self.stand_on_ground();
466 }
467 self.keep_clear_of_ground();
469 }
470
471 fn hold_anchor(
482 &mut self,
483 location: &LatLng,
484 anchor: &ScreenCoordinate,
485 height: f64,
486 before: &CameraOptions,
487 index: usize,
488 ) {
489 if !self.view().is_globe() && !sees_plane(self.view(), anchor, height) {
490 let zoom = self.view().zoom();
491 self.state.set_lat_lng_zoom(&before.center.unwrap_or_default(), zoom);
492 let transition = &mut self.transitions[index];
493 transition.anchor = None;
494 transition.fields &= !CENTER;
495 return;
496 }
497 if let Err(e) = self.state.move_lat_lng_at(location, anchor, height) {
498 log::error!(target: log_target::GENERAL, "{}", e.message);
499 }
500 }
501
502 pub(super) fn update_movement_flags(&mut self) {
504 self.moving = self.transitions.iter().fold(0, |moving, t| moving | (t.fields & t.moving_fields));
505 }
506
507 pub(super) fn finish_transitions(&mut self, finished: Vec<Transition>) {
511 for transition in &finished {
512 self.end_gesture_momentum(transition.gesture);
513 }
514 if !finished.is_empty() {
515 self.come_to_rest();
516 }
517 for transition in finished {
518 self.report_end(transition.command, transition.animation.transition_id, transition.end());
519 let change = CameraChange { mode: transition.mode(), source: transition.source };
522 self.emit(TransformEvent::CameraDidChange(change));
523 }
524 }
525
526 #[must_use]
528 pub fn in_transition(&self) -> bool {
529 !self.transitions.is_empty()
530 }
531
532 pub fn update_transitions(&mut self, now: Option<Instant>) {
535 if self.transitions.is_empty() {
536 return;
537 }
538
539 if self.transitions.iter().any(|t| t.momentum.is_none()) {
540 self.apply_transitions(None, now);
541 }
542 for index in 0..self.transitions.len() {
543 self.advance_momentum(index, now);
544 }
545 if self.transitions.iter().any(|t| t.momentum.is_some()) {
546 self.keep_clear_of_ground();
547 }
548
549 let finished: Vec<_> = self.transitions.extract_if(.., |t| t.has_run_out(now) || t.fields == 0).collect();
550 self.update_movement_flags();
551 if !self.transitions.is_empty() {
552 self.emit(TransformEvent::CameraIsChanging);
553 }
554
555 self.finish_transitions(finished);
556 }
557
558 pub(super) fn release_fields(&mut self, fields: u16) -> Vec<Transition> {
561 for active in &mut self.transitions {
562 let mut replaced = fields;
563 let coupled = active.coupled_fields & active.fields;
566 if coupled & replaced != 0 {
567 replaced |= coupled;
568 }
569 active.fields &= !replaced;
570 if let Some(momentum) = &mut active.momentum {
571 active.fields = momentum.retain(active.fields);
572 }
573 if active.fields == 0 {
574 active.ended_by(TransitionOutcome::Replaced);
575 }
576 }
577 self.transitions.extract_if(.., |active| active.fields == 0).collect()
578 }
579
580 pub(super) fn command(&mut self, start: impl FnOnce(&mut Self)) -> CameraCommandId {
585 if let Some(command) = self.command {
586 start(self);
587 return command;
588 }
589 let command = CameraCommandId(self.next_command);
590 self.next_command += 1;
591 self.command = Some(command);
592 start(self);
593 self.command = None;
594 command
595 }
596
597 pub(super) fn reporting(&self) -> Option<CameraCommandId> {
599 self.command.filter(|_| !self.silent)
600 }
601
602 pub(super) fn join_ends(&mut self, count: u32) {
605 if let Some(command) = self.reporting().filter(|_| count > 1) {
606 self.joint_ends.push(JointEnd { command, remaining: count, outcome: TransitionOutcome::Completed });
607 }
608 }
609
610 fn report_end(&mut self, command: Option<CameraCommandId>, transition_id: Option<u64>, mut end: TransitionEnd) {
613 let Some(command) = command else { return };
614 if let Some(index) = self.joint_ends.iter().position(|joint| joint.command == command) {
615 let joint = &mut self.joint_ends[index];
616 joint.remaining -= 1;
617 joint.outcome = match (joint.outcome, end.outcome) {
618 (TransitionOutcome::Cancelled, _) | (_, TransitionOutcome::Cancelled) => TransitionOutcome::Cancelled,
619 (TransitionOutcome::Closed, _) | (_, TransitionOutcome::Closed) => TransitionOutcome::Closed,
620 (TransitionOutcome::Replaced, _) | (_, TransitionOutcome::Replaced) => TransitionOutcome::Replaced,
621 _ => TransitionOutcome::Completed,
622 };
623 if joint.remaining > 0 {
624 return;
625 }
626 end.outcome = joint.outcome;
627 self.joint_ends.swap_remove(index);
628 }
629 self.emit(TransformEvent::CommandEnded(CommandEnd { command, transition_id, end }));
630 }
631
632 pub(super) fn end_unstarted(&mut self, animation: &AnimationOptions, outcome: TransitionOutcome) {
635 self.report_end(
636 self.reporting(),
637 animation.transition_id,
638 TransitionEnd { outcome, ..TransitionEnd::default() },
639 );
640 }
641
642 pub(crate) fn cancel_transitions(&mut self) {
643 let mut finished = std::mem::take(&mut self.transitions);
644 for transition in &mut finished {
645 transition.ended_by(TransitionOutcome::Cancelled);
646 }
647 self.update_movement_flags();
648 self.finish_transitions(finished);
649 }
650
651 pub fn cancel_transitions_with_id(&mut self, transition_id: u64) -> bool {
655 let mut finished: Vec<_> = self
656 .transitions
657 .extract_if(.., |transition| transition.animation.transition_id == Some(transition_id))
658 .collect();
659 if finished.is_empty() {
660 return false;
661 }
662 for transition in &mut finished {
663 transition.ended_by(TransitionOutcome::Cancelled);
664 }
665 self.update_movement_flags();
666 self.finish_transitions(finished);
667 true
668 }
669
670 pub fn close(&mut self) {
674 for transition in std::mem::take(&mut self.transitions) {
675 let end = TransitionEnd { outcome: TransitionOutcome::Closed, ..transition.end() };
676 self.report_end(transition.command, transition.animation.transition_id, end);
677 }
678 self.update_movement_flags();
679 }
680}