rustial-engine 0.0.1

Framework-agnostic 2.5D map engine for rustial
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! # Multi-touch gesture recognizer
//!
//! Converts raw [`TouchContact`] events into high-level camera
//! [`InputEvent`]s (pan, pinch-zoom, two-finger rotate, two-finger
//! pitch).
//!
//! ## Design
//!
//! The recognizer follows the same architecture as MapLibre GL JS /
//! Mapbox GL JS:
//!
//! - **Single touch** → pan (averaged delta when multiple fingers are
//!   down).
//! - **Two-finger pinch** → zoom, using `log₂(distance / last_distance)`
//!   for smooth proportional zoom.
//! - **Two-finger rotation** → yaw, with an adaptive threshold that
//!   scales with finger distance (smaller circle = higher threshold in
//!   degrees).
//! - **Two-finger vertical drag** → pitch, detected when both fingers
//!   move predominantly vertically in the same direction.
//!
//! ## Gesture disambiguation
//!
//! Pinch-zoom activates after `|log₂(distance / start_distance)| ≥ 0.1`.
//! Rotation activates after the bearing delta exceeds a threshold
//! derived from `ROTATION_THRESHOLD_PX / circumference × 360°`.
//! Pitch requires both finger vectors to be vertical and same-direction.
//! All three can be active simultaneously (zoom+rotate is common during
//! a two-finger gesture).
//!
//! ## Usage
//!
//! ```
//! use rustial_engine::gesture::GestureRecognizer;
//! use rustial_engine::{InputEvent, TouchContact, TouchPhase};
//!
//! let mut gesture = GestureRecognizer::new();
//!
//! // Finger 0 touches down at (100, 200).
//! let events = gesture.process(TouchContact {
//!     id: 0, phase: TouchPhase::Started, x: 100.0, y: 200.0,
//! });
//! assert!(events.is_empty()); // no gesture from a single touch-down
//!
//! // Finger 0 drags to (110, 200) → pan.
//! let events = gesture.process(TouchContact {
//!     id: 0, phase: TouchPhase::Moved, x: 110.0, y: 200.0,
//! });
//! assert_eq!(events.len(), 1);
//! assert!(events[0].is_pan());
//! ```

use crate::input::{InputEvent, TouchContact, TouchPhase};
use std::collections::HashMap;

// ---------------------------------------------------------------------------
// Constants (tuned to match MapLibre / Mapbox GL JS)
// ---------------------------------------------------------------------------

/// Minimum `|log₂(distance / start_distance)|` before pinch-zoom
/// activates.
const ZOOM_THRESHOLD: f64 = 0.1;

/// Pixels along the circumference of the circle formed by two fingers
/// before rotation activates.  Larger values require a more deliberate
/// twist.  (MapBox uses 25.)
const ROTATION_THRESHOLD_PX: f64 = 25.0;

/// Degrees per logical pixel of vertical finger movement for pitch.
/// Negative because dragging down (positive pixel Y) should decrease
/// pitch (tilt toward nadir).
const PITCH_DEGREES_PER_PX: f64 = -0.5;

// ---------------------------------------------------------------------------
// GestureRecognizer
// ---------------------------------------------------------------------------

/// Stateful multi-touch gesture recognizer.
///
/// Feed it [`TouchContact`] events via [`process`](Self::process) and
/// it returns zero or more [`InputEvent`]s that can be forwarded to
/// [`MapState::handle_input`](crate::MapState::handle_input).
pub struct GestureRecognizer {
    /// Active touch contacts keyed by finger id.
    fingers: HashMap<u64, FingerState>,

    // -- Two-finger gesture state -----------------------------------------
    /// The two finger ids locked for the current two-finger gesture.
    two_finger_ids: Option<(u64, u64)>,
    /// Distance between the two locked fingers at gesture start.
    start_distance: f64,
    /// Distance between the two locked fingers last frame.
    last_distance: f64,
    /// Vector from finger A to finger B at gesture start.
    start_vector: Option<[f64; 2]>,
    /// Vector from finger A to finger B last frame.
    last_vector: Option<[f64; 2]>,
    /// Minimum distance between fingers during the gesture (for adaptive
    /// rotation threshold).
    min_diameter: f64,
    /// Whether zoom has passed the activation threshold.
    zoom_active: bool,
    /// Whether rotation has passed the activation threshold.
    rotate_active: bool,
    /// Whether pitch has been validated for this gesture.
    pitch_valid: Option<bool>,
    /// Last finger positions for pitch delta calculation.
    pitch_last_points: Option<([f64; 2], [f64; 2])>,
}

#[derive(Debug, Clone, Copy)]
struct FingerState {
    x: f64,
    y: f64,
}

impl Default for GestureRecognizer {
    fn default() -> Self {
        Self::new()
    }
}

impl GestureRecognizer {
    /// Create a new gesture recognizer with no active touches.
    pub fn new() -> Self {
        Self {
            fingers: HashMap::new(),
            two_finger_ids: None,
            start_distance: 0.0,
            last_distance: 0.0,
            start_vector: None,
            last_vector: None,
            min_diameter: 0.0,
            zoom_active: false,
            rotate_active: false,
            pitch_valid: None,
            pitch_last_points: None,
        }
    }

    /// Reset all gesture state (e.g. when the window loses focus).
    pub fn reset(&mut self) {
        self.fingers.clear();
        self.reset_two_finger();
    }

    /// Number of fingers currently tracked.
    #[inline]
    pub fn finger_count(&self) -> usize {
        self.fingers.len()
    }

    /// Process a single touch contact and return any resulting input
    /// events.
    ///
    /// Typically returns 0–3 events (pan, zoom, rotate may fire
    /// simultaneously from a single two-finger move).
    pub fn process(&mut self, contact: TouchContact) -> Vec<InputEvent> {
        match contact.phase {
            TouchPhase::Started => self.on_start(contact),
            TouchPhase::Moved => self.on_move(contact),
            TouchPhase::Ended | TouchPhase::Cancelled => self.on_end(contact),
        }
    }

    // -- Phase handlers ---------------------------------------------------

    fn on_start(&mut self, c: TouchContact) -> Vec<InputEvent> {
        self.fingers.insert(c.id, FingerState { x: c.x, y: c.y });

        // Lock the first two fingers for two-finger gestures.
        if self.two_finger_ids.is_none() && self.fingers.len() >= 2 {
            let mut ids: Vec<u64> = self.fingers.keys().copied().collect();
            ids.sort_unstable();
            let (id_a, id_b) = (ids[0], ids[1]);
            let a = self.fingers[&id_a];
            let b = self.fingers[&id_b];
            let dist = distance(a.x, a.y, b.x, b.y);
            let vec = [b.x - a.x, b.y - a.y];

            self.two_finger_ids = Some((id_a, id_b));
            self.start_distance = dist;
            self.last_distance = dist;
            self.start_vector = Some(vec);
            self.last_vector = Some(vec);
            self.min_diameter = dist;
            self.zoom_active = false;
            self.rotate_active = false;
            self.pitch_valid = None;
            self.pitch_last_points = Some(([a.x, a.y], [b.x, b.y]));
        }

        Vec::new()
    }

    fn on_move(&mut self, c: TouchContact) -> Vec<InputEvent> {
        // Compute per-finger delta before updating stored position.
        let prev = match self.fingers.get(&c.id) {
            Some(f) => *f,
            None => return Vec::new(), // unknown finger
        };
        let dx = c.x - prev.x;
        let dy = c.y - prev.y;

        // Update stored position.
        self.fingers.insert(c.id, FingerState { x: c.x, y: c.y });

        let mut events = Vec::new();

        // -- Two-finger gestures ------------------------------------------
        if let Some((id_a, id_b)) = self.two_finger_ids {
            if let (Some(a), Some(b)) = (self.fingers.get(&id_a), self.fingers.get(&id_b)) {
                let a = *a;
                let b = *b;

                // Pinch-zoom
                events.extend(self.check_zoom(a, b));

                // Rotation
                events.extend(self.check_rotation(a, b));

                // Pitch
                events.extend(self.check_pitch(a, b, c.id));
            }
        }

        // -- Pan (averaged across all active fingers) ---------------------
        // Only pan when at least one finger is moving.
        // With two-finger gestures active, pan uses the midpoint of the
        // locked fingers as anchor.
        if dx.abs() > f64::EPSILON || dy.abs() > f64::EPSILON {
            let (anchor_x, anchor_y) = self.pan_anchor();
            events.push(InputEvent::Pan {
                dx,
                dy,
                x: Some(anchor_x),
                y: Some(anchor_y),
            });
        }

        events
    }

    fn on_end(&mut self, c: TouchContact) -> Vec<InputEvent> {
        self.fingers.remove(&c.id);

        // If one of the locked two-finger pair lifted, reset the
        // two-finger gesture.
        if let Some((id_a, id_b)) = self.two_finger_ids {
            if c.id == id_a || c.id == id_b {
                self.reset_two_finger();
            }
        }

        Vec::new()
    }

    // -- Two-finger sub-recognizers ---------------------------------------

    fn check_zoom(&mut self, a: FingerState, b: FingerState) -> Option<InputEvent> {
        let dist = distance(a.x, a.y, b.x, b.y);
        if dist < 1.0 {
            return None; // fingers on top of each other
        }

        if !self.zoom_active {
            let delta = (dist / self.start_distance).ln() / std::f64::consts::LN_2;
            if delta.abs() < ZOOM_THRESHOLD {
                return None;
            }
            self.zoom_active = true;
        }

        let zoom_delta = (dist / self.last_distance).ln() / std::f64::consts::LN_2;
        self.last_distance = dist;

        // Convert log₂ delta to multiplicative factor: 2^delta.
        let factor = 2.0_f64.powf(zoom_delta);

        // Anchor at midpoint between fingers.
        let mx = (a.x + b.x) * 0.5;
        let my = (a.y + b.y) * 0.5;

        Some(InputEvent::Zoom {
            factor,
            x: Some(mx),
            y: Some(my),
        })
    }

    fn check_rotation(&mut self, a: FingerState, b: FingerState) -> Option<InputEvent> {
        let vec = [b.x - a.x, b.y - a.y];
        let mag = (vec[0] * vec[0] + vec[1] * vec[1]).sqrt();
        if mag < 1.0 {
            return None;
        }

        self.min_diameter = self.min_diameter.min(mag);

        if !self.rotate_active {
            if let Some(start) = self.start_vector {
                let bearing = angle_between(vec, start);
                let circumference = std::f64::consts::PI * self.min_diameter;
                let threshold_deg = if circumference > 0.0 {
                    ROTATION_THRESHOLD_PX / circumference * 360.0
                } else {
                    360.0
                };
                if bearing.abs() < threshold_deg {
                    self.last_vector = Some(vec);
                    return None;
                }
            }
            self.rotate_active = true;
        }

        let bearing_delta = if let Some(last) = self.last_vector {
            angle_between(vec, last)
        } else {
            0.0
        };
        self.last_vector = Some(vec);

        if bearing_delta.abs() < f64::EPSILON {
            return None;
        }

        // Convert degrees to radians for InputEvent::Rotate.
        let delta_yaw = bearing_delta.to_radians();
        Some(InputEvent::Rotate {
            delta_yaw,
            delta_pitch: 0.0,
        })
    }

    fn check_pitch(&mut self, a: FingerState, b: FingerState, moved_id: u64) -> Option<InputEvent> {
        let (id_a, id_b) = self.two_finger_ids?;

        // Only evaluate pitch when one of the two locked fingers moved.
        if moved_id != id_a && moved_id != id_b {
            return None;
        }

        let last_points = self.pitch_last_points?;
        let vec_a = [a.x - last_points.0[0], a.y - last_points.0[1]];
        let vec_b = [b.x - last_points.1[0], b.y - last_points.1[1]];

        // Determine pitch validity on first significant move.
        // Wait until both fingers have moved at least 2px before deciding,
        // so we can accurately evaluate the direction of both vectors.
        if self.pitch_valid.is_none() {
            let a_mag = (vec_a[0] * vec_a[0] + vec_a[1] * vec_a[1]).sqrt();
            let b_mag = (vec_b[0] * vec_b[0] + vec_b[1] * vec_b[1]).sqrt();
            if a_mag > 2.0 && b_mag > 2.0 {
                let a_vert = vec_a[1].abs() > vec_a[0].abs();
                let b_vert = vec_b[1].abs() > vec_b[0].abs();
                // Same vertical direction: both up or both down.
                let same_dir = vec_a[1] * vec_b[1] > 0.0;
                self.pitch_valid = Some(a_vert && b_vert && same_dir);
            }
        }

        if self.pitch_valid != Some(true) {
            // Don't update last_points until pitch is validated,
            // so the accumulated movement from both fingers is preserved.
            return None;
        }

        // Update last_points only after pitch is validated.
        self.pitch_last_points = Some(([a.x, a.y], [b.x, b.y]));

        // Average vertical delta of both fingers.
        let y_avg = (vec_a[1] + vec_b[1]) * 0.5;
        if y_avg.abs() < f64::EPSILON {
            return None;
        }

        let pitch_delta_rad = (y_avg * PITCH_DEGREES_PER_PX).to_radians();
        Some(InputEvent::Rotate {
            delta_yaw: 0.0,
            delta_pitch: pitch_delta_rad,
        })
    }

    // -- Helpers ----------------------------------------------------------

    fn pan_anchor(&self) -> (f64, f64) {
        if self.fingers.is_empty() {
            return (0.0, 0.0);
        }
        let (mut sx, mut sy) = (0.0, 0.0);
        for f in self.fingers.values() {
            sx += f.x;
            sy += f.y;
        }
        let n = self.fingers.len() as f64;
        (sx / n, sy / n)
    }

    fn reset_two_finger(&mut self) {
        self.two_finger_ids = None;
        self.start_distance = 0.0;
        self.last_distance = 0.0;
        self.start_vector = None;
        self.last_vector = None;
        self.min_diameter = 0.0;
        self.zoom_active = false;
        self.rotate_active = false;
        self.pitch_valid = None;
        self.pitch_last_points = None;
    }
}

// ---------------------------------------------------------------------------
// Geometry helpers
// ---------------------------------------------------------------------------

/// Euclidean distance between two points.
#[inline]
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
    let dx = x2 - x1;
    let dy = y2 - y1;
    (dx * dx + dy * dy).sqrt()
}

/// Signed angle between two 2-D vectors, in degrees.
///
/// Positive = counter-clockwise from `a` to `b`.
fn angle_between(a: [f64; 2], b: [f64; 2]) -> f64 {
    let cross = b[0] * a[1] - b[1] * a[0];
    let dot = a[0] * b[0] + a[1] * b[1];
    cross.atan2(dot).to_degrees()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::input::TouchPhase;

    fn tc(id: u64, phase: TouchPhase, x: f64, y: f64) -> TouchContact {
        TouchContact { id, phase, x, y }
    }

    // -- Single finger pan ------------------------------------------------

    #[test]
    fn single_finger_pan() {
        let mut g = GestureRecognizer::new();
        let _ = g.process(tc(0, TouchPhase::Started, 100.0, 200.0));
        let events = g.process(tc(0, TouchPhase::Moved, 110.0, 205.0));
        assert_eq!(events.len(), 1);
        match events[0] {
            InputEvent::Pan { dx, dy, .. } => {
                assert!((dx - 10.0).abs() < 1e-9);
                assert!((dy - 5.0).abs() < 1e-9);
            }
            _ => panic!("expected Pan"),
        }
    }

    #[test]
    fn finger_end_clears_state() {
        let mut g = GestureRecognizer::new();
        let _ = g.process(tc(0, TouchPhase::Started, 100.0, 200.0));
        let _ = g.process(tc(0, TouchPhase::Ended, 100.0, 200.0));
        assert_eq!(g.finger_count(), 0);
    }

    // -- Two-finger pinch-zoom -------------------------------------------

    #[test]
    fn pinch_zoom_produces_zoom_event() {
        let mut g = GestureRecognizer::new();
        // Two fingers start 100px apart horizontally.
        let _ = g.process(tc(0, TouchPhase::Started, 100.0, 200.0));
        let _ = g.process(tc(1, TouchPhase::Started, 200.0, 200.0));

        // Move fingers apart to 150px each side (distance 200 → well above threshold).
        let _ = g.process(tc(0, TouchPhase::Moved, 50.0, 200.0));
        let events = g.process(tc(1, TouchPhase::Moved, 250.0, 200.0));

        let has_zoom = events.iter().any(|e| e.is_zoom());
        assert!(has_zoom, "expected zoom event from pinch: {events:?}");
    }

    #[test]
    fn pinch_zoom_below_threshold_does_not_activate() {
        let mut g = GestureRecognizer::new();
        let _ = g.process(tc(0, TouchPhase::Started, 100.0, 200.0));
        let _ = g.process(tc(1, TouchPhase::Started, 200.0, 200.0));

        // Tiny pinch (distance changes from 100 to ~101) — below threshold.
        let events = g.process(tc(1, TouchPhase::Moved, 201.0, 200.0));
        let has_zoom = events.iter().any(|e| e.is_zoom());
        assert!(!has_zoom, "should not zoom below threshold");
    }

    // -- Two-finger rotation ----------------------------------------------

    #[test]
    fn rotation_produces_rotate_event() {
        let mut g = GestureRecognizer::new();
        // Fingers 100px apart horizontally.
        let _ = g.process(tc(0, TouchPhase::Started, 100.0, 200.0));
        let _ = g.process(tc(1, TouchPhase::Started, 200.0, 200.0));

        // Rotate by moving finger 1 up and finger 0 down (large twist).
        let _ = g.process(tc(0, TouchPhase::Moved, 100.0, 250.0));
        let events = g.process(tc(1, TouchPhase::Moved, 200.0, 150.0));

        let has_rotate = events.iter().any(|e| {
            matches!(e,
                InputEvent::Rotate { delta_yaw, .. } if delta_yaw.abs() > 1e-6
            )
        });
        assert!(has_rotate, "expected rotation event: {events:?}");
    }

    // -- Two-finger pitch ------------------------------------------------

    #[test]
    fn vertical_drag_produces_pitch() {
        let mut g = GestureRecognizer::new();
        let _ = g.process(tc(0, TouchPhase::Started, 100.0, 200.0));
        let _ = g.process(tc(1, TouchPhase::Started, 200.0, 200.0));

        // Both fingers drag down significantly.
        let _ = g.process(tc(0, TouchPhase::Moved, 100.0, 230.0));
        let events = g.process(tc(1, TouchPhase::Moved, 200.0, 230.0));

        let has_pitch = events.iter().any(|e| {
            matches!(e,
                InputEvent::Rotate { delta_pitch, .. } if delta_pitch.abs() > 1e-6
            )
        });
        assert!(has_pitch, "expected pitch event: {events:?}");
    }

    // -- Gesture lifecycle ------------------------------------------------

    #[test]
    fn lifting_one_finger_resets_two_finger_state() {
        let mut g = GestureRecognizer::new();
        let _ = g.process(tc(0, TouchPhase::Started, 100.0, 200.0));
        let _ = g.process(tc(1, TouchPhase::Started, 200.0, 200.0));
        assert!(g.two_finger_ids.is_some());

        let _ = g.process(tc(1, TouchPhase::Ended, 200.0, 200.0));
        assert!(g.two_finger_ids.is_none());
    }

    #[test]
    fn cancel_resets_everything() {
        let mut g = GestureRecognizer::new();
        let _ = g.process(tc(0, TouchPhase::Started, 100.0, 200.0));
        g.reset();
        assert_eq!(g.finger_count(), 0);
        assert!(g.two_finger_ids.is_none());
    }

    #[test]
    fn third_finger_ignored_for_two_finger_gesture() {
        let mut g = GestureRecognizer::new();
        let _ = g.process(tc(0, TouchPhase::Started, 100.0, 200.0));
        let _ = g.process(tc(1, TouchPhase::Started, 200.0, 200.0));
        let ids_before = g.two_finger_ids;
        let _ = g.process(tc(2, TouchPhase::Started, 300.0, 200.0));
        // Third finger should not change the locked pair.
        assert_eq!(g.two_finger_ids, ids_before);
    }

    // -- Pan anchor -------------------------------------------------------

    #[test]
    fn pan_anchor_is_centroid() {
        let mut g = GestureRecognizer::new();
        let _ = g.process(tc(0, TouchPhase::Started, 100.0, 200.0));
        let _ = g.process(tc(1, TouchPhase::Started, 200.0, 200.0));
        let (ax, ay) = g.pan_anchor();
        assert!((ax - 150.0).abs() < 1e-9);
        assert!((ay - 200.0).abs() < 1e-9);
    }

    // -- Angle helper -----------------------------------------------------

    #[test]
    fn angle_between_90_degrees() {
        let a = [1.0, 0.0];
        let b = [0.0, 1.0];
        let angle = angle_between(a, b);
        assert!((angle.abs() - 90.0).abs() < 0.1, "got {angle}");
    }

    #[test]
    fn angle_between_opposite_is_180() {
        let a = [1.0, 0.0];
        let b = [-1.0, 0.0];
        let angle = angle_between(a, b);
        assert!((angle.abs() - 180.0).abs() < 0.1, "got {angle}");
    }

    // -- Zoom factor direction -------------------------------------------

    #[test]
    fn pinch_out_zooms_in() {
        let mut g = GestureRecognizer::new();
        let _ = g.process(tc(0, TouchPhase::Started, 100.0, 200.0));
        let _ = g.process(tc(1, TouchPhase::Started, 200.0, 200.0));

        // Large spread: distance goes from 100 to 300.
        let _ = g.process(tc(0, TouchPhase::Moved, 0.0, 200.0));
        let events = g.process(tc(1, TouchPhase::Moved, 300.0, 200.0));

        let zoom_event = events.iter().find(|e| e.is_zoom());
        if let Some(InputEvent::Zoom { factor, .. }) = zoom_event {
            assert!(
                *factor > 1.0,
                "spreading fingers should zoom in, got factor={factor}"
            );
        } else {
            panic!("expected zoom event: {events:?}");
        }
    }

    #[test]
    fn pinch_in_zooms_out() {
        let mut g = GestureRecognizer::new();
        let _ = g.process(tc(0, TouchPhase::Started, 0.0, 200.0));
        let _ = g.process(tc(1, TouchPhase::Started, 300.0, 200.0));

        // Large squeeze: distance goes from 300 to 100.
        let _ = g.process(tc(0, TouchPhase::Moved, 100.0, 200.0));
        let events = g.process(tc(1, TouchPhase::Moved, 200.0, 200.0));

        let zoom_event = events.iter().find(|e| e.is_zoom());
        if let Some(InputEvent::Zoom { factor, .. }) = zoom_event {
            assert!(
                *factor < 1.0,
                "squeezing fingers should zoom out, got factor={factor}"
            );
        } else {
            panic!("expected zoom event: {events:?}");
        }
    }
}