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]
521 pub fn options(&self) -> &GestureOptions {
522 &self.options
523 }
524
525 pub fn set_options(&mut self, options: GestureOptions) -> Result<(), InvalidGestureOptions> {
527 options.validate()?;
528 self.options = options;
529 Ok(())
530 }
531
532 #[cfg(test)]
534 #[must_use]
535 pub(crate) fn is_active(&self) -> bool {
536 !matches!(self.mode, Mode::Idle) || self.deltas.is_some()
537 }
538
539 #[must_use]
542 pub fn box_zoom(&self) -> Option<[ScreenCoordinate; 2]> {
543 match self.mode {
544 Mode::BoxZoom { origin } => Some([origin.into(), self.pointers.first()?.position.into()]),
545 _ => None,
546 }
547 }
548
549 #[must_use]
554 pub fn next_tick(&self) -> Option<NextTick> {
555 let easing = self.deltas.is_some_and(|deltas| deltas.eases.iter().any(Option::is_some));
556 let held_still = matches!(self.mode, Mode::Pressed { .. } | Mode::TapDrag { moved: false, .. });
558 if easing || (self.notch_watch.is_some() && !held_still) {
559 return Some(NextTick::Frame);
560 }
561 let long_press = match self.pointers[..] {
562 [pointer] if self.awaits_long_press() => Some(pointer.down_at + self.options.long_press_ms),
563 _ => None,
564 };
565 let idle = self.deltas.map(|deltas| deltas.idle_until);
566 long_press.into_iter().chain(idle).min_by(f64::total_cmp).map(NextTick::At)
567 }
568
569 fn awaits_long_press(&self) -> bool {
571 matches!(
572 self.mode,
573 Mode::Pressed { long_pressed: false } | Mode::TapDrag { moved: false, long_pressed: false, .. }
574 )
575 }
576
577 pub fn take_events(&mut self) -> Vec<GestureEvent> {
579 std::mem::take(&mut self.events)
580 }
581
582 pub fn step_to(&mut self, update: &CameraUpdate) {
588 let set = &update.camera;
589 let center = set.center.is_some();
590 self.stop_step_eases([center, center, set.zoom.is_some(), set.bearing.is_some(), set.pitch.is_some()]);
591 if !self.begun {
594 self.notch_watch = None;
595 }
596 let phase = if self.begun { GesturePhase::Update } else { GesturePhase::End };
597 self.camera.update_camera(&CameraUpdate { phase, ..*update });
598 }
599
600 pub fn tick(&mut self, now: f64) -> Option<NextTick> {
605 self.long_press(now);
606 self.delta_frame(now);
607 if let Some(watch) = &mut self.notch_watch {
608 watch.sample(&self.camera.camera(), &self.options, now, &mut self.events);
609 if !self.begun && self.release_end.as_ref().is_none_or(PendingEnd::has_ended) {
612 self.notch_watch = None;
613 }
614 }
615 self.next_tick()
616 }
617
618 fn long_press(&mut self, now: f64) {
620 if self.awaits_long_press()
621 && let [pointer] = self.pointers[..]
622 && now - pointer.down_at >= self.options.long_press_ms
623 {
624 match &mut self.mode {
625 Mode::Pressed { long_pressed } | Mode::TapDrag { long_pressed, .. } => *long_pressed = true,
626 _ => {}
627 }
628 self.last_tap = None;
629 self.events.push(GestureEvent::LongPress { id: pointer.id, position: pointer.position.into() });
630 }
631 }
632
633 fn delta_frame(&mut self, now: f64) -> bool {
635 let Some(mut gesture) = self.deltas else {
636 return false;
637 };
638 let duration = self.options.step_duration_ms;
639 let max_zoom = self.options.max_step_zoom;
640 let mut amounts = [0.0; DELTA_PARTS];
641 for (part, slot) in gesture.eases.iter_mut().enumerate() {
642 let Some(mut ease) = *slot else { continue };
643 let mut amount = ease.value(now, duration) - ease.applied;
644 if part == DELTA_ZOOM {
645 amount = amount.clamp(-max_zoom, max_zoom);
646 }
647 ease.applied += amount;
648 amounts[part] = amount;
649 let done = ease.progress(now, duration) >= 1.0 && (ease.distance - ease.applied).abs() <= STEP_EASE_DONE;
650 *slot = (!done).then_some(ease);
651 if done {
652 gesture.idle_until = gesture.idle_until.max(now + self.options.delta_idle_ms);
653 }
654 }
655 if !self.begun && amounts.iter().any(|amount| *amount != 0.0) {
658 self.begun = true;
659 self.camera.apply_camera_delta(&CameraDelta { phase: GesturePhase::Update, ..CameraDelta::default() });
660 }
661 self.move_by(amounts, gesture.anchor);
662 if gesture.eases.iter().all(Option::is_none) && now >= gesture.idle_until {
663 self.deltas = None;
664 if matches!(self.mode, Mode::Idle) {
665 self.end_phase(None);
666 }
667 return false;
668 }
669 self.deltas = Some(gesture);
670 true
671 }
672
673 pub fn handle(&mut self, input: Input, now: f64) -> bool {
676 match input {
677 Input::PointerDown { id, kind, position, modes } => {
678 let position = position.into();
679 self.down(Pointer { id, kind, position, down: position, down_at: now, modes })
680 }
681 Input::PointerMove { id, position } => self.moved(id, position.into(), now),
682 Input::PointerUp { id, position } => self.up(id, Some(position.into()), now),
683 Input::PointerCancel { id } => self.up(id, None, now),
684 Input::Modes(modes) => {
687 self.modes = modes;
688 false
689 }
690 Input::Delta { position, discrete, pan, zoom, bearing, pitch } => {
691 self.delta(position.into(), discrete, [pan.x, pan.y, zoom, bearing, pitch], now)
692 }
693 Input::Pinch { center, scale, rotation, phase } => {
694 self.platform_pinch(center.into(), scale, rotation, phase, now)
695 }
696 }
697 }
698
699 fn animation(&self, duration: Duration, easing: UnitBezier) -> AnimationOptions {
701 AnimationOptions {
702 duration: Some(duration),
703 easing: Some(easing),
704 transition_id: Some(self.options.transition_id),
705 ..AnimationOptions::default()
706 }
707 }
708
709 fn begin(&mut self) {
716 if self.begun {
717 return;
718 }
719 self.begun = true;
720 self.caught_glide = self.release_end.take().filter(|end| end.take().is_none());
723 let notches = [&self.options.zoom, &self.options.bearing, &self.options.pitch]
724 .iter()
725 .any(|part| part.enabled && !part.notches.is_empty());
726 self.notch_watch = notches.then(|| NotchWatch::new(&self.camera.camera(), &self.options));
727 let phase = if self.options.interrupt_animations {
728 GesturePhase::Begin
729 } else {
730 self.camera.cancel_transitions_with_id(self.options.transition_id);
731 GesturePhase::Update
732 };
733 self.camera.apply_camera_delta(&CameraDelta { phase, ..CameraDelta::default() });
734 }
735
736 fn update(&mut self, delta: &CameraDelta) {
738 self.begin();
739 self.camera.apply_camera_delta(&CameraDelta { phase: GesturePhase::Update, ..*delta });
740 }
741
742 fn end_phase(&mut self, momentum: Option<&CameraMomentum>) {
745 if !std::mem::replace(&mut self.begun, false) {
746 return;
747 }
748 let animation =
749 AnimationOptions { transition_id: Some(self.options.transition_id), ..AnimationOptions::default() };
750 let phase = GesturePhase::End;
751 let delta = CameraDelta { momentum: momentum.copied(), animation, phase, ..CameraDelta::default() };
752 let end = self.camera.release(&delta);
753 if momentum.is_some() {
756 self.release_end = Some(end);
757 }
758 }
759
760 fn cancel_phase(&mut self) {
764 self.notch_watch = None;
765 if !std::mem::replace(&mut self.begun, false) {
766 return;
767 }
768 let phase = if self.options.interrupt_animations {
769 GesturePhase::Cancel
770 } else {
771 self.camera.cancel_transitions_with_id(self.options.transition_id);
772 GesturePhase::End
773 };
774 self.camera.apply_camera_delta(&CameraDelta { phase, ..CameraDelta::default() });
775 }
776
777 fn stop_step_eases(&mut self, parts: [bool; DELTA_PARTS]) {
779 if let Some(gesture) = self.deltas.as_mut() {
780 for (ease, stop) in gesture.eases.iter_mut().zip(parts) {
781 if stop {
782 *ease = None;
783 }
784 }
785 }
786 }
787
788 fn down(&mut self, pointer: Pointer) -> bool {
790 let Pointer { id, kind, position, down_at: now, .. } = pointer;
791 if self.pointers.iter().any(|p| p.id == id) {
792 return false;
793 }
794 let touch = kind == PointerKind::Touch;
795 if !touch && !self.pointers.is_empty() {
796 return false;
797 }
798 if matches!(self.mode, Mode::Platform) {
799 self.finish(now, Finish::Cancel);
801 }
802 self.pointers.push(pointer);
803 self.deltas = None;
805 self.begin();
806 match (self.mode, self.pointers.len()) {
807 (Mode::Idle, 1) => {
808 self.mode = if touch && self.follows_tap(kind, position, now) {
809 Mode::TapDrag { origin: position, moved: false, long_pressed: false }
810 } else {
811 Mode::Pressed { long_pressed: false }
812 };
813 self.tracking.reset(now);
814 }
815 (Mode::Pressed { .. } | Mode::Pan | Mode::TapDrag { .. }, 2) if touch => {
816 let [a, b] = [self.pointers[0].position, self.pointers[1].position];
817 let vector = b - a;
818 self.mode = Mode::Pinch(Pinch {
819 last: [a, b],
820 start_distance: vector.length(),
821 start_vector: vector,
822 min_diameter: vector.length(),
823 zooming: false,
824 rotating: false,
825 pitch: (!self.options.pitch.enabled || vector.y.abs() > vector.x.abs()).then_some(false),
827 single_since: None,
828 panning: false,
829 tap: now - self.pointers[0].down_at < self.options.tap_interval_ms
830 && matches!(self.mode, Mode::Pressed { .. }),
831 });
832 self.tracking.record(now, Step::default());
833 }
834 _ => self.mode = Mode::Ignored,
835 }
836 true
837 }
838
839 fn moved(&mut self, id: u32, position: V2, now: f64) -> bool {
840 let Some(index) = self.pointers.iter().position(|p| p.id == id) else {
841 return false;
842 };
843 let last = self.pointers[index].position;
844 self.pointers[index].position = position;
845 match &mut self.mode {
846 Mode::Pressed { .. } => {
847 let pointer = self.pointers[index];
848 let down = pointer.down;
849 if position.distance(down) > self.options.click_tolerance {
850 let modes = pointer.modes | self.modes;
852 self.mode = if modes.rotate {
853 Mode::Rotate
854 } else if modes.box_zoom && self.options.zoom.enabled {
855 Mode::BoxZoom { origin: down }
856 } else {
857 Mode::Pan
858 };
859 self.drag_step(down, position, now);
865 }
866 }
867 Mode::Pan | Mode::Rotate => self.drag_step(last, position, now),
868 Mode::TapDrag { origin, moved, .. } => {
869 let (origin, dy) = (*origin, position.y - last.y);
870 *moved = *moved || position.distance(origin) > self.options.click_tolerance;
871 if *moved && self.options.zoom.enabled {
872 let zoom = dy * self.options.tap_drag_zoom;
873 let delta =
874 CameraDelta { scale: Some(zoom.exp2()), anchor: Some(origin.into()), ..CameraDelta::default() };
875 self.update(&delta);
876 self.tracking.record(now, Step { zoom, around: Some(origin), ..Step::default() });
877 }
878 }
879 Mode::Pinch(_) if self.pointers.len() < 2 => {
880 self.mode = Mode::Pan;
883 self.drag_step(last, position, now);
884 }
885 Mode::Pinch(pinch) => {
886 if index > 1 {
887 return true;
888 }
889 let mut pinch = *pinch;
890 let points = [self.pointers[0].position, self.pointers[1].position];
891 self.pinch_step(&mut pinch, points, now);
892 self.mode = Mode::Pinch(pinch);
893 }
894 Mode::BoxZoom { .. } | Mode::Idle | Mode::Ignored | Mode::Platform => {}
895 }
896 true
897 }
898
899 fn drag_step(&mut self, from: V2, to: V2, now: f64) {
901 let delta = to - from;
902 match self.mode {
903 Mode::Rotate => {
904 let bearing = if self.options.bearing.enabled { delta.x * self.options.drag_rotate } else { 0.0 };
905 let pitch = if self.options.pitch.enabled { -delta.y * self.options.drag_pitch } else { 0.0 };
906 let step = CameraDelta { bearing: Some(bearing), pitch: Some(pitch), ..CameraDelta::default() };
907 self.update(&step);
908 self.tracking.record(now, Step { bearing, pitch, ..Step::default() });
909 }
910 Mode::BoxZoom { .. } => {}
911 _ if !self.options.pan.enabled => {}
912 _ => {
913 let step =
916 CameraDelta { offset: Some(delta.into()), anchor: Some(to.into()), ..CameraDelta::default() };
917 self.update(&step);
918 self.tracking.record(now, Step { pan: delta, ..Step::default() });
919 }
920 }
921 }
922
923 fn pinch_step(&mut self, pinch: &mut Pinch, points: [V2; 2], now: f64) {
924 let [a, b] = points;
925 let [la, lb] = pinch.last;
926 let (va, vb) = (a - la, b - lb);
927 let vector = b - a;
928 let tap_tolerance = self.options.tap_tolerance;
929 if pinch.tap
930 && (a.distance(self.pointers[0].down) > tap_tolerance || b.distance(self.pointers[1].down) > tap_tolerance)
931 {
932 pinch.tap = false;
933 }
934 if pinch.pitch.is_none() {
937 let (moved_a, moved_b) = (va.length() >= PITCH_DECIDE_PX, vb.length() >= PITCH_DECIDE_PX);
938 if moved_a && moved_b {
939 let vertical = |v: V2| v.y.abs() > v.x.abs();
940 pinch.pitch = Some(vertical(va) && vertical(vb) && (va.y > 0.0) == (vb.y > 0.0));
941 } else if moved_a || moved_b {
942 let since = *pinch.single_since.get_or_insert(now);
943 if now - since >= PITCH_DECIDE_MS {
944 pinch.pitch = Some(false);
945 }
946 }
947 if pinch.pitch.is_none() {
948 return;
949 }
950 }
951 if pinch.pitch == Some(true) {
952 let pitch = f64::midpoint(va.y, vb.y) * -self.options.drag_pitch;
953 self.update(&CameraDelta { pitch: Some(pitch), ..CameraDelta::default() });
954 pinch.last = points;
955 pinch.tap = false;
956 self.tracking.record(now, Step { pitch, ..Step::default() });
957 return;
958 }
959 let (mid, last_mid) = ((a + b) / 2.0, (la + lb) / 2.0);
960 let distance = vector.length();
961 let last_distance = (lb - la).length();
962 pinch.min_diameter = pinch.min_diameter.min(distance);
963 if !pinch.zooming
964 && self.options.zoom.enabled
965 && (distance / pinch.start_distance).log2().abs() >= self.options.pinch_zoom_threshold
966 {
967 pinch.zooming = true;
968 }
969 if !pinch.rotating && self.options.bearing.enabled {
970 let threshold = self.options.rotate_threshold / (std::f64::consts::PI * pinch.min_diameter) * 360.0;
971 if angle(pinch.start_vector, vector).abs() >= threshold {
972 pinch.rotating = true;
973 }
974 }
975 if !pinch.panning
976 && self.options.pan.enabled
977 && (mid - (self.pointers[0].down + self.pointers[1].down) / 2.0).length() > self.options.click_tolerance
978 {
979 pinch.panning = true;
980 }
981 let pan = if pinch.panning { mid - last_mid } else { V2::ZERO };
982 let zoom = if pinch.zooming && last_distance > 0.0 { (distance / last_distance).log2() } else { 0.0 };
983 let bearing = if pinch.rotating { -angle(lb - la, vector) } else { 0.0 };
985 pinch.last = points;
986 if pan == V2::ZERO && zoom == 0.0 && bearing == 0.0 {
987 return;
988 }
989 let anchored = zoom != 0.0 || bearing != 0.0 || pan != V2::ZERO;
992 self.update(&CameraDelta {
993 offset: (pan != V2::ZERO).then_some(pan.into()),
994 scale: (zoom != 0.0).then_some(zoom.exp2()),
995 bearing: (bearing != 0.0).then_some(bearing),
996 anchor: anchored.then_some(mid.into()),
997 ..CameraDelta::default()
998 });
999 pinch.tap = false;
1000 self.tracking.record(now, Step { pan, zoom, bearing, around: Some(mid), ..Step::default() });
1001 }
1002
1003 fn up(&mut self, id: u32, position: Option<V2>, now: f64) -> bool {
1004 let Some(index) = self.pointers.iter().position(|p| p.id == id) else {
1005 return false;
1006 };
1007 let pointer = self.pointers.remove(index);
1008 let cancelled = position.is_none();
1009 if cancelled && !self.pointers.is_empty() {
1012 self.finish(now, Finish::Cancel);
1013 self.mode = Mode::Ignored;
1014 return true;
1015 }
1016 let unless_cancelled = |finish: Finish| if cancelled { Finish::Cancel } else { finish };
1019 match self.mode {
1020 Mode::Pinch(pinch) => {
1021 if !self.pointers.is_empty() {
1022 let tap = pinch.tap && now - pointer.down_at < self.options.tap_interval_ms;
1025 self.mode = if tap {
1026 Mode::Pinch(pinch)
1027 } else {
1028 self.tracking.stage(now);
1029 Mode::Pan
1030 };
1031 return true;
1032 }
1033 self.finish(now, unless_cancelled(if pinch.tap { Finish::Settle } else { Finish::Glide }));
1034 if pinch.tap && !cancelled {
1035 let mid = (pinch.last[0] + pinch.last[1]) / 2.0;
1036 self.events.push(GestureEvent::TwoFingerTap { position: mid.into() });
1037 self.tap_zoom(mid, self.options.two_finger_tap_zoom, now);
1038 }
1039 }
1040 Mode::Pan if !self.pointers.is_empty() => {}
1041 Mode::Pressed { long_pressed } => {
1042 if self.pointers.is_empty() {
1043 self.finish(now, unless_cancelled(Finish::Settle));
1044 if !cancelled && !long_pressed && now - pointer.down_at >= self.options.long_press_ms {
1046 let position = pointer.position.into();
1047 self.events.push(GestureEvent::LongPress { id: pointer.id, position });
1048 self.last_tap = None;
1049 } else if !cancelled && !long_pressed {
1050 self.tap(pointer, now);
1051 }
1052 }
1053 }
1054 Mode::BoxZoom { origin } => {
1055 self.finish(now, unless_cancelled(Finish::Stop));
1056 if !cancelled {
1057 self.zoom_to_box(origin, position.unwrap_or(pointer.position));
1058 }
1059 }
1060 Mode::TapDrag { origin, moved, long_pressed } => {
1061 if self.pointers.is_empty() {
1062 self.last_tap = None;
1063 self.finish(now, unless_cancelled(if moved { Finish::Glide } else { Finish::Settle }));
1064 if !moved && !cancelled && !long_pressed {
1065 let (id, position) = (pointer.id, origin.into());
1066 if now - pointer.down_at >= self.options.long_press_ms {
1068 self.events.push(GestureEvent::LongPress { id, position });
1069 } else {
1070 self.events
1071 .extend([GestureEvent::Tap { id, position }, GestureEvent::DoubleTap { id, position }]);
1072 self.double_tap_zoom(pointer, origin, now);
1073 }
1074 }
1075 }
1076 }
1077 Mode::Pan | Mode::Rotate => {
1078 self.finish(now, unless_cancelled(Finish::Glide));
1079 }
1080 Mode::Ignored | Mode::Idle | Mode::Platform => {
1081 if self.pointers.is_empty() {
1082 self.finish(now, unless_cancelled(Finish::Stop));
1083 }
1084 }
1085 }
1086 true
1087 }
1088
1089 fn tap(&mut self, pointer: Pointer, now: f64) {
1092 let (id, position) = (pointer.id, pointer.position);
1093 self.events.push(GestureEvent::Tap { id, position: position.into() });
1094 if self.follows_tap(pointer.kind, position, now) {
1095 self.last_tap = None;
1096 self.events.push(GestureEvent::DoubleTap { id, position: position.into() });
1097 self.double_tap_zoom(pointer, position, now);
1098 } else {
1099 self.last_tap = Some((position, now, pointer.kind));
1100 }
1101 }
1102
1103 fn double_tap_zoom(&mut self, pointer: Pointer, at: V2, now: f64) {
1105 let levels = self.options.double_tap_zoom;
1106 let out = (pointer.modes | self.modes).zoom_out;
1107 self.tap_zoom(at, if out { -levels } else { levels }, now);
1108 }
1109
1110 fn tap_zoom(&mut self, at: V2, levels: f64, now: f64) {
1113 if levels != 0.0 {
1114 self.delta(at, true, [0.0, 0.0, levels, 0.0, 0.0], now);
1115 }
1116 }
1117
1118 fn finish(&mut self, now: f64, finish: Finish) {
1121 self.mode = Mode::Idle;
1122 let caught_glide = self
1123 .caught_glide
1124 .take()
1125 .and_then(|end| end.take())
1126 .filter(|end| self.options.carry_caught_glide && end.outcome == TransitionOutcome::Cancelled)
1127 .map(|end| end.velocity);
1128 match finish {
1129 Finish::Cancel => {
1130 self.deltas = None;
1131 self.cancel_phase();
1132 }
1133 Finish::Stop => self.end_phase(None),
1134 Finish::Settle | Finish::Glide => {
1135 let release = if finish == Finish::Glide { self.tracking.release(now) } else { Release::default() };
1136 let momentum = release.into_momentum(caught_glide, &self.options);
1137 self.end_phase(Some(&momentum));
1138 }
1139 }
1140 }
1141
1142 fn follows_tap(&self, kind: PointerKind, position: V2, now: f64) -> bool {
1144 self.last_tap.is_some_and(|(at, time, k)| {
1145 k == kind && now - time < self.options.tap_interval_ms && at.distance(position) < self.options.tap_tolerance
1146 })
1147 }
1148
1149 fn zoom_to_box(&mut self, a: V2, b: V2) {
1152 let size = (b - a).abs();
1153 if size.x < 1.0 || size.y < 1.0 {
1154 return;
1155 }
1156 let Some(center) = self.camera.lat_lng_for_pixel(((a + b) / 2.0).into()) else {
1157 return;
1158 };
1159 let viewport = V2::from(self.camera.viewport());
1160 let zoom = (viewport.x / size.x).min(viewport.y / size.y).log2();
1161 let target = clamp_zoom(&self.camera, zoom_of(&self.camera) + zoom);
1164 let update = CameraUpdate {
1165 mode: CameraUpdateMode::Ease,
1166 camera: CameraOptions { center: Some(center), zoom: Some(target), ..Default::default() },
1167 animation: self.animation(BOX_EASE, EASE),
1168 phase: GesturePhase::None,
1169 };
1170 self.step_to(&update);
1171 }
1172
1173 fn delta(&mut self, position: V2, discrete: bool, mut amounts: [f64; DELTA_PARTS], now: f64) -> bool {
1178 let options = &self.options;
1179 let on = [
1180 options.pan.enabled,
1181 options.pan.enabled,
1182 options.zoom.enabled,
1183 options.bearing.enabled,
1184 options.pitch.enabled,
1185 ];
1186 for (amount, on) in amounts.iter_mut().zip(on) {
1187 if !on || !amount.is_finite() {
1188 *amount = 0.0;
1189 }
1190 }
1191 if amounts.iter().all(|amount| *amount == 0.0) {
1192 return false;
1193 }
1194 let (duration, max_zoom) = (options.step_duration_ms, options.max_step_zoom);
1195 let mut gesture =
1196 self.deltas.unwrap_or(DeltaGesture { anchor: position, idle_until: now, eases: [None; DELTA_PARTS] });
1197 gesture.anchor = position;
1198 gesture.idle_until = now + options.delta_idle_ms;
1199 self.begin();
1200 if discrete {
1201 for (part, amount) in amounts.into_iter().enumerate() {
1202 if amount == 0.0 {
1203 continue;
1204 }
1205 let ease = gesture.eases[part];
1206 gesture.eases[part] = Some(if part == DELTA_ZOOM {
1210 StepEase::retarget(ease, amount, now, duration, |levels| within_zoom_range(&self.camera, levels))
1211 } else {
1212 StepEase::retarget(ease, amount, now, duration, |amount| amount)
1213 });
1214 }
1215 } else {
1216 amounts[DELTA_ZOOM] = amounts[DELTA_ZOOM].clamp(-max_zoom, max_zoom);
1217 self.move_by(amounts, position);
1218 }
1219 self.deltas = Some(gesture);
1220 true
1221 }
1222
1223 fn move_by(&mut self, amounts: [f64; DELTA_PARTS], at: V2) {
1226 let [x, y, zoom, bearing, pitch] = amounts;
1227 if amounts.iter().all(|amount| *amount == 0.0) {
1228 return;
1229 }
1230 let delta = CameraDelta {
1231 offset: (x != 0.0 || y != 0.0).then(|| ScreenCoordinate::new(x, y)),
1232 scale: (zoom != 0.0).then(|| zoom.exp2()),
1233 bearing: (bearing != 0.0).then_some(bearing),
1234 pitch: (pitch != 0.0).then_some(pitch),
1235 anchor: Some(at.into()),
1236 ..CameraDelta::default()
1237 };
1238 self.update(&delta);
1239 }
1240
1241 fn platform_pinch(&mut self, center: V2, scale: f64, rotation: f64, phase: PinchPhase, now: f64) -> bool {
1244 let pinching = matches!(self.mode, Mode::Platform);
1245 match phase {
1246 PinchPhase::End | PinchPhase::Cancel => {
1247 if !pinching {
1248 return false;
1249 }
1250 let finish = if phase == PinchPhase::End { Finish::Glide } else { Finish::Cancel };
1251 self.finish(now, finish);
1252 return true;
1253 }
1254 PinchPhase::Begin | PinchPhase::Update if !pinching => {
1255 if !matches!(self.mode, Mode::Idle) {
1256 return false;
1257 }
1258 self.deltas = None;
1260 self.begin();
1261 self.tracking.reset(now);
1262 self.mode = Mode::Platform;
1263 }
1264 PinchPhase::Begin | PinchPhase::Update => {}
1265 }
1266 let zoom = if scale > 0.0 && scale.is_finite() && self.options.zoom.enabled { scale.log2() } else { 0.0 };
1267 let bearing = if rotation.is_finite() && self.options.bearing.enabled { -rotation } else { 0.0 };
1269 if zoom == 0.0 && bearing == 0.0 {
1270 return true;
1271 }
1272 self.update(&CameraDelta {
1273 scale: (zoom != 0.0).then_some(scale),
1274 bearing: (bearing != 0.0).then_some(bearing),
1275 anchor: Some(center.into()),
1276 ..CameraDelta::default()
1277 });
1278 self.tracking.record(now, Step { zoom, bearing, around: Some(center), ..Step::default() });
1279 true
1280 }
1281}
1282
1283fn zoom_of(camera: &impl GestureCamera) -> f64 {
1284 camera.camera().zoom.unwrap_or(0.0)
1285}
1286
1287fn clamp_zoom(camera: &impl GestureCamera, zoom: f64) -> f64 {
1288 let (min, max) = camera.zoom_range();
1289 zoom.max(min).min(max)
1290}
1291
1292fn within_zoom_range(camera: &impl GestureCamera, levels: f64) -> f64 {
1295 let zoom = zoom_of(camera);
1296 let (min, max) = camera.zoom_range();
1297 levels.clamp((min - zoom).min(0.0), (max - zoom).max(0.0))
1298}
1299
1300fn angle(a: V2, b: V2) -> f64 {
1302 (a.x * b.y - a.y * b.x).atan2(a.dot(b)).to_degrees()
1303}
1304
1305#[cfg(test)]
1306#[path = "recognizer_test.rs"]
1307mod recognizer_test;