1use std::ops::{Add, AddAssign, Div, Mul, Sub};
6use std::time::Duration;
7
8use mln_style::unitbezier::UnitBezier;
9
10use crate::camera::{
11 AnchoredMomentum, AnimationOptions, CameraDelta, CameraMomentum, CameraOptions, CameraUpdate, CameraUpdateMode,
12 CameraVelocity, GesturePhase, MomentumGlide, TransitionOutcome,
13};
14use crate::geo::ScreenCoordinate;
15use crate::gestures::camera::{GestureCamera, PendingEnd};
16use crate::gestures::input::{GestureEvent, Input, Modes, PinchPhase, PointerKind};
17use crate::gestures::notches::NotchWatch;
18use crate::gestures::options::{AxisOptions, GestureOptions, InvalidGestureOptions};
19use crate::gestures::velocity::VelocityTracker;
20
21const BOX_EASE: Duration = Duration::from_millis(500);
23const EASE_X1: f64 = 0.25;
25const EASE_Y1: f64 = 0.1;
26const EASE_X2: f64 = 0.25;
27const EASE_Y2: f64 = 1.0;
28const EASE: UnitBezier = UnitBezier::new(EASE_X1, EASE_Y1, EASE_X2, EASE_Y2);
29const STAGED_RELEASE_MS: f64 = 100.0;
33const PITCH_DECIDE_PX: f64 = 2.0;
37const PITCH_DECIDE_MS: f64 = 100.0;
38const STEP_EASE_HANDLE: f64 = 0.27;
41const STEP_EASE_DONE: f64 = 1e-9;
43const DELTA_PARTS: usize = 5;
46const DELTA_ZOOM: usize = 2;
47
48#[derive(Clone, Copy, Debug, Default, PartialEq)]
50struct V2 {
51 x: f64,
52 y: f64,
53}
54
55impl V2 {
56 const ZERO: V2 = V2 { x: 0.0, y: 0.0 };
57
58 fn new(x: f64, y: f64) -> V2 {
59 V2 { x, y }
60 }
61
62 fn length(self) -> f64 {
63 self.x.hypot(self.y)
64 }
65
66 fn distance(self, other: V2) -> f64 {
67 (self - other).length()
68 }
69
70 fn dot(self, other: V2) -> f64 {
71 self.x * other.x + self.y * other.y
72 }
73
74 fn abs(self) -> V2 {
75 V2::new(self.x.abs(), self.y.abs())
76 }
77}
78
79impl From<ScreenCoordinate> for V2 {
80 fn from(p: ScreenCoordinate) -> V2 {
81 V2::new(p.x, p.y)
82 }
83}
84
85impl From<V2> for ScreenCoordinate {
86 fn from(v: V2) -> ScreenCoordinate {
87 ScreenCoordinate::new(v.x, v.y)
88 }
89}
90
91impl Add for V2 {
92 type Output = V2;
93 fn add(self, o: V2) -> V2 {
94 V2::new(self.x + o.x, self.y + o.y)
95 }
96}
97
98impl AddAssign for V2 {
99 fn add_assign(&mut self, o: V2) {
100 *self = *self + o;
101 }
102}
103
104impl Sub for V2 {
105 type Output = V2;
106 fn sub(self, o: V2) -> V2 {
107 V2::new(self.x - o.x, self.y - o.y)
108 }
109}
110
111impl Mul<f64> for V2 {
112 type Output = V2;
113 fn mul(self, s: f64) -> V2 {
114 V2::new(self.x * s, self.y * s)
115 }
116}
117
118impl Div<f64> for V2 {
119 type Output = V2;
120 fn div(self, s: f64) -> V2 {
121 V2::new(self.x / s, self.y / s)
122 }
123}
124
125#[derive(Clone, Copy, Debug)]
126struct Pointer {
127 id: u32,
128 kind: PointerKind,
129 position: V2,
130 down: V2,
131 down_at: f64,
132 modes: Modes,
134}
135
136#[derive(Clone, Copy, Debug)]
137struct Pinch {
138 last: [V2; 2],
139 start_distance: f64,
140 start_vector: V2,
141 min_diameter: f64,
142 zooming: bool,
143 rotating: bool,
144 pitch: Option<bool>,
146 single_since: Option<f64>,
147 panning: bool,
148 tap: bool,
151}
152
153#[derive(Clone, Copy, Debug)]
154enum Mode {
155 Idle,
156 Pressed {
159 long_pressed: bool,
160 },
161 Pan,
162 BoxZoom {
165 origin: V2,
166 },
167 Rotate,
169 Pinch(Pinch),
170 TapDrag {
173 origin: V2,
174 moved: bool,
175 long_pressed: bool,
176 },
177 Platform,
179 Ignored,
181}
182
183#[derive(Clone, Copy, Debug, Default)]
185struct Step {
186 pan: V2,
187 zoom: f64,
188 bearing: f64,
189 pitch: f64,
190 around: Option<V2>,
191}
192
193#[derive(Clone, Copy, Debug, Default)]
195struct Release {
196 pan: Option<V2>,
197 zoom: Option<f64>,
198 bearing: Option<f64>,
199 pitch: Option<f64>,
200 zoom_anchor: Option<V2>,
201 bearing_anchor: Option<V2>,
202}
203
204#[derive(Debug, Default)]
206struct Tracking {
207 pan: V2,
209 zoom: f64,
210 bearing: f64,
211 pitch: f64,
212 trackers: [VelocityTracker; 5],
214 zoom_anchor: Option<V2>,
215 bearing_anchor: Option<V2>,
216 staged: Option<(f64, Release)>,
219 not_before: f64,
221}
222
223impl Tracking {
224 fn reset(&mut self, now: f64) {
225 *self = Self::default();
226 self.record(now, Step::default());
227 }
228
229 fn record(&mut self, now: f64, step: Step) {
232 self.pan += step.pan;
233 self.zoom += step.zoom;
234 self.bearing += step.bearing;
235 self.pitch += step.pitch;
236 if step.zoom != 0.0 {
237 self.zoom_anchor = step.around;
238 }
239 if step.bearing != 0.0 {
240 self.bearing_anchor = step.around;
241 }
242 if now < self.not_before {
243 return;
244 }
245 let values = [self.pan.x, self.pan.y, self.zoom, self.bearing, self.pitch];
246 let moved =
247 [step.pan != V2::ZERO, step.pan != V2::ZERO, step.zoom != 0.0, step.bearing != 0.0, step.pitch != 0.0];
248 let start = self.trackers.iter().all(VelocityTracker::is_empty);
249 for ((tracker, value), moved) in self.trackers.iter_mut().zip(values).zip(moved) {
250 if moved || start || !tracker.is_empty() {
251 tracker.add(now, value);
252 }
253 }
254 }
255
256 fn release(&mut self, now: f64) -> Release {
258 let [x, y, zoom, bearing, pitch] = self.trackers.each_ref().map(|t| t.velocity(now));
259 let some = |v: f64| (v != 0.0 && v.is_finite()).then_some(v);
261 let mut release = Release {
262 pan: ((x != 0.0 || y != 0.0) && x.is_finite() && y.is_finite()).then_some(V2::new(x, y)),
263 zoom: some(zoom),
264 bearing: some(bearing),
265 pitch: some(pitch),
266 zoom_anchor: self.zoom_anchor,
267 bearing_anchor: self.bearing_anchor,
268 };
269 if let Some((at, staged)) = self.staged.take()
273 && now - at <= STAGED_RELEASE_MS
274 {
275 if release.pan.is_none() {
276 release.pan = staged.pan;
277 }
278 if release.zoom.is_none() {
279 release.zoom = staged.zoom;
280 release.zoom_anchor = staged.zoom_anchor;
281 }
282 if release.bearing.is_none() {
283 release.bearing = staged.bearing;
284 release.bearing_anchor = staged.bearing_anchor;
285 }
286 if release.pitch.is_none() {
287 release.pitch = staged.pitch;
288 }
289 }
290 release
291 }
292
293 fn stage(&mut self, now: f64) {
297 let release = self.release(now);
298 self.staged = Some((now, release));
299 for tracker in &mut self.trackers {
300 tracker.reset();
301 }
302 self.not_before = now + STAGED_RELEASE_MS;
303 }
304}
305
306impl Release {
307 fn into_momentum(self, caught_glide: Option<CameraVelocity>, options: &GestureOptions) -> CameraMomentum {
315 let caught = caught_glide.unwrap_or_default();
316 let pan = options.pan.momentum.and_then(|decay| {
317 let velocity = self.pan.filter(|v| v.length() >= decay.min_speed)?;
318 let caught = V2::from(caught.pan);
319 let velocity = if velocity.dot(caught) > 0.0 { velocity + caught } else { velocity };
320 Some(MomentumGlide { velocity: velocity.into(), decay })
321 });
322 let scalar = |part: &AxisOptions, release: Option<f64>, anchor: Option<V2>, caught: f64| AnchoredMomentum {
323 glide: part.momentum.and_then(|decay| {
324 let velocity = release.filter(|v| v.abs() >= decay.min_speed)?;
325 let velocity =
326 if caught != 0.0 && caught.signum() == velocity.signum() { velocity + caught } else { velocity };
327 Some(MomentumGlide { velocity, decay })
328 }),
329 anchor: anchor.map(ScreenCoordinate::from),
330 snap: part.snap,
331 };
332 CameraMomentum {
333 pan,
334 zoom: scalar(&options.zoom, self.zoom, self.zoom_anchor, caught.zoom),
335 bearing: scalar(&options.bearing, self.bearing, self.bearing_anchor, caught.bearing),
336 pitch: scalar(&options.pitch, self.pitch, None, caught.pitch),
337 }
338 }
339}
340
341#[derive(Clone, Copy, Debug)]
343struct DeltaGesture {
344 anchor: V2,
349 idle_until: f64,
352 eases: [Option<StepEase>; DELTA_PARTS],
354}
355
356#[derive(Clone, Copy, Debug)]
358struct StepEase {
359 start: f64,
360 distance: f64,
362 applied: f64,
363 x1: f64,
365 y1: f64,
366}
367
368impl StepEase {
369 fn retarget(ease: Option<StepEase>, step: f64, now: f64, duration: f64, limit: impl Fn(f64) -> f64) -> StepEase {
375 let (distance, (x1, y1)) = match ease {
376 Some(ease) if ease.progress(now, duration) < 1.0 => {
377 let distance = limit(ease.distance - ease.applied + step);
379 let slope = if distance == 0.0 { 0.0 } else { ease.speed(now, duration) * duration / distance };
384 let x1 = STEP_EASE_HANDLE / (1.0 + slope * slope).sqrt();
385 (distance, (x1, slope * x1))
386 }
387 Some(ease) => (limit(ease.distance - ease.applied + step), (EASE_X1, EASE_Y1)),
388 None => (limit(step), (EASE_X1, EASE_Y1)),
389 };
390 StepEase { start: now, distance, applied: 0.0, x1, y1 }
391 }
392
393 fn curve(&self) -> UnitBezier {
394 UnitBezier::new(self.x1, self.y1, EASE_X2, EASE_Y2)
395 }
396
397 fn progress(&self, now: f64, duration: f64) -> f64 {
399 ((now - self.start) / duration).clamp(0.0, 1.0)
400 }
401
402 fn value(&self, now: f64, duration: f64) -> f64 {
404 let t = self.progress(now, duration);
405 self.distance * if t >= 1.0 { 1.0 } else { self.curve().solve(t, 1e-6) }
406 }
407
408 fn speed(&self, now: f64, duration: f64) -> f64 {
410 let dt = 1.0;
411 (self.value(now + dt, duration) - self.value(now, duration)) / dt
412 }
413}
414
415#[derive(Clone, Copy, Debug, PartialEq)]
417pub enum NextTick {
418 Frame,
421 At(f64),
424}
425
426#[derive(Clone, Copy, Debug, PartialEq, Eq)]
428enum Finish {
429 Cancel,
432 Stop,
434 Settle,
436 Glide,
438}
439
440#[derive(Debug)]
462pub struct GestureRecognizer<C> {
463 camera: C,
465 options: GestureOptions,
466 pointers: Vec<Pointer>,
467 mode: Mode,
468 tracking: Tracking,
469 begun: bool,
472 release_end: Option<PendingEnd>,
475 caught_glide: Option<PendingEnd>,
478 last_tap: Option<(V2, f64, PointerKind)>,
480 modes: Modes,
482 deltas: Option<DeltaGesture>,
483 notch_watch: Option<NotchWatch>,
486 events: Vec<GestureEvent>,
487}
488
489impl<C: GestureCamera> GestureRecognizer<C> {
490 pub fn new(camera: C) -> Self {
492 GestureRecognizer::with(camera, GestureOptions::default())
493 }
494
495 pub fn with_options(camera: C, options: GestureOptions) -> Result<Self, InvalidGestureOptions> {
498 options.validate()?;
499 Ok(GestureRecognizer::with(camera, options))
500 }
501
502 fn with(camera: C, options: GestureOptions) -> Self {
503 GestureRecognizer {
504 camera,
505 options,
506 pointers: Vec::new(),
507 mode: Mode::Idle,
508 tracking: Tracking::default(),
509 begun: false,
510 release_end: None,
511 caught_glide: None,
512 last_tap: None,
513 modes: Modes::default(),
514 deltas: None,
515 notch_watch: None,
516 events: Vec::new(),
517 }
518 }
519
520 #[must_use]
522 pub fn camera(&self) -> &C {
523 &self.camera
524 }
525
526 #[must_use]
527 pub fn options(&self) -> &GestureOptions {
528 &self.options
529 }
530
531 pub fn set_options(&mut self, options: GestureOptions) -> Result<(), InvalidGestureOptions> {
533 options.validate()?;
534 self.options = options;
535 Ok(())
536 }
537
538 #[cfg(test)]
540 #[must_use]
541 pub(crate) fn is_active(&self) -> bool {
542 !matches!(self.mode, Mode::Idle) || self.deltas.is_some()
543 }
544
545 #[must_use]
548 pub fn box_zoom(&self) -> Option<[ScreenCoordinate; 2]> {
549 match self.mode {
550 Mode::BoxZoom { origin } => Some([origin.into(), self.pointers.first()?.position.into()]),
551 _ => None,
552 }
553 }
554
555 #[must_use]
560 pub fn next_tick(&self) -> Option<NextTick> {
561 let easing = self.deltas.is_some_and(|deltas| deltas.eases.iter().any(Option::is_some));
562 let held_still = matches!(self.mode, Mode::Pressed { .. } | Mode::TapDrag { moved: false, .. });
564 if easing || (self.notch_watch.is_some() && !held_still) {
565 return Some(NextTick::Frame);
566 }
567 let long_press = match self.pointers[..] {
568 [pointer] if self.awaits_long_press() => Some(pointer.down_at + self.options.long_press_ms),
569 _ => None,
570 };
571 let idle = self.deltas.map(|deltas| deltas.idle_until);
572 long_press.into_iter().chain(idle).min_by(f64::total_cmp).map(NextTick::At)
573 }
574
575 fn awaits_long_press(&self) -> bool {
577 matches!(
578 self.mode,
579 Mode::Pressed { long_pressed: false } | Mode::TapDrag { moved: false, long_pressed: false, .. }
580 )
581 }
582
583 pub fn take_events(&mut self) -> Vec<GestureEvent> {
585 std::mem::take(&mut self.events)
586 }
587
588 pub fn step_to(&mut self, update: &CameraUpdate) {
594 let set = &update.camera;
595 let center = set.center.is_some();
596 self.stop_step_eases([center, center, set.zoom.is_some(), set.bearing.is_some(), set.pitch.is_some()]);
597 if !self.begun {
600 self.notch_watch = None;
601 }
602 let phase = if self.begun { GesturePhase::Update } else { GesturePhase::End };
603 self.camera.update_camera(&CameraUpdate { phase, ..*update });
604 }
605
606 pub fn tick(&mut self, now: f64) -> Option<NextTick> {
611 self.long_press(now);
612 self.delta_frame(now);
613 if let Some(watch) = &mut self.notch_watch {
614 watch.sample(&self.camera.camera(), &self.options, now, &mut self.events);
615 if !self.begun && self.release_end.as_ref().is_none_or(PendingEnd::has_ended) {
618 self.notch_watch = None;
619 }
620 }
621 self.next_tick()
622 }
623
624 fn long_press(&mut self, now: f64) {
626 if self.awaits_long_press()
627 && let [pointer] = self.pointers[..]
628 && now - pointer.down_at >= self.options.long_press_ms
629 {
630 match &mut self.mode {
631 Mode::Pressed { long_pressed } | Mode::TapDrag { long_pressed, .. } => *long_pressed = true,
632 _ => {}
633 }
634 self.last_tap = None;
635 self.events.push(GestureEvent::LongPress { id: pointer.id, position: pointer.position.into() });
636 }
637 }
638
639 fn delta_frame(&mut self, now: f64) -> bool {
641 let Some(mut gesture) = self.deltas else {
642 return false;
643 };
644 let duration = self.options.step_duration_ms;
645 let max_zoom = self.options.max_step_zoom;
646 let mut amounts = [0.0; DELTA_PARTS];
647 for (part, slot) in gesture.eases.iter_mut().enumerate() {
648 let Some(mut ease) = *slot else { continue };
649 let mut amount = ease.value(now, duration) - ease.applied;
650 if part == DELTA_ZOOM {
651 amount = amount.clamp(-max_zoom, max_zoom);
652 }
653 ease.applied += amount;
654 amounts[part] = amount;
655 let done = ease.progress(now, duration) >= 1.0 && (ease.distance - ease.applied).abs() <= STEP_EASE_DONE;
656 *slot = (!done).then_some(ease);
657 if done {
658 gesture.idle_until = gesture.idle_until.max(now + self.options.delta_idle_ms);
659 }
660 }
661 if !self.begun && amounts.iter().any(|amount| *amount != 0.0) {
664 self.begun = true;
665 self.camera.apply_camera_delta(&CameraDelta { phase: GesturePhase::Update, ..CameraDelta::default() });
666 }
667 self.move_by(amounts, gesture.anchor);
668 if gesture.eases.iter().all(Option::is_none) && now >= gesture.idle_until {
669 self.deltas = None;
670 if matches!(self.mode, Mode::Idle) {
671 self.end_phase(None);
672 }
673 return false;
674 }
675 self.deltas = Some(gesture);
676 true
677 }
678
679 pub fn handle(&mut self, input: Input, now: f64) -> bool {
682 match input {
683 Input::PointerDown { id, kind, position, modes } => {
684 let position = position.into();
685 self.down(Pointer { id, kind, position, down: position, down_at: now, modes })
686 }
687 Input::PointerMove { id, position } => self.moved(id, position.into(), now),
688 Input::PointerUp { id, position } => self.up(id, Some(position.into()), now),
689 Input::PointerCancel { id } => self.up(id, None, now),
690 Input::Modes(modes) => {
693 self.modes = modes;
694 false
695 }
696 Input::Delta { position, discrete, pan, zoom, bearing, pitch } => {
697 self.delta(position.into(), discrete, [pan.x, pan.y, zoom, bearing, pitch], now)
698 }
699 Input::Pinch { center, scale, rotation, phase } => {
700 self.platform_pinch(center.into(), scale, rotation, phase, now)
701 }
702 }
703 }
704
705 fn animation(&self, duration: Duration, easing: UnitBezier) -> AnimationOptions {
707 AnimationOptions {
708 duration: Some(duration),
709 easing: Some(easing),
710 transition_id: Some(self.options.transition_id),
711 ..AnimationOptions::default()
712 }
713 }
714
715 fn begin(&mut self) {
722 if self.begun {
723 return;
724 }
725 self.begun = true;
726 self.caught_glide = self.release_end.take().filter(|end| end.take().is_none());
729 let notches = [&self.options.zoom, &self.options.bearing, &self.options.pitch]
730 .iter()
731 .any(|part| part.enabled && !part.notches.is_empty());
732 self.notch_watch = notches.then(|| NotchWatch::new(&self.camera.camera(), &self.options));
733 let phase = if self.options.interrupt_animations {
734 GesturePhase::Begin
735 } else {
736 self.camera.cancel_transitions_with_id(self.options.transition_id);
737 GesturePhase::Update
738 };
739 self.camera.apply_camera_delta(&CameraDelta { phase, ..CameraDelta::default() });
740 }
741
742 fn update(&mut self, delta: &CameraDelta) {
744 self.begin();
745 self.camera.apply_camera_delta(&CameraDelta { phase: GesturePhase::Update, ..*delta });
746 }
747
748 fn end_phase(&mut self, momentum: Option<&CameraMomentum>) {
751 if !std::mem::replace(&mut self.begun, false) {
752 return;
753 }
754 let animation =
755 AnimationOptions { transition_id: Some(self.options.transition_id), ..AnimationOptions::default() };
756 let phase = GesturePhase::End;
757 let delta = CameraDelta { momentum: momentum.copied(), animation, phase, ..CameraDelta::default() };
758 let end = self.camera.release(&delta);
759 if momentum.is_some() {
762 self.release_end = Some(end);
763 }
764 }
765
766 fn cancel_phase(&mut self) {
770 self.notch_watch = None;
771 if !std::mem::replace(&mut self.begun, false) {
772 return;
773 }
774 let phase = if self.options.interrupt_animations {
775 GesturePhase::Cancel
776 } else {
777 self.camera.cancel_transitions_with_id(self.options.transition_id);
778 GesturePhase::End
779 };
780 self.camera.apply_camera_delta(&CameraDelta { phase, ..CameraDelta::default() });
781 }
782
783 fn stop_step_eases(&mut self, parts: [bool; DELTA_PARTS]) {
785 if let Some(gesture) = self.deltas.as_mut() {
786 for (ease, stop) in gesture.eases.iter_mut().zip(parts) {
787 if stop {
788 *ease = None;
789 }
790 }
791 }
792 }
793
794 fn down(&mut self, pointer: Pointer) -> bool {
796 let Pointer { id, kind, position, down_at: now, .. } = pointer;
797 if self.pointers.iter().any(|p| p.id == id) {
798 return false;
799 }
800 let touch = kind == PointerKind::Touch;
801 if !touch && !self.pointers.is_empty() {
802 return false;
803 }
804 if matches!(self.mode, Mode::Platform) {
805 self.finish(now, Finish::Cancel);
807 }
808 self.pointers.push(pointer);
809 self.deltas = None;
811 self.begin();
812 match (self.mode, self.pointers.len()) {
813 (Mode::Idle, 1) => {
814 self.mode = if touch && self.follows_tap(kind, position, now) {
815 Mode::TapDrag { origin: position, moved: false, long_pressed: false }
816 } else {
817 Mode::Pressed { long_pressed: false }
818 };
819 self.tracking.reset(now);
820 }
821 (Mode::Pressed { .. } | Mode::Pan | Mode::TapDrag { .. }, 2) if touch => {
822 let [a, b] = [self.pointers[0].position, self.pointers[1].position];
823 let vector = b - a;
824 self.mode = Mode::Pinch(Pinch {
825 last: [a, b],
826 start_distance: vector.length(),
827 start_vector: vector,
828 min_diameter: vector.length(),
829 zooming: false,
830 rotating: false,
831 pitch: (!self.options.pitch.enabled || vector.y.abs() > vector.x.abs()).then_some(false),
833 single_since: None,
834 panning: false,
835 tap: now - self.pointers[0].down_at < self.options.tap_interval_ms
836 && matches!(self.mode, Mode::Pressed { .. }),
837 });
838 self.tracking.record(now, Step::default());
839 }
840 _ => self.mode = Mode::Ignored,
841 }
842 true
843 }
844
845 fn moved(&mut self, id: u32, position: V2, now: f64) -> bool {
846 let Some(index) = self.pointers.iter().position(|p| p.id == id) else {
847 return false;
848 };
849 let last = self.pointers[index].position;
850 self.pointers[index].position = position;
851 match &mut self.mode {
852 Mode::Pressed { .. } => {
853 let pointer = self.pointers[index];
854 let down = pointer.down;
855 if position.distance(down) > self.options.click_tolerance {
856 let modes = pointer.modes | self.modes;
858 self.mode = if modes.rotate {
859 Mode::Rotate
860 } else if modes.box_zoom && self.options.zoom.enabled {
861 Mode::BoxZoom { origin: down }
862 } else {
863 Mode::Pan
864 };
865 self.drag_step(down, position, now);
871 }
872 }
873 Mode::Pan | Mode::Rotate => self.drag_step(last, position, now),
874 Mode::TapDrag { origin, moved, .. } => {
875 let (origin, dy) = (*origin, position.y - last.y);
876 *moved = *moved || position.distance(origin) > self.options.click_tolerance;
877 if *moved && self.options.zoom.enabled {
878 let zoom = dy * self.options.tap_drag_zoom;
879 let delta =
880 CameraDelta { scale: Some(zoom.exp2()), anchor: Some(origin.into()), ..CameraDelta::default() };
881 self.update(&delta);
882 self.tracking.record(now, Step { zoom, around: Some(origin), ..Step::default() });
883 }
884 }
885 Mode::Pinch(_) if self.pointers.len() < 2 => {
886 self.mode = Mode::Pan;
889 self.drag_step(last, position, now);
890 }
891 Mode::Pinch(pinch) => {
892 if index > 1 {
893 return true;
894 }
895 let mut pinch = *pinch;
896 let points = [self.pointers[0].position, self.pointers[1].position];
897 self.pinch_step(&mut pinch, points, now);
898 self.mode = Mode::Pinch(pinch);
899 }
900 Mode::BoxZoom { .. } | Mode::Idle | Mode::Ignored | Mode::Platform => {}
901 }
902 true
903 }
904
905 fn drag_step(&mut self, from: V2, to: V2, now: f64) {
907 let delta = to - from;
908 match self.mode {
909 Mode::Rotate => {
910 let bearing = if self.options.bearing.enabled { delta.x * self.options.drag_rotate } else { 0.0 };
911 let pitch = if self.options.pitch.enabled { -delta.y * self.options.drag_pitch } else { 0.0 };
912 let step = CameraDelta { bearing: Some(bearing), pitch: Some(pitch), ..CameraDelta::default() };
913 self.update(&step);
914 self.tracking.record(now, Step { bearing, pitch, ..Step::default() });
915 }
916 Mode::BoxZoom { .. } => {}
917 _ if !self.options.pan.enabled => {}
918 _ => {
919 let step =
922 CameraDelta { offset: Some(delta.into()), anchor: Some(to.into()), ..CameraDelta::default() };
923 self.update(&step);
924 self.tracking.record(now, Step { pan: delta, ..Step::default() });
925 }
926 }
927 }
928
929 fn pinch_step(&mut self, pinch: &mut Pinch, points: [V2; 2], now: f64) {
930 let [a, b] = points;
931 let [la, lb] = pinch.last;
932 let (va, vb) = (a - la, b - lb);
933 let vector = b - a;
934 let tap_tolerance = self.options.tap_tolerance;
935 if pinch.tap
936 && (a.distance(self.pointers[0].down) > tap_tolerance || b.distance(self.pointers[1].down) > tap_tolerance)
937 {
938 pinch.tap = false;
939 }
940 if pinch.pitch.is_none() {
943 let (moved_a, moved_b) = (va.length() >= PITCH_DECIDE_PX, vb.length() >= PITCH_DECIDE_PX);
944 if moved_a && moved_b {
945 let vertical = |v: V2| v.y.abs() > v.x.abs();
946 pinch.pitch = Some(vertical(va) && vertical(vb) && (va.y > 0.0) == (vb.y > 0.0));
947 } else if moved_a || moved_b {
948 let since = *pinch.single_since.get_or_insert(now);
949 if now - since >= PITCH_DECIDE_MS {
950 pinch.pitch = Some(false);
951 }
952 }
953 if pinch.pitch.is_none() {
954 return;
955 }
956 }
957 if pinch.pitch == Some(true) {
958 let pitch = f64::midpoint(va.y, vb.y) * -self.options.drag_pitch;
959 self.update(&CameraDelta { pitch: Some(pitch), ..CameraDelta::default() });
960 pinch.last = points;
961 pinch.tap = false;
962 self.tracking.record(now, Step { pitch, ..Step::default() });
963 return;
964 }
965 let (mid, last_mid) = ((a + b) / 2.0, (la + lb) / 2.0);
966 let distance = vector.length();
967 let last_distance = (lb - la).length();
968 pinch.min_diameter = pinch.min_diameter.min(distance);
969 if !pinch.zooming
970 && self.options.zoom.enabled
971 && (distance / pinch.start_distance).log2().abs() >= self.options.pinch_zoom_threshold
972 {
973 pinch.zooming = true;
974 }
975 if !pinch.rotating && self.options.bearing.enabled {
976 let threshold = self.options.rotate_threshold / (std::f64::consts::PI * pinch.min_diameter) * 360.0;
977 if angle(pinch.start_vector, vector).abs() >= threshold {
978 pinch.rotating = true;
979 }
980 }
981 if !pinch.panning
982 && self.options.pan.enabled
983 && (mid - (self.pointers[0].down + self.pointers[1].down) / 2.0).length() > self.options.click_tolerance
984 {
985 pinch.panning = true;
986 }
987 let pan = if pinch.panning { mid - last_mid } else { V2::ZERO };
988 let zoom = if pinch.zooming && last_distance > 0.0 { (distance / last_distance).log2() } else { 0.0 };
989 let bearing = if pinch.rotating { -angle(lb - la, vector) } else { 0.0 };
991 pinch.last = points;
992 if pan == V2::ZERO && zoom == 0.0 && bearing == 0.0 {
993 return;
994 }
995 let anchored = zoom != 0.0 || bearing != 0.0 || pan != V2::ZERO;
998 self.update(&CameraDelta {
999 offset: (pan != V2::ZERO).then_some(pan.into()),
1000 scale: (zoom != 0.0).then_some(zoom.exp2()),
1001 bearing: (bearing != 0.0).then_some(bearing),
1002 anchor: anchored.then_some(mid.into()),
1003 ..CameraDelta::default()
1004 });
1005 pinch.tap = false;
1006 self.tracking.record(now, Step { pan, zoom, bearing, around: Some(mid), ..Step::default() });
1007 }
1008
1009 fn up(&mut self, id: u32, position: Option<V2>, now: f64) -> bool {
1010 let Some(index) = self.pointers.iter().position(|p| p.id == id) else {
1011 return false;
1012 };
1013 let pointer = self.pointers.remove(index);
1014 let cancelled = position.is_none();
1015 if cancelled && !self.pointers.is_empty() {
1018 self.finish(now, Finish::Cancel);
1019 self.mode = Mode::Ignored;
1020 return true;
1021 }
1022 let unless_cancelled = |finish: Finish| if cancelled { Finish::Cancel } else { finish };
1025 match self.mode {
1026 Mode::Pinch(pinch) => {
1027 if !self.pointers.is_empty() {
1028 let tap = pinch.tap && now - pointer.down_at < self.options.tap_interval_ms;
1031 self.mode = if tap {
1032 Mode::Pinch(pinch)
1033 } else {
1034 self.tracking.stage(now);
1035 Mode::Pan
1036 };
1037 return true;
1038 }
1039 self.finish(now, unless_cancelled(if pinch.tap { Finish::Settle } else { Finish::Glide }));
1040 if pinch.tap && !cancelled {
1041 let mid = (pinch.last[0] + pinch.last[1]) / 2.0;
1042 self.events.push(GestureEvent::TwoFingerTap { position: mid.into() });
1043 self.tap_zoom(mid, self.options.two_finger_tap_zoom, now);
1044 }
1045 }
1046 Mode::Pan if !self.pointers.is_empty() => {}
1047 Mode::Pressed { long_pressed } => {
1048 if self.pointers.is_empty() {
1049 self.finish(now, unless_cancelled(Finish::Settle));
1050 if !cancelled && !long_pressed && now - pointer.down_at >= self.options.long_press_ms {
1052 let position = pointer.position.into();
1053 self.events.push(GestureEvent::LongPress { id: pointer.id, position });
1054 self.last_tap = None;
1055 } else if !cancelled && !long_pressed {
1056 self.tap(pointer, now);
1057 }
1058 }
1059 }
1060 Mode::BoxZoom { origin } => {
1061 self.finish(now, unless_cancelled(Finish::Stop));
1062 if !cancelled {
1063 self.zoom_to_box(origin, position.unwrap_or(pointer.position));
1064 }
1065 }
1066 Mode::TapDrag { origin, moved, long_pressed } => {
1067 if self.pointers.is_empty() {
1068 self.last_tap = None;
1069 self.finish(now, unless_cancelled(if moved { Finish::Glide } else { Finish::Settle }));
1070 if !moved && !cancelled && !long_pressed {
1071 let (id, position) = (pointer.id, origin.into());
1072 if now - pointer.down_at >= self.options.long_press_ms {
1074 self.events.push(GestureEvent::LongPress { id, position });
1075 } else {
1076 self.events
1077 .extend([GestureEvent::Tap { id, position }, GestureEvent::DoubleTap { id, position }]);
1078 self.double_tap_zoom(pointer, origin, now);
1079 }
1080 }
1081 }
1082 }
1083 Mode::Pan | Mode::Rotate => {
1084 self.finish(now, unless_cancelled(Finish::Glide));
1085 }
1086 Mode::Ignored | Mode::Idle | Mode::Platform => {
1087 if self.pointers.is_empty() {
1088 self.finish(now, unless_cancelled(Finish::Stop));
1089 }
1090 }
1091 }
1092 true
1093 }
1094
1095 fn tap(&mut self, pointer: Pointer, now: f64) {
1098 let (id, position) = (pointer.id, pointer.position);
1099 self.events.push(GestureEvent::Tap { id, position: position.into() });
1100 if self.follows_tap(pointer.kind, position, now) {
1101 self.last_tap = None;
1102 self.events.push(GestureEvent::DoubleTap { id, position: position.into() });
1103 self.double_tap_zoom(pointer, position, now);
1104 } else {
1105 self.last_tap = Some((position, now, pointer.kind));
1106 }
1107 }
1108
1109 fn double_tap_zoom(&mut self, pointer: Pointer, at: V2, now: f64) {
1111 let levels = self.options.double_tap_zoom;
1112 let out = (pointer.modes | self.modes).zoom_out;
1113 self.tap_zoom(at, if out { -levels } else { levels }, now);
1114 }
1115
1116 fn tap_zoom(&mut self, at: V2, levels: f64, now: f64) {
1119 if levels != 0.0 {
1120 self.delta(at, true, [0.0, 0.0, levels, 0.0, 0.0], now);
1121 }
1122 }
1123
1124 fn finish(&mut self, now: f64, finish: Finish) {
1127 self.mode = Mode::Idle;
1128 let caught_glide = self
1129 .caught_glide
1130 .take()
1131 .and_then(|end| end.take())
1132 .filter(|end| self.options.carry_caught_glide && end.outcome == TransitionOutcome::Cancelled)
1133 .map(|end| end.velocity);
1134 match finish {
1135 Finish::Cancel => {
1136 self.deltas = None;
1137 self.cancel_phase();
1138 }
1139 Finish::Stop => self.end_phase(None),
1140 Finish::Settle | Finish::Glide => {
1141 let release = if finish == Finish::Glide { self.tracking.release(now) } else { Release::default() };
1142 let momentum = release.into_momentum(caught_glide, &self.options);
1143 self.end_phase(Some(&momentum));
1144 }
1145 }
1146 }
1147
1148 fn follows_tap(&self, kind: PointerKind, position: V2, now: f64) -> bool {
1150 self.last_tap.is_some_and(|(at, time, k)| {
1151 k == kind && now - time < self.options.tap_interval_ms && at.distance(position) < self.options.tap_tolerance
1152 })
1153 }
1154
1155 fn zoom_to_box(&mut self, a: V2, b: V2) {
1158 let size = (b - a).abs();
1159 if size.x < 1.0 || size.y < 1.0 {
1160 return;
1161 }
1162 let Some(center) = self.camera.lat_lng_for_pixel(((a + b) / 2.0).into()) else {
1163 return;
1164 };
1165 let viewport = V2::from(self.camera.viewport());
1166 let zoom = (viewport.x / size.x).min(viewport.y / size.y).log2();
1167 let target = clamp_zoom(&self.camera, zoom_of(&self.camera) + zoom);
1170 let update = CameraUpdate {
1171 mode: CameraUpdateMode::Ease,
1172 camera: CameraOptions { center: Some(center), zoom: Some(target), ..Default::default() },
1173 animation: self.animation(BOX_EASE, EASE),
1174 phase: GesturePhase::None,
1175 };
1176 self.step_to(&update);
1177 }
1178
1179 fn delta(&mut self, position: V2, discrete: bool, mut amounts: [f64; DELTA_PARTS], now: f64) -> bool {
1184 let options = &self.options;
1185 let on = [
1186 options.pan.enabled,
1187 options.pan.enabled,
1188 options.zoom.enabled,
1189 options.bearing.enabled,
1190 options.pitch.enabled,
1191 ];
1192 for (amount, on) in amounts.iter_mut().zip(on) {
1193 if !on || !amount.is_finite() {
1194 *amount = 0.0;
1195 }
1196 }
1197 if amounts.iter().all(|amount| *amount == 0.0) {
1198 return false;
1199 }
1200 let (duration, max_zoom) = (options.step_duration_ms, options.max_step_zoom);
1201 let mut gesture =
1202 self.deltas.unwrap_or(DeltaGesture { anchor: position, idle_until: now, eases: [None; DELTA_PARTS] });
1203 gesture.anchor = position;
1204 gesture.idle_until = now + options.delta_idle_ms;
1205 self.begin();
1206 if discrete {
1207 for (part, amount) in amounts.into_iter().enumerate() {
1208 if amount == 0.0 {
1209 continue;
1210 }
1211 let ease = gesture.eases[part];
1212 gesture.eases[part] = Some(if part == DELTA_ZOOM {
1216 StepEase::retarget(ease, amount, now, duration, |levels| within_zoom_range(&self.camera, levels))
1217 } else {
1218 StepEase::retarget(ease, amount, now, duration, |amount| amount)
1219 });
1220 }
1221 } else {
1222 amounts[DELTA_ZOOM] = amounts[DELTA_ZOOM].clamp(-max_zoom, max_zoom);
1223 self.move_by(amounts, position);
1224 }
1225 self.deltas = Some(gesture);
1226 true
1227 }
1228
1229 fn move_by(&mut self, amounts: [f64; DELTA_PARTS], at: V2) {
1232 let [x, y, zoom, bearing, pitch] = amounts;
1233 if amounts.iter().all(|amount| *amount == 0.0) {
1234 return;
1235 }
1236 let delta = CameraDelta {
1237 offset: (x != 0.0 || y != 0.0).then(|| ScreenCoordinate::new(x, y)),
1238 scale: (zoom != 0.0).then(|| zoom.exp2()),
1239 bearing: (bearing != 0.0).then_some(bearing),
1240 pitch: (pitch != 0.0).then_some(pitch),
1241 anchor: Some(at.into()),
1242 ..CameraDelta::default()
1243 };
1244 self.update(&delta);
1245 }
1246
1247 fn platform_pinch(&mut self, center: V2, scale: f64, rotation: f64, phase: PinchPhase, now: f64) -> bool {
1250 let pinching = matches!(self.mode, Mode::Platform);
1251 match phase {
1252 PinchPhase::End | PinchPhase::Cancel => {
1253 if !pinching {
1254 return false;
1255 }
1256 let finish = if phase == PinchPhase::End { Finish::Glide } else { Finish::Cancel };
1257 self.finish(now, finish);
1258 return true;
1259 }
1260 PinchPhase::Begin | PinchPhase::Update if !pinching => {
1261 if !matches!(self.mode, Mode::Idle) {
1262 return false;
1263 }
1264 self.deltas = None;
1266 self.begin();
1267 self.tracking.reset(now);
1268 self.mode = Mode::Platform;
1269 }
1270 PinchPhase::Begin | PinchPhase::Update => {}
1271 }
1272 let zoom = if scale > 0.0 && scale.is_finite() && self.options.zoom.enabled { scale.log2() } else { 0.0 };
1273 let bearing = if rotation.is_finite() && self.options.bearing.enabled { -rotation } else { 0.0 };
1275 if zoom == 0.0 && bearing == 0.0 {
1276 return true;
1277 }
1278 self.update(&CameraDelta {
1279 scale: (zoom != 0.0).then_some(scale),
1280 bearing: (bearing != 0.0).then_some(bearing),
1281 anchor: Some(center.into()),
1282 ..CameraDelta::default()
1283 });
1284 self.tracking.record(now, Step { zoom, bearing, around: Some(center), ..Step::default() });
1285 true
1286 }
1287}
1288
1289fn zoom_of(camera: &impl GestureCamera) -> f64 {
1290 camera.camera().zoom.unwrap_or(0.0)
1291}
1292
1293fn clamp_zoom(camera: &impl GestureCamera, zoom: f64) -> f64 {
1294 let (min, max) = camera.zoom_range();
1295 zoom.max(min).min(max)
1296}
1297
1298fn within_zoom_range(camera: &impl GestureCamera, levels: f64) -> f64 {
1301 let zoom = zoom_of(camera);
1302 let (min, max) = camera.zoom_range();
1303 levels.clamp((min - zoom).min(0.0), (max - zoom).max(0.0))
1304}
1305
1306fn angle(a: V2, b: V2) -> f64 {
1308 (a.x * b.y - a.y * b.x).atan2(a.dot(b)).to_degrees()
1309}
1310
1311#[cfg(test)]
1312#[path = "recognizer_test.rs"]
1313mod recognizer_test;