Skip to main content

stable_flight/guidance/vtol/
quadplane.rs

1//! [`QuadPlaneGuidance`]: hover and plane guidance under one [`LiftTransition`].
2
3use super::{
4    FallbackHold, ForwardThrust, ForwardThrustConfig, LiftTransition, LiftTransitionConfig,
5    LiftTransitionStep, OffNoseSpeed, OffNoseSpeedConfig, ThrustHandoff,
6};
7use crate::controllers::InvalidConfig;
8use crate::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
9use crate::guidance::plane::{PlaneGuidance, PlaneGuidanceConfig};
10use crate::math::{DEG, bank_rad, saturate_symmetric, saturate_throttle};
11use crate::params::{ParamError, Params, locate};
12use crate::{
13    AttitudeSetpoint, BlendSetpoint, Configurable, ControlInput, FlightMode, FlightModeReport,
14    FlightRegime, Guidance, ModeRefusal, PlaneSetpoint, Saturation, Setpoint, VehicleState,
15    WaypointCommand, WindEstimate,
16};
17
18mod deceleration;
19#[cfg(test)]
20mod tests;
21
22use deceleration::BackDeceleration;
23
24/// [`QuadPlaneGuidance`] settings: its two guidances', the transition's, forward thrust's, and
25/// the off-nose speed cut's.
26#[derive(Clone, Copy, Debug, Default, PartialEq)]
27pub struct QuadPlaneGuidanceConfig {
28    /// Hover guidance, on the lift rotors.
29    pub hover: CopterGuidanceConfig,
30    /// Wing-borne guidance, on the surfaces and pusher.
31    pub plane: PlaneGuidanceConfig,
32    /// The transition between them, its pusher, handoff blend, and roll limit.
33    pub transition: LiftTransitionConfig,
34    /// The pusher in copter flight; off by default.
35    pub forward: ForwardThrustConfig,
36    /// The waypoint speed cut in copter flight while the nose is off the waypoint; on by
37    /// default.
38    pub off_nose: OffNoseSpeedConfig,
39}
40
41impl QuadPlaneGuidanceConfig {
42    /// `Ok` when each part validates.
43    ///
44    /// # Errors
45    ///
46    /// The first part's [`InvalidConfig`], in its section (`hover`, `plane`, `transition`,
47    /// `forward`, `off_nose`).
48    pub fn validate(&self) -> Result<(), InvalidConfig> {
49        self.hover.validate().map_err(|e| e.in_section("hover"))?;
50        self.plane.validate().map_err(|e| e.in_section("plane"))?;
51        self.transition
52            .validate()
53            .map_err(|e| e.in_section("transition"))?;
54        self.forward
55            .validate()
56            .map_err(|e| e.in_section("forward"))?;
57        self.off_nose
58            .validate()
59            .map_err(|e| e.in_section("off_nose"))
60    }
61}
62
63/// Guidance for a lift+cruise VTOL (quadplane): [`CopterGuidance`] on the lift rotors and
64/// [`PlaneGuidance`] on the surfaces and pusher, with a [`LiftTransition`] choosing between
65/// them and trading the lift across the transitions. The vehicle stays level throughout, so
66/// there's no [`View`](crate::View).
67///
68/// Each tick:
69///
70/// 1. The requested regime is the command's, except that [`ControlInput::Land`] asks for
71///    `Copter`: it lands as a copter, transitioning back first.
72/// 2. The transition steps, unless the bank is past
73///    [`roll_limit_rad`](LiftTransitionConfig::roll_limit_rad) in a transition: then it's cut
74///    short ([`LiftTransition::cut_short`]).
75/// 3. The mode picks the setpoint:
76///
77///    | Mode | Setpoint |
78///    |---|---|
79///    | `Copter` | hover guidance, on the command's input; after a fallback, until `Copter` is requested, a waypoint as a hover where copter flight took over; on a waypoint or land with [`ForwardThrust`] on, [`Setpoint::Blend`] at lift share 1: the hover's attitude with its nose-down pitch held to the limit, the plane side at that roll and pitch, the pusher on the rest |
80///    | `ToPlane` | [`Setpoint::Blend`]: both sides wings level at the plane guidance's pitch for the command, within ArduPilot's transition limits; hover holding the altitude the transition began at, heading held; the pusher on the plane guidance's thrust, rising at most [`pusher_slew_per_s`](LiftTransitionConfig::pusher_slew_per_s), up to [`forward_thrust`](LiftTransitionConfig::forward_thrust); the step's lift share |
81///    | `Plane` | plane guidance, on the command's input |
82///    | `ToCopter` | [`Setpoint::Blend`]: both sides wings level, the nose up to slow it ([`back_decel_mps2`](LiftTransitionConfig::back_decel_mps2)); hover holding the altitude the back transition began at, heading held; the pusher stopped; the step's lift share |
83///
84///    The hover side holds altitude with the copter's altitude loop (ArduPilot holds it through
85///    its airspeed wait, `ArduPlane/quadplane.cpp:1535-1538`). Going forward the pusher and
86///    pitch are the plane's, as ArduPilot flies its throttle and pitch from the plane
87///    controller with pitch held to 0 below 3 m/s of ground speed, ±3° while waiting, and ±8°
88///    on the ramp (`:4747-4766`): its airspeed loop keeps the lift ramp from overspeeding, and
89///    its altitude loop trims the wing. Going back the pusher stops (PX4, `standard.cpp:269`)
90///    and the nose comes up while it slows less than `back_decel_mps2`, at most about 17°
91///    (PX4's back-transition deceleration, `FlightTaskTransition.cpp:112-153`; ArduPilot
92///    decelerates at its `Q_TRANS_DECEL`, `ArduPlane/quadplane.cpp:304`): drag alone left the
93///    Alia at 31 m/s on its 28 s timeout (#496).
94///
95/// 4. A side that starts flying is primed: the plane guidance as the forward transition
96///    begins and again entering `Plane` (through the transition its total energy control flies
97///    from no airspeed, and only its thrust is used), the hover guidance as the back transition
98///    begins. Entering `Plane`, the
99///    pusher's thrust blends from where it was over
100///    [`handoff_s`](LiftTransitionConfig::handoff_s) ([`ThrustHandoff`]).
101///
102///    Forward thrust flies only position-controlled input, as ArduPilot's `Q_FWD_THR_USE` 1
103///    (`ArduPlane/quadplane.cpp:2897-2937`): sticks keep the pilot's tilt. A waypoint in
104///    `Copter` reaches the hover guidance with its speed cut while the nose is off it
105///    ([`OffNoseSpeed`]); land flies uncut, since it lands where the vehicle already is.
106///
107/// Pair it with a [`QuadPlaneStabilizer`](crate::stabilizers::vtol::QuadPlaneStabilizer).
108/// Params chain the parts' (`GUID_*`, `PGUID_*`, `TRAN_*`, `FWD_*`, `OFFNOSE_*`).
109///
110/// # Examples
111///
112/// ```
113/// use stable_flight::guidance::vtol::{QuadPlaneGuidance, QuadPlaneGuidanceConfig};
114/// use stable_flight::{
115///     AttitudeCommand, ControlInput, FlightMode, FlightRegime, Guidance, Setpoint, Vec3,
116///     VehicleState,
117/// };
118///
119/// let mut guidance = QuadPlaneGuidance::new(QuadPlaneGuidanceConfig::default());
120/// guidance.prime(&VehicleState::default());
121///
122/// let sticks = ControlInput::Attitude(AttitudeCommand { throttle: 0.6, ..Default::default() });
123/// let high = VehicleState { position_m: Vec3::new(0.0, 0.0, 20.0), ..Default::default() };
124/// let setpoint = guidance.guide(0.01, FlightRegime::Plane, &sticks, &high);
125/// let Setpoint::Blend(blend) = setpoint else { panic!("{setpoint:?}") };
126/// assert_eq!(blend.lift_share, 1.0); // the lift rotors hold it up while the pusher spins up
127/// assert_eq!(guidance.flight_mode().unwrap().mode, FlightMode::ToPlane);
128/// ```
129pub struct QuadPlaneGuidance {
130    config: QuadPlaneGuidanceConfig,
131    hover: CopterGuidance,
132    plane: PlaneGuidance,
133    transition: LiftTransition,
134    forward: ForwardThrust,
135    off_nose: OffNoseSpeed,
136    handoff: ThrustHandoff,
137    fallback_hold: FallbackHold,
138    deceleration: BackDeceleration,
139    /// The mode the last tick flew.
140    mode: FlightMode,
141    /// The pusher's linear thrust on the last tick.
142    pusher_thrust: f32,
143    /// The altitude a transition holds, latched as it begins, in m.
144    hold_altitude_m: f32,
145}
146
147/// Largest pitch, up or down, while the forward transition waits on airspeed: ArduPilot's
148/// `Q_TRAN_PIT_MAX` (`ArduPlane/quadplane.cpp:143`).
149const WAIT_PITCH_MAX_RAD: f32 = 3.0 * DEG;
150
151/// Largest pitch, up or down, on the forward lift ramp: ArduPilot's `2 (Q_TRAN_PIT_MAX + 1°)`
152/// (`quadplane.cpp:4788`).
153const RAMP_PITCH_MAX_RAD: f32 = 8.0 * DEG;
154
155/// Below this ground speed the forward transition holds pitch at 0, in m/s (ArduPilot,
156/// `quadplane.cpp:4781-4783`).
157const LEVEL_BELOW_MPS: f32 = 3.0;
158
159impl QuadPlaneGuidance {
160    /// Guidance with `config`, in `Copter`.
161    ///
162    /// # Panics
163    ///
164    /// If `config` is invalid ([`QuadPlaneGuidanceConfig::validate`]).
165    pub fn new(config: QuadPlaneGuidanceConfig) -> Self {
166        if let Err(error) = config.validate() {
167            panic!("invalid QuadPlaneGuidanceConfig: {error}");
168        }
169        QuadPlaneGuidance {
170            config,
171            hover: CopterGuidance::new(config.hover),
172            plane: PlaneGuidance::new(config.plane),
173            transition: LiftTransition::new(config.transition),
174            forward: ForwardThrust::new(config.forward),
175            off_nose: OffNoseSpeed::new(config.off_nose),
176            handoff: ThrustHandoff::new(config.transition.handoff_s),
177            fallback_hold: FallbackHold::default(),
178            deceleration: BackDeceleration::default(),
179            mode: FlightMode::Copter,
180            pusher_thrust: 0.0,
181            hold_altitude_m: f32::NAN,
182        }
183    }
184
185    /// This tick's step: the transition cut short if it has banked past the limit, else
186    /// stepped.
187    fn step(
188        &mut self,
189        dt: f32,
190        requested: FlightRegime,
191        state: &VehicleState,
192    ) -> LiftTransitionStep {
193        let transitioning = matches!(self.mode, FlightMode::ToPlane | FlightMode::ToCopter);
194        // `>` is false for NaN: an unknown attitude leaves it to the timeouts.
195        let rolled_over = transitioning
196            && bank_rad(&state.attitude).abs() > self.config.transition.roll_limit_rad;
197        if rolled_over {
198            self.transition.cut_short(ModeRefusal::RollError)
199        } else {
200            self.transition.update(dt, requested, state)
201        }
202    }
203
204    /// Readies the side that starts flying as the mode changes from the last tick's to `to`.
205    fn enter(&mut self, to: FlightMode, state: &VehicleState) {
206        match to {
207            FlightMode::ToPlane => {
208                self.plane.prime(state);
209                self.hold_altitude_m = state.position_m.z;
210                self.pusher_thrust = 0.0;
211            }
212            FlightMode::Plane => {
213                // Fresh either way: out of the back transition it hasn't flown, and out of the
214                // forward one its energy control flew from no airspeed, its demands and
215                // integrals filled by a transition that only took its pusher thrust (the
216                // X-Plane Alia dove 90 m at full nose-down on them, #454). The pusher's
217                // thrust carries over in the handoff below.
218                self.plane.prime(state);
219                self.handoff = ThrustHandoff::new(self.config.transition.handoff_s);
220                self.handoff.start(self.pusher_thrust);
221            }
222            FlightMode::ToCopter if self.mode == FlightMode::Plane => {
223                self.hover.prime(state);
224                self.hold_altitude_m = state.position_m.z;
225                self.deceleration.reset();
226            }
227            _ => {}
228        }
229    }
230
231    /// The hover side through a transition: the hover guidance holding
232    /// [`hold_altitude_m`](Self::hold_altitude_m) where the vehicle is, wings level at
233    /// `pitch_rad`. The waypoint moves with the vehicle at its own velocity, so the lateral loop
234    /// asks for nothing, and its tilt is replaced anyway. Flying it as a waypoint keeps the
235    /// altitude loop's state continuous with waypoint flight on either side of a transition.
236    fn hold_level(&mut self, dt: f32, pitch_rad: f32, state: &VehicleState) -> AttitudeSetpoint {
237        let hold = ControlInput::Waypoint(WaypointCommand {
238            position_m: state.position_m.xy(),
239            velocity_mps: Some(state.velocity_mps.xy()),
240            altitude_m: self.hold_altitude_m,
241            cruise_speed_mps: 0.0,
242            heading_rad: None,
243        });
244        match self.hover.guide(dt, FlightRegime::Copter, &hold, state) {
245            Setpoint::Attitude(setpoint) => AttitudeSetpoint {
246                roll_rad: 0.0,
247                pitch_rad,
248                ..setpoint
249            },
250            _ => unreachable!("copter guidance flies a waypoint as an attitude"),
251        }
252    }
253
254    /// `input` for the wing through the forward transition: a waypoint's altitude replaced by
255    /// [`hold_altitude_m`](Self::hold_altitude_m), the one the lift rotors hold, so the wing
256    /// pitches for level flight and carries the weight as the lift ramps out. Toward a lower
257    /// altitude the wing would pitch nose down while the lift rotors hold, enter plane flight
258    /// sinking and unloaded, and stall pulling out: the sim Alia sank at 19 m/s (#491). A climb
259    /// or descent starts once the wing is flying. PX4 flies the transition at the wing's trim
260    /// pitch whatever the altitude (`vtol_att_control/standard.cpp:240`). Other inputs pass
261    /// through.
262    fn at_held_altitude(&self, input: &ControlInput) -> ControlInput {
263        match input {
264            ControlInput::Waypoint(waypoint) => ControlInput::Waypoint(WaypointCommand {
265                altitude_m: self.hold_altitude_m,
266                ..*waypoint
267            }),
268            _ => *input,
269        }
270    }
271
272    /// The parts whose params chain, in order.
273    fn parts(&self) -> [&dyn Params; 5] {
274        [
275            &self.hover,
276            &self.plane,
277            &self.transition,
278            &self.forward,
279            &self.off_nose,
280        ]
281    }
282
283    /// [`parts`](Self::parts), mutably, in the same order.
284    fn parts_mut(&mut self) -> [&mut dyn Params; 5] {
285        [
286            &mut self.hover,
287            &mut self.plane,
288            &mut self.transition,
289            &mut self.forward,
290            &mut self.off_nose,
291        ]
292    }
293
294    /// Copter flight: the hover guidance on `input`, a waypoint's speed cut while the nose is
295    /// off it ([`OffNoseSpeed`]), its nose-down pitch handed to the pusher on a waypoint or
296    /// land while [`ForwardThrust`] is on.
297    fn copter(&mut self, dt: f32, input: &ControlInput, state: &VehicleState) -> Setpoint {
298        let cut;
299        let flown = match input {
300            ControlInput::Waypoint(waypoint) => {
301                cut = ControlInput::Waypoint(self.off_nose.cap(waypoint, state));
302                &cut
303            }
304            _ => input,
305        };
306        let setpoint = self.hover.guide(dt, FlightRegime::Copter, flown, state);
307        let positioned = matches!(input, ControlInput::Waypoint(_) | ControlInput::Land(_));
308        let (true, Setpoint::Attitude(hover)) = (positioned && self.forward.enabled(), setpoint)
309        else {
310            self.pusher_thrust = 0.0;
311            return setpoint;
312        };
313        let split = self.forward.split(hover.pitch_rad);
314        self.pusher_thrust = split.thrust;
315        Setpoint::Blend(BlendSetpoint {
316            hover: AttitudeSetpoint {
317                pitch_rad: split.pitch_rad,
318                ..hover
319            },
320            plane: PlaneSetpoint {
321                roll_rad: hover.roll_rad,
322                pitch_rad: split.pitch_rad,
323                thrust: split.thrust,
324                ..PlaneSetpoint::default()
325            },
326            lift_share: 1.0,
327        })
328    }
329
330    /// Copies the parts' configs back after a param write, so [`Configurable::config`] stays
331    /// the one view of them.
332    fn sync_config(&mut self) {
333        self.config = QuadPlaneGuidanceConfig {
334            hover: *self.hover.config(),
335            plane: *self.plane.config(),
336            transition: *self.transition.config(),
337            forward: *self.forward.config(),
338            off_nose: *self.off_nose.config(),
339        };
340    }
341}
342
343/// The forward transition's pitch limit, up or down: ArduPilot's transition limits, 0 below
344/// [`LEVEL_BELOW_MPS`] of ground speed, then [`WAIT_PITCH_MAX_RAD`] while the lift rotors carry
345/// it all, [`RAMP_PITCH_MAX_RAD`] on the ramp (`ArduPlane/quadplane.cpp:4779-4789`).
346fn forward_pitch_limit_rad(lift_share: f32, state: &VehicleState) -> f32 {
347    if lift_share < 1.0 {
348        RAMP_PITCH_MAX_RAD
349    } else if state.velocity_mps.xy().norm_squared() >= LEVEL_BELOW_MPS * LEVEL_BELOW_MPS {
350        WAIT_PITCH_MAX_RAD
351    } else {
352        0.0
353    }
354}
355
356/// The forward transition's pitch: the plane guidance's for the command (its altitude loop on
357/// a waypoint, toward the altitude the transition holds; the stick in stabilized flight; 0 for
358/// rates), within `limit_rad` either way.
359fn forward_pitch_rad(wing: &Setpoint, limit_rad: f32) -> f32 {
360    let Setpoint::Plane(plane) = wing else {
361        return 0.0;
362    };
363    saturate_symmetric(plane.pitch_rad, limit_rad)
364}
365
366impl Guidance for QuadPlaneGuidance {
367    fn guide(
368        &mut self,
369        dt: f32,
370        regime: FlightRegime,
371        input: &ControlInput,
372        state: &VehicleState,
373    ) -> Setpoint {
374        let requested = if matches!(input, ControlInput::Land(_)) {
375            FlightRegime::Copter
376        } else {
377            regime
378        };
379        let step = self.step(dt, requested, state);
380        if step.mode != self.mode {
381            self.enter(step.mode, state);
382        }
383        // The drag model needs all thrust along the lift rotors' axis: no transition, and no
384        // pusher thrust on the last tick, which this tick's state still carries.
385        self.hover
386            .set_wind_paused(step.mode != FlightMode::Copter || self.pusher_thrust > 0.0);
387        let transition = self.config.transition;
388
389        let setpoint = match step.mode {
390            FlightMode::ToPlane => {
391                let wing_input = self.at_held_altitude(input);
392                // The plane guidance's energy control flies within the transition's limits, so
393                // its pitch integral stops where the pitch does (`quadplane.cpp:4791-4793`).
394                let limit_rad = forward_pitch_limit_rad(step.lift_share, state);
395                let wing = self.plane.guide_capped(
396                    dt,
397                    FlightRegime::Plane,
398                    &wing_input,
399                    state,
400                    Some(limit_rad),
401                );
402                let rising = self.pusher_thrust + transition.pusher_slew_per_s * dt;
403                self.pusher_thrust = saturate_throttle(wing.thrust())
404                    .min(rising)
405                    .min(transition.forward_thrust);
406                let pitch_rad = forward_pitch_rad(&wing, limit_rad);
407                Setpoint::Blend(BlendSetpoint {
408                    hover: self.hold_level(dt, pitch_rad, state),
409                    plane: PlaneSetpoint {
410                        pitch_rad,
411                        thrust: self.pusher_thrust,
412                        ..PlaneSetpoint::default()
413                    },
414                    lift_share: step.lift_share,
415                })
416            }
417            FlightMode::Plane => {
418                let setpoint = self.plane.guide(dt, FlightRegime::Plane, input, state);
419                let setpoint = if self.handoff.active() {
420                    setpoint.with_thrust(self.handoff.apply(dt, setpoint.thrust()))
421                } else {
422                    setpoint
423                };
424                self.pusher_thrust = setpoint.thrust();
425                setpoint
426            }
427            FlightMode::ToCopter => {
428                self.pusher_thrust = 0.0;
429                let pitch_rad = self.deceleration.pitch_rad(
430                    dt,
431                    state,
432                    transition.back_decel_mps2,
433                    transition.back_decel_i,
434                );
435                Setpoint::Blend(BlendSetpoint {
436                    hover: self.hold_level(dt, pitch_rad, state),
437                    plane: PlaneSetpoint {
438                        pitch_rad,
439                        ..PlaneSetpoint::default()
440                    },
441                    lift_share: step.lift_share,
442                })
443            }
444            _ => {
445                let fallen_back = self.transition.fallen_back();
446                let flown = self.fallback_hold.input(fallen_back, input, state);
447                self.copter(dt, &flown, state)
448            }
449        };
450        self.mode = step.mode;
451        setpoint
452    }
453
454    /// Primes both guidances and the transition (back to `Copter`), and ends any blend.
455    fn prime(&mut self, state: &VehicleState) {
456        self.hover.prime(state);
457        self.plane.prime(state);
458        self.transition.prime(state);
459        self.handoff = ThrustHandoff::new(self.config.transition.handoff_s);
460        self.fallback_hold.clear();
461        self.deceleration.reset();
462        self.mode = FlightMode::Copter;
463        self.pusher_thrust = 0.0;
464        self.hold_altitude_m = f32::NAN;
465    }
466
467    /// The side that flew the last tick: plane in `Plane`, hover otherwise (its altitude loop
468    /// flies the transitions).
469    fn saturation(&self) -> Saturation {
470        match self.mode {
471            FlightMode::Plane => self.plane.saturation(),
472            _ => self.hover.saturation(),
473        }
474    }
475
476    /// The transition's report.
477    fn flight_mode(&self) -> Option<FlightModeReport> {
478        Some(self.transition.report())
479    }
480
481    /// The hover guidance's, updated while it flies.
482    fn wind(&self) -> Option<WindEstimate> {
483        self.hover.wind()
484    }
485}
486
487impl Configurable for QuadPlaneGuidance {
488    type Config = QuadPlaneGuidanceConfig;
489
490    fn config(&self) -> &QuadPlaneGuidanceConfig {
491        &self.config
492    }
493
494    /// Validates the whole config first, then hands each part its own.
495    fn set_config(&mut self, config: QuadPlaneGuidanceConfig) -> Result<(), InvalidConfig> {
496        config.validate()?;
497        self.hover.set_config(config.hover)?;
498        self.plane.set_config(config.plane)?;
499        self.transition.set_config(config.transition)?;
500        self.forward.set_config(config.forward)?;
501        self.off_nose.set_config(config.off_nose)?;
502        self.config = config;
503        Ok(())
504    }
505}
506
507/// The parts' params, chained: hover (`GUID_*`), plane (`PGUID_*`), transition (`TRAN_*`),
508/// forward thrust (`FWD_*`), off-nose speed (`OFFNOSE_*`).
509impl Params for QuadPlaneGuidance {
510    fn param_count(&self) -> usize {
511        self.parts().iter().map(|part| part.param_count()).sum()
512    }
513
514    fn param_name(&self, index: usize) -> Option<&'static str> {
515        let (part, i) = locate(&self.parts(), index)?;
516        self.parts()[part].param_name(i)
517    }
518
519    fn param_at(&self, index: usize) -> Option<f32> {
520        let (part, i) = locate(&self.parts(), index)?;
521        self.parts()[part].param_at(i)
522    }
523
524    fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError> {
525        let (part, i) = locate(&self.parts(), index).ok_or(ParamError::Unknown)?;
526        let result = self.parts_mut()[part].set_param_at(i, value);
527        self.sync_config();
528        result
529    }
530}