stable-flight 0.3.0

no_std autopilot core for Stable Flight: copter, plane, tailsitter, and quadplane guidance and stabilizers, waypoint navigation, failsafe, autotune, mixers, and the per-tick flight loop
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
use core::f32::consts::PI;

use approx::assert_relative_eq;

use super::*;
use crate::Vec3;

#[test]
fn saturation_clamps_to_range_and_maps_nan_to_neutral() {
    // (input, saturate_unit, saturate_throttle)
    let cases = [
        (0.0, 0.0, 0.0),
        (0.4, 0.4, 0.4),
        (-0.4, -0.4, 0.0),
        (1.7, 1.0, 1.0),
        (-4.6, -1.0, 0.0),
        (f32::INFINITY, 1.0, 1.0),
        (f32::NEG_INFINITY, -1.0, 0.0),
        (f32::NAN, 0.0, 0.0),
    ];
    for (input, unit, throttle) in cases {
        assert!(saturate_unit(input) == unit, "saturate_unit({input})");
        assert!(
            saturate_throttle(input) == throttle,
            "saturate_throttle({input})"
        );
    }
}

#[test]
fn saturate_symmetric_bounds_value_and_maps_nan_to_neutral() {
    // (value, limit, expected); a negative or NaN limit acts as 0.
    let cases = [
        (0.3, 0.5, 0.3),
        (0.9, 0.5, 0.5),
        (-0.9, 0.5, -0.5),
        (f32::INFINITY, 0.5, 0.5),
        (f32::NEG_INFINITY, 0.5, -0.5),
        (f32::NAN, 0.5, 0.0),
        (0.3, -1.0, 0.0),
        (0.3, f32::NAN, 0.0),
    ];
    for (value, limit, expected) in cases {
        assert!(
            saturate_symmetric(value, limit) == expected,
            "saturate_symmetric({value}, {limit})"
        );
    }
}

#[test]
fn clamp_symmetric_bounds_value_and_never_panics_on_a_bad_limit() {
    // (value, limit, expected); a negative or NaN limit acts as 0.
    let cases = [
        (0.5, 1.0, 0.5),
        (3.0, 2.0, 2.0),
        (-4.0, 2.0, -2.0),
        (f32::INFINITY, 2.0, 2.0),
        (f32::NEG_INFINITY, 2.0, -2.0),
        (5.0, f32::INFINITY, 5.0),
        (5.0, 0.0, 0.0),
        (5.0, -1.0, 0.0),
        (5.0, f32::NAN, 0.0),
    ];
    for (value, limit, expected) in cases {
        assert!(
            clamp_symmetric(value, limit) == expected,
            "clamp_symmetric({value}, {limit})"
        );
    }
    assert!(clamp_symmetric(f32::NAN, 1.0).is_nan());

    let each = clamp_symmetric_each(Vec3::new(f32::NAN, 5.0, -5.0), 2.0);
    assert!(each.x.is_nan() && each.y == 2.0 && each.z == -2.0);
}

#[test]
fn euler_angles_match_nalgebra_and_are_nan_for_a_non_finite_attitude() {
    use nalgebra::{Quaternion, UnitQuaternion};

    // (roll, pitch, yaw): round-trips through nalgebra's constructor
    let cases = [
        (0.0, 0.0, 0.0),
        (0.3, -0.2, 1.1),
        (-1.2, 0.8, -2.9),
        (PI / 2.0, -1.4, PI - 0.01),
    ];
    for (roll, pitch, yaw) in cases {
        let attitude = UnitQuaternion::from_euler_angles(roll, pitch, yaw);
        let (r, p, y) = euler_angles(&attitude);
        assert_relative_eq!(r, roll, epsilon = 1e-5);
        assert_relative_eq!(p, pitch, epsilon = 1e-5);
        assert_relative_eq!(y, yaw, epsilon = 1e-5);
    }

    // (w, x, y, z) of a corrupted estimate
    let cases = [
        [f32::NAN, f32::NAN, f32::NAN, f32::NAN],
        [1.0, f32::NAN, 0.0, 0.0],
        [f32::INFINITY, 0.0, 0.0, 0.0],
    ];
    for [w, i, j, k] in cases {
        let attitude = UnitQuaternion::new_unchecked(Quaternion::new(w, i, j, k));
        let (r, p, y) = euler_angles(&attitude);
        assert!(
            r.is_nan() && p.is_nan() && y.is_nan(),
            "({w}, {i}, {j}, {k}) gave ({r}, {p}, {y})"
        );
    }
}

/// Float rounding pushes the `asin` argument just past ±1 near vertical; a valid attitude must
/// still give a finite pitch, not NaN (which the controllers would treat as "no estimate").
#[test]
fn euler_angles_pitch_stays_finite_at_vertical() {
    use nalgebra::{Quaternion, UnitQuaternion};

    // (roll, yaw) paired with pitches swept up to ±π/2
    let cases = [(0.0, 0.0), (0.3, 1.0), (-2.0, -2.5)];
    for (roll, yaw) in cases {
        for step in 0..2000 {
            for sign in [1.0, -1.0] {
                let pitch = sign * (PI / 2.0 - step as f32 * 1e-7);
                let attitude = UnitQuaternion::from_euler_angles(roll, pitch, yaw);
                let (_, p, _) = euler_angles(&attitude);
                assert!(
                    (p - pitch).abs() < 1e-3,
                    "pitch {pitch} (roll {roll}, yaw {yaw}) gave {p}"
                );
            }
        }
    }

    // Slightly non-unit, as a backend reporting unnormalized quaternions may send.
    let over_unit = UnitQuaternion::new_unchecked(Quaternion::new(0.7072, 0.0, 0.7072, 0.0));
    assert_relative_eq!(euler_angles(&over_unit).1, PI / 2.0);
}

#[test]
fn all_finite_rejects_any_nan_or_infinite_component() {
    // (input, all finite)
    let cases = [
        ([0.0, 1.0, -1.0], true),
        ([f32::NAN, 0.0, 0.0], false),
        ([0.0, f32::INFINITY, 0.0], false),
        ([0.0, 0.0, f32::NEG_INFINITY], false),
    ];
    for (input, expected) in cases {
        assert!(
            all_finite(&Vec3::from(input)) == expected,
            "all_finite({input:?})"
        );
    }
}

#[test]
fn neu_to_ned_flips_only_up() {
    assert_eq!(
        neu_to_ned(Vec3::new(1.0, -2.0, 3.0)),
        Vec3::new(1.0, -2.0, -3.0)
    );
}

#[test]
fn wrap_angle_maps_into_minus_pi_to_pi() {
    // (angle, wrapped)
    let cases = [
        (0.0, 0.0),
        (PI / 2.0, PI / 2.0),
        (-0.0, 0.0),
        // Half-open: +π maps to -π, and -π stays.
        (PI, -PI),
        (-PI, -PI),
        (3.0 * PI / 2.0, -PI / 2.0),
        (-3.0 * PI / 2.0, PI / 2.0),
        (4.0 * PI + 0.25, 0.25),
        // Negative inputs: `%` alone would leave these below -π.
        (-PI - 0.25, PI - 0.25),
        (-2.0 * PI, 0.0),
        (-4.0 * PI - 0.25, -0.25),
        (-7.0 * PI / 2.0, PI / 2.0),
    ];
    for (angle, wrapped) in cases {
        assert_relative_eq!(wrap_angle(angle), wrapped, epsilon = 1e-5);
    }
    assert!(wrap_angle(f32::NAN).is_nan());
    assert!(wrap_angle(f32::INFINITY).is_nan());
    assert!(wrap_angle(f32::NEG_INFINITY).is_nan());
}

/// Outputs shift together into [0, 1], keeping their differences: down from above 1, up from
/// below 0 by at most twice the collective (none at zero). Spreads over 1 scale about the
/// collective first.
#[test]
fn desaturate_keeps_moments_by_giving_up_collective() {
    // (input, collective, expected, (lowered, moments_lost))
    type Row = ([f32; 4], f32, [f32; 4], (bool, bool));
    let cases: [Row; 11] = [
        (
            [0.5, 0.5, 0.5, 0.5],
            0.5,
            [0.5, 0.5, 0.5, 0.5],
            (false, false),
        ),
        (
            [1.0, 0.2, 0.0, 0.7],
            0.5,
            [1.0, 0.2, 0.0, 0.7],
            (false, false),
        ), // already fits
        // Too high: down, collective gives way.
        (
            [1.15, 0.85, 1.15, 0.45],
            0.9,
            [1.0, 0.7, 1.0, 0.3],
            (true, false),
        ),
        // Too low: up, nothing lost.
        (
            [0.25, -0.15, 0.35, -0.05],
            0.1,
            [0.4, 0.0, 0.5, 0.1],
            (false, false),
        ),
        // Zero collective: clipped, moments lost.
        (
            [0.2, -0.2, 0.2, -0.2],
            0.0,
            [0.2, 0.0, 0.2, 0.0],
            (false, true),
        ),
        (
            [0.2, -0.2, 0.2, -0.2],
            -0.1,
            [0.2, 0.0, 0.2, 0.0],
            (false, true),
        ), // below zero
        // Near idle the raise is capped at 2 × collective: up 0.02, not the 0.03 needed.
        (
            [0.07, -0.03, 0.07, -0.03],
            0.01,
            [0.09, 0.0, 0.09, 0.0],
            (false, true),
        ),
        // Spread 2 about 0.5: shares halve, fitting exactly.
        (
            [1.5, -0.5, 0.5, 0.5],
            0.5,
            [1.0, 0.0, 0.5, 0.5],
            (false, true),
        ),
        // Spread 2 about 0.8: halved to [1.2, 0.2], then down 0.2.
        (
            [1.6, -0.4, 0.8, 0.8],
            0.8,
            [1.0, 0.0, 0.6, 0.6],
            (true, true),
        ),
        // Spread 1.25 about 0.1: scaled by 0.8 to [0.9, -0.1], then up 0.1.
        (
            [1.1, -0.15, 0.1, 0.1],
            0.1,
            [1.0, 0.0, 0.2, 0.2],
            (false, true),
        ),
        // Spread 2 at zero collective: halved to [0.5, -0.5], not raised, clipped.
        (
            [1.0, -1.0, 0.0, 0.0],
            0.0,
            [0.5, 0.0, 0.0, 0.0],
            (false, true),
        ),
    ];
    for (input, collective, expected, (lowered, moments_lost)) in cases {
        let mut outputs = input;
        let desaturation = desaturate(&mut outputs, collective);
        for (o, e) in outputs.iter().zip(expected) {
            assert_relative_eq!(*o, e, epsilon = 1e-6);
        }
        assert!(
            desaturation
                == Desaturation {
                    lowered,
                    moments_lost
                },
            "{input:?} at {collective}: {desaturation:?}"
        );
    }
}

/// Long vectors shrink to `max` along their direction; short ones pass; non-finite ones have
/// no direction and become zero.
#[test]
fn cap_magnitude_keeps_direction_and_neutralizes_non_finite() {
    let nan = f32::NAN;
    let inf = f32::INFINITY;
    // (input, max, expected)
    let cases = [
        (Vec2::new(0.3, -0.4), 1.0, Vec2::new(0.3, -0.4)),
        (Vec2::new(3.0, 4.0), 1.0, Vec2::new(0.6, 0.8)),
        (Vec2::new(-30.0, 40.0), 0.5, Vec2::new(-0.3, 0.4)),
        (Vec2::new(nan, 1.0), 1.0, Vec2::zeros()),
        (Vec2::new(inf, 0.0), 1.0, Vec2::zeros()),
        (Vec2::new(-inf, inf), 0.6, Vec2::zeros()),
    ];
    for (input, max, expected) in cases {
        let capped = cap_magnitude(input, max);
        assert_relative_eq!(capped.x, expected.x, epsilon = 1e-6);
        assert_relative_eq!(capped.y, expected.y, epsilon = 1e-6);
    }
}

#[test]
fn assert_dt_accepts_only_positive_finite_steps() {
    // (dt, ok)
    let cases = [
        (0.004, true),
        (1.0, true),
        (0.0, false),
        (-0.01, false),
        (f32::NAN, false),
        (f32::INFINITY, false),
    ];
    for (dt, ok) in cases {
        assert_eq!(
            std::panic::catch_unwind(|| assert_dt(dt)).is_ok(),
            ok,
            "{dt}"
        );
    }
}

/// `tilt_boost` is `1 / cos(tilt)` from the rotation matrix's `(2, 2)` entry, at most 2× past
/// 60°, fading linearly to 0 as the cosine falls from 0.1 to 0 (about 84°–90°) and 0 when
/// inverted; a non-finite attitude counts as level.
#[test]
fn tilt_boost_compensates_tilt_and_cuts_out_inverted() {
    let euler = |roll: f32, pitch: f32, yaw: f32| {
        UnitQuaternion::from_euler_angles(
            f32::to_radians(roll),
            f32::to_radians(pitch),
            f32::to_radians(yaw),
        )
    };
    // Below 60°: exactly 1 / cos(tilt).
    for (roll, pitch, yaw) in [
        (0.0, 0.0, 0.0),
        (30.0, 0.0, 1.0),
        (0.0, -30.0, -2.0),
        (20.0, 20.0, 0.5),
        (-45.0, 10.0, 3.0),
    ] {
        let attitude = euler(roll, pitch, yaw);
        let expected = 1.0 / attitude.to_rotation_matrix()[(2, 2)];
        assert_relative_eq!(tilt_boost(&attitude), expected, epsilon = 1e-5);
    }
    let roll_for_cosine = |cosine: f32| euler(cosine.acos().to_degrees(), 0.0, 0.0);
    let nan = UnitQuaternion::new_unchecked(nalgebra::Quaternion::new(f32::NAN, 0.0, 0.0, 0.0));
    // (attitude, expected boost)
    let cases = [
        (euler(70.0, 0.0, 0.0), 2.0),  // floored
        (roll_for_cosine(0.1), 2.0),   // start of the fade: no jump
        (roll_for_cosine(0.05), 1.0),  // halfway
        (euler(90.0, 0.0, 0.0), 0.0),  // on its side
        (euler(120.0, 0.0, 0.0), 0.0), // past it
        (euler(180.0, 0.0, 0.0), 0.0), // upside down
        (
            euler(0.0, 89.0, 0.0),
            2.0 * (89.0_f32.to_radians().cos() / 0.1),
        ),
        (nan, 1.0),
    ];
    for (attitude, expected) in cases {
        assert_relative_eq!(tilt_boost(&attitude), expected, epsilon = 1e-4);
    }
}

/// `nose_up_cosine` is the sine of the pitch, whatever the roll and heading, and stays defined
/// nose up (pitch 90°), where the Euler angles are degenerate.
#[test]
fn nose_up_cosine_is_the_sine_of_the_pitch() {
    // (roll°, pitch°, heading°, expected)
    let cases = [
        (0.0, 0.0, 0.0, 0.0),
        (0.0, 90.0, 0.0, 1.0),
        (0.0, -90.0, 0.0, -1.0),
        (0.0, 45.0, 120.0, core::f32::consts::FRAC_1_SQRT_2),
        (30.0, 30.0, -60.0, 0.5),
        (170.0, 90.0, 33.0, 1.0), // nose up, any roll/heading split
        (180.0, 0.0, 0.0, 0.0),   // inverted, level nose
    ];
    for (roll, pitch, heading, expected) in cases {
        let attitude = UnitQuaternion::from_euler_angles(
            f32::to_radians(roll),
            f32::to_radians(pitch),
            f32::to_radians(heading),
        );
        assert_relative_eq!(nose_up_cosine(&attitude), expected, epsilon = 1e-5);
    }
    let nan = UnitQuaternion::new_unchecked(nalgebra::Quaternion::new(f32::NAN, 0.0, 0.0, 0.0));
    assert!(nose_up_cosine(&nan).is_nan());
}

/// The attitude error is the tilt (at the current heading) and the wrapped heading error
/// weighted by the tilt's cosine, as body-frame rotations: per-axis Euler differences near
/// level, zero when the setpoint is the current attitude, a heading error that never leaks into
/// roll or pitch, and clean pitch errors far over.
#[test]
fn attitude_error_is_tilt_then_heading_in_body_axes() {
    let deg = f32::to_radians;
    let at = |roll: f32, pitch: f32, heading: f32| {
        UnitQuaternion::from_euler_angles(deg(roll), deg(pitch), deg(heading))
    };
    // (current, setpoint roll°, pitch°, heading°, expected (x, y, z)°, tolerance°)
    let cases = [
        (at(0.0, 0.0, 0.0), 0.0, 0.0, 0.0, [0.0, 0.0, 0.0], 1e-4),
        (at(0.0, 0.0, 0.0), 10.0, 0.0, 0.0, [10.0, 0.0, 0.0], 1e-3),
        (at(0.0, 0.0, 0.0), 0.0, -8.0, 0.0, [0.0, -8.0, 0.0], 1e-3),
        (at(0.0, 0.0, 0.0), 0.0, 0.0, 30.0, [0.0, 0.0, 30.0], 1e-3),
        // The heading error fades with tilt: cos 60° halves it, and far over it's nearly gone.
        (at(0.0, 60.0, 0.0), 0.0, 60.0, 10.0, [0.0, 0.0, 5.0], 1e-3),
        (
            at(0.0, -80.0, 30.0),
            0.0,
            -80.0,
            40.0,
            [0.0, 0.0, 1.736],
            1e-2,
        ),
        // Tilt is relative to the current heading, whatever the heading setpoint.
        (at(0.0, 0.0, 120.0), 0.0, 6.0, 120.0, [0.0, 6.0, 0.0], 1e-3),
        (
            at(0.0, 0.0, 120.0),
            6.0,
            0.0,
            -50.0,
            [6.0, 0.0, -170.0],
            1e-3,
        ),
        // Near level: the Euler differences, as body rates.
        (at(3.0, -2.0, 45.0), 5.0, 1.0, 50.0, [2.0, 3.0, 5.0], 0.2),
        // Holding a two-axis tilt (current Euler angles as the setpoint): no error at all.
        (
            at(20.0, 20.0, 70.0),
            20.0,
            20.0,
            70.0,
            [0.0, 0.0, 0.0],
            1e-3,
        ),
        (
            at(-15.0, 30.0, -100.0),
            -15.0,
            30.0,
            -100.0,
            [0.0, 0.0, 0.0],
            1e-3,
        ),
        // Exactly upside down from the setpoint: roll back over (not a zero error).
        (at(180.0, 0.0, 0.0), 0.0, 0.0, 0.0, [180.0, 0.0, 0.0], 1e-3),
        // Upside down: no heading correction.
        (at(180.0, 0.0, 0.0), 180.0, 0.0, 20.0, [0.0, 0.0, 0.0], 1e-3),
        // Heading wraps the short way.
        (at(0.0, 0.0, 178.0), 0.0, 0.0, -178.0, [0.0, 0.0, 4.0], 1e-3),
        // Far over, where Euler roll and heading degenerate: still a clean pitch error.
        (
            at(0.0, -80.0, 30.0),
            0.0,
            -85.0,
            30.0,
            [0.0, -5.0, 0.0],
            1e-2,
        ),
        (at(0.0, 89.0, 0.0), 0.0, 80.0, 0.0, [0.0, -9.0, 0.0], 1e-2),
    ];
    for (current, roll, pitch, heading, expected, tolerance) in cases {
        let error = attitude_error(&current, deg(roll), deg(pitch), deg(heading));
        for axis in 0..3 {
            assert!(
                (error[axis].to_degrees() - expected[axis]).abs() <= tolerance,
                "{roll}/{pitch}/{heading}: axis {axis} gave {}°, expected {}°",
                error[axis].to_degrees(),
                expected[axis]
            );
        }
    }

    let nan = UnitQuaternion::new_unchecked(nalgebra::Quaternion::new(1.0, f32::NAN, 0.0, 0.0));
    assert!(
        attitude_error(&nan, 0.0, 0.0, 0.0)
            .iter()
            .all(|e| e.is_nan())
    );
    let error = attitude_error(&at(0.0, 0.0, 0.0), deg(5.0), 0.0, f32::NAN);
    assert!(error.x > 0.0 && error.y == 0.0 && error.z.is_nan());
}

/// `bank_rad` is the roll about the nose, through inverted, at any heading and moderate pitch.
#[test]
fn bank_is_roll_about_the_nose() {
    // (roll°, pitch°, heading°, expected°)
    let cases = [
        (0.0, 0.0, 0.0, 0.0),
        (30.0, 0.0, 70.0, 30.0),
        (-45.0, 20.0, -120.0, -45.0),
        (120.0, 10.0, 0.0, 120.0),
        (180.0, 0.0, 0.0, 180.0),
    ];
    for (roll, pitch, heading, expected) in cases {
        let attitude = UnitQuaternion::from_euler_angles(
            f32::to_radians(roll),
            f32::to_radians(pitch),
            f32::to_radians(heading),
        );
        let bank = bank_rad(&attitude).to_degrees();
        assert!(
            crate::wrap_angle((bank - expected).to_radians()).abs() < 1e-3,
            "{roll}/{pitch}/{heading}: {bank}"
        );
    }
    let nan = UnitQuaternion::new_unchecked(nalgebra::Quaternion::new(f32::NAN, 0.0, 0.0, 0.0));
    assert!(bank_rad(&nan).is_nan());
}

#[test]
fn guard_sink_adds_thrust_past_the_sink_limit() {
    // (thrust, climb m/s, limit m/s, gain, expected)
    let cases = [
        (0.5, 2.0, 1.0, 0.4, None),            // climbing
        (0.5, -1.0, 1.0, 0.4, None),           // at the limit
        (0.5, -2.0, 1.0, 0.4, Some(0.9)),      // 1 m/s past it
        (0.5, -5.0, 1.0, 0.4, Some(1.0)),      // saturated
        (0.5, -2.0, 1.0, 0.0, Some(0.5)),      // acting, adding nothing
        (0.5, -3.0, 0.0, 0.4, None),           // disabled
        (0.5, f32::NAN, 1.0, 0.4, None),       // unknown climb
        (f32::NAN, -2.0, 1.0, 0.4, Some(0.0)), // NaN thrust saturates to 0
    ];
    for (thrust, climb_mps, limit_mps, gain, expected) in cases {
        let guarded = guard_sink(thrust, climb_mps, limit_mps, gain);
        match (guarded, expected) {
            (Some(guarded), Some(expected)) => {
                assert_relative_eq!(guarded, expected, epsilon = 1e-6)
            }
            _ => assert!(
                guarded == expected,
                "{thrust}, {climb_mps}, {limit_mps}, {gain}"
            ),
        }
    }
}

#[test]
fn shaped_closing_speed_brakes_to_zero_at_the_target() {
    // p 1.5, accel 1: the linear part ends at 1 / 2.25 = 0.444 m, at 0.667 m/s.
    // (distance m, p, accel m/s², expected m/s)
    let cases = [
        (0.0, 1.5, 1.0, 0.0),
        (-1.0, 1.5, 1.0, 0.0),
        (f32::NAN, 1.5, 1.0, 0.0),
        (0.2, 1.5, 1.0, 0.3),                                  // linear
        (1.0 / 2.25, 1.5, 1.0, 1.0 / 1.5),                     // the joint
        (2.0, 1.5, 1.0, libm::sqrtf(2.0 * (2.0 - 1.0 / 4.5))), // square root
        (10.0, 1.5, 1.0, libm::sqrtf(2.0 * (10.0 - 1.0 / 4.5))),
        (10.0, 1.5, 0.0, 15.0), // no deceleration limit: linear
        (10.0, 1.5, f32::NAN, 15.0),
        (2.0, 0.0, 1.0, 2.0), // no P: square root alone
        (2.0, 0.0, -1.0, 0.0),
    ];
    for (distance_m, p, accel, expected) in cases {
        assert_relative_eq!(
            shaped_closing_speed(distance_m, p, accel),
            expected,
            epsilon = 1e-5
        );
    }
}

/// The speed is continuous where the linear part meets the square root.
#[test]
fn shaped_closing_speed_is_continuous_at_the_joint() {
    let joint_m = 1.0 / 2.25;
    let below = shaped_closing_speed(joint_m - 1e-4, 1.5, 1.0);
    let above = shaped_closing_speed(joint_m + 1e-4, 1.5, 1.0);
    assert!((above - below).abs() < 1e-3, "{below} → {above}");
}

/// The twist reads the turn about its axis, ignores turns about axes square to it, and a
/// quaternion's negation reads 2π away, which `wrap_angle` folds back:
/// (case, rotation, axis, twist in rad).
#[test]
fn twist_reads_the_turn_about_an_axis() {
    let about = |axis: Vec3, angle: f32| UnitQuaternion::from_scaled_axis(axis * angle);
    let cases = [
        (
            "a quarter roll",
            about(Vec3::x(), PI / 2.0),
            Vec3::x(),
            PI / 2.0,
        ),
        ("a back roll", about(Vec3::x(), -2.0), Vec3::x(), -2.0),
        (
            "three quarters",
            about(Vec3::y(), 1.5 * PI),
            Vec3::y(),
            -PI / 2.0,
        ),
        (
            "a pitch, read about roll",
            about(Vec3::y(), 1.0),
            Vec3::x(),
            0.0,
        ),
        (
            "a roll after a pitch",
            about(Vec3::y(), 0.3) * about(Vec3::x(), 0.8),
            Vec3::x(),
            0.8,
        ),
    ];
    for (case, rotation, axis, expected) in cases {
        let twist = twist_angle_rad(&rotation, &axis);
        assert_relative_eq!(wrap_angle(twist - expected), 0.0, epsilon = 0.06);
        let negated = UnitQuaternion::new_unchecked(-rotation.into_inner());
        let twist_negated = twist_angle_rad(&negated, &axis);
        assert!(
            wrap_angle(twist_negated - twist).abs() < 1e-5,
            "{case}: the negation reads the same turn"
        );
    }
    let nan = UnitQuaternion::new_unchecked(nalgebra::Quaternion::new(f32::NAN, 0.0, 0.0, 0.0));
    assert!(twist_angle_rad(&nan, &Vec3::x()).is_nan());
}