Skip to main content

stable_flight/controllers/
attitude.rs

1use core::f32::consts::FRAC_PI_4;
2
3use crate::Vec2;
4
5use super::derivative::DerivativeState;
6use super::{Gains, InvalidConfig, check_limit, rescale_integral};
7use crate::math::{assert_dt, clamp_symmetric, clamp_symmetric_each, saturate_symmetric};
8
9/// Configures the attitude controller for a vehicle.
10/// Defines PID gains, maximum angles, and maximum angular rates for roll and pitch control.
11/// Yaw is typically handled separately by a dedicated yaw controller.
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub struct AttitudeControllerConfig {
14    /// PID gains for roll.
15    pub roll_gains: Gains,
16
17    /// PID gains for pitch.
18    pub pitch_gains: Gains,
19
20    /// Maximum angles in radians for roll (x) and pitch (y) (e.g., π/4 = 45°).
21    /// Limits the vehicle's tilt in each axis.
22    pub max_angles_rad: Vec2,
23
24    /// Maximum absolute value of the integrated angle error, in rad·s, per axis.
25    /// Prevents integral windup by limiting error accumulation.
26    pub max_integral: f32,
27
28    /// Maximum angular rates in radians/second for roll (x) and pitch (y).
29    /// Limits the output rates sent to the rate controller.
30    pub max_rate_radps: Vec2,
31}
32
33impl Default for AttitudeControllerConfig {
34    /// Untuned starting values (45° tilt, 2 rad/s rate cap); airframes override them with
35    /// flight-checked sets.
36    fn default() -> Self {
37        let gains = Gains {
38            p: 3.0,
39            i: 0.001,
40            d: 1.0,
41        };
42        Self {
43            roll_gains: gains,
44            pitch_gains: gains,
45            max_angles_rad: Vec2::new(FRAC_PI_4, FRAC_PI_4), // 45° for roll and pitch
46            max_integral: 100.0,
47            max_rate_radps: Vec2::new(2.0, 2.0), // 2 rad/s (~114°/s) for roll and pitch
48        }
49    }
50}
51
52impl AttitudeControllerConfig {
53    /// Checks the config: `max_angles_rad`, `max_rate_radps`, and `max_integral` must be
54    /// non-negative and finite.
55    ///
56    /// # Examples
57    ///
58    /// ```
59    /// use stable_flight::controllers::AttitudeControllerConfig;
60    /// use stable_flight::Vec2;
61    ///
62    /// assert!(AttitudeControllerConfig::default().validate().is_ok());
63    /// let bad = AttitudeControllerConfig {
64    ///     max_angles_rad: Vec2::new(-1.0, 0.5),
65    ///     ..Default::default()
66    /// };
67    /// assert!(bad.validate().is_err());
68    /// ```
69    pub fn validate(&self) -> Result<(), InvalidConfig> {
70        check_limit("max_angles_rad.x", self.max_angles_rad.x)?;
71        check_limit("max_angles_rad.y", self.max_angles_rad.y)?;
72        check_limit("max_rate_radps.x", self.max_rate_radps.x)?;
73        check_limit("max_rate_radps.y", self.max_rate_radps.y)?;
74        check_limit("max_integral", self.max_integral)
75    }
76
77    /// Gains per axis: roll, pitch.
78    fn axis_gains(&self) -> [Gains; 2] {
79        [self.roll_gains, self.pitch_gains]
80    }
81}
82
83/// Roll/pitch angle PID loop: turns roll/pitch setpoints in radians into body-rate setpoints for the
84/// [`BodyRateController`](super::BodyRateController).
85///
86/// It holds only state (integral and derivative history); gains and limits come from the
87/// [`AttitudeControllerConfig`] passed to each [`control`](Self::control) call, so they can
88/// change between ticks without resetting the state.
89#[derive(Clone, Debug, Default, PartialEq)]
90pub struct AttitudeController {
91    integrated_error: Vec2, // Accumulated error (roll, pitch)
92    /// Previous error per axis for the derivative term; empty on the first tick and after a
93    /// gap.
94    derivative: [DerivativeState<f32>; 2],
95}
96
97impl AttitudeController {
98    /// Computes desired angular rates to achieve target roll and pitch angles.
99    ///
100    /// Uses a PID controller to convert angle errors into angular rates (rad/s)
101    /// for the rate control loop. Input angles are clamped to
102    /// [-max_angles_rad.x, max_angles_rad.x] for roll and [-max_angles_rad.y, max_angles_rad.y] for pitch.
103    /// Output rates are clamped to [-max_rate_radps.x, max_rate_radps.x] for roll and
104    /// [-max_rate_radps.y, max_rate_radps.y] for pitch.
105    ///
106    /// # Arguments
107    /// * `config` - Gains and limits; assumed valid ([`AttitudeControllerConfig::validate`]).
108    ///   An invalid limit does not panic: a negative or NaN limit acts as 0.
109    /// * `dt` - Time step since the last update in seconds (must be positive and finite).
110    /// * `desired_angles_rad` - Target roll/pitch in radians. Values beyond `max_angles_rad`
111    ///   saturate to it, and NaN is treated as 0 (level).
112    /// * `estimated_angles_rad` - Current roll/pitch angles in radians
113    ///
114    /// # Returns
115    /// Desired angular rates (roll rate, pitch rate) in radians/second,
116    /// clamped to configured max_rate_radps limits
117    ///
118    /// # Panics
119    ///
120    /// If `dt` is not positive and finite.
121    ///
122    /// # Examples
123    ///
124    /// ```
125    /// use stable_flight::controllers::{AttitudeController, AttitudeControllerConfig};
126    /// use stable_flight::Vec2;
127    ///
128    /// let config = AttitudeControllerConfig::default();
129    /// let mut controller = AttitudeController::default();
130    /// let dt = 0.004;
131    /// let desired_angles_rad = Vec2::new(0.4, -0.15); // roll right, pitch down
132    /// let estimated_angles_rad = Vec2::new(0.1, 0.0); // current roll/pitch in radians
133    ///
134    /// let angular_rates = controller.control(&config, dt, desired_angles_rad, estimated_angles_rad);
135    /// assert!(angular_rates.x > 0.0 && angular_rates.y < 0.0);
136    /// ```
137    pub fn control(
138        &mut self,
139        config: &AttitudeControllerConfig,
140        dt: f32,
141        desired_angles_rad: Vec2,
142        estimated_angles_rad: Vec2,
143    ) -> Vec2 {
144        let error = Self::angle_error(config, desired_angles_rad, estimated_angles_rad);
145        self.control_error(config, dt, error)
146    }
147
148    /// The PID of [`control`](Self::control) on an angle error already taken (roll, pitch, in
149    /// radians): for a caller that measures the error itself, e.g. from quaternions. Output
150    /// rates are clamped to `max_rate_radps`; a non-finite error gives zero rates.
151    ///
152    /// # Panics
153    ///
154    /// If `dt` is not positive and finite.
155    pub(crate) fn control_error(
156        &mut self,
157        config: &AttitudeControllerConfig,
158        dt: f32,
159        error: Vec2,
160    ) -> Vec2 {
161        assert_dt(dt);
162
163        // A non-finite error (NaN/∞ estimate) yields no rate command and never enters the
164        // integral or derivative history (see `crate::math` for the policy).
165        if !(error.x.is_finite() && error.y.is_finite()) {
166            self.derivative.iter_mut().for_each(DerivativeState::forget);
167            return Vec2::zeros();
168        }
169
170        // Derivative term: rate of change of error (skipped on the first tick after a gap)
171        let error_derivative = Vec2::from_fn(|axis, _| self.derivative[axis].step(error[axis], dt));
172
173        // Integral term with anti-windup
174        self.integrated_error =
175            clamp_symmetric_each(self.integrated_error + dt * error, config.max_integral);
176
177        // PID calculation per axis: Kp×error + Ki×∫error + Kd×d(error)/dt
178        let gains = config.axis_gains();
179        let rates = Vec2::from_fn(|axis, _| {
180            let Gains { p, i, d } = gains[axis];
181            p * error[axis] + i * self.integrated_error[axis] + d * error_derivative[axis]
182        });
183
184        // Scale output to configured maximum rates
185        Vec2::new(
186            clamp_symmetric(rates.x, config.max_rate_radps.x),
187            clamp_symmetric(rates.y, config.max_rate_radps.y),
188        )
189    }
190
191    /// The angle error (setpoint − estimate) the loop acts on, per axis. Outer loops and pilots
192    /// can ask for more than full tilt, or NaN: the setpoint saturates to `max_angles_rad`
193    /// (NaN is level) rather than panic the flight loop.
194    pub(crate) fn angle_error(
195        config: &AttitudeControllerConfig,
196        desired_angles_rad: Vec2,
197        estimated_angles_rad: Vec2,
198    ) -> Vec2 {
199        Self::saturate_setpoint(config.max_angles_rad, desired_angles_rad) - estimated_angles_rad
200    }
201
202    /// `desired_angles_rad` saturated to `max_angles_rad` (roll, pitch), NaN as level.
203    pub(crate) fn saturate_setpoint(max_angles_rad: Vec2, desired_angles_rad: Vec2) -> Vec2 {
204        Vec2::new(
205            saturate_symmetric(desired_angles_rad.x, max_angles_rad.x),
206            saturate_symmetric(desired_angles_rad.y, max_angles_rad.y),
207        )
208    }
209
210    /// Restarts `axis` with no derivative history, keeping its integral. The other axis is
211    /// untouched.
212    pub(crate) fn hand_back(&mut self, axis: usize) {
213        self.derivative[axis] = DerivativeState::default();
214    }
215
216    /// Zeroes the integral, keeping the derivative history.
217    pub(crate) fn clear_integral(&mut self) {
218        self.integrated_error = Vec2::zeros();
219    }
220
221    /// Rescales the integral for a change of integral gain from `old` to `new`, so the next
222    /// tick's I term picks up where the last left off (`rescale_integral`).
223    pub(crate) fn rescale_integral(
224        &mut self,
225        old: &AttitudeControllerConfig,
226        new: &AttitudeControllerConfig,
227    ) {
228        let (old, new) = (old.axis_gains(), new.axis_gains());
229        self.integrated_error = Vec2::from_fn(|axis, _| {
230            rescale_integral(self.integrated_error[axis], old[axis].i, new[axis].i)
231        });
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    fn gains(p: f32, i: f32, d: f32) -> AttitudeControllerConfig {
240        AttitudeControllerConfig {
241            roll_gains: Gains { p, i, d },
242            pitch_gains: Gains { p, i, d },
243            ..AttitudeControllerConfig::default()
244        }
245    }
246
247    #[test]
248    fn default_is_zeroed_state() {
249        let controller = AttitudeController::default();
250
251        assert_eq!(controller.integrated_error, Vec2::zeros());
252        assert_eq!(controller.derivative, [DerivativeState::default(); 2]);
253    }
254
255    /// A fresh controller has no previous error, so D alone gives nothing on the first tick.
256    #[test]
257    fn first_tick_has_no_derivative_kick() {
258        let mut controller = AttitudeController::default();
259        let rates = controller.control(
260            &gains(0.0, 0.0, 0.5),
261            0.1,
262            Vec2::new(0.3, -0.2),
263            Vec2::zeros(),
264        );
265        assert_eq!(rates, Vec2::zeros());
266    }
267
268    #[test]
269    fn validate_rejects_negative_or_non_finite_limits() {
270        let default = AttitudeControllerConfig::default();
271        let (angles, rates) = (default.max_angles_rad, default.max_rate_radps);
272        // (max_angles_rad, max_rate_radps, max_integral, offending field)
273        let cases = [
274            (Vec2::new(-1.0, angles.y), rates, 1.0, "max_angles_rad.x"),
275            (Vec2::new(angles.x, -1.0), rates, 1.0, "max_angles_rad.y"),
276            (angles, Vec2::new(-1.0, rates.y), 1.0, "max_rate_radps.x"),
277            (angles, Vec2::new(rates.x, -1.0), 1.0, "max_rate_radps.y"),
278            (angles, rates, -1.0, "max_integral"),
279        ];
280        assert!(default.validate().is_ok());
281        for (max_angles_rad, max_rate_radps, max_integral, field) in cases {
282            let config = AttitudeControllerConfig {
283                max_angles_rad,
284                max_rate_radps,
285                max_integral,
286                ..default
287            };
288            assert_eq!(config.validate().map_err(|e| e.field), Err(field));
289        }
290    }
291
292    /// An invalid limit fails `validate` but `control` stays panic-free: the limit acts as 0.
293    #[test]
294    fn invalid_limits_give_neutral_output_without_panicking() {
295        for bad in [-1.0, f32::NAN] {
296            let config = AttitudeControllerConfig {
297                max_angles_rad: Vec2::new(bad, bad),
298                max_rate_radps: Vec2::new(bad, bad),
299                max_integral: bad,
300                ..AttitudeControllerConfig::default()
301            };
302            let mut controller = AttitudeController::default();
303            let rates = controller.control(&config, 0.1, Vec2::new(1.0, -1.0), Vec2::new(0.2, 0.0));
304
305            assert_eq!(rates, Vec2::zeros(), "limit {bad}");
306            assert_eq!(controller.integrated_error, Vec2::zeros(), "limit {bad}");
307        }
308    }
309
310    #[test]
311    fn test_control_zero_error() {
312        let mut controller = AttitudeController::default();
313
314        let rates = controller.control(
315            &AttitudeControllerConfig::default(),
316            0.1,
317            Vec2::zeros(),
318            Vec2::zeros(),
319        );
320
321        assert_eq!(rates, Vec2::zeros()); // No error, no rate output
322        assert_eq!(controller.integrated_error, Vec2::zeros()); // No integral buildup
323    }
324
325    #[test]
326    fn test_control_proportional_response() {
327        let config = gains(2.0, 0.0, 0.0);
328        let mut controller = AttitudeController::default();
329        let dt = 0.1;
330        let desired_angles = Vec2::new(1.0, -1.0); // Beyond 45°: saturates to the max
331
332        let rates = controller.control(&config, dt, desired_angles, Vec2::zeros());
333
334        let expected_error = Vec2::new(FRAC_PI_4, -FRAC_PI_4); // 45° in radians
335        let expected_rates = Vec2::new(
336            config.roll_gains.p * expected_error.x,
337            config.pitch_gains.p * expected_error.y,
338        );
339        assert!((rates.x - expected_rates.x).abs() < 1e-6);
340        assert!((rates.y - expected_rates.y).abs() < 1e-6);
341        assert_eq!(controller.integrated_error, dt * expected_error);
342    }
343
344    #[test]
345    fn test_control_rate_clamping() {
346        let config = AttitudeControllerConfig {
347            max_rate_radps: Vec2::new(2.0, 2.0),
348            ..gains(100.0, 0.0, 0.0) // High P gain to exceed max_rate_radps
349        };
350
351        let rates =
352            AttitudeController::default().control(&config, 0.1, Vec2::new(1.0, 1.0), Vec2::zeros());
353
354        assert_eq!(rates, Vec2::new(2.0, 2.0)); // Clamped to max_rate_radps
355    }
356
357    /// A retune rescales each axis's integral by its own gain change: doubling roll's `i`
358    /// halves roll's integral and leaves pitch's alone.
359    #[test]
360    fn retune_rescales_each_axis_integral_by_its_own_gain() {
361        let old = gains(0.0, 1.0, 0.0);
362        let mut controller = AttitudeController::default();
363        controller.control(&old, 0.1, Vec2::new(0.5, 0.5), Vec2::zeros());
364        let integral = controller.integrated_error;
365
366        let new = AttitudeControllerConfig {
367            roll_gains: Gains {
368                i: 2.0,
369                ..old.roll_gains
370            },
371            ..old
372        };
373        controller.rescale_integral(&old, &new);
374
375        approx::assert_relative_eq!(controller.integrated_error.x, integral.x / 2.0);
376        assert_eq!(controller.integrated_error.y, integral.y);
377    }
378
379    /// Handing back one axis clears its derivative history and keeps its integral; the other
380    /// axis keeps both.
381    #[test]
382    fn hand_back_restarts_one_axis_only() {
383        let config = gains(1.0, 2.0, 0.5);
384        let mut controller = AttitudeController::default();
385        controller.control(&config, 0.1, Vec2::new(0.5, 0.5), Vec2::zeros());
386        let roll_integral = controller.integrated_error.x;
387        let pitch_integral = controller.integrated_error.y;
388        let pitch_derivative = controller.derivative[1];
389
390        controller.hand_back(0);
391
392        assert_eq!(controller.integrated_error.x, roll_integral);
393        assert_eq!(controller.derivative[0], DerivativeState::default());
394        assert_eq!(controller.integrated_error.y, pitch_integral);
395        assert_eq!(controller.derivative[1], pitch_derivative);
396    }
397
398    /// Roll uses `roll_gains` and pitch `pitch_gains`, for each PID term.
399    #[test]
400    fn each_axis_uses_its_own_gains() {
401        let pid = |p, i, d| Gains { p, i, d };
402        // (roll gains, pitch gains, expected first-tick rates for a 0.5 rad error on both axes
403        // over dt 0.1: P·e + I·e·dt, no derivative yet)
404        let cases = [
405            (pid(1.0, 0.0, 0.0), pid(3.0, 0.0, 0.0), Vec2::new(0.5, 1.5)),
406            (pid(0.0, 2.0, 0.0), pid(0.0, 4.0, 0.0), Vec2::new(0.1, 0.2)),
407        ];
408        for (roll_gains, pitch_gains, expected) in cases {
409            let config = AttitudeControllerConfig {
410                roll_gains,
411                pitch_gains,
412                max_rate_radps: Vec2::new(10.0, 10.0),
413                ..AttitudeControllerConfig::default()
414            };
415            let rates = AttitudeController::default().control(
416                &config,
417                0.1,
418                Vec2::new(0.5, 0.5),
419                Vec2::zeros(),
420            );
421            approx::assert_relative_eq!(rates, expected, epsilon = 1e-6);
422        }
423
424        // Derivative: second tick after the error drops by 0.1 rad on both axes.
425        let config = AttitudeControllerConfig {
426            roll_gains: pid(0.0, 0.0, 0.1),
427            pitch_gains: pid(0.0, 0.0, 0.3),
428            max_rate_radps: Vec2::new(10.0, 10.0),
429            ..AttitudeControllerConfig::default()
430        };
431        let mut controller = AttitudeController::default();
432        controller.control(&config, 0.1, Vec2::new(0.5, 0.5), Vec2::zeros());
433        let rates = controller.control(&config, 0.1, Vec2::new(0.5, 0.5), Vec2::new(0.1, 0.1));
434        approx::assert_relative_eq!(rates, Vec2::new(-0.1, -0.3), epsilon = 1e-5);
435    }
436
437    #[test]
438    fn test_control_integral_buildup() {
439        let config = gains(1.0, 1.0, 0.0);
440        let mut controller = AttitudeController::default();
441        let dt = 0.1;
442        let desired_angles = Vec2::new(0.5, 0.5);
443
444        controller.control(&config, dt, desired_angles, Vec2::zeros());
445        let rates2 = controller.control(&config, dt, desired_angles, Vec2::zeros());
446
447        let error = desired_angles;
448        let expected_integral = dt * 2.0 * error; // Two steps
449        assert_eq!(controller.integrated_error, expected_integral);
450        let expected_rates = 1.0 * error + 1.0 * expected_integral; // P + I terms
451        assert!((rates2.x - expected_rates.x).abs() < 1e-6);
452        assert!((rates2.y - expected_rates.y).abs() < 1e-6);
453    }
454
455    #[test]
456    fn test_control_integral_clamping() {
457        let config = AttitudeControllerConfig {
458            max_integral: 1.0,         // Low limit for testing
459            ..gains(0.0, 8000.0, 0.0)  // High I to hit max_integral
460        };
461        let mut controller = AttitudeController::default();
462        let dt = 2.0; // Large dt to quickly reach max_integral
463
464        let rates = controller.control(&config, dt, Vec2::new(1.0, 1.0), Vec2::zeros());
465
466        assert_eq!(controller.integrated_error, Vec2::new(1.0, 1.0)); // Clamped to max_integral
467        assert_eq!(rates, Vec2::new(2.0, 2.0));
468    }
469
470    /// A gain change between ticks applies on the next tick and keeps the integral; a shrunk
471    /// `max_integral` clamps the existing integral.
472    #[test]
473    fn config_change_between_ticks_keeps_state() {
474        let mut controller = AttitudeController::default();
475        controller.control(
476            &gains(0.0, 1.0, 0.0),
477            1.0,
478            Vec2::new(1.0, 0.0),
479            Vec2::zeros(),
480        );
481        let integral = controller.integrated_error;
482
483        let rates = controller.control(&gains(0.0, 2.0, 0.0), 0.1, Vec2::zeros(), Vec2::zeros());
484        assert_eq!(controller.integrated_error, integral);
485        approx::assert_relative_eq!(rates.x, 2.0 * integral.x);
486
487        let shrunk = AttitudeControllerConfig {
488            max_integral: 0.1,
489            ..gains(0.0, 1.0, 0.0)
490        };
491        controller.control(&shrunk, 0.1, Vec2::zeros(), Vec2::zeros());
492        assert_eq!(controller.integrated_error.x, 0.1);
493    }
494
495    #[test]
496    fn test_control_derivative_response() {
497        let config = gains(0.0, 0.0, 0.5);
498        let mut controller = AttitudeController::default();
499        let dt = 0.1;
500        let desired_angles = Vec2::new(1.0, 1.0); // saturates to 45°
501        let estimated_angles2 = Vec2::new(0.5 * FRAC_PI_4, 0.5 * FRAC_PI_4);
502
503        controller.control(&config, dt, desired_angles, Vec2::zeros());
504        let rates2 = controller.control(&config, dt, desired_angles, estimated_angles2);
505
506        let error1 = Vec2::new(FRAC_PI_4, FRAC_PI_4);
507        let error2 = error1 - estimated_angles2;
508        let derivative = (error2 - error1) / dt;
509        let expected_rates = Vec2::new(
510            config.roll_gains.d * derivative.x,
511            config.pitch_gains.d * derivative.y,
512        );
513        assert!((rates2.x - expected_rates.x).abs() < 1e-6);
514        assert!((rates2.y - expected_rates.y).abs() < 1e-6);
515    }
516
517    #[test]
518    #[should_panic(expected = "dt must be positive and finite")]
519    fn zero_dt_panics() {
520        AttitudeController::default().control(
521            &AttitudeControllerConfig::default(),
522            0.0,
523            Vec2::zeros(),
524            Vec2::zeros(),
525        );
526    }
527
528    #[test]
529    fn out_of_range_or_nan_desired_angles_saturate_instead_of_panicking() {
530        let config = AttitudeControllerConfig::default();
531        let max = FRAC_PI_4; // default max_angles_rad
532        // (requested angles in rad, equivalent in-range request)
533        let cases = [
534            (Vec2::new(2.0, 0.0), Vec2::new(max, 0.0)),
535            (Vec2::new(0.0, -4.6), Vec2::new(0.0, -max)),
536            (Vec2::new(-1.5, 3.0), Vec2::new(-max, max)),
537            (Vec2::new(f32::NAN, 0.5), Vec2::new(0.0, 0.5)),
538            (
539                Vec2::new(f32::INFINITY, f32::NEG_INFINITY),
540                Vec2::new(max, -max),
541            ),
542        ];
543        for (requested, equivalent) in cases {
544            let rates =
545                AttitudeController::default().control(&config, 0.1, requested, Vec2::zeros());
546            let expected =
547                AttitudeController::default().control(&config, 0.1, equivalent, Vec2::zeros());
548            assert!(
549                rates.x.is_finite() && rates.y.is_finite(),
550                "{requested:?} gave non-finite rates {rates:?}"
551            );
552            approx::assert_relative_eq!(rates.x, expected.x);
553            approx::assert_relative_eq!(rates.y, expected.y);
554        }
555    }
556
557    #[test]
558    fn nan_estimate_does_not_poison_later_ticks() {
559        let config = AttitudeControllerConfig::default();
560        let mut controller = AttitudeController::default();
561        let desired = Vec2::new(0.5, -0.5);
562
563        let during = controller.control(&config, 0.1, desired, Vec2::new(f32::NAN, 0.0));
564        assert!(during == Vec2::zeros(), "NaN estimate gave {during:?}");
565        assert!(controller.integrated_error == Vec2::zeros());
566
567        // First finite tick after the gap: P + I only (no derivative from the pre-gap error).
568        let after_nan = controller.control(&config, 0.1, desired, Vec2::zeros());
569        let error = desired;
570        let [roll, pitch] = config.axis_gains();
571        let expected = Vec2::new(
572            roll.p * error.x + roll.i * (0.1 * error.x),
573            pitch.p * error.y + pitch.i * (0.1 * error.y),
574        );
575        approx::assert_relative_eq!(after_nan.x, expected.x.clamp(-2.0, 2.0));
576        approx::assert_relative_eq!(after_nan.y, expected.y.clamp(-2.0, 2.0));
577    }
578}