stable_flight/controllers/lateral.rs
1use crate::Vec2;
2
3use super::derivative::DerivativeState;
4use crate::controllers::{Gains, InvalidConfig, check_limit, rescale_integral};
5use crate::math::{all_finite, assert_dt, cap_magnitude, clamp_symmetric_each};
6
7/// Configures the [`LateralController`]: a position loop feeding a velocity loop.
8#[derive(Clone, Copy, Debug, PartialEq)]
9pub struct LateralControllerConfig {
10 /// Proportional gain from position error (m) to desired velocity (m/s), in 1/s. Sets how
11 /// fast the vehicle closes on a target before the speed limit applies. Must be
12 /// non-negative and finite.
13 pub position_p: f32,
14
15 /// PID gains from velocity error (m/s) to horizontal acceleration (m/s²).
16 pub velocity: Gains,
17
18 /// Maximum absolute value of the integrated velocity error, in m, per axis.
19 /// Prevents integral windup by limiting error accumulation.
20 pub max_integral: f32,
21}
22
23impl Default for LateralControllerConfig {
24 fn default() -> Self {
25 Self {
26 // Unsaturated, `velocity.p · (position_p · e − v)` is the flight-checked position
27 // PD (#108, rescaled for the atan tilt in #71): P 0.63, D 1.26, ζ ≈ 0.8.
28 position_p: 0.5,
29 velocity: Gains {
30 p: 1.26,
31 i: 0.0,
32 d: 0.0,
33 },
34 max_integral: 100.0, // Arbitrary limit
35 }
36 }
37}
38
39impl LateralControllerConfig {
40 /// Checks the config: `position_p` and `max_integral` must be non-negative and finite.
41 ///
42 /// # Examples
43 ///
44 /// ```
45 /// use stable_flight::controllers::LateralControllerConfig;
46 ///
47 /// assert!(LateralControllerConfig::default().validate().is_ok());
48 /// let bad = LateralControllerConfig { max_integral: f32::NAN, ..Default::default() };
49 /// assert!(bad.validate().is_err());
50 /// ```
51 pub fn validate(&self) -> Result<(), InvalidConfig> {
52 check_limit("position_p", self.position_p)?;
53 check_limit("max_integral", self.max_integral)
54 }
55}
56
57/// What the [`LateralController`] tracks: a horizontal position, a velocity fed forward
58/// toward it, and a speed limit. Horizontal components are (north, east), as in the
59/// [`VehicleState`](crate::VehicleState) frame contract.
60///
61/// # Examples
62///
63/// ```
64/// use stable_flight::Vec2;
65/// use stable_flight::controllers::LateralTarget;
66///
67/// // Fly to 20 m north at up to 5 m/s, stopping there.
68/// let target = LateralTarget {
69/// position_m: Vec2::new(20.0, 0.0),
70/// velocity_mps: Vec2::zeros(),
71/// max_speed_mps: 5.0,
72/// };
73/// ```
74#[derive(Clone, Copy, Debug, PartialEq)]
75pub struct LateralTarget {
76 /// Desired position in meters.
77 pub position_m: Vec2,
78 /// Velocity in m/s added to the position loop's demand: zero stops at the target, a
79 /// non-zero value flies through it.
80 pub velocity_mps: Vec2,
81 /// Cap on the desired speed in m/s. Zero, negative, or NaN means no cap (the guidance's
82 /// tilt limit still applies).
83 pub max_speed_mps: f32,
84}
85
86/// The vehicle's current horizontal state as the [`LateralController`] consumes it, (north,
87/// east) per the [`VehicleState`](crate::VehicleState) frame contract.
88///
89/// # Examples
90///
91/// ```
92/// use stable_flight::Vec2;
93/// use stable_flight::controllers::LateralEstimate;
94///
95/// // 4 m north, 1 m east, drifting north at 0.1 m/s.
96/// let estimate = LateralEstimate {
97/// position_m: Vec2::new(4.0, 1.0),
98/// velocity_mps: Vec2::new(0.1, 0.0),
99/// };
100/// ```
101#[derive(Clone, Copy, Debug, PartialEq)]
102pub struct LateralEstimate {
103 /// Estimated position in meters.
104 pub position_m: Vec2,
105 /// Estimated velocity in m/s.
106 pub velocity_mps: Vec2,
107}
108
109/// Horizontal position → velocity → acceleration cascade: turns a position target into a
110/// horizontal acceleration demand.
111///
112/// The position loop asks for `position_p · error + target velocity`, capped in magnitude at
113/// the target's `max_speed_mps` (direction kept), and the velocity PID turns the velocity
114/// error into acceleration. Turning the acceleration into tilt is the guidance's job (it
115/// depends on the airframe and its heading);
116/// [`CopterGuidance`](crate::guidance::copter::CopterGuidance) tilts by `atan(|a| / g)` toward
117/// it.
118///
119/// It holds only state (the velocity integral and derivative history); gains and limits come
120/// from the [`LateralControllerConfig`] passed to each [`control`](Self::control) call, so
121/// they can change between ticks without resetting the state.
122#[derive(Clone, Debug, Default, PartialEq)]
123pub struct LateralController {
124 integrated_error: Vec2, // Accumulated velocity error (x, y)
125 /// Previous velocity error for the derivative term; empty on the first tick and after a gap.
126 derivative: DerivativeState<Vec2>,
127}
128
129impl LateralController {
130 /// Desired horizontal acceleration toward `target`.
131 ///
132 /// # Arguments
133 ///
134 /// * `config` - Gains and limits; assumed valid ([`LateralControllerConfig::validate`]).
135 /// An invalid limit does not panic: a negative or NaN `max_integral` acts as 0.
136 /// * `dt` - Time step since the last update in seconds (must be positive and finite).
137 /// * `target` - Desired position, feedforward velocity, and speed limit.
138 /// * `estimate` - Current position and velocity.
139 ///
140 /// # Returns
141 ///
142 /// Desired horizontal acceleration (x, y) in m/s², in the position frame. It is not
143 /// saturated: the caller caps the tilt it turns into. A non-finite target or estimate gives
144 /// zero (level) and leaves the integral untouched. The integral is clamped to
145 /// `max_integral` to limit windup.
146 ///
147 /// # Panics
148 ///
149 /// If `dt` is not positive and finite.
150 ///
151 /// # Examples
152 ///
153 /// ```
154 /// use stable_flight::controllers::{
155 /// LateralController, LateralControllerConfig, LateralEstimate, LateralTarget,
156 /// };
157 /// use stable_flight::Vec2;
158 ///
159 /// let config = LateralControllerConfig::default();
160 /// let mut controller = LateralController::default();
161 /// let target = LateralTarget {
162 /// position_m: Vec2::new(5.0, 2.0), // 5 m north, 2 m east
163 /// velocity_mps: Vec2::zeros(),
164 /// max_speed_mps: 3.0,
165 /// };
166 /// let estimate = LateralEstimate {
167 /// position_m: Vec2::new(4.0, 1.0),
168 /// velocity_mps: Vec2::new(0.1, 0.05),
169 /// };
170 ///
171 /// // Target is north-east: accelerate north (+x) and east (+y)
172 /// let accel_mps2 = controller.control(&config, 0.004, target, estimate);
173 /// assert!(accel_mps2.x > 0.0 && accel_mps2.y > 0.0);
174 /// ```
175 pub fn control(
176 &mut self,
177 config: &LateralControllerConfig,
178 dt: f32,
179 target: LateralTarget,
180 estimate: LateralEstimate,
181 ) -> Vec2 {
182 assert_dt(dt);
183 let gains = &config.velocity;
184
185 // `>` is false for NaN: zero, negative, and NaN limits all mean no cap.
186 let max_speed_mps = if target.max_speed_mps > 0.0 {
187 target.max_speed_mps
188 } else {
189 f32::INFINITY
190 };
191 let desired_velocity =
192 config.position_p * (target.position_m - estimate.position_m) + target.velocity_mps;
193 let velocity_error = cap_magnitude(desired_velocity, max_speed_mps) - estimate.velocity_mps;
194
195 // A non-finite target or estimate yields no acceleration and never enters the integral
196 // or derivative history, where NaN would stick (it survives clamping). `cap_magnitude`
197 // zeroes a non-finite demand, so check its input too.
198 if !(all_finite(&desired_velocity) && all_finite(&velocity_error)) {
199 self.derivative.forget();
200 return Vec2::zeros();
201 }
202 let error_derivative = self.derivative.step(velocity_error, dt);
203
204 self.integrated_error = clamp_symmetric_each(
205 self.integrated_error + dt * velocity_error,
206 config.max_integral,
207 );
208 gains.p * velocity_error + gains.i * self.integrated_error + gains.d * error_derivative
209 }
210
211 /// The accumulated error, for tests of the composites' integrator policy.
212 #[cfg(test)]
213 pub(crate) fn integrated_error(&self) -> Vec2 {
214 self.integrated_error
215 }
216
217 /// Rescales the integral for a change of integral gain from `old` to `new`, so the next
218 /// tick's I term picks up where the last left off (`rescale_integral`).
219 pub(crate) fn rescale_integral(
220 &mut self,
221 old: &LateralControllerConfig,
222 new: &LateralControllerConfig,
223 ) {
224 let (old_i, new_i) = (old.velocity.i, new.velocity.i);
225 self.integrated_error = self
226 .integrated_error
227 .map(|e| rescale_integral(e, old_i, new_i));
228 }
229}
230
231#[cfg(test)]
232mod tests {
233 use crate::Vec2;
234
235 use super::*;
236
237 /// A target at `position_m`, stopping there, with no speed cap.
238 fn at(position_m: Vec2) -> LateralTarget {
239 LateralTarget {
240 position_m,
241 velocity_mps: Vec2::zeros(),
242 max_speed_mps: 0.0,
243 }
244 }
245
246 /// The vehicle at the origin moving at `velocity_mps`.
247 fn moving(velocity_mps: Vec2) -> LateralEstimate {
248 LateralEstimate {
249 position_m: Vec2::zeros(),
250 velocity_mps,
251 }
252 }
253
254 fn p_only() -> LateralControllerConfig {
255 LateralControllerConfig {
256 position_p: 0.5,
257 velocity: Gains {
258 p: 2.0,
259 i: 0.0,
260 d: 0.0,
261 },
262 ..Default::default()
263 }
264 }
265
266 #[test]
267 fn accelerates_toward_the_target_against_velocity() {
268 // (target, velocity, expected acceleration) with the vehicle at the origin
269 let cases = [
270 (at(Vec2::zeros()), Vec2::zeros(), Vec2::zeros()),
271 (
272 at(Vec2::new(10.0, 0.0)),
273 Vec2::zeros(),
274 Vec2::new(10.0, 0.0),
275 ), // no cap
276 (
277 at(Vec2::new(0.0, -3.0)),
278 Vec2::zeros(),
279 Vec2::new(0.0, -3.0),
280 ),
281 (
282 at(Vec2::zeros()),
283 Vec2::new(4.0, -2.0),
284 Vec2::new(-8.0, 4.0),
285 ), // brakes
286 (at(Vec2::new(0.0, f32::NAN)), Vec2::zeros(), Vec2::zeros()),
287 (
288 at(Vec2::new(f32::INFINITY, 0.0)),
289 Vec2::zeros(),
290 Vec2::zeros(),
291 ), // non-finite
292 ];
293 for (target, velocity, expected) in cases {
294 let mut controller = LateralController::default();
295 let accel = controller.control(&p_only(), 0.004, target, moving(velocity));
296 assert!(
297 (accel - expected).amax() < 1e-5,
298 "target {target:?}, velocity {velocity:?} gave {accel:?}, expected {expected:?}"
299 );
300 }
301 }
302
303 /// The desired velocity is capped at `max_speed_mps`, keeping its direction; zero,
304 /// negative, and NaN limits leave it uncapped.
305 #[test]
306 fn caps_the_desired_speed() {
307 let far = Vec2::new(30.0, 40.0); // 50 m away: desired 25 m/s uncapped
308 // (max_speed_mps, velocity feedforward, expected acceleration from rest)
309 let cases = [
310 (5.0, Vec2::zeros(), Vec2::new(6.0, 8.0)), // 5 m/s toward (3, 4)/5, × P 2
311 (100.0, Vec2::zeros(), Vec2::new(30.0, 40.0)),
312 (0.0, Vec2::zeros(), Vec2::new(30.0, 40.0)),
313 (-1.0, Vec2::zeros(), Vec2::new(30.0, 40.0)),
314 (f32::NAN, Vec2::zeros(), Vec2::new(30.0, 40.0)),
315 // Feedforward adds before the cap.
316 (5.0, Vec2::new(15.0, 20.0), Vec2::new(6.0, 8.0)),
317 ];
318 for (max_speed_mps, velocity_mps, expected) in cases {
319 let target = LateralTarget {
320 position_m: far,
321 velocity_mps,
322 max_speed_mps,
323 };
324 let accel = LateralController::default().control(
325 &p_only(),
326 0.004,
327 target,
328 moving(Vec2::zeros()),
329 );
330 assert!(
331 (accel - expected).amax() < 1e-4,
332 "max {max_speed_mps}, ff {velocity_mps:?} gave {accel:?}, expected {expected:?}"
333 );
334 }
335 }
336
337 /// On the target, the feedforward velocity is the whole demand: flying at it needs no
338 /// acceleration, and at rest the loop accelerates toward it.
339 #[test]
340 fn feedforward_flies_through_the_target() {
341 let target = LateralTarget {
342 position_m: Vec2::zeros(),
343 velocity_mps: Vec2::new(7.0, 0.0),
344 max_speed_mps: 7.0,
345 };
346 let config = p_only();
347 let cruising = LateralController::default().control(
348 &config,
349 0.004,
350 target,
351 moving(Vec2::new(7.0, 0.0)),
352 );
353 let at_rest =
354 LateralController::default().control(&config, 0.004, target, moving(Vec2::zeros()));
355 assert!(cruising == Vec2::zeros());
356 assert!((at_rest - Vec2::new(14.0, 0.0)).amax() < 1e-5);
357 }
358
359 /// Below the cap, the default cascade is the flight-checked position PD it replaced:
360 /// `0.63 · e − 1.26 · v`.
361 #[test]
362 fn default_gains_match_the_position_pd() {
363 let config = LateralControllerConfig::default();
364 // (position error, velocity)
365 let cases = [
366 (Vec2::new(2.0, -1.0), Vec2::zeros()),
367 (Vec2::zeros(), Vec2::new(1.0, 0.5)),
368 (Vec2::new(-3.0, 4.0), Vec2::new(0.4, -0.2)),
369 ];
370 for (error, velocity) in cases {
371 let accel =
372 LateralController::default().control(&config, 0.004, at(error), moving(velocity));
373 let expected = 0.63 * error - 1.26 * velocity;
374 assert!(
375 (accel - expected).amax() < 1e-5,
376 "error {error:?}, velocity {velocity:?} gave {accel:?}"
377 );
378 }
379 }
380
381 /// A NaN or infinite velocity estimate gives no acceleration, not NaN.
382 #[test]
383 fn non_finite_velocity_yields_no_acceleration() {
384 let nan = f32::NAN;
385 let inf = f32::INFINITY;
386 let velocities = [
387 Vec2::new(nan, 0.0),
388 Vec2::new(0.0, inf),
389 Vec2::new(-inf, nan),
390 ];
391 let config = LateralControllerConfig::default();
392 for velocity in velocities {
393 let mut controller = LateralController::default();
394 let accel =
395 controller.control(&config, 0.004, at(Vec2::new(10.0, 5.0)), moving(velocity));
396 assert!(
397 accel == Vec2::zeros(),
398 "velocity {velocity:?} gave {accel:?}"
399 );
400 }
401 }
402
403 #[test]
404 fn integral_term_is_clamped_to_max_integral() {
405 let config = LateralControllerConfig {
406 max_integral: 5.0,
407 ..Default::default()
408 };
409 let mut controller = LateralController::default();
410
411 // A large, persistent error for many ticks would wind the integral far past the limit.
412 for _ in 0..10_000 {
413 controller.control(
414 &config,
415 0.01,
416 at(Vec2::new(100.0, -100.0)),
417 moving(Vec2::zeros()),
418 );
419 }
420
421 assert!(controller.integrated_error == Vec2::new(5.0, -5.0));
422 }
423
424 #[test]
425 fn recovers_after_a_nan_tick() {
426 let config = LateralControllerConfig {
427 velocity: Gains {
428 p: 1.0,
429 i: 0.5,
430 d: 0.1,
431 },
432 ..Default::default()
433 };
434 let mut controller = LateralController::default();
435 let at_rest = moving(Vec2::zeros());
436
437 // One tick with a NaN target must not poison later ticks.
438 let during = controller.control(&config, 0.004, at(Vec2::new(f32::NAN, 0.0)), at_rest);
439 let after = controller.control(&config, 0.004, at(Vec2::new(10.0, 0.0)), at_rest);
440
441 assert!(during == Vec2::zeros(), "NaN tick gave {during:?}");
442 let fresh =
443 LateralController::default().control(&config, 0.004, at(Vec2::new(10.0, 0.0)), at_rest);
444 assert!(after == fresh, "valid target after NaN gave {after:?}");
445 }
446
447 /// The D term acts on the change in velocity error, with no kick on the first tick.
448 #[test]
449 fn derivative_acts_on_the_velocity_error_change() {
450 let config = LateralControllerConfig {
451 position_p: 0.0,
452 velocity: Gains {
453 p: 0.0,
454 i: 0.0,
455 d: 0.5,
456 },
457 ..Default::default()
458 };
459 let mut controller = LateralController::default();
460 let target = at(Vec2::zeros());
461 let first = controller.control(&config, 0.1, target, moving(Vec2::new(1.0, 0.0)));
462 let second = controller.control(&config, 0.1, target, moving(Vec2::new(2.0, 0.0)));
463 assert!(first == Vec2::zeros());
464 assert!((second - Vec2::new(-5.0, 0.0)).amax() < 1e-4);
465 }
466
467 /// An invalid limit fails `validate` but `control` stays panic-free: it acts as 0.
468 #[test]
469 fn invalid_config_is_rejected_and_does_not_panic_the_tick() {
470 let negative_integral = LateralControllerConfig {
471 max_integral: -1.0,
472 ..Default::default()
473 };
474 let nan_position_p = LateralControllerConfig {
475 position_p: f32::NAN,
476 ..Default::default()
477 };
478 assert_eq!(
479 negative_integral.validate().map_err(|e| e.field),
480 Err("max_integral")
481 );
482 assert_eq!(
483 nan_position_p.validate().map_err(|e| e.field),
484 Err("position_p")
485 );
486 for max_integral in [-1.0, f32::NAN] {
487 let config = LateralControllerConfig {
488 max_integral,
489 ..Default::default()
490 };
491 let mut controller = LateralController::default();
492 controller.control(
493 &config,
494 0.01,
495 at(Vec2::new(1.0, 1.0)),
496 moving(Vec2::zeros()),
497 );
498 assert!(
499 controller.integrated_error == Vec2::zeros(),
500 "max_integral {max_integral}"
501 );
502 }
503 }
504
505 /// A gain change between ticks applies on the next tick and keeps the integral.
506 #[test]
507 fn gain_change_between_ticks_keeps_state() {
508 let config = LateralControllerConfig::default();
509 let mut controller = LateralController::default();
510 controller.control(&config, 1.0, at(Vec2::new(0.0, 1.0)), moving(Vec2::zeros()));
511 let integral = controller.integrated_error;
512
513 let retuned = LateralControllerConfig {
514 position_p: 0.0,
515 velocity: Gains {
516 p: 0.0,
517 i: 2.0,
518 d: 0.0,
519 },
520 ..config
521 };
522 let accel = controller.control(&retuned, 0.01, at(Vec2::zeros()), moving(Vec2::zeros()));
523
524 assert!(controller.integrated_error == integral);
525 approx::assert_relative_eq!(accel.y, 2.0 * integral.y, epsilon = 1e-6);
526 }
527
528 #[test]
529 #[should_panic(expected = "dt must be positive and finite")]
530 fn zero_dt_panics() {
531 LateralController::default().control(
532 &LateralControllerConfig::default(),
533 0.0,
534 at(Vec2::zeros()),
535 moving(Vec2::zeros()),
536 );
537 }
538}