Skip to main content

stable_flight/stabilizers/
plane.rs

1//! Fixed-wing stabilization: [`PlaneStabilizer`] tracks a [`Setpoint::Plane`] attitude or a
2//! [`Setpoint::PlaneRate`] body rate with control surfaces, scaled for airspeed.
3//!
4//! | Setpoint | Behavior |
5//! |---|---|
6//! | [`Setpoint::Plane`] | Bank and pitch (saturated to [`max_bank_rad`](PlaneStabilizerConfig::max_bank_rad) / [`max_pitch_rad`](PlaneStabilizerConfig::max_pitch_rad), pitch to ±π/2 for a [`transition`](PlaneSetpoint::transition) ramp) → rate targets = error / time constant, plus the coordinated-turn rates for the current bank and airspeed → rate loop |
7//! | [`Setpoint::PlaneRate`] | Absolute body rates (saturated to [`max_body_rate_radps`](PlaneStabilizerConfig::max_body_rate_radps)) → rate loop, at any attitude: acro, rolls, loops |
8//! | others | Neutral (zero thrust and moments) |
9//!
10//! The structure is PX4's fixed-wing attitude and rate control
11//! (`FixedwingAttitudeControl.cpp`, `FixedwingRateControl.cpp`), described, not copied:
12//!
13//! - The attitude error is the yaw-free part of the reduced attitude error the copter uses:
14//!   the rotation that turns the body `z` axis onto the setpoint's, in body axes, so it's
15//!   defined at any attitude, inverted included.
16//! - A level turn at bank φ and speed V turns at ψ̇ = g·tan φ / V, which in body axes is a pitch
17//!   rate ψ̇·sin φ·cos θ and a yaw rate ψ̇·cos φ·cos θ; both are fed forward so the wing turns
18//!   without slipping or losing its nose, faded out between 70° and 75° of bank (PX4's
19//!   turn-coordination fade).
20//! - The rate loop ([`PlaneRateController`]) scales by airspeed and freezes its integral
21//!   below [`min_airspeed_mps`](PlaneStabilizerConfig::min_airspeed_mps). Without an airspeed
22//!   it assumes trim airspeed (PX4).
23//! - Each axis adds its [`trim`](PlaneRateControllerConfig::trim), the moment the wing needs
24//!   in steady flight, scaled like the feedback (PX4's `TRIM_ROLL`/`_PITCH`/`_YAW`).
25//!
26//! Unlike the copter's, the integrals aren't cleared at zero thrust: gliding is normal flight.
27//! Rate flight (acro, a maneuver) leaves them as it found them: the rate integrals are saved
28//! when a [`Setpoint::PlaneRate`] follows any other setpoint and restored when a
29//! [`Setpoint::Plane`] follows it, so what a roll or loop winds up doesn't carry into the
30//! attitude flight after it.
31
32use crate::controllers::{
33    InvalidConfig, PlaneRateController, PlaneRateControllerConfig, check, check_limit,
34    check_positive,
35};
36use crate::math::{
37    DEG, assert_dt, attitude_error, bank_rad, clamp_symmetric, pitch_limit_rad, saturate_rates,
38    saturate_symmetric, thrust_curve,
39};
40use crate::{
41    BodyRateSetpoint, Configurable, ControlOutput, GRAVITY, PlaneSetpoint, Saturation, Setpoint,
42    Stabilizer, Vec2, Vec3, VehicleState,
43};
44
45mod params;
46#[cfg(test)]
47mod tests;
48
49/// Bank where turn coordination starts to fade, and where it's gone (PX4's 70°–75°).
50const COORDINATION_FADE_RAD: (f32, f32) = (70.0 * DEG, 75.0 * DEG);
51
52/// [`PlaneStabilizer`] settings.
53#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct PlaneStabilizerConfig {
55    /// The rate loop's gains and integral limit.
56    pub rate: PlaneRateControllerConfig,
57    /// How fast the attitude loops close their error, roll (`x`) and pitch (`y`), in s: the
58    /// rate target is the error divided by it.
59    pub time_constant_s: Vec2,
60    /// Largest roll (`x`) and pitch (`y`) rate the attitude loops ask for, in rad/s.
61    pub max_attitude_rate_radps: Vec2,
62    /// Largest body rate an absolute-rate setpoint gets, per axis, in rad/s.
63    pub max_body_rate_radps: Vec3,
64    /// Largest bank an attitude setpoint gets, in radians.
65    pub max_bank_rad: f32,
66    /// Largest pitch, up or down, an attitude setpoint gets, in radians; a
67    /// [`transition`](PlaneSetpoint::transition) ramp's isn't held to it.
68    pub max_pitch_rad: f32,
69    /// The airspeed the gains are tuned at (scale 1), in m/s; assumed without an airspeed.
70    pub trim_airspeed_mps: f32,
71    /// Below this airspeed the scale stops growing and the rate integrals hold, in m/s.
72    pub min_airspeed_mps: f32,
73    /// Above this airspeed the scale stops shrinking, in m/s.
74    pub max_airspeed_mps: f32,
75    /// Linear throttle → motor command exponent (1 passes throttle through). A tailsitter uses
76    /// its hover stabilizer's, so a handoff keeps motor commands continuous.
77    pub thrust_curve_exponent: f32,
78}
79
80impl Default for PlaneStabilizerConfig {
81    /// PX4's fixed-wing defaults (time constants 0.4 s, attitude rate limits 70°/s roll and
82    /// 60°/s pitch, `fw_att_control_params.yaml`), acro up to 180°/s roll and pitch and 60°/s
83    /// yaw, 50° bank and 30° pitch, airspeeds 10/15/25 m/s, and throttle passed through.
84    /// Placeholders until an airframe is tuned.
85    fn default() -> Self {
86        PlaneStabilizerConfig {
87            rate: PlaneRateControllerConfig::default(),
88            time_constant_s: Vec2::new(0.4, 0.4),
89            max_attitude_rate_radps: Vec2::new(70.0 * DEG, 60.0 * DEG),
90            max_body_rate_radps: Vec3::new(180.0 * DEG, 180.0 * DEG, 60.0 * DEG),
91            max_bank_rad: 50.0 * DEG,
92            max_pitch_rad: 30.0 * DEG,
93            trim_airspeed_mps: 15.0,
94            min_airspeed_mps: 10.0,
95            max_airspeed_mps: 25.0,
96            thrust_curve_exponent: 1.0,
97        }
98    }
99}
100
101impl PlaneStabilizerConfig {
102    /// `Ok` when every field is in range: positive time constants, non-negative rate limits,
103    /// bank and pitch limits in `[0, π]`, positive airspeeds, and a positive thrust exponent.
104    /// Each is checked on its own; the scale clamps the airspeed to `[min, max]` with a `max`
105    /// below `min` read as `min`, so out-of-order airspeeds degrade, not fail.
106    ///
107    /// # Errors
108    ///
109    /// [`InvalidConfig`] naming the first field out of range.
110    pub fn validate(&self) -> Result<(), InvalidConfig> {
111        self.rate.validate().map_err(|e| e.in_section("rate"))?;
112        check_positive("time_constant_s.x", self.time_constant_s.x)?;
113        check_positive("time_constant_s.y", self.time_constant_s.y)?;
114        check_limit("max_attitude_rate_radps.x", self.max_attitude_rate_radps.x)?;
115        check_limit("max_attitude_rate_radps.y", self.max_attitude_rate_radps.y)?;
116        check_limit("max_body_rate_radps.x", self.max_body_rate_radps.x)?;
117        check_limit("max_body_rate_radps.y", self.max_body_rate_radps.y)?;
118        check_limit("max_body_rate_radps.z", self.max_body_rate_radps.z)?;
119        let half_turn = |angle: f32| (0.0..=core::f32::consts::PI).contains(&angle);
120        check(
121            "max_bank_rad",
122            half_turn(self.max_bank_rad),
123            "in [0, π] rad",
124        )?;
125        check(
126            "max_pitch_rad",
127            half_turn(self.max_pitch_rad),
128            "in [0, π] rad",
129        )?;
130        check_positive("trim_airspeed_mps", self.trim_airspeed_mps)?;
131        check_positive("min_airspeed_mps", self.min_airspeed_mps)?;
132        check_positive("max_airspeed_mps", self.max_airspeed_mps)?;
133        check_positive("thrust_curve_exponent", self.thrust_curve_exponent)
134    }
135}
136
137/// A fixed-wing stabilizer: attitude and rate loops on the control surfaces, with turn
138/// coordination and airspeed scaling. See the [module docs](self).
139///
140/// # Examples
141///
142/// ```
143/// use stable_flight::stabilizers::plane::{PlaneStabilizer, PlaneStabilizerConfig};
144/// use stable_flight::{PlaneSetpoint, Setpoint, Stabilizer, VehicleState};
145///
146/// let mut stabilizer = PlaneStabilizer::new(PlaneStabilizerConfig::default());
147/// let bank_right = Setpoint::Plane(PlaneSetpoint {
148///     roll_rad: 0.3,
149///     thrust: 0.6,
150///     ..Default::default()
151/// });
152/// let output = stabilizer.stabilize(0.004, &bank_right, &VehicleState::default());
153/// assert!(output.moments.x > 0.0); // roll right
154/// assert_eq!(output.thrust, 0.6);
155/// ```
156#[derive(Clone, Debug, PartialEq)]
157pub struct PlaneStabilizer {
158    config: PlaneStabilizerConfig,
159    rate: PlaneRateController,
160    /// The rate loop as attitude flight left it, while flying a [`Setpoint::PlaneRate`].
161    attitude_rate: Option<PlaneRateController>,
162    saturation: Saturation,
163}
164
165impl PlaneStabilizer {
166    /// A stabilizer with `config`.
167    ///
168    /// # Panics
169    ///
170    /// If `config` is invalid ([`PlaneStabilizerConfig::validate`]).
171    pub fn new(config: PlaneStabilizerConfig) -> Self {
172        if let Err(error) = config.validate() {
173            panic!("invalid PlaneStabilizerConfig: {error}");
174        }
175        PlaneStabilizer {
176            config,
177            rate: PlaneRateController::default(),
178            attitude_rate: None,
179            saturation: Saturation::default(),
180        }
181    }
182
183    /// Rate targets for an attitude setpoint: the error over the time constant, clamped, plus
184    /// the coordinated-turn rates.
185    fn attitude_rates(&mut self, setpoint: &PlaneSetpoint, state: &VehicleState) -> Vec3 {
186        let config = &self.config;
187        let max_pitch_rad = pitch_limit_rad(config.max_pitch_rad, setpoint.transition);
188        // `>` is false for NaN, which saturates to level.
189        self.saturation.tilt = setpoint.roll_rad.abs() > config.max_bank_rad
190            || setpoint.pitch_rad.abs() > max_pitch_rad;
191        let roll_rad = saturate_symmetric(setpoint.roll_rad, config.max_bank_rad);
192        let pitch_rad = saturate_symmetric(setpoint.pitch_rad, max_pitch_rad);
193        let error = attitude_error(&state.attitude, roll_rad, pitch_rad, f32::NAN);
194        let correction = Vec2::new(
195            clamp_symmetric(
196                error.x / config.time_constant_s.x,
197                config.max_attitude_rate_radps.x,
198            ),
199            clamp_symmetric(
200                error.y / config.time_constant_s.y,
201                config.max_attitude_rate_radps.y,
202            ),
203        );
204        coordinated_turn_radps(state, self.airspeed_mps(state))
205            + Vec3::new(correction.x, correction.y, 0.0)
206    }
207
208    /// Rate targets for an absolute-rate setpoint, saturated (NaN as zero).
209    fn body_rates(&self, setpoint: &BodyRateSetpoint) -> Vec3 {
210        saturate_rates(
211            Vec3::new(
212                setpoint.roll_radps,
213                setpoint.pitch_radps,
214                setpoint.yaw_radps,
215            ),
216            self.config.max_body_rate_radps,
217        )
218    }
219
220    /// The airspeed the loops work with: the state's when valid, clamped to the configured
221    /// range, else trim.
222    fn airspeed_mps(&self, state: &VehicleState) -> f32 {
223        let config = &self.config;
224        state
225            .valid_airspeed_mps()
226            .map_or(config.trim_airspeed_mps, |airspeed_mps| {
227                let max_mps = config.max_airspeed_mps.max(config.min_airspeed_mps);
228                airspeed_mps.clamp(config.min_airspeed_mps, max_mps)
229            })
230    }
231
232    /// The rate loop at `desired_radps`, scaled for airspeed, and the thrust.
233    fn track(
234        &mut self,
235        dt: f32,
236        desired_radps: Vec3,
237        thrust: f32,
238        state: &VehicleState,
239    ) -> ControlOutput {
240        let config = &self.config;
241        let scale = config.trim_airspeed_mps / self.airspeed_mps(state);
242        // Without an airspeed there's nothing to hold the integral for.
243        let integrate = state
244            .valid_airspeed_mps()
245            .is_none_or(|airspeed_mps| airspeed_mps >= config.min_airspeed_mps);
246        let moments = self.rate.control(
247            &config.rate,
248            dt,
249            desired_radps,
250            state.angular_velocity_radps,
251            scale,
252            integrate,
253        );
254        self.saturation.thrust = !(0.0..=1.0).contains(&thrust) && !thrust.is_nan();
255        ControlOutput {
256            thrust: thrust_curve(thrust, config.thrust_curve_exponent),
257            moments,
258            cruise: None,
259        }
260    }
261}
262
263/// The body rates of a level turn at the vehicle's bank and `airspeed_mps`: ψ̇ = g·tan φ / V,
264/// as pitch rate ψ̇·sin φ·cos θ and yaw rate ψ̇·cos φ·cos θ, read from the rotation matrix's
265/// bottom row (`cos θ sin φ`, `cos θ cos φ`) without Euler angles. Faded out between 70° and
266/// 75° of bank; zero inverted or for a non-finite attitude.
267fn coordinated_turn_radps(state: &VehicleState, airspeed_mps: f32) -> Vec3 {
268    let m = state.attitude.to_rotation_matrix();
269    let (sin_roll_cos_pitch, cos_roll_cos_pitch) = (m[(2, 1)], m[(2, 2)]);
270    let bank_rad = bank_rad(&state.attitude).abs();
271    let (start, end) = COORDINATION_FADE_RAD;
272    let fade = ((end - bank_rad) / (end - start)).clamp(0.0, 1.0);
273    // A NaN bank (non-finite attitude) fades to NaN: no feedforward either.
274    if fade.is_nan() || fade <= 0.0 || !airspeed_mps.is_finite() {
275        return Vec3::zeros();
276    }
277    // ψ̇·cos φ·cos θ = g·sin φ·cos θ / V, and ψ̇·sin φ·cos θ = that · tan φ.
278    let yaw_radps = GRAVITY * sin_roll_cos_pitch / airspeed_mps;
279    let pitch_radps = yaw_radps * sin_roll_cos_pitch / cos_roll_cos_pitch;
280    Vec3::new(0.0, pitch_radps, yaw_radps) * fade
281}
282
283impl Configurable for PlaneStabilizer {
284    type Config = PlaneStabilizerConfig;
285
286    fn config(&self) -> &PlaneStabilizerConfig {
287        &self.config
288    }
289
290    /// Validates with [`PlaneStabilizerConfig::validate`]; the rate integrals, and those saved
291    /// for attitude flight, are rescaled to the new integral gains.
292    fn set_config(&mut self, config: PlaneStabilizerConfig) -> Result<(), InvalidConfig> {
293        config.validate()?;
294        self.rate.rescale_integral(&self.config.rate, &config.rate);
295        if let Some(saved) = &mut self.attitude_rate {
296            saved.rescale_integral(&self.config.rate, &config.rate);
297        }
298        self.config = config;
299        Ok(())
300    }
301}
302
303impl Stabilizer for PlaneStabilizer {
304    /// Flies a [`Setpoint::Plane`] or [`Setpoint::PlaneRate`]; neutral for any other.
305    fn stabilize(&mut self, dt: f32, setpoint: &Setpoint, state: &VehicleState) -> ControlOutput {
306        assert_dt(dt);
307        self.saturation = Saturation::default();
308        let output = match setpoint {
309            Setpoint::Plane(plane) => {
310                if let Some(saved) = self.attitude_rate.take() {
311                    self.rate = saved;
312                }
313                let rates = self.attitude_rates(plane, state);
314                self.track(dt, rates, plane.thrust, state)
315            }
316            Setpoint::PlaneRate(rates) => {
317                if self.attitude_rate.is_none() {
318                    self.attitude_rate = Some(self.rate.clone());
319                }
320                let rates_radps = self.body_rates(rates);
321                self.track(dt, rates_radps, rates.thrust, state)
322            }
323            _ => return ControlOutput::default(),
324        };
325        self.saturation.moments = output.moments.map(|m| m.abs() >= 1.0).into();
326        output
327    }
328
329    /// Clears the rate integrals, those saved for attitude flight, and saturation.
330    fn prime(&mut self, _state: &VehicleState) {
331        self.rate.clear_integral();
332        self.attitude_rate = None;
333        self.saturation = Saturation::default();
334    }
335
336    /// `tilt` when an attitude setpoint's bank or pitch was beyond its limit, `thrust` when
337    /// the setpoint's thrust was outside `[0, 1]`, and `moments` per axis at ±1.
338    fn saturation(&self) -> Saturation {
339        self.saturation
340    }
341}