Skip to main content

stable_flight/guidance/vtol/
tailsitter.rs

1//! [`TailsitterGuidance`]: hover and plane guidance under one [`Transition`].
2
3use core::f32::consts::FRAC_PI_2;
4
5use super::{FallbackHold, ThrustHandoff, Transition, TransitionConfig, TransitionStep};
6use crate::controllers::InvalidConfig;
7use crate::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
8use crate::guidance::plane::{PlaneGuidance, PlaneGuidanceConfig};
9use crate::math::{bank_rad, guard_sink};
10use crate::params::{ParamError, Params, locate};
11use crate::{
12    AbsoluteAttitudeCommand, AttitudeSetpoint, Configurable, ControlInput, FlightMode,
13    FlightModeReport, FlightRegime, Guidance, ModeRefusal, PlaneSetpoint, Saturation, Setpoint,
14    VehicleState, View, WindEstimate,
15};
16
17#[cfg(test)]
18mod tests;
19
20/// [`TailsitterGuidance`] settings: its two guidances' and the transition's.
21#[derive(Clone, Copy, Debug, Default, PartialEq)]
22pub struct TailsitterGuidanceConfig {
23    /// Hover guidance, flown in the tailsitter [`View`].
24    pub hover: CopterGuidanceConfig,
25    /// Wing-borne guidance, in the airplane frame.
26    pub plane: PlaneGuidanceConfig,
27    /// The transition between them, its thrusts, handoff blend, and roll limit.
28    pub transition: TransitionConfig,
29}
30
31impl TailsitterGuidanceConfig {
32    /// `Ok` when each part validates.
33    ///
34    /// # Errors
35    ///
36    /// The first part's [`InvalidConfig`], in its section (`hover`, `plane`, `transition`).
37    pub fn validate(&self) -> Result<(), InvalidConfig> {
38        self.hover.validate().map_err(|e| e.in_section("hover"))?;
39        self.plane.validate().map_err(|e| e.in_section("plane"))?;
40        self.transition
41            .validate()
42            .map_err(|e| e.in_section("transition"))
43    }
44}
45
46/// Guidance for a tailsitter: hover guidance (copter guidance in the tailsitter [`View`]) and
47/// [`PlaneGuidance`], with a [`Transition`] choosing between them and flying the transitions.
48///
49/// Each tick:
50///
51/// 1. The requested regime is the command's, except that [`ControlInput::Land`] asks for
52///    `Copter`: a tailsitter lands as a copter, transitioning back first.
53/// 2. The transition steps, unless it has rolled past
54///    [`roll_limit_rad`](TransitionConfig::roll_limit_rad): then it's cut short
55///    ([`Transition::cut_short`]), checked first because a sideways lean also tilts the nose
56///    from vertical, which would count as progress. The roll is the hover view's going
57///    forward and the airplane's bank coming back (ArduPilot `tailsitter.cpp`,
58///    `transition_fw_complete` and `transition_vtol_complete`).
59/// 3. The mode picks the setpoint:
60///
61///    | Mode | Setpoint |
62///    |---|---|
63///    | `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 |
64///    | `ToPlane` | hover guidance on an absolute attitude: wings level, view pitch −tilt, heading held, thrust the larger of [`forward_thrust`](TransitionConfig::forward_thrust) and the hover thrust when it began; a [`transition`](AttitudeSetpoint::transition) ramp |
65///    | `Plane` | plane guidance, on the command's input |
66///    | `ToCopter` | plane guidance on an absolute attitude: wings level, pitch π/2 − tilt, [`back_thrust`](TransitionConfig::back_thrust) raised while sinking past [`back_sink_limit_mps`](TransitionConfig::back_sink_limit_mps); a [`transition`](PlaneSetpoint::transition) ramp |
67///
68///    A ramp's pitch isn't held to the stabilizer's limits (hover tilt, plane pitch), which
69///    would stop it short of completing.
70///
71/// 4. On a handoff (`ToPlane` → `Plane`, `ToCopter` → `Copter`) the incoming guidance is
72///    primed, and thrust blends from its last value over
73///    [`handoff_s`](TransitionConfig::handoff_s) ([`ThrustHandoff`]).
74/// 5. After the handoff into `Plane`, stick throttle (attitude or rate sticks) is held at
75///    least at the plane's [`cruise_thrust`](PlaneGuidanceConfig::cruise_thrust) until the
76///    stick reaches it: the forward ramp flies a fixed thrust and ignores the stick, so a stick
77///    left low would otherwise cut thrust as the wing takes over. Offboard thrust is flown as
78///    given.
79///
80/// Pair it with a [`TailsitterStabilizer`](crate::stabilizers::vtol::TailsitterStabilizer),
81/// which flies each setpoint on the matching side. Params chain the parts' (`GUID_*`,
82/// `PGUID_*`, `TRAN_*`).
83///
84/// # Examples
85///
86/// ```
87/// use stable_flight::guidance::vtol::{TailsitterGuidance, TailsitterGuidanceConfig};
88/// use stable_flight::nalgebra::UnitQuaternion;
89/// use stable_flight::{
90///     AttitudeCommand, ControlInput, FlightMode, FlightRegime, Guidance, Setpoint, Vec3,
91///     VehicleState,
92/// };
93///
94/// let mut guidance = TailsitterGuidance::new(TailsitterGuidanceConfig::default());
95/// let hover = VehicleState {
96///     attitude: UnitQuaternion::from_euler_angles(0.0, core::f32::consts::FRAC_PI_2, 0.0),
97///     ..Default::default()
98/// };
99/// guidance.prime(&hover);
100///
101/// let sticks = ControlInput::Attitude(AttitudeCommand { throttle: 0.6, ..Default::default() });
102/// let high = VehicleState { position_m: Vec3::new(0.0, 0.0, 20.0), ..hover };
103/// let setpoint = guidance.guide(0.01, FlightRegime::Plane, &sticks, &high);
104/// assert!(matches!(setpoint, Setpoint::Attitude(_))); // the hover side flies the ramp
105/// assert_eq!(guidance.flight_mode().unwrap().mode, FlightMode::ToPlane);
106/// ```
107pub struct TailsitterGuidance {
108    config: TailsitterGuidanceConfig,
109    hover: View<CopterGuidance>,
110    plane: PlaneGuidance,
111    transition: Transition,
112    handoff: ThrustHandoff,
113    fallback_hold: FallbackHold,
114    /// The mode the last tick flew.
115    mode: FlightMode,
116    /// The last setpoint's thrust: where a handoff blend starts.
117    last_thrust: f32,
118    /// The forward ramp's thrust, set when it begins.
119    forward_thrust: f32,
120    /// Least stick thrust after a handoff into `Plane`, until the stick reaches it.
121    throttle_floor: Option<f32>,
122    /// The back ramp's sink guard raised its thrust on the last tick.
123    sink_guarded: bool,
124}
125
126impl TailsitterGuidance {
127    /// Guidance with `config`, in `Copter`.
128    ///
129    /// # Panics
130    ///
131    /// If `config` is invalid ([`TailsitterGuidanceConfig::validate`]).
132    pub fn new(config: TailsitterGuidanceConfig) -> Self {
133        if let Err(error) = config.validate() {
134            panic!("invalid TailsitterGuidanceConfig: {error}");
135        }
136        TailsitterGuidance {
137            config,
138            hover: View::tailsitter(CopterGuidance::new(config.hover)),
139            plane: PlaneGuidance::new(config.plane),
140            transition: Transition::new(config.transition),
141            handoff: ThrustHandoff::new(config.transition.handoff_s),
142            fallback_hold: FallbackHold::default(),
143            mode: FlightMode::Copter,
144            last_thrust: 0.0,
145            forward_thrust: 0.0,
146            throttle_floor: None,
147            sink_guarded: false,
148        }
149    }
150
151    /// This tick's step: the transition cut short if it has rolled past the limit, else
152    /// stepped. The check comes first: a sideways lean also tilts the nose from vertical,
153    /// which the transition would otherwise count as progress.
154    fn step(&mut self, dt: f32, requested: FlightRegime, state: &VehicleState) -> TransitionStep {
155        let attitude = match self.mode {
156            // The hover view's roll: the thrust axis leaning out of the ramp's plane.
157            FlightMode::ToPlane => Some(state.attitude * self.hover.rotation()),
158            // The airplane's bank.
159            FlightMode::ToCopter => Some(state.attitude),
160            _ => None,
161        };
162        // `>` is false for NaN: an unknown attitude leaves it to the timeout.
163        let rolled_over = attitude.is_some_and(|attitude| {
164            bank_rad(&attitude).abs() > self.config.transition.roll_limit_rad
165        });
166        if rolled_over {
167            self.transition.cut_short(ModeRefusal::RollError)
168        } else {
169            self.transition.update(dt, requested, state)
170        }
171    }
172
173    /// Primes the guidance taking over at a handoff and starts the thrust blend.
174    fn hand_off(&mut self, to: FlightMode, state: &VehicleState) {
175        match to {
176            FlightMode::Plane => {
177                self.plane.prime(state);
178                self.throttle_floor = Some(self.config.plane.cruise_thrust);
179            }
180            _ => self.hover.prime(state),
181        }
182        self.handoff = ThrustHandoff::new(self.config.transition.handoff_s);
183        self.handoff.start(self.last_thrust);
184    }
185
186    /// `setpoint` with stick throttle held at the floor set by the handoff into `Plane`, until
187    /// the stick reaches it; offboard thrust passes through.
188    fn floor_stick_throttle(&mut self, setpoint: Setpoint, input: &ControlInput) -> Setpoint {
189        let Some(floor) = self.throttle_floor else {
190            return setpoint;
191        };
192        if !input.is_sticks() || setpoint.thrust() >= floor {
193            self.throttle_floor = None;
194            return setpoint;
195        }
196        setpoint.with_thrust(floor)
197    }
198
199    /// The back ramp's thrust: [`back_thrust`](TransitionConfig::back_thrust), raised by the
200    /// sink guard while sinking past its limit.
201    fn back_thrust(&mut self, state: &VehicleState) -> f32 {
202        let transition = &self.config.transition;
203        let guarded = guard_sink(
204            transition.back_thrust,
205            state.velocity_mps.z,
206            transition.back_sink_limit_mps,
207            transition.back_sink_gain,
208        );
209        self.sink_guarded = guarded.is_some();
210        guarded.unwrap_or(transition.back_thrust)
211    }
212
213    /// Copies the parts' configs back after a param write, so [`Configurable::config`] stays
214    /// the one view of them.
215    fn sync_config(&mut self) {
216        self.config = TailsitterGuidanceConfig {
217            hover: *self.hover.config(),
218            plane: *self.plane.config(),
219            transition: *self.transition.config(),
220        };
221    }
222}
223
224/// `setpoint` marked as a transition ramp, so the stabilizer flies its pitch past the side's
225/// limit to the handover.
226fn transition_ramp(setpoint: Setpoint) -> Setpoint {
227    match setpoint {
228        Setpoint::Attitude(attitude) => Setpoint::Attitude(AttitudeSetpoint {
229            transition: true,
230            ..attitude
231        }),
232        Setpoint::Plane(plane) => Setpoint::Plane(PlaneSetpoint {
233            transition: true,
234            ..plane
235        }),
236        other => other,
237    }
238}
239
240impl Guidance for TailsitterGuidance {
241    fn guide(
242        &mut self,
243        dt: f32,
244        regime: FlightRegime,
245        input: &ControlInput,
246        state: &VehicleState,
247    ) -> Setpoint {
248        let requested = if matches!(input, ControlInput::Land(_)) {
249            FlightRegime::Copter
250        } else {
251            regime
252        };
253        let step = self.step(dt, requested, state);
254        if step.handoff {
255            self.hand_off(step.mode, state);
256        }
257        // The drag model holds in hover only, not pitched over with the wing lifting.
258        self.hover
259            .inner_mut()
260            .set_wind_paused(step.mode != FlightMode::Copter);
261        if step.mode == FlightMode::ToPlane && self.mode != FlightMode::ToPlane {
262            self.forward_thrust = self.last_thrust.max(self.config.transition.forward_thrust);
263        }
264        self.sink_guarded = false;
265        let tilt_rad = step.tilt_target_rad.unwrap_or(0.0);
266
267        let setpoint = match step.mode {
268            FlightMode::ToPlane => {
269                let ramp = ControlInput::AbsoluteAttitude(AbsoluteAttitudeCommand {
270                    roll_rad: 0.0,
271                    pitch_rad: -tilt_rad,
272                    heading_rad: f32::NAN,
273                    thrust: self.forward_thrust,
274                });
275                transition_ramp(self.hover.guide(dt, FlightRegime::Copter, &ramp, state))
276            }
277            FlightMode::Plane => {
278                let setpoint = self.plane.guide(dt, FlightRegime::Plane, input, state);
279                self.floor_stick_throttle(setpoint, input)
280            }
281            FlightMode::ToCopter => {
282                let ramp = ControlInput::AbsoluteAttitude(AbsoluteAttitudeCommand {
283                    roll_rad: 0.0,
284                    pitch_rad: FRAC_PI_2 - tilt_rad,
285                    heading_rad: f32::NAN,
286                    thrust: self.back_thrust(state),
287                });
288                transition_ramp(self.plane.guide(dt, FlightRegime::Plane, &ramp, state))
289            }
290            _ => {
291                let fallen_back = self.transition.fallen_back();
292                let flown = self.fallback_hold.input(fallen_back, input, state);
293                self.hover.guide(dt, FlightRegime::Copter, &flown, state)
294            }
295        };
296        let setpoint = if self.handoff.active() {
297            setpoint.with_thrust(self.handoff.apply(dt, setpoint.thrust()))
298        } else {
299            setpoint
300        };
301        if step.mode != FlightMode::Plane {
302            self.throttle_floor = None;
303        }
304        self.mode = step.mode;
305        self.last_thrust = setpoint.thrust();
306        setpoint
307    }
308
309    /// Primes both guidances and the transition (back to `Copter`), and ends any blend.
310    fn prime(&mut self, state: &VehicleState) {
311        self.hover.prime(state);
312        self.plane.prime(state);
313        self.transition.prime(state);
314        self.handoff = ThrustHandoff::new(self.config.transition.handoff_s);
315        self.fallback_hold.clear();
316        self.mode = FlightMode::Copter;
317        self.last_thrust = 0.0;
318        self.throttle_floor = None;
319        self.sink_guarded = false;
320    }
321
322    /// The side that flew the last tick: hover in `Copter` and `ToPlane`, plane otherwise.
323    /// `thrust` is also set while the back ramp's sink guard raises its thrust.
324    fn saturation(&self) -> Saturation {
325        match self.mode {
326            FlightMode::Plane => self.plane.saturation(),
327            FlightMode::ToCopter => {
328                let saturation = self.plane.saturation();
329                Saturation {
330                    thrust: saturation.thrust || self.sink_guarded,
331                    ..saturation
332                }
333            }
334            _ => self.hover.saturation(),
335        }
336    }
337
338    /// The transition's report.
339    fn flight_mode(&self) -> Option<FlightModeReport> {
340        Some(self.transition.report())
341    }
342
343    /// The hover guidance's, updated while it flies.
344    fn wind(&self) -> Option<WindEstimate> {
345        self.hover.wind()
346    }
347}
348
349impl Configurable for TailsitterGuidance {
350    type Config = TailsitterGuidanceConfig;
351
352    fn config(&self) -> &TailsitterGuidanceConfig {
353        &self.config
354    }
355
356    /// Validates the whole config first, then hands each part its own.
357    fn set_config(&mut self, config: TailsitterGuidanceConfig) -> Result<(), InvalidConfig> {
358        config.validate()?;
359        self.hover.set_config(config.hover)?;
360        self.plane.set_config(config.plane)?;
361        self.transition.set_config(config.transition)?;
362        self.config = config;
363        Ok(())
364    }
365}
366
367/// The parts' params, chained: hover (`GUID_*`), plane (`PGUID_*`), transition (`TRAN_*`).
368impl Params for TailsitterGuidance {
369    fn param_count(&self) -> usize {
370        self.hover.param_count() + self.plane.param_count() + self.transition.param_count()
371    }
372
373    fn param_name(&self, index: usize) -> Option<&'static str> {
374        match locate(&[&self.hover, &self.plane, &self.transition], index)? {
375            (0, i) => self.hover.param_name(i),
376            (1, i) => self.plane.param_name(i),
377            (_, i) => self.transition.param_name(i),
378        }
379    }
380
381    fn param_at(&self, index: usize) -> Option<f32> {
382        match locate(&[&self.hover, &self.plane, &self.transition], index)? {
383            (0, i) => self.hover.param_at(i),
384            (1, i) => self.plane.param_at(i),
385            (_, i) => self.transition.param_at(i),
386        }
387    }
388
389    fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError> {
390        let parts: [&dyn Params; 3] = [&self.hover, &self.plane, &self.transition];
391        let result = match locate(&parts, index).ok_or(ParamError::Unknown)? {
392            (0, i) => self.hover.set_param_at(i, value),
393            (1, i) => self.plane.set_param_at(i, value),
394            (_, i) => self.transition.set_param_at(i, value),
395        };
396        self.sync_config();
397        result
398    }
399}