Skip to main content

stable_flight/controllers/
body_rate.rs

1use crate::Vec3;
2
3use super::derivative::DerivativeState;
4use super::{Gains, InvalidConfig, check_limit, rescale_integral};
5use crate::math::{assert_dt, clamp_symmetric};
6
7/// Default proportional gain, in normalized moment per rad/s of rate error.
8const DEFAULT_P: f32 = 0.15;
9/// Default derivative gain, in normalized moment per rad/s².
10const DEFAULT_D: f32 = 0.003;
11/// Roll and pitch rate I as a share of rate P, in 1/s: the autotune's rule for every gain it sets
12/// (`tuning::autotune`). The I term holds a steady trim moment (a CG offset, a weak motor)
13/// so the vehicle doesn't tilt while the attitude loop's slow I winds. Higher: trim held
14/// sooner; the sim autotune passed every clean and delayed robustness row at 0.1–0.3 and
15/// failed most at 1.0, ArduPilot's final ratio (`AUTOTUNE_PI_RATIO_FINAL`) (#374).
16pub const RATE_I_PER_P: f32 = 0.2;
17/// Yaw rate I as a share of yaw rate P, in 1/s: the autotune's rule for the yaw I it sets. A
18/// multirotor's yaw trim is large (0.40 of the moment on QuadCopterX, #192), and after liftoff
19/// the I has to rebuild it. Higher: trim back sooner; on the sim's QuadCopterX yaw the
20/// liftoff heading is back within 2° in 4.9 s against 7.3 s at 0.2, with the same tuned P.
21/// Past 0.3 the tuned steps overshoot more: 0.05 at 0.4, past the step spec's 0.05 at 0.5
22/// (#558).
23pub const YAW_RATE_I_PER_P: f32 = 0.3;
24/// Default yaw proportional gain. Yaw authority comes only from differential prop drag, so
25/// yaw needs more gain than roll and pitch.
26const DEFAULT_YAW_P: f32 = 0.3;
27/// Default yaw integral gain, in normalized moment per rad of accumulated error.
28const DEFAULT_YAW_I: f32 = 0.1;
29/// Default roll and pitch integral limit, in rad (accumulated rate error).
30const DEFAULT_MAX_INTEGRAL: f32 = 1.0;
31/// Default yaw integral limit, in rad (accumulated rate error). The I term holds a moment of
32/// at most `i · yaw_max_integral`, and a multirotor's yaw trim can be large: QuadCopterX
33/// hovers on 0.40 of yaw moment in RealFlight (#192). At 5 rad the autotune's I
34/// ([`YAW_RATE_I_PER_P`] of P) holds 0.40 from P 0.27 up; at 1 rad a fifth of P would need
35/// P 2, and the sim yaw search kept its start on every 0.40-trim row (#296).
36const DEFAULT_YAW_MAX_INTEGRAL: f32 = 5.0;
37
38/// Configures the [BodyRateController] with PID gains and operational limits.
39///
40/// Gains map rate error (rad/s) straight to a normalized moment in `[-1, 1]`: `p` is moment per
41/// rad/s, `i` per rad of accumulated error, and `d` per rad/s².
42#[derive(Clone, Copy, Debug, PartialEq)]
43pub struct BodyRateControllerConfig {
44    /// PID gains for the roll rate.
45    pub roll_gains: Gains,
46
47    /// PID gains for the pitch rate.
48    pub pitch_gains: Gains,
49
50    /// PID gains for the yaw rate.
51    pub yaw_gains: Gains,
52
53    /// Maximum absolute value of the integrated roll and pitch rate error, in rad, each.
54    /// Prevents integral windup by limiting error accumulation.
55    pub max_integral: f32,
56
57    /// Maximum absolute value of the integrated yaw rate error, in rad: the yaw I term holds
58    /// at most `yaw_gains.i · yaw_max_integral` of trim moment.
59    pub yaw_max_integral: f32,
60}
61
62impl Default for BodyRateControllerConfig {
63    fn default() -> Self {
64        let roll_pitch_gains = Gains {
65            p: DEFAULT_P,
66            i: RATE_I_PER_P * DEFAULT_P,
67            d: DEFAULT_D,
68        };
69        Self {
70            roll_gains: roll_pitch_gains,
71            pitch_gains: roll_pitch_gains,
72            yaw_gains: Gains {
73                p: DEFAULT_YAW_P,
74                i: DEFAULT_YAW_I,
75                d: 0.0,
76            },
77            max_integral: DEFAULT_MAX_INTEGRAL,
78            yaw_max_integral: DEFAULT_YAW_MAX_INTEGRAL,
79        }
80    }
81}
82
83impl BodyRateControllerConfig {
84    /// Checks the config: `max_integral` and `yaw_max_integral` must be non-negative and
85    /// finite.
86    ///
87    /// # Examples
88    ///
89    /// ```
90    /// use stable_flight::controllers::BodyRateControllerConfig;
91    ///
92    /// assert!(BodyRateControllerConfig::default().validate().is_ok());
93    /// let bad = BodyRateControllerConfig { max_integral: -1.0, ..Default::default() };
94    /// assert!(bad.validate().is_err());
95    /// ```
96    pub fn validate(&self) -> Result<(), InvalidConfig> {
97        check_limit("max_integral", self.max_integral)?;
98        check_limit("yaw_max_integral", self.yaw_max_integral)
99    }
100
101    /// Gains per axis: roll, pitch, yaw.
102    fn axis_gains(&self) -> [Gains; 3] {
103        [self.roll_gains, self.pitch_gains, self.yaw_gains]
104    }
105
106    /// Integral limits per axis, in rad: roll, pitch, yaw.
107    fn axis_max_integrals(&self) -> [f32; 3] {
108        [self.max_integral, self.max_integral, self.yaw_max_integral]
109    }
110}
111
112/// A PID-based controller for managing angular rates (roll, pitch, yaw) of a vehicle.
113///
114/// This controller uses a PID algorithm to compute corrective moments based on desired and estimated
115/// angular rates. It is designed as the innermost control loop, directly affecting motor commands.
116///
117/// It holds only state (integral and derivative history); gains and limits come from the
118/// [`BodyRateControllerConfig`] passed to each [`control`](Self::control) call, so they can
119/// change between ticks without resetting the state.
120///
121/// # Units
122/// - Time (`dt`) is in seconds.
123/// - Desired and estimated rates are expected in rad/s.
124/// - Output moments are `P·e + I·∫e − D·ω̇`, saturated to `[-1, 1]` per axis; the mixer scales
125///   them to motor commands.
126///
127/// # D on the measured rate
128///
129/// D damps the measured rate's change (`ω̇`, the angular acceleration), not the error's, so a
130/// setpoint step adds no derivative kick: on the error, a step of `A` rad/s would kick the
131/// moment by `D·A/dt` for one tick (35·A with a designed `d` of 0.139 at 250 Hz), clipping it
132/// and showing as overshoot. Inside the loop the two are the same, so stability and the
133/// response to a disturbance don't change; only a setpoint change is followed by P and I alone.
134/// PX4's `RateControl` takes D on the measured rate too; ArduPilot's `AC_PID` takes it on the
135/// error and low-passes it (`ATC_RAT_RLL_FLTD`).
136#[derive(Clone, Debug, Default, PartialEq)]
137pub struct BodyRateController {
138    /// Roll, pitch, and yaw, each with its own PID state.
139    axes: [RateAxis; 3],
140}
141
142/// One axis of the rate loop: its integral and derivative history.
143#[derive(Clone, Copy, Debug, Default, PartialEq)]
144struct RateAxis {
145    /// Integrated rate error, in rad.
146    integrated_error: f32,
147
148    /// Previous measured rate for the derivative term; empty on the first tick and after a gap.
149    derivative: DerivativeState<f32>,
150}
151
152impl RateAxis {
153    /// `P·e + I·∫e − D·ω̇` for one axis, with `e = desired − measured` and `ω̇` the measured
154    /// rate's change, saturated to `[-1, 1]`. A non-finite error gives 0 and stays out of the
155    /// integral and derivative state.
156    ///
157    /// While the moment is clipped, the integral may shrink but not grow: growing it can't
158    /// add moment, and it would wind up and overshoot once the clip ends (anti-windup). The
159    /// clip is this loop's own ±1; a mixer limit below it isn't seen, where ArduPilot's
160    /// `AC_PID::update_i` holds the integral on the mixer's limit flags.
161    fn step(
162        &mut self,
163        gains: Gains,
164        max_integral: f32,
165        dt: f32,
166        desired_radps: f32,
167        measured_radps: f32,
168    ) -> f32 {
169        let error_radps = desired_radps - measured_radps;
170        if !error_radps.is_finite() {
171            self.derivative.forget();
172            return 0.0;
173        }
174
175        let accel_radps2 = self.derivative.step(measured_radps, dt);
176        let pd = gains.p * error_radps - gains.d * accel_radps2;
177        let integrated_error =
178            clamp_symmetric(self.integrated_error + dt * error_radps, max_integral);
179        let moment = pd + gains.i * integrated_error;
180        let clipped = moment.abs() > 1.0;
181        if !clipped || integrated_error.abs() < self.integrated_error.abs() {
182            self.integrated_error = integrated_error;
183        }
184
185        clamp_symmetric(pd + gains.i * self.integrated_error, 1.0)
186    }
187}
188
189impl BodyRateController {
190    /// Controls the angular velocity (body rates) of the vehicle using a PID controller.
191    ///
192    /// Computes the error between desired and estimated rates (both rad/s) and applies PID
193    /// control to it, per axis with `config.roll_gains`, `pitch_gains`, and `yaw_gains`.
194    ///
195    /// # Arguments
196    ///
197    /// * `config` - Gains and limits; assumed valid ([`BodyRateControllerConfig::validate`]).
198    ///   An invalid limit does not panic: a negative or NaN integral limit acts as 0.
199    /// * `dt` - Time step since the last update in seconds (must be positive and finite).
200    /// * `desired_rates_radps` - Desired angular rates (roll, pitch, yaw) in rad/s.
201    /// * `estimated_rates_radps` - Current measured angular rates (roll, pitch, yaw) in rad/s.
202    ///
203    /// # Returns
204    ///
205    /// Moments (roll, pitch, yaw), each saturated to `[-1, 1]`.
206    ///
207    /// # Panics
208    ///
209    /// If `dt` is not positive and finite.
210    ///
211    /// A non-finite component in `desired_rates_radps` or `estimated_rates_radps` gives a zero
212    /// moment on that axis alone and leaves that axis's state untouched, so a bad gyro axis
213    /// doesn't take damping off the others (the input policy in `architecture.md`).
214    ///
215    /// # Examples
216    ///
217    /// ```
218    /// use stable_flight::controllers::{BodyRateController, BodyRateControllerConfig};
219    /// use stable_flight::Vec3;
220    ///
221    /// let config = BodyRateControllerConfig::default();
222    /// let mut controller = BodyRateController::default();
223    /// let dt = 0.004; // seconds; 250 Hz control loop
224    /// let desired_rates_radps = Vec3::new(0.1, 0.0, 0.05); // roll, pitch, yaw rates (rad/s)
225    /// let estimated_rates_radps = Vec3::zeros();
226    ///
227    /// let moments = controller.control(&config, dt, desired_rates_radps, estimated_rates_radps);
228    /// assert!(moments.x > 0.0 && moments.z > 0.0);
229    /// assert!(moments.iter().all(|m| (-1.0..=1.0).contains(m)));
230    /// ```
231    pub fn control(
232        &mut self,
233        config: &BodyRateControllerConfig,
234        dt: f32,
235        desired_rates_radps: Vec3,
236        estimated_rates_radps: Vec3,
237    ) -> Vec3 {
238        assert_dt(dt);
239        let gains = config.axis_gains();
240        let max_integrals = config.axis_max_integrals();
241        Vec3::from_fn(|axis, _| {
242            self.axes[axis].step(
243                gains[axis],
244                max_integrals[axis],
245                dt,
246                desired_rates_radps[axis],
247                estimated_rates_radps[axis],
248            )
249        })
250    }
251
252    /// Rescales the integral for a change of integral gain from `old` to `new`, so the next
253    /// tick's I term picks up where the last left off (`rescale_integral`).
254    pub(crate) fn rescale_integral(
255        &mut self,
256        old: &BodyRateControllerConfig,
257        new: &BodyRateControllerConfig,
258    ) {
259        let gains = old.axis_gains().into_iter().zip(new.axis_gains());
260        for (axis, (old, new)) in self.axes.iter_mut().zip(gains) {
261            axis.integrated_error = rescale_integral(axis.integrated_error, old.i, new.i);
262        }
263    }
264
265    /// Zeroes every axis's integral, keeping the derivative history.
266    pub(crate) fn clear_integral(&mut self) {
267        for axis in &mut self.axes {
268            axis.integrated_error = 0.0;
269        }
270    }
271
272    /// The I term (`i · integral`) of `axis` (0 roll, 1 pitch, 2 yaw): the moment the loop
273    /// holds as trim.
274    #[cfg(test)]
275    pub(crate) fn integral_term(&self, config: &BodyRateControllerConfig, axis: usize) -> f32 {
276        config.axis_gains()[axis].i * self.axes[axis].integrated_error
277    }
278
279    /// Restarts `axis` with no derivative history, keeping its integral. The other axes are
280    /// untouched.
281    pub(crate) fn hand_back(&mut self, axis: usize) {
282        self.axes[axis].derivative = DerivativeState::default();
283    }
284
285    /// The integrated rate error per axis, in rad.
286    #[cfg(test)]
287    fn integrated_error(&self) -> Vec3 {
288        Vec3::from_fn(|axis, _| self.axes[axis].integrated_error)
289    }
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295    use approx::assert_abs_diff_eq;
296    use assert2::assert;
297
298    const DT: f32 = 0.004;
299
300    /// The same gains on every axis.
301    fn config(p: f32, i: f32, d: f32) -> BodyRateControllerConfig {
302        BodyRateControllerConfig {
303            roll_gains: Gains { p, i, d },
304            pitch_gains: Gains { p, i, d },
305            yaw_gains: Gains { p, i, d },
306            max_integral: 1.0,
307            yaw_max_integral: 1.0,
308        }
309    }
310
311    /// Handing back one axis clears its derivative history and keeps its integral; the other
312    /// axes keep both.
313    #[test]
314    fn hand_back_restarts_one_axis_only() {
315        let config = config(1.0, 2.0, 0.5);
316        let mut controller = BodyRateController::default();
317        controller.control(&config, DT, Vec3::new(0.5, 0.5, 0.5), Vec3::zeros());
318        let before = controller.axes;
319
320        controller.hand_back(0);
321
322        assert!(controller.axes[0].integrated_error == before[0].integrated_error);
323        assert!(controller.axes[0].derivative == DerivativeState::default());
324        assert!(controller.axes[1..] == before[1..]);
325    }
326
327    /// One tick from a fresh controller is `P·e + I·e·dt` (no derivative history yet; see
328    /// `first_tick_has_no_derivative_kick`), saturated to `[-1, 1]` per axis.
329    #[test]
330    fn first_tick_output_is_saturated_p_plus_i() {
331        // (p, i, desired, estimated, expected)
332        let cases = [
333            (0.15, 0.0, Vec3::zeros(), Vec3::zeros(), Vec3::zeros()),
334            (
335                0.15,
336                0.0,
337                Vec3::new(1.0, 0.0, 0.0),
338                Vec3::zeros(),
339                Vec3::new(0.15, 0.0, 0.0),
340            ),
341            (
342                0.15,
343                0.0,
344                Vec3::new(0.0, 2.0, -2.0),
345                Vec3::zeros(),
346                Vec3::new(0.0, 0.3, -0.3),
347            ),
348            (
349                0.15,
350                0.0,
351                Vec3::new(1.0, 1.0, 1.0),
352                Vec3::new(1.0, 2.0, 0.0),
353                Vec3::new(0.0, -0.15, 0.15),
354            ),
355            (
356                0.15,
357                0.0,
358                Vec3::new(10.0, -10.0, 0.0),
359                Vec3::zeros(),
360                Vec3::new(1.0, -1.0, 0.0),
361            ),
362            (
363                0.0,
364                10.0,
365                Vec3::new(5.0, 0.0, 0.0),
366                Vec3::zeros(),
367                Vec3::new(10.0 * 5.0 * DT, 0.0, 0.0),
368            ),
369        ];
370        for (p, i, desired, estimated, expected) in cases {
371            let mut c = BodyRateController::default();
372            let out = c.control(&config(p, i, 0.0), DT, desired, estimated);
373            assert!(
374                (out - expected).amax() < 1e-6,
375                "p={p} i={i} {desired:?}/{estimated:?}: {out:?}"
376            );
377        }
378    }
379
380    /// Closed loop against a constant yaw disturbance torque (`testing::settled_yaw_rate`),
381    /// commanding zero rate: the integral cancels it up to its authority
382    /// `I · yaw_max_integral`; past it, the rate settles at `−(D − I · yaw_max_integral) / P`
383    /// (#192).
384    #[test]
385    fn integral_cancels_a_constant_yaw_torque_up_to_its_authority() {
386        let cfg = BodyRateControllerConfig {
387            yaw_gains: Gains {
388                p: 0.6,
389                i: 0.2,
390                d: 0.0,
391            },
392            yaw_max_integral: 1.0,
393            ..config(0.0, 0.0, 0.0)
394        };
395        // (disturbance torque, expected settled yaw rate in rad/s)
396        let cases = [
397            (0.0, 0.0),
398            (0.15, 0.0),
399            (-0.15, 0.0),
400            (0.4, -0.333_333), // past the authority: CCW drift (#192)
401            (-0.4, 0.333_333),
402        ];
403        for (disturbance, expected) in cases {
404            let rate = crate::testing::settled_yaw_rate(&cfg, disturbance);
405            assert!(
406                (rate - expected).abs() < 1e-3,
407                "disturbance {disturbance}: settled at {rate} rad/s, expected {expected}"
408            );
409        }
410    }
411
412    /// The output is independent of `dt` for a pure P controller (no hidden normalization).
413    #[test]
414    fn proportional_output_does_not_depend_on_dt() {
415        for dt in [0.0001, 0.004, 0.02, 0.1] {
416            let mut c = BodyRateController::default();
417            let out = c.control(
418                &config(0.15, 0.0, 0.0),
419                dt,
420                Vec3::new(1.0, 0.0, 0.0),
421                Vec3::zeros(),
422            );
423            assert_abs_diff_eq!(out.x, 0.15, epsilon = 1e-6);
424        }
425    }
426
427    /// The derivative term is `−D·Δω/dt` on the measured rate: a rising rate is damped.
428    #[test]
429    fn derivative_term_opposes_a_rising_rate() {
430        let cfg = config(0.0, 0.0, 0.003);
431        let mut c = BodyRateController::default();
432        c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::zeros());
433        let steady = c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::zeros());
434        let rising = c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.5, 0.0, 0.0));
435
436        assert_abs_diff_eq!(steady.x, 0.0, epsilon = 1e-6);
437        assert_abs_diff_eq!(rising.x, 0.003 * -0.5 / DT, epsilon = 1e-5);
438    }
439
440    /// A setpoint step on a held rate moves the moment by `P·A` alone: no `D·A/dt` kick, for
441    /// any step size or D (#373).
442    #[test]
443    fn a_setpoint_step_has_no_derivative_kick() {
444        // (step in rad/s, d): the d's span the hand tune (0.003) to a designed quad_x (0.139).
445        let rows = [
446            (1.0, 0.003),
447            (-1.0, 0.003),
448            (0.2, 0.139),
449            (1.0, 0.139),
450            (-3.0, 0.05),
451        ];
452        let p = 0.15;
453        for (step_radps, d) in rows {
454            let cfg = config(p, 0.0, d);
455            let mut c = BodyRateController::default();
456            let measured = Vec3::new(0.3, 0.3, 0.3);
457            c.control(&cfg, DT, measured, measured);
458            let stepped = measured + Vec3::repeat(step_radps);
459            let moments = c.control(&cfg, DT, stepped, measured);
460            let expected = clamp_symmetric(p * step_radps, 1.0);
461            assert!(
462                (moments - Vec3::repeat(expected)).amax() < 1e-6,
463                "step {step_radps} rad/s, d {d}: {moments:?}"
464            );
465        }
466    }
467
468    /// A fresh controller has no previous rate, so D alone gives nothing on the first tick.
469    #[test]
470    fn first_tick_has_no_derivative_kick() {
471        let mut c = BodyRateController::default();
472        let moments = c.control(
473            &config(0.0, 0.0, 0.01),
474            DT,
475            Vec3::new(1.0, -2.0, 0.5),
476            Vec3::zeros(),
477        );
478        assert!(moments == Vec3::zeros());
479    }
480
481    /// The accumulated error grows by `e·dt` per tick and stops at the axis's limit:
482    /// `max_integral` for roll and pitch, `yaw_max_integral` for yaw.
483    #[test]
484    fn integral_accumulates_and_clamps_per_axis() {
485        let cfg = BodyRateControllerConfig {
486            max_integral: 1.0,
487            yaw_max_integral: 1.5,
488            ..config(0.0, 0.1, 0.0)
489        };
490        let error = Vec3::new(2.0, -2.0, 2.0);
491        let mut c = BodyRateController::default();
492        c.control(&cfg, 0.1, error, Vec3::zeros());
493        assert!((c.integrated_error() - Vec3::new(0.2, -0.2, 0.2)).amax() < 1e-6);
494
495        for _ in 0..20 {
496            c.control(&cfg, 0.1, error, Vec3::zeros());
497        }
498        assert!((c.integrated_error() - Vec3::new(1.0, -1.0, 1.5)).amax() < 1e-6);
499    }
500
501    /// While the moment is clipped, the integral shrinks but doesn't grow; unclipped, it
502    /// grows as usual.
503    #[test]
504    fn clipped_moment_stops_the_integral_growing() {
505        let start = 0.5;
506        // (case, p, error, expected integral after one 0.1 s tick)
507        let rows = [
508            ("unclipped grows", 0.1, 1.0, start + 0.1),
509            ("clipped toward the error holds", 2.0, 1.0, start),
510            (
511                "clipped against the integral shrinks",
512                2.0,
513                -1.0,
514                start - 0.1,
515            ),
516            (
517                "clipped, error crossing zero shrinks",
518                2.0,
519                -0.6,
520                start - 0.06,
521            ),
522        ];
523        for (case, p, error, expected) in rows {
524            let cfg = config(p, 0.1, 0.0);
525            let mut c = BodyRateController::default();
526            c.axes[0].integrated_error = start;
527            let out = c.control(&cfg, 0.1, Vec3::new(error, 0.0, 0.0), Vec3::zeros());
528            let integral = c.integrated_error().x;
529            assert!((integral - expected).abs() < 1e-6, "{case}: {integral}");
530            assert!(out.x.abs() <= 1.0, "{case}");
531        }
532    }
533
534    /// Each axis uses its own gains: roll `roll_gains`, pitch `pitch_gains`, yaw `yaw_gains`.
535    #[test]
536    fn each_axis_uses_its_own_gains() {
537        let p_only = |p| Gains { p, i: 0.0, d: 0.0 };
538        let cfg = BodyRateControllerConfig {
539            roll_gains: p_only(0.15),
540            pitch_gains: p_only(0.25),
541            yaw_gains: p_only(0.5),
542            max_integral: 1.0,
543            yaw_max_integral: 1.0,
544        };
545        let out = BodyRateController::default().control(
546            &cfg,
547            DT,
548            Vec3::new(1.0, 1.0, 1.0),
549            Vec3::zeros(),
550        );
551
552        assert!((out - Vec3::new(0.15, 0.25, 0.5)).amax() < 1e-6);
553    }
554
555    /// A gain change between ticks takes effect on the next tick and keeps the integral.
556    #[test]
557    fn gain_change_between_ticks_keeps_state() {
558        let mut c = BodyRateController::default();
559        c.control(
560            &config(0.0, 0.1, 0.0),
561            0.1,
562            Vec3::new(2.0, 0.0, 0.0),
563            Vec3::zeros(),
564        );
565        let integral = c.integrated_error();
566
567        let out = c.control(&config(0.0, 0.5, 0.0), 0.1, Vec3::zeros(), Vec3::zeros());
568
569        assert!(c.integrated_error() == integral);
570        assert_abs_diff_eq!(out.x, 0.5 * integral.x, epsilon = 1e-6);
571    }
572
573    /// A shrunk `max_integral` clamps the existing integral on the next tick.
574    #[test]
575    fn shrinking_max_integral_clamps_the_integral() {
576        let mut c = BodyRateController::default();
577        c.control(
578            &config(0.0, 0.1, 0.0),
579            1.0,
580            Vec3::new(0.8, 0.0, 0.0),
581            Vec3::zeros(),
582        );
583
584        let shrunk = BodyRateControllerConfig {
585            max_integral: 0.25,
586            ..config(0.0, 0.1, 0.0)
587        };
588        c.control(&shrunk, DT, Vec3::zeros(), Vec3::zeros());
589
590        assert_abs_diff_eq!(c.integrated_error().x, 0.25, epsilon = 1e-6);
591    }
592
593    /// An invalid limit fails `validate` but does not panic `control`: it acts as 0 on its
594    /// axes.
595    #[test]
596    fn invalid_max_integral_is_rejected_and_does_not_panic_the_tick() {
597        type SetLimit = fn(&mut BodyRateControllerConfig, f32);
598        // (field, how to set it, the error axis it limits)
599        let rows: [(&str, SetLimit, Vec3); 2] = [
600            ("max_integral", |c, v| c.max_integral = v, Vec3::x()),
601            ("yaw_max_integral", |c, v| c.yaw_max_integral = v, Vec3::z()),
602        ];
603        for (field, set, error) in rows {
604            for limit in [-1.0, f32::NAN] {
605                let mut cfg = config(0.0, 0.1, 0.0);
606                set(&mut cfg, limit);
607                assert_eq!(cfg.validate().map_err(|e| e.field), Err(field));
608                let mut c = BodyRateController::default();
609                let out = c.control(&cfg, DT, error, Vec3::zeros());
610                assert!(c.integrated_error() == Vec3::zeros(), "{field} {limit}");
611                assert!(out == Vec3::zeros(), "{field} {limit}");
612            }
613        }
614    }
615
616    #[test]
617    #[should_panic(expected = "dt must be positive and finite")]
618    fn zero_dt_panics() {
619        BodyRateController::default().control(
620            &config(0.15, 0.0, 0.0),
621            0.0,
622            Vec3::zeros(),
623            Vec3::zeros(),
624        );
625    }
626
627    /// A non-finite desired or estimated rate zeroes that axis alone: the other axes
628    /// match a controller that never saw it, the bad axis's integral is untouched, and its
629    /// first finite tick afterwards has no derivative kick.
630    #[test]
631    fn non_finite_rate_zeroes_only_its_axis() {
632        let nan = f32::NAN;
633        let inf = f32::INFINITY;
634        // (desired, estimated)
635        let cases = [
636            (Vec3::new(inf, 0.3, -0.2), Vec3::zeros()),
637            (Vec3::new(0.4, 0.3, -0.2), Vec3::new(0.0, nan, 0.0)),
638            (Vec3::new(0.4, 0.3, nan), Vec3::zeros()),
639            (Vec3::new(0.4, inf, 0.0), Vec3::new(0.0, inf, 0.0)), // ∞ − ∞
640            (Vec3::new(nan, nan, nan), Vec3::zeros()),
641        ];
642        let cfg = config(0.15, 0.1, 0.003);
643        let warm_up = Vec3::new(0.5, -0.4, 0.3);
644        let after_gap = Vec3::new(0.2, 0.2, 0.2);
645        for (desired, estimated) in cases {
646            let bad = (desired - estimated).map(|e| !e.is_finite());
647            let finite = |v: Vec3| v.map(|c| if c.is_finite() { c } else { 0.0 });
648            let mut c = BodyRateController::default();
649            let mut twin = BodyRateController::default();
650            // A valid tick first, so there is derivative history to go stale.
651            c.control(&cfg, DT, warm_up, Vec3::zeros());
652            twin.control(&cfg, DT, warm_up, Vec3::zeros());
653            let integral_before = c.integrated_error();
654
655            let during = c.control(&cfg, DT, desired, estimated);
656            let twin_during = twin.control(&cfg, DT, finite(desired), finite(estimated));
657            let after = c.control(&cfg, DT, after_gap, Vec3::zeros());
658            let twin_after = twin.control(&cfg, DT, after_gap, Vec3::zeros());
659
660            for axis in 0..3 {
661                let row = format!("{desired:?}/{estimated:?} axis {axis}");
662                if bad[axis] {
663                    assert!(during[axis] == 0.0, "{row}: {during:?}");
664                    // After the gap: P + I only, no derivative from the pre-gap error.
665                    let integral = integral_before[axis] + DT * after_gap[axis];
666                    let expected = 0.15 * after_gap[axis] + 0.1 * integral;
667                    assert!((after[axis] - expected).abs() < 1e-6, "{row}: {after:?}");
668                } else {
669                    assert!(during[axis] == twin_during[axis], "{row}: {during:?}");
670                    assert!(after[axis] == twin_after[axis], "{row}: {after:?}");
671                }
672            }
673        }
674    }
675}