Skip to main content

stable_flight/guidance/
plane.rs

1//! Fixed-wing guidance: [`PlaneGuidance`] turns pilot sticks and offboard commands into
2//! [`Setpoint::Plane`] and [`Setpoint::PlaneRate`] for a
3//! [`PlaneStabilizer`](crate::stabilizers::plane::PlaneStabilizer).
4//!
5//! | Control input | Setpoint |
6//! |---|---|
7//! | [`ControlInput::Attitude`] | [`Setpoint::Plane`]: roll stick × [`max_bank_rad`](PlaneGuidanceConfig::max_bank_rad), pitch stick × [`max_pitch_up_rad`](PlaneGuidanceConfig::max_pitch_up_rad) or [`max_pitch_down_rad`](PlaneGuidanceConfig::max_pitch_down_rad), throttle as thrust (ArduPlane's FBWA); turns coordinated, yaw stick unused |
8//! | [`ControlInput::Rate`] | [`Setpoint::PlaneRate`]: sticks × [`max_rate_radps`](PlaneGuidanceConfig::max_rate_radps) (acro: rolls, loops), throttle as thrust |
9//! | [`ControlInput::AbsoluteAttitude`] | [`Setpoint::Plane`]: roll, pitch, and thrust as given (heading unused) |
10//! | [`ControlInput::AbsoluteRate`] | [`Setpoint::PlaneRate`]: rates and thrust as given |
11//! | [`ControlInput::Waypoint`] | [`Setpoint::Plane`]: with a leg velocity, L1 along the line through the waypoint in its direction; without one (a route's final hold, an offboard point), a clockwise loiter of [`loiter_radius_m`](PlaneGuidanceConfig::loiter_radius_m) around it; bank `atan(a/g)` capped at [`max_bank_rad`](PlaneGuidanceConfig::max_bank_rad). Pitch and thrust hold the waypoint's altitude and its `cruise_speed_mps` as airspeed by total energy control ([`TecsConfig`]: thrust for the total energy, pitch for its balance); without an airspeed or a speed target, pitch holds the altitude (a PI loop) and thrust is [`cruise_thrust`](PlaneGuidanceConfig::cruise_thrust) plus a climb's share |
12//! | [`ControlInput::Land`] | Neutral (level, zero thrust): a plane doesn't land here; a VTOL lands as a copter |
13//!
14//! Sticks and angles saturate (NaN as centered or level), throttle to `[0, 1]` (NaN as
15//! none). It flies only [`FlightRegime::Plane`], and reports a `Copter` request as
16//! [`ModeRefusal::Unsupported`](crate::ModeRefusal::Unsupported)
17//! ([`FlightModeReport::plane_only`]).
18
19use crate::controllers::{InvalidConfig, check, check_limit, check_positive};
20use crate::math::{DEG, all_finite, assert_dt, clamp_symmetric, saturate_throttle, saturate_unit};
21use crate::{
22    BodyRateSetpoint, Configurable, ControlInput, FlightModeReport, FlightRegime, Guidance,
23    PlaneSetpoint, Setpoint, Vec3, VehicleState, WaypointCommand,
24};
25
26mod navigation;
27mod params;
28mod tecs;
29#[cfg(test)]
30mod tests;
31
32use navigation::{PiLoop, bank_for_accel_rad, loiter_accel_mps2, track_accel_mps2};
33pub use tecs::{
34    DEFAULT_AIRSPEED_RATE_TIME_CONSTANT_S, DEFAULT_HEIGHT_DEMAND_TIME_CONSTANT_S,
35    DEFAULT_KINETIC_RATE_HIGH_PASS_S, DEFAULT_UNDERSPEED_SHARE, TecsConfig,
36};
37use tecs::{Limits, Tecs};
38
39/// [`PlaneGuidance`] settings.
40#[derive(Clone, Copy, Debug, PartialEq)]
41pub struct PlaneGuidanceConfig {
42    /// Bank at full roll stick, in radians.
43    pub max_bank_rad: f32,
44    /// Pitch at full back stick, in radians.
45    pub max_pitch_up_rad: f32,
46    /// Pitch (down) at full forward stick, in radians, positive.
47    pub max_pitch_down_rad: f32,
48    /// Body rates at full stick in rate (acro) flight, roll/pitch/yaw, in rad/s.
49    pub max_rate_radps: Vec3,
50    /// Pitch for wings-level cruise, in radians.
51    pub trim_pitch_rad: f32,
52    /// Throttle for wings-level cruise at the trim airspeed, `[0, 1]`: total energy control's
53    /// thrust at a steady energy.
54    pub cruise_thrust: f32,
55    /// L1 period, in seconds: how quickly the path is captured (shorter is tighter).
56    pub l1_period_s: f32,
57    /// L1 damping ratio.
58    pub l1_damping: f32,
59    /// Radius of the loiter around a waypoint with no leg, in meters.
60    pub loiter_radius_m: f32,
61    /// Without an airspeed: pitch per meter of altitude error, rad/m.
62    pub altitude_p: f32,
63    /// Without an airspeed: pitch per meter-second of accumulated altitude error.
64    pub altitude_i: f32,
65    /// Without an airspeed: the altitude loop's integral limit, in m·s.
66    pub altitude_max_integral: f32,
67    /// Total energy control of altitude and airspeed, with an airspeed and a speed target.
68    pub tecs: TecsConfig,
69    /// Least thrust waypoint flight commands, `[0, 1]`.
70    pub min_thrust: f32,
71    /// Most thrust waypoint flight commands, `[0, 1]`.
72    pub max_thrust: f32,
73    /// Without an airspeed: thrust added per radian of pitch up (a climb needs more).
74    pub climb_thrust_per_rad: f32,
75}
76
77impl Default for PlaneGuidanceConfig {
78    /// ArduPlane's FBWA limits (45° bank, +20°/−25° pitch, `mode_fbwa.cpp`), its acro rates
79    /// (180°/s roll and pitch, yaw stick unused), level trim, and half throttle to cruise;
80    /// for waypoints, ArduPilot's L1 damping (0.75) with a shorter period than its 17 s (12 s,
81    /// for a small airframe), a 40 m loiter, ArduPilot's total energy control defaults
82    /// ([`TecsConfig::default`]), and starting gains for the altitude loop without an airspeed
83    /// (an airframe tunes its own).
84    fn default() -> Self {
85        PlaneGuidanceConfig {
86            max_bank_rad: 45.0 * DEG,
87            max_pitch_up_rad: 20.0 * DEG,
88            max_pitch_down_rad: 25.0 * DEG,
89            max_rate_radps: Vec3::new(180.0 * DEG, 180.0 * DEG, 0.0),
90            trim_pitch_rad: 0.0,
91            cruise_thrust: 0.5,
92            l1_period_s: 12.0,
93            l1_damping: 0.75,
94            loiter_radius_m: 40.0,
95            altitude_p: 0.05,
96            altitude_i: 0.01,
97            altitude_max_integral: 20.0,
98            tecs: TecsConfig::default(),
99            min_thrust: 0.2,
100            max_thrust: 1.0,
101            climb_thrust_per_rad: 0.5,
102        }
103    }
104}
105
106impl PlaneGuidanceConfig {
107    /// `Ok` when the angle limits are in `[0, π/2]`, the rates non-negative, the trim pitch in
108    /// `[−π/2, π/2]`, the cruise thrust in `[0, 1]`, and [`TecsConfig::validate`] passes.
109    ///
110    /// # Errors
111    ///
112    /// [`InvalidConfig`] naming the first field out of range.
113    pub fn validate(&self) -> Result<(), InvalidConfig> {
114        let quarter_turn = |angle: f32| (0.0..=core::f32::consts::FRAC_PI_2).contains(&angle);
115        let in_range = "in [0, π/2] rad";
116        check("max_bank_rad", quarter_turn(self.max_bank_rad), in_range)?;
117        check(
118            "max_pitch_up_rad",
119            quarter_turn(self.max_pitch_up_rad),
120            in_range,
121        )?;
122        check(
123            "max_pitch_down_rad",
124            quarter_turn(self.max_pitch_down_rad),
125            in_range,
126        )?;
127        check_limit("max_rate_radps.x", self.max_rate_radps.x)?;
128        check_limit("max_rate_radps.y", self.max_rate_radps.y)?;
129        check_limit("max_rate_radps.z", self.max_rate_radps.z)?;
130        let half = core::f32::consts::FRAC_PI_2;
131        check(
132            "trim_pitch_rad",
133            (-half..=half).contains(&self.trim_pitch_rad),
134            "in [−π/2, π/2] rad",
135        )?;
136        let unit = |value: f32| (0.0..=1.0).contains(&value);
137        check("cruise_thrust", unit(self.cruise_thrust), "in [0, 1]")?;
138        check_positive("l1_period_s", self.l1_period_s)?;
139        check_positive("l1_damping", self.l1_damping)?;
140        check_positive("loiter_radius_m", self.loiter_radius_m)?;
141        check_limit("altitude_p", self.altitude_p)?;
142        check_limit("altitude_i", self.altitude_i)?;
143        check_limit("altitude_max_integral", self.altitude_max_integral)?;
144        self.tecs.validate().map_err(|e| e.in_section("tecs"))?;
145        check("min_thrust", unit(self.min_thrust), "in [0, 1]")?;
146        check("max_thrust", unit(self.max_thrust), "in [0, 1]")?;
147        check_limit("climb_thrust_per_rad", self.climb_thrust_per_rad)
148    }
149}
150
151/// Fixed-wing guidance for piloted and offboard flight. See the [module docs](self).
152///
153/// # Examples
154///
155/// ```
156/// use stable_flight::guidance::plane::{PlaneGuidance, PlaneGuidanceConfig};
157/// use stable_flight::{AttitudeCommand, ControlInput, FlightRegime, Guidance, Setpoint, VehicleState};
158///
159/// let mut guidance = PlaneGuidance::new(PlaneGuidanceConfig::default());
160/// let full_right = ControlInput::Attitude(AttitudeCommand {
161///     throttle: 0.7,
162///     roll: 1.0,
163///     ..Default::default()
164/// });
165/// let state = VehicleState::default();
166/// let Setpoint::Plane(setpoint) = guidance.guide(0.01, FlightRegime::Plane, &full_right, &state)
167/// else {
168///     unreachable!("sticks give a plane attitude");
169/// };
170/// assert_eq!(setpoint.roll_rad, 45f32.to_radians());
171/// assert_eq!(setpoint.thrust, 0.7);
172/// ```
173#[derive(Clone, Debug, PartialEq)]
174pub struct PlaneGuidance {
175    config: PlaneGuidanceConfig,
176    requested: FlightRegime,
177    /// Waypoint flight without an airspeed: altitude (→ pitch).
178    altitude: PiLoop,
179    /// Waypoint flight with an airspeed: total energy control.
180    tecs: Tecs,
181}
182
183impl PlaneGuidance {
184    /// Guidance with `config`.
185    ///
186    /// # Panics
187    ///
188    /// If `config` is invalid ([`PlaneGuidanceConfig::validate`]).
189    pub fn new(config: PlaneGuidanceConfig) -> Self {
190        if let Err(error) = config.validate() {
191            panic!("invalid PlaneGuidanceConfig: {error}");
192        }
193        PlaneGuidance {
194            config,
195            requested: FlightRegime::Plane,
196            altitude: PiLoop::default(),
197            tecs: Tecs::default(),
198        }
199    }
200
201    /// [`Guidance::guide`], with waypoint flight's pitch held within `pitch_cap_rad` either
202    /// way when given: the forward transition's limits, so the energy control's pitch integral
203    /// stops where the transition stops the pitch (`SLT_Transition::set_FW_roll_pitch`).
204    pub(crate) fn guide_capped(
205        &mut self,
206        dt: f32,
207        regime: FlightRegime,
208        input: &ControlInput,
209        state: &VehicleState,
210        pitch_cap_rad: Option<f32>,
211    ) -> Setpoint {
212        assert_dt(dt);
213        self.requested = regime;
214        if !matches!(input, ControlInput::Waypoint(_)) {
215            // The navigation loops are idle: clear them so waypoint flight starts fresh.
216            self.altitude = PiLoop::default();
217            self.tecs.reset();
218        }
219        let config = &self.config;
220        match input {
221            ControlInput::Attitude(sticks) => {
222                Setpoint::Plane(self.sticks(sticks.roll, sticks.pitch, sticks.throttle))
223            }
224            ControlInput::Rate(sticks) => Setpoint::PlaneRate(BodyRateSetpoint {
225                roll_radps: saturate_unit(sticks.roll_rate) * config.max_rate_radps.x,
226                pitch_radps: saturate_unit(sticks.pitch_rate) * config.max_rate_radps.y,
227                yaw_radps: saturate_unit(sticks.yaw_rate) * config.max_rate_radps.z,
228                thrust: saturate_throttle(sticks.throttle),
229                idle: false,
230            }),
231            ControlInput::AbsoluteAttitude(command) => Setpoint::Plane(PlaneSetpoint {
232                roll_rad: command.roll_rad,
233                pitch_rad: command.pitch_rad,
234                thrust: saturate_throttle(command.thrust),
235                transition: false,
236            }),
237            ControlInput::AbsoluteRate(command) => {
238                let mut rates = BodyRateSetpoint::from(command);
239                rates.thrust = saturate_throttle(command.thrust);
240                Setpoint::PlaneRate(rates)
241            }
242            ControlInput::Waypoint(waypoint) => {
243                Setpoint::Plane(self.navigate(dt, waypoint, state, pitch_cap_rad))
244            }
245            ControlInput::Land(_) => Setpoint::Plane(PlaneSetpoint::default()),
246        }
247    }
248
249    /// Waypoint flight: bank from L1 along the leg (or a loiter without one); pitch and thrust
250    /// from total energy control, or without an airspeed or a speed target, pitch from the
251    /// altitude loop and thrust from cruise and the pitch.
252    fn navigate(
253        &mut self,
254        dt: f32,
255        waypoint: &WaypointCommand,
256        state: &VehicleState,
257        pitch_cap_rad: Option<f32>,
258    ) -> PlaneSetpoint {
259        let config = &self.config;
260        let cap = |limit_rad: f32| pitch_cap_rad.map_or(limit_rad, |cap| limit_rad.min(cap));
261        let (pitch_up_rad, pitch_down_rad) =
262            (cap(config.max_pitch_up_rad), cap(config.max_pitch_down_rad));
263        let (position_m, velocity_mps) = (state.position_m.xy(), state.velocity_mps.xy());
264        let (period_s, damping) = (config.l1_period_s, config.l1_damping);
265        let leg = waypoint.velocity_mps.filter(all_finite);
266        let accel_mps2 = match leg {
267            Some(leg) => track_accel_mps2(
268                position_m,
269                velocity_mps,
270                waypoint.position_m,
271                leg,
272                period_s,
273                damping,
274            ),
275            None => loiter_accel_mps2(
276                position_m,
277                velocity_mps,
278                waypoint.position_m,
279                config.loiter_radius_m,
280                period_s,
281                damping,
282            ),
283        };
284        let roll_rad = clamp_symmetric(bank_for_accel_rad(accel_mps2), config.max_bank_rad);
285
286        let (low, high) = (config.min_thrust, config.max_thrust.max(config.min_thrust));
287        let trim = config.trim_pitch_rad;
288        let target_mps = Some(waypoint.cruise_speed_mps).filter(|speed| *speed > 0.0);
289        let (pitch_rad, thrust) = match (target_mps, state.valid_airspeed_mps()) {
290            (Some(target_mps), Some(airspeed_mps)) => {
291                self.altitude = PiLoop::default();
292                let limits = Limits {
293                    pitch_up_rad,
294                    pitch_down_rad,
295                    trim_pitch_rad: trim,
296                    min_thrust: low,
297                    max_thrust: high,
298                    cruise_thrust: config.cruise_thrust,
299                };
300                self.tecs.step(
301                    dt,
302                    &config.tecs,
303                    &limits,
304                    (waypoint.altitude_m, target_mps),
305                    airspeed_mps,
306                    state,
307                )
308            }
309            _ => {
310                self.tecs.reset();
311                // Pitch around trim, within the pitch limits; cruise thrust plus what a climb
312                // needs.
313                let pitch_rad = trim
314                    + self.altitude.step(
315                        dt,
316                        waypoint.altitude_m - state.position_m.z,
317                        config.altitude_p,
318                        config.altitude_i,
319                        config.altitude_max_integral,
320                        (-pitch_down_rad - trim, pitch_up_rad - trim),
321                        0.0,
322                    );
323                let thrust = (config.cruise_thrust
324                    + config.climb_thrust_per_rad * (pitch_rad - trim))
325                    .clamp(low, high);
326                (pitch_rad, thrust)
327            }
328        };
329        PlaneSetpoint {
330            roll_rad,
331            pitch_rad,
332            thrust,
333            transition: false,
334        }
335    }
336
337    /// FBWA: sticks to bank and pitch, pitch asymmetric.
338    fn sticks(&self, roll: f32, pitch: f32, throttle: f32) -> PlaneSetpoint {
339        let config = &self.config;
340        let pitch = saturate_unit(pitch);
341        let pitch_limit = if pitch >= 0.0 {
342            config.max_pitch_up_rad
343        } else {
344            config.max_pitch_down_rad
345        };
346        PlaneSetpoint {
347            roll_rad: saturate_unit(roll) * config.max_bank_rad,
348            pitch_rad: pitch * pitch_limit,
349            thrust: saturate_throttle(throttle),
350            transition: false,
351        }
352    }
353}
354
355impl Configurable for PlaneGuidance {
356    type Config = PlaneGuidanceConfig;
357
358    fn config(&self) -> &PlaneGuidanceConfig {
359        &self.config
360    }
361
362    /// Validates with [`PlaneGuidanceConfig::validate`]; applies from the next tick.
363    fn set_config(&mut self, config: PlaneGuidanceConfig) -> Result<(), InvalidConfig> {
364        config.validate()?;
365        self.config = config;
366        Ok(())
367    }
368}
369
370impl Guidance for PlaneGuidance {
371    fn guide(
372        &mut self,
373        dt: f32,
374        regime: FlightRegime,
375        input: &ControlInput,
376        state: &VehicleState,
377    ) -> Setpoint {
378        self.guide_capped(dt, regime, input, state, None)
379    }
380
381    /// Clears the navigation loops: integrals, demands, and underspeed.
382    fn prime(&mut self, _state: &VehicleState) {
383        self.altitude = PiLoop::default();
384        self.tecs.reset();
385    }
386
387    /// Always plane; a `Copter` request is refused as unsupported.
388    fn flight_mode(&self) -> Option<FlightModeReport> {
389        Some(FlightModeReport::plane_only(self.requested))
390    }
391}