Skip to main content

stable_flight/commanders/
maneuver.rs

1//! Scripted maneuvers: a [`Maneuver`] is a short list of [`Segment`]s, each a body rate about
2//! one axis held until an angle has turned or a time has passed, or a pause, and a
3//! [`ManeuverRunner`] flies one from the attitude it starts at, then levels the wings and hands
4//! back.
5//!
6//! | Maneuver | Segments |
7//! |---|---|
8//! | [`Maneuver::roll`] | Roll 360° at a set rate (negative: left), holding its line |
9//! | [`Maneuver::loop_`] | Pitch 360° at `V / R`: a loop of radius `R` at speed `V` (negative: outside), holding its circle |
10//! | [`Maneuver::doublet`] | `+rate` then `−rate` about one axis, a half width each, then a [`DOUBLET_PAUSE_S`] pause, on rates alone: a step response in flight |
11//! | [`Maneuver::pause`] | Zero body rate at cruise thrust for a time, on rates alone: centered rate sticks |
12//!
13//! A new maneuver is a new list of segments, up to [`MAX_SEGMENTS`]: an Immelmann is half a
14//! loop then half a roll, a split-S the reverse, a hammerhead's pivot a yaw. [`Segment`] is
15//! non-exhaustive, so segments that hold an attitude (Aresti lines, point-roll hesitations) can
16//! join it.
17//!
18//! The rates go out as [`ControlInput::AbsoluteRate`], each segment's rate plus the pitch and
19//! yaw rate that steer it back onto its [`Path`] ([`PathConfig`]), each segment at its
20//! [`Thrust`]: rolls and loops at [`ManeuverConfig::thrust`], doublets and pauses at
21//! [`ManeuverConfig::cruise_thrust`], so a doublet measures the rate loop as it flies in
22//! cruise (on a tailsitter the propwash over the elevons grows its authority with thrust). The
23//! recovery is a level [`ControlInput::AbsoluteAttitude`] until the wings stay level and the
24//! body rates small ([`RecoveryConfig`]). The shapes are ArduPilot's scripted aerobatics
25//! (`libraries/AP_Scripting/applets/Aerobatics/FixedWing/plane_aerobatics.lua` at `3d24375`):
26//! its loop is a vertical arc of a given radius (`loop`), its roll whole turns along a
27//! straight (`straight_roll`), and both hold their path the way [`Path`] does. Unlike
28//! ArduPilot, each segment ends on the angle the attitude has turned rather than on a time
29//! along the path, and holds a fixed thrust where ArduPilot holds the speed by throttle
30//! (`speed_controller`, `AEROM_THR_PIT_FF`; on the sim, neither less thrust down a loop nor a
31//! speed hold improved on the path hold, #481).
32//!
33//! The angle a segment has turned is read from the attitude, not Euler angles (which clamp at
34//! ±90° in a loop): the twist about the segment's axis of the rotation since it began,
35//! unwrapped tick to tick. A segment that can't read it (a non-finite attitude) ends at a
36//! timeout instead, so nothing stalls a maneuver.
37
38use nalgebra::UnitQuaternion;
39
40use crate::controllers::{InvalidConfig, check, check_positive, check_unit_interval};
41use crate::math::{DEG, assert_dt, euler_angles, twist_angle_rad, wrap_angle};
42use crate::{AbsoluteAttitudeCommand, AbsoluteRateCommand, ControlInput, VehicleState};
43
44mod path;
45mod segment;
46#[cfg(test)]
47mod tests;
48
49use path::PathHold;
50pub use path::{Path, PathConfig};
51pub use segment::{
52    Axis, DEFAULT_DOUBLET_HALF_S, DOUBLET_PAUSE_S, MAX_SEGMENTS, Maneuver, ManeuverError, RateLaw,
53    Segment, SegmentEnd, Thrust,
54};
55use segment::{UNUSED, positive};
56
57/// How a [`ManeuverRunner`] levels the wings after a maneuver.
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct RecoveryConfig {
60    /// The pitch held level, in rad.
61    pub pitch_rad: f32,
62    /// Thrust while recovering, `[0, 1]`.
63    pub thrust: f32,
64    /// Bank, and pitch off [`pitch_rad`](Self::pitch_rad), within which the wings count as
65    /// level, in rad.
66    pub level_band_rad: f32,
67    /// Body rate (magnitude) under which the wings count as settled, in rad/s.
68    pub max_body_rate_radps: f32,
69    /// How long the wings stay level and settled before the recovery ends, in s.
70    pub settle_s: f32,
71    /// Longest recovery, in s: past it the route takes over, level or not.
72    pub timeout_s: f32,
73}
74
75impl Default for RecoveryConfig {
76    /// Level within 10° and 20°/s for 0.5 s, at full thrust, given up after 10 s: placeholders
77    /// until an airframe is tuned.
78    fn default() -> Self {
79        RecoveryConfig {
80            pitch_rad: 0.0,
81            thrust: 1.0,
82            level_band_rad: 10.0 * DEG,
83            max_body_rate_radps: 20.0 * DEG,
84            settle_s: 0.5,
85            timeout_s: 10.0,
86        }
87    }
88}
89
90/// [`ManeuverRunner`] settings.
91#[derive(Clone, Copy, Debug, PartialEq)]
92pub struct ManeuverConfig {
93    /// Thrust through [`Thrust::Maneuver`] segments (rolls, loops), `[0, 1]`.
94    pub thrust: f32,
95    /// Thrust through [`Thrust::Cruise`] segments (doublets and their pause), `[0, 1]`: the airframe's
96    /// level-flight thrust.
97    pub cruise_thrust: f32,
98    /// An [`Angle`](SegmentEnd::Angle) segment ends after this many times the time its angle
99    /// takes at the rate it began with (at least 1): a turn the vehicle can't fly, or can't
100    /// measure, ends anyway.
101    pub timeout_factor: f32,
102    /// How hard each segment steers back onto its [`Path`].
103    pub path: PathConfig,
104    /// The recovery after the last segment.
105    pub recovery: RecoveryConfig,
106}
107
108impl Default for ManeuverConfig {
109    /// Full thrust for aerobatics (a loop climbs on it, and on a tailsitter a roll needs the
110    /// propwash's authority), [`PlaneGuidanceConfig`](crate::guidance::plane::PlaneGuidanceConfig)'s
111    /// default cruise thrust (0.5), a timeout at twice a segment's time, and the default path
112    /// hold and recovery.
113    fn default() -> Self {
114        ManeuverConfig {
115            thrust: 1.0,
116            cruise_thrust: 0.5,
117            timeout_factor: 2.0,
118            path: PathConfig::default(),
119            recovery: RecoveryConfig::default(),
120        }
121    }
122}
123
124impl ManeuverConfig {
125    /// `Ok` when the thrusts are in `[0, 1]`, the timeout factor at least 1, the path hold
126    /// valid ([`PathConfig::validate`]), the level pitch in `[-π/2, π/2]`, and the band, rate,
127    /// settle, and timeout positive and finite.
128    ///
129    /// # Errors
130    ///
131    /// [`InvalidConfig`] naming the first field out of range.
132    pub fn validate(&self) -> Result<(), InvalidConfig> {
133        check_unit_interval("thrust", self.thrust)?;
134        check_unit_interval("cruise_thrust", self.cruise_thrust)?;
135        check(
136            "timeout_factor",
137            self.timeout_factor >= 1.0 && self.timeout_factor.is_finite(),
138            "at least 1 and finite",
139        )?;
140        self.path
141            .validate()
142            .map_err(|e: InvalidConfig| e.in_section("path"))?;
143        let recovery = &self.recovery;
144        let section = |e: InvalidConfig| e.in_section("recovery");
145        check(
146            "pitch_rad",
147            (-core::f32::consts::FRAC_PI_2..=core::f32::consts::FRAC_PI_2)
148                .contains(&recovery.pitch_rad),
149            "in [-π/2, π/2]",
150        )
151        .map_err(section)?;
152        check_unit_interval("thrust", recovery.thrust).map_err(section)?;
153        check_positive("level_band_rad", recovery.level_band_rad).map_err(section)?;
154        check_positive("max_body_rate_radps", recovery.max_body_rate_radps).map_err(section)?;
155        check_positive("settle_s", recovery.settle_s).map_err(section)?;
156        check_positive("timeout_s", recovery.timeout_s).map_err(section)
157    }
158}
159
160/// Where a [`ManeuverRunner`] is.
161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
162pub enum ManeuverPhase {
163    /// Nothing started.
164    Idle,
165    /// Flying segment `segment`.
166    Rotation {
167        /// The segment's index.
168        segment: usize,
169    },
170    /// Leveling the wings.
171    Recovery,
172    /// Finished: the caller flies on.
173    Done,
174}
175
176/// Progress through the segment being flown.
177#[derive(Clone, Copy, Debug)]
178struct SegmentProgress {
179    /// The inverse of the attitude it began at.
180    start_inverse: UnitQuaternion<f32>,
181    /// The last finite twist read since then, in rad.
182    last_twist_rad: f32,
183    /// The angle turned, unwrapped, in rad.
184    turned_rad: f32,
185    /// Time flown, in s.
186    elapsed_s: f32,
187    /// When it ends regardless of the attitude, in s: a duration, or an angle's timeout.
188    limit_s: f32,
189    /// The path it holds, laid out where it began.
190    path: PathHold,
191}
192
193impl SegmentProgress {
194    /// `segment` beginning at `state`.
195    fn new(segment: &Segment, state: &VehicleState, timeout_factor: f32) -> Self {
196        let limit_s = match *segment {
197            Segment::Pause { duration_s, .. } => duration_s,
198            Segment::Rotate {
199                end: SegmentEnd::Duration { s },
200                ..
201            } => s,
202            Segment::Rotate {
203                rate,
204                end: SegmentEnd::Angle { rad },
205                ..
206            } => {
207                let radps = rate.radps(state).abs();
208                // No rate to fly it at (no speed for a radius): end at once.
209                if positive(radps) {
210                    rad / radps * timeout_factor
211                } else {
212                    0.0
213                }
214            }
215        };
216        SegmentProgress {
217            start_inverse: state.attitude.inverse(),
218            last_twist_rad: 0.0,
219            turned_rad: 0.0,
220            elapsed_s: 0.0,
221            limit_s,
222            path: PathHold::new(segment, state),
223        }
224    }
225
226    /// Whether `segment` has ended at `state`; reads the turn for an angle.
227    fn ended(&mut self, segment: &Segment, state: &VehicleState) -> bool {
228        if self.elapsed_s >= self.limit_s {
229            return true;
230        }
231        let Segment::Rotate {
232            axis,
233            rate,
234            end: SegmentEnd::Angle { rad },
235            ..
236        } = *segment
237        else {
238            return false;
239        };
240        let rotation = self.start_inverse * state.attitude;
241        let twist_rad = twist_angle_rad(&rotation, &axis.unit());
242        // Each tick turns far less than half a turn, so the wrapped step is the turn since
243        // the last reading. A non-finite one is skipped: the timeout ends the segment.
244        let step_rad = wrap_angle(twist_rad - self.last_twist_rad);
245        if step_rad.is_finite() {
246            self.turned_rad += step_rad;
247            self.last_twist_rad = twist_rad;
248        }
249        self.turned_rad * rate.direction() >= rad
250    }
251}
252
253/// Leveling after the last segment.
254#[derive(Clone, Copy, Debug, Default)]
255struct Recovery {
256    /// Time recovering, in s.
257    elapsed_s: f32,
258    /// Time continuously level and settled, in s.
259    level_s: f32,
260}
261
262impl Recovery {
263    /// This tick's level attitude command, or `None` once level and settled for
264    /// [`settle_s`](RecoveryConfig::settle_s) or past the timeout.
265    fn next(
266        &mut self,
267        config: &RecoveryConfig,
268        dt: f32,
269        state: &VehicleState,
270    ) -> Option<ControlInput> {
271        let (roll_rad, pitch_rad, _) = euler_angles(&state.attitude);
272        // `<=` is false for NaN: an unknown attitude or rate isn't level.
273        let level = roll_rad.abs() <= config.level_band_rad
274            && (pitch_rad - config.pitch_rad).abs() <= config.level_band_rad
275            && state.angular_velocity_radps.norm() <= config.max_body_rate_radps;
276        self.level_s = if level { self.level_s + dt } else { 0.0 };
277        if self.level_s >= config.settle_s || self.elapsed_s >= config.timeout_s {
278            return None;
279        }
280        self.elapsed_s += dt;
281        Some(ControlInput::AbsoluteAttitude(AbsoluteAttitudeCommand {
282            roll_rad: 0.0,
283            pitch_rad: config.pitch_rad,
284            heading_rad: f32::NAN,
285            thrust: config.thrust,
286        }))
287    }
288}
289
290/// Flies a [`Maneuver`]: its segments in order from the attitude it starts at, then a recovery
291/// to level ([`RecoveryConfig`]), then nothing, so the caller (a script, a route) flies on.
292/// The caller decides where it starts: level, at the speed and height the maneuver needs.
293///
294/// # Examples
295///
296/// ```
297/// use stable_flight::commanders::maneuver::{Maneuver, ManeuverPhase, ManeuverRunner};
298/// use stable_flight::{ControlInput, VehicleState};
299///
300/// let mut runner = ManeuverRunner::default();
301/// let level = VehicleState::default();
302/// runner.start(Maneuver::roll(1.5).expect("a nonzero rate"), &level);
303/// let Some(ControlInput::AbsoluteRate(rates)) = runner.next(0.004, &level) else {
304///     unreachable!("a roll begins with a roll rate");
305/// };
306/// assert_eq!(rates.roll_radps, 1.5);
307/// assert_eq!(runner.phase(), ManeuverPhase::Rotation { segment: 0 });
308/// ```
309#[derive(Clone, Debug)]
310pub struct ManeuverRunner {
311    config: ManeuverConfig,
312    maneuver: Option<Maneuver>,
313    phase: ManeuverPhase,
314    progress: SegmentProgress,
315    recovery: Recovery,
316}
317
318impl Default for ManeuverRunner {
319    /// A runner with [`ManeuverConfig::default`].
320    fn default() -> Self {
321        ManeuverRunner::new(ManeuverConfig::default())
322    }
323}
324
325impl ManeuverRunner {
326    /// An idle runner with `config`.
327    ///
328    /// # Panics
329    ///
330    /// If `config` is invalid ([`ManeuverConfig::validate`]).
331    pub fn new(config: ManeuverConfig) -> Self {
332        if let Err(error) = config.validate() {
333            panic!("invalid ManeuverConfig: {error}");
334        }
335        ManeuverRunner {
336            config,
337            maneuver: None,
338            phase: ManeuverPhase::Idle,
339            progress: SegmentProgress::new(&UNUSED, &VehicleState::default(), 1.0),
340            recovery: Recovery::default(),
341        }
342    }
343
344    /// The settings.
345    pub fn config(&self) -> &ManeuverConfig {
346        &self.config
347    }
348
349    /// Starts `maneuver` at `state`, replacing any in progress.
350    pub fn start(&mut self, maneuver: Maneuver, state: &VehicleState) {
351        self.maneuver = Some(maneuver);
352        self.begin(0, state);
353    }
354
355    /// Cuts a maneuver's segments short and recovers; a recovery or a finished maneuver is
356    /// left alone.
357    pub fn abort(&mut self) {
358        if matches!(self.phase, ManeuverPhase::Rotation { .. }) {
359            self.recover();
360        }
361    }
362
363    /// Where the runner is.
364    pub fn phase(&self) -> ManeuverPhase {
365        self.phase
366    }
367
368    /// True while a maneuver is flying or recovering.
369    pub fn is_active(&self) -> bool {
370        matches!(
371            self.phase,
372            ManeuverPhase::Rotation { .. } | ManeuverPhase::Recovery
373        )
374    }
375
376    /// This tick's command: a segment's body rate or the recovery's level attitude, or `None`
377    /// once done (or idle). A segment that ends this tick hands over to the next phase in the
378    /// same tick.
379    ///
380    /// # Panics
381    ///
382    /// If `dt` is not positive and finite.
383    pub fn next(&mut self, dt: f32, state: &VehicleState) -> Option<ControlInput> {
384        assert_dt(dt);
385        loop {
386            match self.phase {
387                ManeuverPhase::Idle | ManeuverPhase::Done => return None,
388                ManeuverPhase::Rotation { segment: index } => {
389                    let segment = self.segment(index)?;
390                    if self.progress.ended(&segment, state) {
391                        self.begin(index + 1, state);
392                        continue;
393                    }
394                    self.progress.elapsed_s += dt;
395                    return Some(self.rates(&segment, state));
396                }
397                ManeuverPhase::Recovery => {
398                    let command = self.recovery.next(&self.config.recovery, dt, state);
399                    if command.is_none() {
400                        self.phase = ManeuverPhase::Done;
401                    }
402                    return command;
403                }
404            }
405        }
406    }
407
408    /// Segment `index` of the maneuver being flown.
409    fn segment(&self, index: usize) -> Option<Segment> {
410        self.maneuver.as_ref()?.segments().get(index).copied()
411    }
412
413    /// Begins segment `index` at `state`, or the recovery past the last.
414    fn begin(&mut self, index: usize, state: &VehicleState) {
415        let Some(segment) = self.segment(index) else {
416            self.recover();
417            return;
418        };
419        self.phase = ManeuverPhase::Rotation { segment: index };
420        self.progress = SegmentProgress::new(&segment, state, self.config.timeout_factor);
421    }
422
423    /// Begins the recovery.
424    fn recover(&mut self) {
425        self.phase = ManeuverPhase::Recovery;
426        self.recovery = Recovery::default();
427    }
428
429    /// `segment`'s body rate at `state` plus the pitch and yaw rate back onto its path, and its
430    /// thrust.
431    fn rates(&self, segment: &Segment, state: &VehicleState) -> ControlInput {
432        let (axis, radps, thrust) = match *segment {
433            Segment::Rotate {
434                axis, rate, thrust, ..
435            } => (Some(axis), rate.radps(state), thrust),
436            Segment::Pause { thrust, .. } => (None, 0.0, thrust),
437        };
438        let correction_radps = self
439            .progress
440            .path
441            .correction_radps(&self.config.path, state);
442        let rate = |about: Axis| {
443            let own_radps = if axis == Some(about) { radps } else { 0.0 };
444            own_radps + correction_radps.dot(&about.unit())
445        };
446        ControlInput::AbsoluteRate(AbsoluteRateCommand {
447            roll_radps: rate(Axis::Roll),
448            pitch_radps: rate(Axis::Pitch),
449            yaw_radps: rate(Axis::Yaw),
450            thrust: match thrust {
451                Thrust::Maneuver => self.config.thrust,
452                Thrust::Cruise => self.config.cruise_thrust,
453            },
454        })
455    }
456}