use glam::DVec3;
use crate::grid::GroundRoute;
pub const WAYPOINT_REACH_M: f64 = 0.4;
pub const WAYPOINT_STOP_M: f64 = 0.2;
pub const LAST_REACH_SLACK_M: f64 = 0.01;
pub const STALL_HEADWAY_M: f64 = 0.5;
pub const STALL_TIMEOUT_S: f64 = 3.0;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FollowDistances {
pub waypoint_reach_m: f64,
pub waypoint_stop_m: f64,
pub last_stop_m: f64,
pub last_reach_m: f64,
}
impl FollowDistances {
#[must_use]
pub const fn new(last_stop_m: f64) -> Self {
Self {
waypoint_reach_m: WAYPOINT_REACH_M,
waypoint_stop_m: WAYPOINT_STOP_M,
last_stop_m,
last_reach_m: last_stop_m + LAST_REACH_SLACK_M,
}
}
#[must_use]
pub fn reach_for(&self, index: usize, count: usize) -> f64 {
if index + 1 < count {
self.waypoint_reach_m
} else {
self.last_reach_m
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Steer {
pub waypoint: DVec3,
pub stop_distance_m: f64,
pub reach_m: f64,
pub is_last: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RouteFollower {
waypoints: Vec<DVec3>,
next: usize,
distances: FollowDistances,
}
impl RouteFollower {
#[must_use]
pub fn new(route: GroundRoute, distances: FollowDistances) -> Self {
Self {
waypoints: route.waypoints,
next: 0,
distances,
}
}
pub fn advance(&mut self, feet: DVec3) -> Option<Steer> {
let count = self.waypoints.len();
while self.next < count
&& ground_distance(feet, self.waypoints[self.next])
<= self.distances.reach_for(self.next, count)
{
self.next += 1;
}
let waypoint = *self.waypoints.get(self.next)?;
let is_last = self.next + 1 == count;
Some(Steer {
waypoint,
stop_distance_m: if is_last {
self.distances.last_stop_m
} else {
self.distances.waypoint_stop_m
},
reach_m: self.distances.reach_for(self.next, count),
is_last,
})
}
#[must_use]
pub fn remaining(&self) -> &[DVec3] {
&self.waypoints[self.next..]
}
#[must_use]
pub fn is_finished(&self) -> bool {
self.next == self.waypoints.len()
}
#[must_use]
pub fn distances(&self) -> FollowDistances {
self.distances
}
pub fn set_last_stop_m(&mut self, last_stop_m: f64) {
self.distances.last_stop_m = last_stop_m;
self.distances.last_reach_m = last_stop_m + LAST_REACH_SLACK_M;
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StallDetector {
pub headway_m: f64,
pub timeout_s: f64,
anchor: Option<DVec3>,
since_headway_s: f64,
}
impl Default for StallDetector {
fn default() -> Self {
Self::new(STALL_HEADWAY_M, STALL_TIMEOUT_S)
}
}
impl StallDetector {
#[must_use]
pub const fn new(headway_m: f64, timeout_s: f64) -> Self {
Self {
headway_m,
timeout_s,
anchor: None,
since_headway_s: 0.0,
}
}
pub fn tick(&mut self, feet: DVec3, walking: bool, dt_s: f64) -> bool {
if !(dt_s.is_finite() && dt_s > 0.0) {
return self.is_stalled();
}
let headway = self
.anchor
.is_none_or(|anchor| ground_distance(anchor, feet) >= self.headway_m);
if !walking || headway {
self.anchor = Some(feet);
self.since_headway_s = 0.0;
} else {
self.since_headway_s += dt_s;
}
self.is_stalled()
}
#[must_use]
pub fn is_stalled(&self) -> bool {
self.since_headway_s >= self.timeout_s
}
#[must_use]
pub fn anchor(&self) -> Option<DVec3> {
self.anchor
}
#[must_use]
pub fn since_headway_s(&self) -> f64 {
self.since_headway_s
}
pub fn reset(&mut self) {
self.anchor = None;
self.since_headway_s = 0.0;
}
}
fn ground_distance(a: DVec3, b: DVec3) -> f64 {
(b.x - a.x).hypot(b.z - a.z)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::grid::{GridCell, GroundGrid, GroundGridConfig};
const CELL_M: f64 = 0.5;
fn walled_field() -> GroundGrid {
let mut cells = vec![GridCell::Walkable; 25];
for column in [0, 1, 3, 4] {
cells[2 * 5 + column] = GridCell::Blocked;
}
GroundGrid::new(GroundGridConfig::new(DVec3::ZERO, CELL_M, 5, 5), cells).unwrap()
}
fn centre(column: usize, row: usize) -> DVec3 {
DVec3::new(
(column as f64 + 0.5) * CELL_M,
0.0,
(row as f64 + 0.5) * CELL_M,
)
}
fn crosses_blocked(grid: &GroundGrid, a: DVec3, b: DVec3) -> bool {
(0..=200).any(|step| {
let point = a.lerp(b, f64::from(step) / 200.0);
grid.plan(point, point).is_err()
})
}
#[test]
fn an_l_shaped_route_through_a_doorway_turns_at_its_corner() {
let grid = walled_field();
let route = grid.plan(centre(0, 1), centre(2, 4)).unwrap();
let corner = centre(2, 1);
assert_eq!(
route.waypoints,
vec![
centre(1, 1),
corner,
centre(2, 2),
centre(2, 3),
centre(2, 4)
],
"along the wall, then through the doorway"
);
let stop = 1.0;
let mut follower = RouteFollower::new(route.clone(), FollowDistances::new(stop));
let feet = DVec3::new(0.75, 0.0, 0.9);
let to_corner = ground_distance(feet, corner);
assert!(to_corner < stop && to_corner > WAYPOINT_REACH_M);
let naive = route
.waypoints
.iter()
.copied()
.find(|&point| ground_distance(feet, point) > stop)
.unwrap();
assert!(
crosses_blocked(&grid, feet, naive),
"dropping by the stop distance makes for {naive} across the jamb"
);
let steer = follower.advance(feet).unwrap();
assert_eq!(
steer,
Steer {
waypoint: corner,
stop_distance_m: WAYPOINT_STOP_M,
reach_m: WAYPOINT_REACH_M,
is_last: false,
}
);
assert!(!crosses_blocked(&grid, feet, steer.waypoint));
assert_eq!(follower.remaining(), &route.waypoints[1..]);
let outside = corner - DVec3::X * (WAYPOINT_REACH_M + 0.01);
assert_eq!(follower.advance(outside).unwrap().waypoint, corner);
let inside = corner - DVec3::X * (WAYPOINT_REACH_M - 0.01);
let steer = follower.advance(inside).unwrap();
assert_eq!(steer.waypoint, centre(2, 2));
assert!(!crosses_blocked(&grid, inside, steer.waypoint));
}
#[test]
fn the_last_waypoint_uses_the_callers_stop_distance() {
let stop = 1.0;
let first = DVec3::new(1.0, 0.0, 0.0);
let last = DVec3::new(1.0, 0.0, 3.0);
let mut follower = RouteFollower::new(
GroundRoute {
waypoints: vec![first, last],
},
FollowDistances::new(stop),
);
assert!(!follower.is_finished());
let steer = follower.advance(first).unwrap();
assert_eq!(
steer,
Steer {
waypoint: last,
stop_distance_m: stop,
reach_m: stop + LAST_REACH_SLACK_M,
is_last: true,
}
);
let short = last - DVec3::Z * (stop * 0.9);
assert!(ground_distance(short, last) > WAYPOINT_REACH_M);
assert_eq!(follower.advance(short), None);
assert!(follower.is_finished());
assert!(follower.remaining().is_empty());
assert_eq!(
follower.advance(DVec3::ZERO),
None,
"a dropped waypoint never comes back"
);
}
#[test]
fn a_last_stop_changed_mid_route_applies_from_the_next_advance() {
let first = DVec3::new(1.0, 0.0, 0.0);
let last = DVec3::new(1.0, 0.0, 3.0);
let mut follower = RouteFollower::new(
GroundRoute {
waypoints: vec![first, last],
},
FollowDistances::new(0.5),
);
let feet = last - DVec3::Z * 1.5;
follower.set_last_stop_m(0.25);
let near_first = first + DVec3::Z * (WAYPOINT_REACH_M * 0.5);
assert_eq!(
follower.advance(near_first).unwrap().waypoint,
last,
"the first waypoint still drops by the waypoint reach"
);
let steer = follower.advance(feet).unwrap();
assert_eq!(
(steer.stop_distance_m, steer.reach_m),
(0.25, 0.25 + LAST_REACH_SLACK_M)
);
follower.set_last_stop_m(2.0);
assert_eq!(follower.distances().last_stop_m, 2.0);
assert_eq!(follower.advance(feet), None, "1.5 m off is inside 2 m");
assert!(follower.is_finished());
}
#[test]
fn a_waypoint_is_reached_beside_it_whatever_the_height() {
let below = DVec3::new(0.0, 0.0, 0.0);
let next = DVec3::new(2.0, 0.0, 0.0);
let mut follower = RouteFollower::new(
GroundRoute {
waypoints: vec![below + DVec3::Y * 2.0, next],
},
FollowDistances::new(0.5),
);
assert_eq!(follower.advance(below).unwrap().waypoint, next);
}
#[test]
fn an_empty_route_is_walked_from_the_start() {
let mut follower = RouteFollower::new(
GroundRoute {
waypoints: Vec::new(),
},
FollowDistances::new(1.0),
);
assert!(follower.is_finished());
assert_eq!(follower.advance(DVec3::ZERO), None);
}
#[test]
fn a_waypoint_exactly_at_the_reach_is_reached() {
let distances = FollowDistances::new(1.0);
let follower_to =
|waypoints: Vec<DVec3>| RouteFollower::new(GroundRoute { waypoints }, distances);
let far = DVec3::new(10.0, 0.0, 0.0);
for (reach, last) in [
(distances.waypoint_reach_m, false),
(distances.last_reach_m, true),
] {
let at = DVec3::X * reach;
assert_eq!(ground_distance(DVec3::ZERO, at), reach);
let beyond = DVec3::X * reach.next_up();
let route = |waypoint| {
if last {
vec![waypoint]
} else {
vec![waypoint, far]
}
};
let reached = follower_to(route(at)).advance(DVec3::ZERO);
assert_eq!(
reached.map(|steer| steer.waypoint),
(!last).then_some(far),
"at exactly the reach ({reach} m) the waypoint is reached; last: {last}"
);
let held = follower_to(route(beyond)).advance(DVec3::ZERO);
assert_eq!(
held.map(|steer| steer.waypoint),
Some(beyond),
"one ulp past the reach the waypoint still holds; last: {last}"
);
}
}
#[test]
fn the_reach_per_waypoint_is_the_waypoint_reach_until_the_last() {
let distances = FollowDistances::new(1.5);
assert_eq!(distances.reach_for(0, 3), WAYPOINT_REACH_M);
assert_eq!(distances.reach_for(1, 3), WAYPOINT_REACH_M);
assert_eq!(distances.reach_for(2, 3), 1.5 + LAST_REACH_SLACK_M);
assert_eq!(distances.reach_for(0, 1), 1.5 + LAST_REACH_SLACK_M);
assert_eq!(
distances,
FollowDistances {
waypoint_reach_m: 0.4,
waypoint_stop_m: 0.2,
last_stop_m: 1.5,
last_reach_m: 1.51,
},
"EW's values"
);
}
#[test]
fn a_walker_at_rest_just_past_its_stop_distance_has_arrived() {
const COVER_STOP_M: f64 = 0.25;
let cover = DVec3::new(3.0, 0.0, 0.0);
let route = GroundRoute {
waypoints: vec![cover],
};
let mut follower = RouteFollower::new(route, FollowDistances::new(COVER_STOP_M));
let walking = follower
.advance(DVec3::ZERO)
.expect("three metres out is not there yet");
assert_eq!(walking.stop_distance_m, COVER_STOP_M);
assert!(walking.reach_m > walking.stop_distance_m, "{walking:?}");
let at_rest = cover - DVec3::X * (COVER_STOP_M + 1e-9);
assert_eq!(follower.advance(at_rest), None, "arrived at cover");
assert!(follower.is_finished());
let mut retargeted = RouteFollower::new(
GroundRoute {
waypoints: vec![cover],
},
FollowDistances::new(2.0),
);
retargeted.set_last_stop_m(COVER_STOP_M);
assert!(
retargeted.advance(cover - DVec3::X).is_some(),
"a metre out is past the lowered reach, not inside the old one"
);
assert_eq!(retargeted.advance(at_rest), None);
}
const TICK_S: f64 = 0.5;
fn tick_through_timeout(
detector: &mut StallDetector,
mut feet: impl FnMut(usize) -> DVec3,
walking: bool,
) -> bool {
let ticks = (STALL_TIMEOUT_S / TICK_S) as usize - 1;
for tick in 0..ticks {
assert!(
!detector.tick(feet(tick), walking, TICK_S),
"stalled at tick {tick}"
);
}
detector.tick(feet(ticks), walking, TICK_S)
}
#[test]
fn jostling_in_place_while_walking_stalls_after_the_timeout() {
let mut detector = StallDetector::default();
assert!(
!detector.tick(DVec3::ZERO, true, TICK_S),
"the first anchors"
);
let jostle = |tick: usize| DVec3::X * (STALL_HEADWAY_M * 0.1 * (tick % 2) as f64);
assert!(tick_through_timeout(&mut detector, jostle, true));
assert_eq!(detector.since_headway_s(), STALL_TIMEOUT_S);
assert_eq!(detector.anchor(), Some(DVec3::ZERO));
assert!(detector.tick(DVec3::ZERO, true, TICK_S), "it stays stalled");
detector.reset();
assert_eq!(detector.anchor(), None);
assert!(!detector.tick(DVec3::ZERO, true, TICK_S));
}
#[test]
fn waiting_never_stalls() {
let mut detector = StallDetector::default();
for _ in 0..100 {
assert!(!detector.tick(DVec3::ZERO, false, TICK_S));
}
assert_eq!(detector.since_headway_s(), 0.0);
let resumed = DVec3::new(0.1, 0.0, 0.0);
assert!(!detector.tick(resumed, false, TICK_S));
assert!(tick_through_timeout(&mut detector, |_| resumed, true));
}
#[test]
fn steady_progress_never_stalls() {
let mut detector = StallDetector::default();
let step = STALL_HEADWAY_M * 0.2;
for tick in 0..100 {
let feet = DVec3::Z * (step * f64::from(tick));
assert!(!detector.tick(feet, true, TICK_S), "stalled at {feet}");
}
let anchor = detector.anchor().unwrap();
assert!(anchor.z > 99.0 * step - STALL_HEADWAY_M, "{anchor}");
}
#[test]
fn headway_re_anchors_and_restarts_the_clock() {
let mut detector = StallDetector::default();
let ticks = (STALL_TIMEOUT_S / TICK_S) as usize;
for _ in 0..ticks {
assert!(!detector.tick(DVec3::ZERO, true, TICK_S));
}
let ahead = DVec3::new(0.0, 5.0, STALL_HEADWAY_M);
assert!(!detector.tick(ahead, true, TICK_S));
assert_eq!(detector.anchor(), Some(ahead));
assert_eq!(detector.since_headway_s(), 0.0);
let near = ahead + DVec3::new(0.0, -5.0, STALL_HEADWAY_M * 0.9);
assert!(tick_through_timeout(&mut detector, |_| near, true));
assert_eq!(detector.anchor(), Some(ahead));
}
#[test]
fn a_tick_with_no_time_changes_nothing() {
let mut detector = StallDetector::default();
assert!(!detector.tick(DVec3::ZERO, true, TICK_S));
let before = detector;
for dt in [0.0, -1.0, f64::NAN, f64::INFINITY] {
assert!(!detector.tick(DVec3::X * 9.0, false, dt), "{dt}");
assert_eq!(detector, before, "{dt}");
}
assert!(tick_through_timeout(&mut detector, |_| DVec3::ZERO, true));
}
}