ferrostar 0.51.0

The core of modern turn-by-turn navigation.
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! Tools for deciding when the user has sufficiently deviated from a route.
//!
//! The types in this module are designed around route deviation detection as a single responsibility:
//!
//! While the most common use for this is triggering route recalculation,
//! the decision to reroute (or display an overlay on screen, or any other action) lies with higher levels.
//!
//! For example, on iOS and Android, the `FerrostarCore` class is in charge of deciding
//! when to kick off a new route request.
//! Similarly, you may observe this in your own UI layer and display an overlay under certain conditions.
//!
//! When architecting a Ferrostar core integration for a new platform,
//! we suggest enforcing a similar separation of concerns.

use crate::algorithms::deviation_from_line;
use crate::models::Route;
use crate::navigation_controller::models::TripState;
#[cfg(test)]
use crate::{models::UserLocation, navigation_controller::test_helpers::get_navigating_trip_state};
#[cfg(feature = "alloc")]
use alloc::sync::Arc;
use geo::Point;
use serde::{Deserialize, Serialize};
#[cfg(feature = "wasm-bindgen")]
use tsify::Tsify;

#[cfg(test)]
use {
    crate::{
        models::GeographicCoordinate,
        navigation_controller::test_helpers::{gen_dummy_route_step, gen_route_from_steps},
    },
    proptest::prelude::*,
};

#[cfg(all(test, feature = "std", not(feature = "web-time")))]
use std::time::SystemTime;

#[cfg(all(test, feature = "web-time"))]
use web_time::SystemTime;

/// Determines if the user has deviated from the expected route.
#[derive(Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[cfg_attr(feature = "wasm-bindgen", derive(Tsify))]
#[cfg_attr(feature = "wasm-bindgen", tsify(from_wasm_abi))]
pub enum RouteDeviationTracking {
    /// No checks will be done, and we assume the user is always following the route.
    None,
    /// Detects deviation from the route using a configurable static distance threshold from the route line.
    #[cfg_attr(feature = "wasm-bindgen", serde(rename_all = "camelCase"))]
    StaticThreshold {
        /// The minimum required horizontal accuracy of the user location, in meters.
        /// Values larger than this will not trigger route deviation warnings.
        minimum_horizontal_accuracy: u16,
        /// The maximum acceptable deviation from the route line, in meters.
        ///
        /// If the distance between the reported location and the expected route line
        /// is greater than this threshold, it will be flagged as an off route condition.
        max_acceptable_deviation: f64,
    },
    // TODO: Standard variants that account for mode of travel. For example, `DefaultFor(modeOfTravel: ModeOfTravel)` with sensible defaults for walking, driving, cycling, etc.
    /// An arbitrary user-defined implementation.
    /// You decide with your own [`RouteDeviationDetector`] implementation!
    #[serde(skip)]
    Custom {
        detector: Arc<dyn RouteDeviationDetector>,
    },
}

impl RouteDeviationTracking {
    #[must_use]
    pub(crate) fn check_route_deviation(
        &self,
        route: &Route,
        trip_state: &TripState,
    ) -> RouteDeviation {
        match self {
            RouteDeviationTracking::None => RouteDeviation::NoDeviation,
            RouteDeviationTracking::StaticThreshold {
                minimum_horizontal_accuracy,
                max_acceptable_deviation,
            } => match trip_state {
                TripState::Idle { .. } | TripState::Complete { .. } => RouteDeviation::NoDeviation,
                TripState::Navigating {
                    user_location,
                    remaining_steps,
                    ..
                } => {
                    // Short-circuit in case the GPS is going wild (e.g. in a tunnel or deep urban canyon).
                    if user_location.horizontal_accuracy > f64::from(*minimum_horizontal_accuracy) {
                        return RouteDeviation::NoDeviation;
                    }

                    let user_point = Point::from(*user_location);

                    // No steps remain, so... ;)
                    let Some(current_step) = remaining_steps.first() else {
                        return RouteDeviation::NoDeviation;
                    };

                    let current_step_distance =
                        deviation_from_line(&user_point, &current_step.get_linestring())
                            .unwrap_or(0.0);

                    // Check if the user is on the current step.
                    if current_step_distance <= *max_acceptable_deviation {
                        return RouteDeviation::NoDeviation;
                    }

                    // User is off the current step. Check if they're on any future step.
                    for step in remaining_steps.iter().skip(1) {
                        let distance = deviation_from_line(&user_point, &step.get_linestring())
                            .unwrap_or(f64::MAX);
                        if distance <= *max_acceptable_deviation {
                            return RouteDeviation::Deviation {
                                kind: DeviationKind::OffStepOnRoute {
                                    deviation_from_step_line: current_step_distance,
                                },
                            };
                        }
                    }

                    // Not within the distance threshold of *any* step, so we're off the route.
                    RouteDeviation::Deviation {
                        kind: DeviationKind::CompletelyOffRoute {
                            deviation_from_route_line: current_step_distance,
                        },
                    }
                }
            },
            RouteDeviationTracking::Custom { detector } => {
                detector.check_route_deviation(route.clone(), trip_state.clone())
            }
        }
    }
}

/// The kind of deviation from the expected route.
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[cfg_attr(feature = "wasm-bindgen", derive(Tsify))]
#[cfg_attr(feature = "wasm-bindgen", tsify(into_wasm_abi, from_wasm_abi))]
pub enum DeviationKind {
    /// The user is off the current step, but still on the route polyline (on a future step).
    ///
    /// This can happen when the user takes a shortcut, GPS noise places them on a future step,
    /// or the route self-intersects. Step advance conditions can use this to limit advancement.
    #[cfg_attr(feature = "wasm-bindgen", serde(rename_all = "camelCase"))]
    OffStepOnRoute {
        /// The deviation from the current step line, in meters.
        deviation_from_step_line: f64,
    },
    /// The user is off the expected route entirely
    /// (not within threshold of any remaining step,
    /// neither the current one nor any future one).
    #[cfg_attr(feature = "wasm-bindgen", serde(rename_all = "camelCase"))]
    CompletelyOffRoute {
        /// The deviation from the route line, in meters.
        deviation_from_route_line: f64,
    },
}

/// Status information that describes whether the user is proceeding according to the route or not.
///
/// Note that the name is intentionally a bit generic to allow for expansion of other states.
/// For example, we could conceivably add a "wrong way" status in the future.
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[cfg_attr(feature = "wasm-bindgen", derive(Tsify))]
#[cfg_attr(feature = "wasm-bindgen", tsify(into_wasm_abi, from_wasm_abi))]
pub enum RouteDeviation {
    /// The user is proceeding on course within the expected tolerances; everything is normal.
    NoDeviation,
    /// The user has deviated from the expected route.
    ///
    /// Check the [`DeviationKind`] to determine if the user is still on the route polyline
    /// (off the current step but on a future step) or off the route entirely.
    Deviation { kind: DeviationKind },
}

impl RouteDeviation {
    /// Whether the user is no longer on the current step's polyline.
    ///
    /// This can happen either because the user has moved onto a future step
    /// without triggering advance, or because they have left the route entirely.
    /// In other words: **any deviation from the current step**.
    #[must_use]
    pub fn is_deviated_from_current_step(&self) -> bool {
        matches!(self, RouteDeviation::Deviation { .. })
    }

    /// Whether the user has deviated from the route entirely.
    ///
    /// This is true when the user is not just deviated from the current step,
    /// but also from the route as a whole (they didn't just take a shortcut).
    #[must_use]
    pub fn is_completely_off_route(&self) -> bool {
        matches!(
            self,
            RouteDeviation::Deviation {
                kind: DeviationKind::CompletelyOffRoute { .. }
            }
        )
    }
}

/// A custom deviation detector (for extending the behavior of [`RouteDeviationTracking`]).
///
/// This allows for arbitrarily complex implementations when the provided ones are not enough.
/// For example, detecting that the user is proceeding the wrong direction by keeping a ring buffer
/// of recent locations, or perform local map matching.
#[cfg_attr(feature = "uniffi", uniffi::export(with_foreign))]
pub trait RouteDeviationDetector: Send + Sync {
    /// Determines whether the user is following the route correctly or not.
    ///
    /// NOTE: This function has a single responsibility.
    /// Side-effects like whether to recalculate a route are left to higher levels,
    /// and implementations should only be concerned with determining the facts.
    ///
    /// IMPORTANT: If you are short circuiting [`StepAdvanceCondition`]'s to allow
    /// skipping steps, you must always fall back to checking the deviation from the
    /// full route line.
    #[must_use]
    fn check_route_deviation(&self, route: Route, trip_state: TripState) -> RouteDeviation;
}

#[cfg(test)]
proptest! {
    /// Tests [`RouteDeviationTracking::None`] behavior,
    /// which never reports that the user is off route, even when they obviously are.
    #[test]
    fn no_deviation_tracking(
        x1: f64, y1: f64,
        x2: f64, y2: f64,
        x3: f64, y3: f64,
    ) {
        let tracking = RouteDeviationTracking::None;
        let current_route_step = gen_dummy_route_step(x1, y1, x2, y2);
        let route = gen_route_from_steps(vec![current_route_step.clone()]);

        // Set the user location to the start of the route step.
        // This is clearly on the route.
        let user_location_on_route = UserLocation {
            coordinates: GeographicCoordinate {
                lng: x1,
                lat: y1,
            },
            horizontal_accuracy: 0.0,
            course_over_ground: None,
            timestamp: SystemTime::now(),
            speed: None
        };
        let trip_state = get_navigating_trip_state(
            user_location_on_route.clone(),
            vec![current_route_step.clone()],
            vec![],
            RouteDeviation::NoDeviation
        );
        prop_assert_eq!(
            tracking.check_route_deviation(&route, &trip_state),
            RouteDeviation::NoDeviation
        );

        // Set the user location to a random value.
        // This may be well off route, but we don't care in this mode.
        let user_location_random = UserLocation {
            coordinates: GeographicCoordinate {
                lng: x3,
                lat: y3,
            },
            horizontal_accuracy: 0.0,
            course_over_ground: None,
            timestamp: SystemTime::now(),
            speed: None
        };
        let trip_state_random = get_navigating_trip_state(
            user_location_random.clone(),
            vec![current_route_step.clone()],
            vec![],
            RouteDeviation::NoDeviation
        );
        prop_assert_eq!(
            tracking.check_route_deviation(&route, &trip_state_random),
            RouteDeviation::NoDeviation
        );
    }

    /// Implements the same behavior as [`RouteDeviationTracking::None`]
    /// with user-supplied code.
    #[test]
    fn custom_no_deviation_mode(
        x1: f64, y1: f64,
        x2: f64, y2: f64,
        x3: f64, y3: f64,
    ) {
        struct NeverDetector {}

        impl RouteDeviationDetector for NeverDetector {
            fn check_route_deviation(
                &self,
                _route: Route,
                _trip_state: TripState,
            ) -> RouteDeviation {
                return RouteDeviation::NoDeviation
            }
        }

        let tracking = RouteDeviationTracking::Custom {
            detector: Arc::new(NeverDetector {})
        };
        let current_route_step = gen_dummy_route_step(x1, y1, x2, y2);
        let route = gen_route_from_steps(vec![current_route_step.clone()]);

        // Set the user location to the start of the route step.
        // This is clearly on the route.
        let user_location_on_route = UserLocation {
            coordinates: GeographicCoordinate {
                lng: x1,
                lat: y1,
            },
            horizontal_accuracy: 0.0,
            course_over_ground: None,
            timestamp: SystemTime::now(),
            speed: None
        };
        let trip_state_on_route = get_navigating_trip_state(
            user_location_on_route.clone(),
            vec![current_route_step.clone()],
            vec![],
            RouteDeviation::NoDeviation
        );
        prop_assert_eq!(
            tracking.check_route_deviation(&route, &trip_state_on_route),
            RouteDeviation::NoDeviation
        );

        // Set the user location to a random value.
        // This may be well off route, but we don't care in this mode.
        let user_location_random = UserLocation {
            coordinates: GeographicCoordinate {
                lng: x3,
                lat: y3,
            },
            horizontal_accuracy: 0.0,
            course_over_ground: None,
            timestamp: SystemTime::now(),
            speed: None
        };
        let trip_state_random = get_navigating_trip_state(
            user_location_random.clone(),
            vec![current_route_step.clone()],
            vec![],
            RouteDeviation::NoDeviation
        );
        prop_assert_eq!(
            tracking.check_route_deviation(&route, &trip_state_random),
            RouteDeviation::NoDeviation
        );
    }

    /// Custom behavior claiming that the user is always off the route.
    #[test]
    fn custom_always_off_route(
        x1: f64, y1: f64,
        x2: f64, y2: f64,
        x3: f64, y3: f64,
    ) {
        struct NeverDetector {}

        impl RouteDeviationDetector for NeverDetector {
            fn check_route_deviation(
                &self,
                _route: Route,
                _trip_state: TripState,
            ) -> RouteDeviation {
                RouteDeviation::Deviation {
                    kind: DeviationKind::CompletelyOffRoute {
                        deviation_from_route_line: 7.0,
                    },
                }
            }
        }

        let tracking = RouteDeviationTracking::Custom {
            detector: Arc::new(NeverDetector {})
        };
        let current_route_step = gen_dummy_route_step(x1, y1, x2, y2);
        let route = gen_route_from_steps(vec![current_route_step.clone()]);

        // Set the user location to the start of the route step.
        // This is clearly on the route.
        let user_location_on_route = UserLocation {
            coordinates: GeographicCoordinate {
                lng: x1,
                lat: y1,
            },
            horizontal_accuracy: 0.0,
            course_over_ground: None,
            timestamp: SystemTime::now(),
            speed: None
        };
        let trip_state_on_route = get_navigating_trip_state(
            user_location_on_route.clone(),
            vec![current_route_step.clone()],
            vec![],
            RouteDeviation::NoDeviation
        );
        prop_assert_eq!(
            tracking.check_route_deviation(&route, &trip_state_on_route),
            RouteDeviation::Deviation {
                kind: DeviationKind::CompletelyOffRoute {
                    deviation_from_route_line: 7.0,
                },
            }
        );

        // Set the user location to a random value.
        // This may be well off route, but we don't care in this mode.
        let user_location_random = UserLocation {
            coordinates: GeographicCoordinate {
                lng: x3,
                lat: y3,
            },
            horizontal_accuracy: 0.0,
            course_over_ground: None,
            timestamp: SystemTime::now(),
            speed: None
        };
        let trip_state_random = get_navigating_trip_state(
            user_location_random.clone(),
            vec![current_route_step.clone()],
            vec![],
            RouteDeviation::NoDeviation
        );
        prop_assert_eq!(
            tracking.check_route_deviation(&route, &trip_state_random),
            RouteDeviation::Deviation {
                kind: DeviationKind::CompletelyOffRoute {
                    deviation_from_route_line: 7.0,
                },
            }
        );
    }

    /// Tests [`RouteDeviationTracking::StaticThreshold`] behavior,
    /// using [`algorithms::deviation_from_line`](crate::algorithms::deviation_from_line)
    #[test]
    fn static_threshold_oracle_test(
        x1: f64, y1: f64,
        x2: f64, y2: f64,
        x3: f64, y3: f64,
        minimum_horizontal_accuracy: u16,
        horizontal_accuracy: f64,
        max_acceptable_deviation in 0f64..,
    ) {
        let tracking = RouteDeviationTracking::StaticThreshold {
            minimum_horizontal_accuracy,
            max_acceptable_deviation
        };
        let current_route_step = gen_dummy_route_step(x1, y1, x2, y2);
        let route = gen_route_from_steps(vec![current_route_step.clone()]);

        // Set the user location to the start of the route step.
        // This is clearly on the route.
        let user_location_on_route = UserLocation {
            coordinates: GeographicCoordinate {
                lng: x1,
                lat: y1,
            },
            horizontal_accuracy,
            course_over_ground: None,
            timestamp: SystemTime::now(),
            speed: None
        };
        let trip_state = get_navigating_trip_state(
            user_location_on_route.clone(),
            vec![current_route_step.clone()],
            vec![],
            RouteDeviation::NoDeviation
        );
        prop_assert_eq!(
            tracking.check_route_deviation(&route, &trip_state),
            RouteDeviation::NoDeviation
        );

        // Set the user location to a random value.
        // This may be well off route. Check the deviation_from_line helper
        // as an oracle.
        let coordinates = GeographicCoordinate {
            lng: x3,
            lat: y3,
        };
        let user_location_random = UserLocation {
            coordinates,
            horizontal_accuracy: 0.0,
            course_over_ground: None,
            timestamp: SystemTime::now(),
            speed: None
        };
        let trip_state_random = get_navigating_trip_state(
            user_location_random.clone(),
            vec![current_route_step.clone()],
            vec![],
            RouteDeviation::NoDeviation
        );
        let deviation = deviation_from_line(&Point::from(coordinates), &current_route_step.get_linestring());
        match tracking.check_route_deviation(&route, &trip_state_random) {
            RouteDeviation::NoDeviation => {
                if let Some(calculated) = deviation {
                    prop_assert!(calculated <= max_acceptable_deviation);
                }
            }
            RouteDeviation::Deviation { kind: DeviationKind::OffStepOnRoute { .. } } => {
                // Cannot happen with a single-step route, but handle for exhaustiveness.
                prop_assert!(false, "OffStep should not occur with a single-step route");
            }
            RouteDeviation::Deviation { kind: DeviationKind::CompletelyOffRoute { deviation_from_route_line } } => {
                prop_assert_eq!(
                    deviation_from_route_line,
                    deviation.unwrap()
                );
            }
        }
    }

    /// Tests [`RouteDeviationTracking::StaticThreshold`] behavior
    /// for values which are not accurate enough.
    #[test]
    fn static_threshold_ignores_inaccurate_location_updates(
        x1 in -180f64..=180f64, y1 in -90f64..=90f64,
        x2 in -180f64..=180f64, y2 in -90f64..=90f64,
        x3 in -180f64..=180f64, y3 in -90f64..=90f64,
        horizontal_accuracy in 1u16..,
        max_acceptable_deviation: f64,
    ) {
        let tracking = RouteDeviationTracking::StaticThreshold {
            minimum_horizontal_accuracy: horizontal_accuracy - 1,
            max_acceptable_deviation
        };
        let current_route_step = gen_dummy_route_step(x1, y1, x2, y2);
        let route = gen_route_from_steps(vec![current_route_step.clone()]);

        let coordinates = GeographicCoordinate {
            lng: x3,
            lat: y3,
        };
        let user_location_random = UserLocation {
            coordinates,
            horizontal_accuracy: horizontal_accuracy as f64,
            course_over_ground: None,
            timestamp: SystemTime::now(),
            speed: None
        };
        let trip_state_random = get_navigating_trip_state(
            user_location_random.clone(),
            vec![current_route_step.clone()],
            vec![],
            RouteDeviation::NoDeviation
        );
        prop_assert_eq!(
            tracking.check_route_deviation(&route, &trip_state_random),
            RouteDeviation::NoDeviation
        );
    }
}

#[cfg(test)]
mod off_step_tests {
    use super::*;
    use crate::models::GeographicCoordinate;
    use crate::navigation_controller::test_helpers::{gen_dummy_route_step, gen_route_from_steps};

    #[cfg(all(feature = "std", not(feature = "web-time")))]
    use std::time::SystemTime;

    #[cfg(feature = "web-time")]
    use web_time::SystemTime;

    fn make_location(lng: f64, lat: f64) -> UserLocation {
        UserLocation {
            coordinates: GeographicCoordinate { lng, lat },
            horizontal_accuracy: 5.0,
            course_over_ground: None,
            timestamp: SystemTime::now(),
            speed: None,
        }
    }

    #[test]
    fn test_off_step_detected_when_on_future_step() {
        // Route: Step 1 goes east, Step 2 goes north
        let step1 = gen_dummy_route_step(0.0, 0.0, 0.001, 0.0); // ~111m east
        let step2 = gen_dummy_route_step(0.001, 0.0, 0.001, 0.001); // ~111m north

        let route = gen_route_from_steps(vec![step1.clone(), step2.clone()]);
        let tracking = RouteDeviationTracking::StaticThreshold {
            minimum_horizontal_accuracy: 10,
            max_acceptable_deviation: 50.0,
        };

        // User is on step 2's geometry (far from step 1)
        let user_on_step2 = make_location(0.001, 0.0005);
        let trip_state = get_navigating_trip_state(
            user_on_step2,
            vec![step1.clone(), step2.clone()],
            vec![],
            RouteDeviation::NoDeviation,
        );

        let result = tracking.check_route_deviation(&route, &trip_state);
        assert!(
            matches!(
                result,
                RouteDeviation::Deviation {
                    kind: DeviationKind::OffStepOnRoute { .. }
                }
            ),
            "Should detect OffStep when user is on a future step, got: {result:?}"
        );
    }

    #[test]
    fn test_no_deviation_when_on_current_step() {
        let step1 = gen_dummy_route_step(0.0, 0.0, 0.001, 0.0);
        let step2 = gen_dummy_route_step(0.001, 0.0, 0.001, 0.001);

        let route = gen_route_from_steps(vec![step1.clone(), step2.clone()]);
        let tracking = RouteDeviationTracking::StaticThreshold {
            minimum_horizontal_accuracy: 10,
            max_acceptable_deviation: 50.0,
        };

        // User is on step 1's geometry
        let user_on_step1 = make_location(0.0005, 0.0);
        let trip_state = get_navigating_trip_state(
            user_on_step1,
            vec![step1, step2],
            vec![],
            RouteDeviation::NoDeviation,
        );

        let result = tracking.check_route_deviation(&route, &trip_state);
        assert_eq!(
            result,
            RouteDeviation::NoDeviation,
            "Should be NoDeviation when user is on current step"
        );
    }

    #[test]
    fn test_off_route_when_not_on_any_step() {
        let step1 = gen_dummy_route_step(0.0, 0.0, 0.001, 0.0);
        let step2 = gen_dummy_route_step(0.001, 0.0, 0.001, 0.001);

        let route = gen_route_from_steps(vec![step1.clone(), step2.clone()]);
        let tracking = RouteDeviationTracking::StaticThreshold {
            minimum_horizontal_accuracy: 10,
            max_acceptable_deviation: 50.0,
        };

        // User is far from both steps (~5.5km north)
        let user_off_route = make_location(0.0005, 0.05);
        let trip_state = get_navigating_trip_state(
            user_off_route,
            vec![step1, step2],
            vec![],
            RouteDeviation::NoDeviation,
        );

        let result = tracking.check_route_deviation(&route, &trip_state);
        assert!(
            matches!(
                result,
                RouteDeviation::Deviation {
                    kind: DeviationKind::CompletelyOffRoute { .. }
                }
            ),
            "Should be CompletelyOffRoute when user is not on any step, got: {result:?}"
        );
    }

    #[test]
    fn test_off_step_has_deviation_distance() {
        // Step 1 goes east, step 2 goes north — perpendicular
        let step1 = gen_dummy_route_step(0.0, 0.0, 0.001, 0.0); // ~111m east
        let step2 = gen_dummy_route_step(0.001, 0.0, 0.001, 0.002); // ~222m north

        let route = gen_route_from_steps(vec![step1.clone(), step2.clone()]);
        let tracking = RouteDeviationTracking::StaticThreshold {
            minimum_horizontal_accuracy: 10,
            max_acceptable_deviation: 50.0,
        };

        // User is clearly on step 2's geometry, far from step 1
        // (~111m north of step 1's end, on step 2's line)
        let user_on_step2 = make_location(0.001, 0.001);
        let trip_state = get_navigating_trip_state(
            user_on_step2,
            vec![step1, step2],
            vec![],
            RouteDeviation::NoDeviation,
        );

        let result = tracking.check_route_deviation(&route, &trip_state);
        match result {
            RouteDeviation::Deviation {
                kind:
                    DeviationKind::OffStepOnRoute {
                        deviation_from_step_line,
                    },
            } => {
                assert!(
                    deviation_from_step_line > 0.0,
                    "OffStep should have a positive deviation distance"
                );
            }
            _ => panic!("Expected OffStep, got: {result:?}"),
        }
    }
}