Skip to main content

stable_flight/commanders/maneuver/
path.rs

1//! The path a [`Segment::Rotate`] holds while it turns: see [`Path`].
2
3use crate::controllers::{InvalidConfig, check_limit};
4use crate::math::{all_finite, neu_to_ned};
5use crate::{GRAVITY, Vec3, VehicleState};
6
7use super::segment::{RateLaw, Segment, positive, speed_mps};
8
9#[cfg(doc)]
10use super::ManeuverRunner;
11
12#[cfg(test)]
13mod tests;
14
15/// The path a [`Segment::Rotate`] holds while it turns, laid out from where the segment
16/// begins. Flying rates alone, a roll sinks as its lift tips over and a loop stretches as it
17/// speeds up coming down; holding a path, the [`ManeuverRunner`] steers back toward it with
18/// pitch and yaw rate on top of the segment's own rate, harder the further off it is
19/// ([`PathConfig`]).
20///
21/// This is ArduPilot's scripted aerobatics' correction
22/// (`libraries/AP_Scripting/applets/Aerobatics/FixedWing/plane_aerobatics.lua:2615-2645` at
23/// `3d24375`): only the error across the path counts, a PD turns it into an acceleration, and
24/// the acceleration divided by the speed is the turn rate, in pitch and yaw, never roll.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Path {
27    /// No path: the segment's rates alone, as a doublet measures them.
28    Free,
29    /// The straight line along the direction of travel at the start: a roll keeps its height
30    /// and its line.
31    Line,
32    /// The circle its [`RateLaw::Radius`] turns about its axis, tangent to the nose at the
33    /// start: a loop about pitch (center above the canopy, or below it for a negative radius),
34    /// a flat circle about yaw. Needs a radius and a pitch or yaw axis.
35    Circle,
36}
37
38/// How hard a [`ManeuverRunner`] steers back onto a segment's [`Path`]. All zero flies the
39/// segments' rates alone.
40///
41/// On `stable-flight-sim`'s plane, tailsitter, and eXplora the defaults end loops of 10 and 25 m
42/// within 1.1 m of their entry height and 3% of their radius, and rolls at 90 and 180°/s lose
43/// at most 3.5 m and climb at most 2.6 m, where rates alone lost up to 37 m in a roll and 6.4 m
44/// in a loop (#481).
45#[derive(Clone, Copy, Debug, PartialEq)]
46pub struct PathConfig {
47    /// Acceleration back toward the path per meter off it, in m/s² per m (1/s²). Higher holds
48    /// the path tighter; 4 (with a velocity gain of 4) balloons a 90°/s roll 4.5 m on the sim
49    /// for no less sink (#481). ArduPilot's `AEROM_ERR_COR_P` (`plane_aerobatics.lua:91-95`).
50    pub position_gain_per_s2: f32,
51    /// Acceleration against the speed away from the path, in m/s² per m/s (1/s): damps the
52    /// return. ArduPilot's `AEROM_ERR_COR_D` (`:98-102`).
53    pub velocity_gain_per_s: f32,
54    /// On a [`Path::Line`], the share of the weight the wing stops carrying as it rolls away
55    /// from upright (none upright, all of it on knife edge, twice it inverted) steered against
56    /// up front instead of waiting for the sink. Higher: less sink, more climb. 0 leaves it all
57    /// to the gains, as ArduPilot does: on the sim rolls then lose up to 5.2 m (the
58    /// tailsitter's at 180°/s) against 3.5 m at 0.5, which climbs up to 2.6 m (#481).
59    pub line_gravity_share: f32,
60}
61
62impl Default for PathConfig {
63    /// ArduPilot's gains, 2 and 2.8, and half the lost lift up front (#481).
64    fn default() -> Self {
65        PathConfig {
66            position_gain_per_s2: 2.0,
67            velocity_gain_per_s: 2.8,
68            line_gravity_share: 0.5,
69        }
70    }
71}
72
73impl PathConfig {
74    /// `Ok` when every field is non-negative and finite.
75    ///
76    /// # Errors
77    ///
78    /// [`InvalidConfig`] naming the first field out of range.
79    pub fn validate(&self) -> Result<(), InvalidConfig> {
80        check_limit("position_gain_per_s2", self.position_gain_per_s2)?;
81        check_limit("velocity_gain_per_s", self.velocity_gain_per_s)?;
82        check_limit("line_gravity_share", self.line_gravity_share)
83    }
84}
85
86/// Below this speed, in m/s, a turn rate from an acceleration (`a / V`) runs away: no
87/// correction.
88const MIN_SPEED_MPS: f32 = 1.0;
89
90/// A segment's [`Path`], laid out in NED where it began.
91#[derive(Clone, Copy, Debug)]
92pub(super) struct PathHold {
93    laid: Laid,
94    /// The direction of travel where it began, a unit vector: a line's direction, and the
95    /// direction of travel without a ground speed to read it from.
96    entry_direction: Vec3,
97}
98
99/// A [`Path`] in place.
100#[derive(Clone, Copy, Debug)]
101enum Laid {
102    /// [`Path::Free`], or a [`Segment::Pause`].
103    Free,
104    /// [`Path::Line`] from `start_m` along the entry direction.
105    Line {
106        /// Where the segment began, in m.
107        start_m: Vec3,
108    },
109    /// [`Path::Circle`].
110    Circle {
111        /// Its center, in m.
112        center_m: Vec3,
113        /// Its axis (the segment's, at the start), a unit vector.
114        normal: Vec3,
115        /// Its radius, in m (positive).
116        radius_m: f32,
117    },
118}
119
120impl PathHold {
121    /// `segment`'s path, beginning at `state`.
122    pub(super) fn new(segment: &Segment, state: &VehicleState) -> Self {
123        let start_m = neu_to_ned(state.position_m);
124        let entry_direction =
125            travel_direction(neu_to_ned(state.velocity_mps), state.attitude * Vec3::x());
126        let laid = match *segment {
127            Segment::Rotate {
128                path: Path::Line, ..
129            } => Laid::Line { start_m },
130            Segment::Rotate {
131                axis,
132                rate: RateLaw::Radius { radius_m },
133                path: Path::Circle,
134                ..
135            } => {
136                // The center sits off the nose, square to it and to the axis, on the side the
137                // rate turns toward: above the canopy for a loop (pitch: y × x = −z, body up),
138                // right of it for a yaw circle (z × x = y).
139                let toward_center = axis.unit().cross(&Vec3::x());
140                Laid::Circle {
141                    center_m: start_m + state.attitude * toward_center * radius_m,
142                    normal: state.attitude * axis.unit(),
143                    radius_m: radius_m.abs(),
144                }
145            }
146            // A circle without a radius is refused when the maneuver is built.
147            _ => Laid::Free,
148        };
149        PathHold {
150            laid,
151            entry_direction,
152        }
153    }
154
155    /// The body rates, in rad/s (FRD: `x` roll, always 0; `y` pitch, nose up; `z` yaw, nose
156    /// right), that steer `state` back onto the path: zero on it, for a [`Path::Free`], without
157    /// a speed, or for a non-finite state.
158    ///
159    /// The error across the path (`e`, m) and its rate (`ė`, m/s) give the acceleration back
160    /// toward it, `a = −(k_p·e + k_d·ė)` (NED, m/s²); a line adds `share · (1 − up_body·up) · g`
161    /// up. Turning the velocity at that acceleration takes the rate `v̂ × a / V`, rotated into
162    /// the body.
163    pub(super) fn correction_radps(&self, config: &PathConfig, state: &VehicleState) -> Vec3 {
164        let speed_mps = speed_mps(state);
165        // An unknown speed corrects nothing.
166        if speed_mps.is_nan() || speed_mps < MIN_SPEED_MPS {
167            return Vec3::zeros();
168        }
169        let position_m = neu_to_ned(state.position_m);
170        let velocity_mps = neu_to_ned(state.velocity_mps);
171        let Some((error_m, error_rate_mps)) = self.error(position_m, velocity_mps) else {
172            return Vec3::zeros();
173        };
174        let mut accel_mps2 =
175            -(error_m * config.position_gain_per_s2 + error_rate_mps * config.velocity_gain_per_s);
176        if let Laid::Line { .. } = self.laid {
177            // NED up; the body's up is its −z.
178            let up = -Vec3::z();
179            let body_up = state.attitude * -Vec3::z();
180            let lift_lost = 1.0 - body_up.dot(&up);
181            accel_mps2 += up * (config.line_gravity_share * lift_lost * GRAVITY);
182        }
183        let travel = travel_direction(velocity_mps, self.entry_direction);
184        let turn_radps = travel.cross(&accel_mps2) / speed_mps;
185        let body_radps = state.attitude.inverse() * turn_radps;
186        let correction = Vec3::new(0.0, body_radps.y, body_radps.z);
187        if all_finite(&correction) {
188            correction
189        } else {
190            Vec3::zeros()
191        }
192    }
193
194    /// The position off the path across it, in m, and its rate, in m/s (NED); `None` without a
195    /// path, or at a circle's center, which has no direction back to it.
196    fn error(&self, position_m: Vec3, velocity_mps: Vec3) -> Option<(Vec3, Vec3)> {
197        match self.laid {
198            Laid::Free => None,
199            Laid::Line { start_m } => {
200                let direction = self.entry_direction;
201                let across = |v: Vec3| v - direction * v.dot(&direction);
202                Some((across(position_m - start_m), across(velocity_mps)))
203            }
204            Laid::Circle {
205                center_m,
206                normal,
207                radius_m,
208            } => {
209                let offset_m = position_m - center_m;
210                let off_plane_m = normal * offset_m.dot(&normal);
211                let in_plane_m = offset_m - off_plane_m;
212                let distance_m = in_plane_m.norm();
213                if !positive(distance_m) {
214                    return None;
215                }
216                let outward = in_plane_m / distance_m;
217                let error_m = outward * (distance_m - radius_m) + off_plane_m;
218                let error_rate_mps =
219                    outward * velocity_mps.dot(&outward) + normal * velocity_mps.dot(&normal);
220                Some((error_m, error_rate_mps))
221            }
222        }
223    }
224}
225
226/// The direction of `velocity_mps`, a unit vector, or `fallback` below [`MIN_SPEED_MPS`] (a
227/// headwind as strong as the airspeed leaves no ground speed to read it from).
228fn travel_direction(velocity_mps: Vec3, fallback: Vec3) -> Vec3 {
229    if velocity_mps.norm() >= MIN_SPEED_MPS {
230        velocity_mps.normalize()
231    } else {
232        fallback
233    }
234}