stable_flight/commanders/waypoint.rs
1//! Follows a fixed list of waypoints, looping, holding, or landing at the end.
2
3use core::fmt;
4
5use crate::commanders::TouchdownDetector;
6use crate::math::all_finite;
7use crate::{Command, Commander, ControlInput, LandCommand, Vec2, VehicleState, WaypointCommand};
8
9#[cfg(test)]
10mod tests;
11
12/// Default horizontal distance (meters) within which the active waypoint is considered
13/// reached and the follower advances to the next one.
14pub const DEFAULT_ACCEPTANCE_RADIUS_M: f32 = 3.0;
15
16/// Returned by [`WaypointFollower::new`] when given no waypoints; there is nothing to fly.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct EmptyWaypoints;
19
20impl fmt::Display for EmptyWaypoints {
21 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22 f.write_str("waypoint list is empty")
23 }
24}
25
26impl core::error::Error for EmptyWaypoints {}
27
28/// What a [`WaypointFollower`] does after reaching the last waypoint.
29#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
30pub enum RouteEnd {
31 /// Wrap to the first waypoint and fly the route again, forever.
32 #[default]
33 Loop,
34 /// Stop on the last waypoint and hover there;
35 /// [`is_complete`](WaypointFollower::is_complete) turns true on reaching it.
36 Hold,
37 /// Land on the last waypoint: on reaching it, descend there
38 /// ([`ControlInput::Land`]) until a [`TouchdownDetector`] reports touchdown, then disarm
39 /// for good. [`is_complete`](WaypointFollower::is_complete) turns true on touchdown.
40 Land,
41}
42
43/// A [`Commander`] that flies a sequence of waypoints.
44///
45/// Each tick it emits the active waypoint as an armed [`ControlInput::Waypoint`]. When the
46/// vehicle is within the acceptance radius of it (horizontal distance only), or has passed it
47/// along the leg that leads to it (missed it wide), it advances to the next. After the last it
48/// follows its [`RouteEnd`]: wrap to the first ([`RouteEnd::Loop`], the default), hold the last
49/// ([`RouteEnd::Hold`]), or land on the last and disarm ([`RouteEnd::Land`]). It knows nothing
50/// about where the waypoints came from or what shape they trace.
51///
52/// So the vehicle flies each leg at cruise speed instead of slowing at every waypoint, a
53/// waypoint without its own `velocity_mps` is emitted with one along the leg that leads to it:
54/// from the previous waypoint, at the waypoint's `cruise_speed_mps`. The first waypoint
55/// flown, a waypoint with no positive cruise speed, and the waypoint held at the route's end
56/// get none, so the vehicle stops on them.
57///
58/// Generic over the storage: anything that is `AsRef<[WaypointCommand]>`. Firmware can use a
59/// `[WaypointCommand; N]` or `&'static [WaypointCommand]`; a host can use a `Vec`. It never
60/// allocates.
61///
62/// # Examples
63///
64/// ```
65/// use stable_flight::Vec2;
66/// use stable_flight::commanders::{RouteEnd, WaypointFollower};
67/// use stable_flight::{Commander, ControlInput, VehicleState, WaypointCommand};
68///
69/// let square = [
70/// WaypointCommand { position_m: Vec2::zeros(), altitude_m: 10.0, ..Default::default() },
71/// WaypointCommand { position_m: Vec2::new(20.0, 0.0), altitude_m: 10.0, ..Default::default() },
72/// WaypointCommand { position_m: Vec2::new(20.0, 20.0), altitude_m: 10.0, ..Default::default() },
73/// WaypointCommand { position_m: Vec2::new(0.0, 20.0), altitude_m: 10.0, ..Default::default() },
74/// ];
75/// let mut follower = WaypointFollower::new(square)
76/// .expect("non-empty")
77/// .with_acceptance_radius(2.0)
78/// .with_route_end(RouteEnd::Hold);
79///
80/// // Starting on the first waypoint, the follower advances to the second.
81/// let command = follower.next_command(0.004, &VehicleState::default());
82/// let ControlInput::Waypoint(target) = command.input else {
83/// unreachable!("WaypointFollower only emits waypoint commands");
84/// };
85/// assert_eq!(target.position_m.x, 20.0);
86/// assert!(!follower.is_complete());
87/// ```
88#[derive(Debug, Clone)]
89pub struct WaypointFollower<W> {
90 waypoints: W,
91 current: usize,
92 acceptance_radius_squared: f32,
93 route_end: RouteEnd,
94 /// Unit direction of the leg into the active waypoint, from the previous one; `None` for
95 /// the first waypoint flown or a zero-length leg. Set on each advance, so the per-tick
96 /// path does no sqrt.
97 leg_direction: Option<Vec2>,
98 /// Velocity emitted with the active waypoint when it has none of its own.
99 leg_velocity_mps: Option<Vec2>,
100 /// The last waypoint has been reached under [`RouteEnd::Hold`] or [`RouteEnd::Land`].
101 reached_end: bool,
102 /// Watches the land under [`RouteEnd::Land`].
103 touchdown: TouchdownDetector,
104}
105
106impl<W: AsRef<[WaypointCommand]>> WaypointFollower<W> {
107 /// Starts at the first waypoint with [`DEFAULT_ACCEPTANCE_RADIUS_M`].
108 ///
109 /// # Errors
110 ///
111 /// Returns [`EmptyWaypoints`] if `waypoints` is empty.
112 pub fn new(waypoints: W) -> Result<Self, EmptyWaypoints> {
113 if waypoints.as_ref().is_empty() {
114 return Err(EmptyWaypoints);
115 }
116 Ok(WaypointFollower {
117 waypoints,
118 current: 0,
119 acceptance_radius_squared: DEFAULT_ACCEPTANCE_RADIUS_M * DEFAULT_ACCEPTANCE_RADIUS_M,
120 route_end: RouteEnd::default(),
121 leg_direction: None,
122 leg_velocity_mps: None,
123 reached_end: false,
124 touchdown: TouchdownDetector::default(),
125 })
126 }
127
128 /// Sets what happens after the last waypoint (default [`RouteEnd::Loop`]).
129 pub fn with_route_end(mut self, route_end: RouteEnd) -> Self {
130 self.route_end = route_end;
131 self
132 }
133
134 /// Overrides the horizontal acceptance radius (meters). `radius_m` must be non-negative.
135 pub fn with_acceptance_radius(mut self, radius_m: f32) -> Self {
136 debug_assert!(
137 radius_m >= 0.0,
138 "acceptance radius must be non-negative, got {radius_m}"
139 );
140 self.acceptance_radius_squared = radius_m * radius_m;
141 self
142 }
143
144 /// The waypoints being followed.
145 pub fn waypoints(&self) -> &[WaypointCommand] {
146 self.waypoints.as_ref()
147 }
148
149 /// Index of the active waypoint.
150 pub fn current_index(&self) -> usize {
151 self.current
152 }
153
154 /// True once the last waypoint has been reached under [`RouteEnd::Hold`] (the follower
155 /// keeps holding it), or once landed on it under [`RouteEnd::Land`] (the follower stays
156 /// disarmed). Always false under [`RouteEnd::Loop`].
157 pub fn is_complete(&self) -> bool {
158 match self.route_end {
159 RouteEnd::Loop => false,
160 RouteEnd::Hold => self.reached_end,
161 RouteEnd::Land => self.touchdown.touched_down(),
162 }
163 }
164
165 /// Makes `next` the active waypoint, arriving from `previous`.
166 fn advance(&mut self, previous: usize, next: usize) {
167 self.current = next;
168 let waypoints = self.waypoints.as_ref();
169 let to = &waypoints[next];
170 // A zero-length or non-finite leg has no direction.
171 self.leg_direction = (to.position_m - waypoints[previous].position_m)
172 .try_normalize(0.0)
173 .filter(all_finite);
174 let holds_here = self.route_end != RouteEnd::Loop && next == waypoints.len() - 1;
175 // `>` is false for NaN: no positive cruise speed, no leg velocity.
176 self.leg_velocity_mps = if !holds_here && to.cruise_speed_mps > 0.0 {
177 self.leg_direction
178 .map(|direction| direction * to.cruise_speed_mps)
179 .filter(all_finite)
180 } else {
181 None
182 };
183 }
184}
185
186impl<W: AsRef<[WaypointCommand]>> Commander for WaypointFollower<W> {
187 fn next_command(&mut self, dt: f32, current_state: &VehicleState) -> Command {
188 let waypoints = self.waypoints.as_ref();
189
190 // Compare squared horizontal distance to avoid a per-tick sqrt.
191 let target = &waypoints[self.current];
192 let dx = target.position_m.x - current_state.position_m.x;
193 let dy = target.position_m.y - current_state.position_m.y;
194 let within_radius = dx * dx + dy * dy <= self.acceptance_radius_squared;
195 // Past the waypoint along its leg: the vehicle missed it wide. Without this, the leg
196 // velocity fed forward would park it past the waypoint, outside the radius, where the
197 // position loop's pull back balances it.
198 let passed = self
199 .leg_direction
200 .is_some_and(|direction| direction.x * dx + direction.y * dy <= 0.0);
201 if !self.reached_end && (within_radius || passed) {
202 let previous = self.current;
203 let last = waypoints.len() - 1;
204 match self.route_end {
205 RouteEnd::Hold | RouteEnd::Land if previous == last => self.reached_end = true,
206 _ => self.advance(previous, (previous + 1) % waypoints.len()),
207 }
208 }
209
210 if self.route_end == RouteEnd::Land && self.reached_end {
211 let land = ControlInput::Land(LandCommand {
212 position_m: self.waypoints.as_ref()[self.current].position_m,
213 });
214 let down = self.touchdown.update(dt, current_state.velocity_mps.z);
215 return Command::new(!down, land);
216 }
217
218 let mut target = self.waypoints.as_ref()[self.current];
219 if target.velocity_mps.is_none() {
220 target.velocity_mps = self.leg_velocity_mps;
221 }
222 Command::armed(ControlInput::Waypoint(target))
223 }
224}