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