stable_flight/guidance/vtol.rs
1//! Copter ⇄ plane transitions for a VTOL: [`Transition`] decides the [`FlightMode`] each tick
2//! from the requested [`FlightRegime`] and the vehicle's tilt, and ramps a tilt target for the
3//! controller flying the transition; [`ThrustHandoff`] blends thrust when control passes from
4//! one controller to the other.
5//!
6//! Both are pure building blocks for a VTOL guidance ([`TailsitterGuidance`]): they build no
7//! setpoints and know no frames. The tilt is the nose's (body `x`) angle from vertical: 0 in hover,
8//! π/2 in level forward flight. A tailsitter's hover controller, in its
9//! [`View`](crate::View), flies view pitch `−tilt`; its plane controller flies airplane pitch
10//! `π/2 − tilt`.
11//!
12//! A lift+cruise VTOL (quadplane) stays level and flies both sides at once, trading lift
13//! between its lift rotors and its wing: [`LiftTransition`] is its state machine.
14//!
15//! # Modes
16//!
17//! The request is a level, so a repeated request finds the same row and a running ramp
18//! continues. First matching row wins:
19//!
20//! | Mode | Condition | Next | Handoff | Refusal reported |
21//! |---|---|---|---|---|
22//! | `Copter` | `Copter` requested | `Copter` | | none; clears a timeout |
23//! | `Copter` | `Plane` requested after a fallback | `Copter` | | why: `TransitionTimeout`, `RollError`, `BelowPlaneMinAltitude` |
24//! | `Copter` | `Plane` requested below `min_height_m` or `plane_min_height_m` (or NaN altitude) | `Copter` | | `BelowMinAltitude` |
25//! | `Copter` | `Plane` requested | `ToPlane`, ramp from the current tilt | | |
26//! | `ToPlane` | `Copter` requested | `Copter` (same hover controller) | | |
27//! | `ToPlane` | tilt ≥ `forward_done_rad` and airspeed ≥ `min_airspeed_mps` (when valid) | `Plane` | yes | |
28//! | `ToPlane` | longer than `timeout_s` | `Copter` | | `TransitionTimeout` |
29//! | `Plane` | `Copter` requested | `ToCopter`, ramp from the current tilt | | |
30//! | `Plane` | below `plane_min_height_m` | `ToCopter`, a fallback | | `BelowPlaneMinAltitude` |
31//! | `ToCopter` | `Plane` requested, and no fallback | `Plane` (same plane controller) | | |
32//! | `ToCopter` | tilt ≤ `back_done_rad`, or longer than `timeout_s` | `Copter` | yes | |
33//!
34//! The caller can cut a transition short ([`Transition::cut_short`], e.g. on a roll error it
35//! measures): forward is abandoned like a timeout, back completes with a handoff.
36//!
37//! A fallback is a forward transition abandoned (timed out or cut short) or plane flight
38//! below `plane_min_height_m` sent back to copter (a quadchute). After one, `Plane` is
39//! refused until `Copter` is requested (`ToCopter` completes as if it were, reporting the
40//! fallback), and the VTOL guidance flies a waypoint as a hover where copter flight took
41//! over, so a plane leg's distant waypoint isn't chased on the rotors. A standing `Plane` request refused for height starts the transition once
42//! the vehicle climbs past both heights.
43//! Height is above the altitude at [`prime`](Transition::prime) (where the vehicle armed);
44//! before the first `prime` there is none, and `Plane` is refused.
45//! A `Land` input means `Copter`: the guidance driving this passes that as the request.
46//!
47//! # Sources
48//!
49//! ArduPilot (master `e506f3a`) and PX4 (main `edeba2f`), described, not copied:
50//!
51//! - Both fly the forward transition on the hover controller, pitching the nose down at a
52//! fixed rate, and complete on pitch: ArduPilot at `Q_TAILSIT_ANGLE` (45°) from vertical
53//! (`ArduPlane/tailsitter.cpp:40`, `:537`), PX4 at −60° in its hover frame plus airspeed
54//! when valid (`vtol_att_control/tailsitter.h:52`, `tailsitter.cpp:379-396`).
55//! - ArduPilot ramps at `Q_TAILSIT_RAT_FW`/`RAT_VT` (50°/s each, `tailsitter.cpp:128`,
56//! `:135`) and hands back to hover at `Q_TAILSIT_ANG_VT`, which defaults to the forward
57//! angle (`:47`).
58//! - A forward timeout reverts to hover in PX4 (`VT_TRANS_TIMEOUT` 15 s,
59//! `vtol_att_control_params.yaml:92-98`, then quadchute), where ArduPilot completes it
60//! (`tailsitter.cpp:546`); a back timeout completes in both (`tailsitter.cpp:586`).
61//! - PX4 falls back to hover below `VT_FW_MIN_ALT` (off by default) in plane flight and the
62//! transitions, latched until plane flight is requested again, then by default returns home
63//! (`vtol_type.cpp:231-243`, `vtol_att_control_main.cpp:195-244`, commander `COM_QC_ACT`);
64//! it switches to hover at once, where here the back transition flies, and only plane
65//! flight is watched: a forward transition starts above the floor and holds height.
66//! ArduPilot instead assists on the lift motors below `Q_ASSIST_ALT` and stays in plane
67//! flight (`VTOL_Assist.cpp:16-45`, `:109`).
68//! - PX4 blends thrust over 0.5 s when the back transition takes over from the plane
69//! controller (`tailsitter.h:58`).
70//! - Through the back ramp ArduPilot flies a fixed throttle (`Q_TAILSIT_THR_VT`, by default
71//! the hover throttle, at least cruise; `tailsitter.cpp:137-142`, `:306-341`) with no
72//! altitude loop; PX4 flies its hover vertical-speed loop, its setpoint decaying to 0
73//! (`FlightTaskTransition.cpp:50-86`, main `e146fe4`). Here the thrust is fixed and raised
74//! only while sinking: one side of PX4's loop, since a climb costs height and a sink can
75//! end in the ground.
76
77use core::f32::consts::FRAC_PI_2;
78
79use crate::controllers::{InvalidConfig, check, check_limit, check_positive};
80use crate::math::{assert_dt, nose_up_cosine, saturate_throttle};
81use crate::{
82 Configurable, ControlInput, FlightMode, FlightModeReport, FlightRegime, ModeRefusal,
83 VehicleState, WaypointCommand,
84};
85
86mod forward;
87mod lift;
88mod off_nose;
89mod params;
90mod quadplane;
91mod tailsitter;
92
93pub use forward::{ForwardSplit, ForwardThrust, ForwardThrustConfig};
94pub use lift::{LiftTransition, LiftTransitionConfig, LiftTransitionStep};
95pub use off_nose::{DEFAULT_OFF_NOSE_SPEED_MPS, OffNoseSpeed, OffNoseSpeedConfig};
96pub use quadplane::{QuadPlaneGuidance, QuadPlaneGuidanceConfig};
97pub use tailsitter::{TailsitterGuidance, TailsitterGuidanceConfig};
98#[cfg(test)]
99mod tests;
100
101/// Transition settings: what [`Transition`] uses (ramp rates, completion tilts, the airspeed
102/// gate, the timeout, the height a forward transition needs) and what the VTOL guidance around
103/// it applies (thrusts, the handoff blend, the roll limit). Angles are the nose's tilt from
104/// vertical. Each field is checked on its own: a `forward_max_tilt_rad` below
105/// `forward_done_rad` is accepted, and leaves the forward transition to its timeout.
106#[derive(Debug, Clone, Copy, PartialEq)]
107pub struct TransitionConfig {
108 /// How fast the forward (nose-down) tilt target ramps, in rad/s.
109 pub forward_rate_radps: f32,
110 /// The tilt from vertical that completes the forward transition, in radians, in
111 /// `(0, π/2)`.
112 pub forward_done_rad: f32,
113 /// Where the forward ramp stops while the transition waits on airspeed, in radians, in
114 /// `(0, π/2]`; at least `forward_done_rad` for the ramp to reach completion.
115 pub forward_max_tilt_rad: f32,
116 /// The airspeed the forward transition also needs when the state has a valid one, in m/s;
117 /// `0` turns the gate off.
118 pub min_airspeed_mps: f32,
119 /// How fast the back (nose-up) tilt target ramps, in rad/s.
120 pub back_rate_radps: f32,
121 /// The tilt from vertical that completes the back transition, in radians, in `(0, π/2)`.
122 pub back_done_rad: f32,
123 /// The longest either transition runs, in seconds: forward falls back to copter, back
124 /// completes.
125 pub timeout_s: f32,
126 /// The height above the arming altitude a forward transition needs to start, in meters.
127 pub min_height_m: f32,
128 /// The height above the arming altitude plane flight falls back to copter below, in
129 /// meters; a forward transition also needs it to start. Higher: falls back sooner, with
130 /// more height to lose in the back transition (3.3 m at a 4.6 m/s sink on the sim
131 /// tailsitter). `0` turns it off.
132 pub plane_min_height_m: f32,
133 /// Least linear thrust through the forward transition, `[0, 1]`: the hover thrust when it
134 /// began, if higher, holds.
135 pub forward_thrust: f32,
136 /// Linear thrust through the back transition, `[0, 1]`, raised while sinking past
137 /// [`back_sink_limit_mps`](Self::back_sink_limit_mps).
138 pub back_thrust: f32,
139 /// Sink rate past which the back transition gets more thrust than
140 /// [`back_thrust`](Self::back_thrust), in m/s: [`back_sink_gain`](Self::back_sink_gain)
141 /// per m/s of sink past it. Slowing nose-high with too little thrust, the wing stalls and
142 /// the vehicle falls; this catches it. Non-negative; `0` turns it off.
143 pub back_sink_limit_mps: f32,
144 /// Thrust added per m/s of sink past [`back_sink_limit_mps`](Self::back_sink_limit_mps),
145 /// in s/m. Non-negative.
146 pub back_sink_gain: f32,
147 /// How long thrust blends from one controller to the other at a handoff, in seconds
148 /// ([`ThrustHandoff`]); 0 switches at once.
149 pub handoff_s: f32,
150 /// Roll error past which a transition is cut short, in radians, in `(0, π]`: forward
151 /// aborts to copter, back completes ([`Transition::cut_short`]).
152 pub roll_limit_rad: f32,
153}
154
155impl TransitionConfig {
156 /// `Ok` when every field is in range (see each field).
157 ///
158 /// # Errors
159 ///
160 /// [`InvalidConfig`] naming the first field out of range.
161 pub fn validate(&self) -> Result<(), InvalidConfig> {
162 let in_quarter_turn = |value: f32| value > 0.0 && value < FRAC_PI_2;
163 check_positive("forward_rate_radps", self.forward_rate_radps)?;
164 check(
165 "forward_done_rad",
166 in_quarter_turn(self.forward_done_rad),
167 "in (0, π/2) rad",
168 )?;
169 check(
170 "forward_max_tilt_rad",
171 self.forward_max_tilt_rad > 0.0 && self.forward_max_tilt_rad <= FRAC_PI_2,
172 "in (0, π/2] rad",
173 )?;
174 check_limit("min_airspeed_mps", self.min_airspeed_mps)?;
175 check_positive("back_rate_radps", self.back_rate_radps)?;
176 check(
177 "back_done_rad",
178 in_quarter_turn(self.back_done_rad),
179 "in (0, π/2) rad",
180 )?;
181 check_positive("timeout_s", self.timeout_s)?;
182 check_limit("min_height_m", self.min_height_m)?;
183 check_limit("plane_min_height_m", self.plane_min_height_m)?;
184 let unit = |value: f32| (0.0..=1.0).contains(&value);
185 check("forward_thrust", unit(self.forward_thrust), "in [0, 1]")?;
186 check("back_thrust", unit(self.back_thrust), "in [0, 1]")?;
187 check_limit("back_sink_limit_mps", self.back_sink_limit_mps)?;
188 check_limit("back_sink_gain", self.back_sink_gain)?;
189 check_limit("handoff_s", self.handoff_s)?;
190 check(
191 "roll_limit_rad",
192 self.roll_limit_rad > 0.0 && self.roll_limit_rad <= core::f32::consts::PI,
193 "in (0, π] rad",
194 )
195 }
196}
197
198impl Default for TransitionConfig {
199 /// ArduPilot's tailsitter rates and angles (50°/s each way, complete at 45° from vertical
200 /// both ways) and roll limit (45°), the forward ramp stopping at 80°, PX4's 15 s timeout
201 /// and 0.5 s thrust blend, no airspeed gate, 5 m of height, no plane minimum height (PX4's
202 /// `VT_FW_MIN_ALT`), half thrust each way (an airframe sets its own), and a back sink guard
203 /// of 0.4 per m/s past 1 m/s; see the [module sources](self#sources).
204 fn default() -> Self {
205 TransitionConfig {
206 forward_rate_radps: 50.0_f32.to_radians(),
207 forward_done_rad: 45.0_f32.to_radians(),
208 forward_max_tilt_rad: 80.0_f32.to_radians(),
209 min_airspeed_mps: 0.0,
210 back_rate_radps: 50.0_f32.to_radians(),
211 back_done_rad: 45.0_f32.to_radians(),
212 timeout_s: 15.0,
213 min_height_m: 5.0,
214 plane_min_height_m: 0.0,
215 forward_thrust: 0.5,
216 back_thrust: 0.5,
217 // Measured on the sim tailsitter (#343): a 25°/s ramp at thrust 0.3–0.5, which
218 // without it stalls nose-high and falls 30 m, hands over climbing at most 7 m.
219 back_sink_limit_mps: 1.0,
220 back_sink_gain: 0.4,
221 handoff_s: 0.5,
222 roll_limit_rad: 45.0_f32.to_radians(),
223 }
224 }
225}
226
227/// What [`Transition::update`] decided this tick.
228#[derive(Debug, Clone, Copy, PartialEq)]
229pub struct TransitionStep {
230 /// The mode to fly this tick.
231 pub mode: FlightMode,
232 /// While transitioning, the nose's tilt from vertical to fly, in radians: ramping toward
233 /// plane flight in `ToPlane`, toward hover in `ToCopter`. `None` otherwise.
234 pub tilt_target_rad: Option<f32>,
235 /// Control passed between the hover and the plane controller this tick
236 /// (`ToPlane` → `Plane`, `ToCopter` → `Copter`): prime the incoming one and start a
237 /// [`ThrustHandoff`].
238 pub handoff: bool,
239}
240
241/// The copter ⇄ plane transition state machine: owns the [`FlightMode`]. See the
242/// [module docs](self) for the rows it follows.
243///
244/// Call [`prime`](Self::prime) when the vehicle arms, then [`update`](Self::update) every
245/// armed tick. Allocation-free and trig-free per tick (one `acos` when a ramp starts).
246///
247/// # Examples
248///
249/// ```
250/// use stable_flight::guidance::vtol::{Transition, TransitionConfig};
251/// use stable_flight::nalgebra::UnitQuaternion;
252/// use stable_flight::{FlightMode, FlightRegime, Vec3, VehicleState};
253///
254/// // Hovering nose up, 10 m above where it armed.
255/// let hover = VehicleState {
256/// attitude: UnitQuaternion::from_euler_angles(0.0, core::f32::consts::FRAC_PI_2, 0.0),
257/// ..Default::default()
258/// };
259/// let mut transition = Transition::new(TransitionConfig::default());
260/// transition.prime(&hover);
261///
262/// let climbed = VehicleState { position_m: Vec3::new(0.0, 0.0, 10.0), ..hover };
263/// let step = transition.update(0.01, FlightRegime::Plane, &climbed);
264/// assert_eq!(step.mode, FlightMode::ToPlane);
265/// assert!(step.tilt_target_rad.unwrap() > 0.0); // nose starting down
266/// ```
267#[derive(Debug, Clone, PartialEq)]
268pub struct Transition {
269 config: TransitionConfig,
270 forward_done_cosine: f32,
271 back_done_cosine: f32,
272 mode: FlightMode,
273 refusal: Option<ModeRefusal>,
274 gate: ForwardGate,
275 elapsed_s: f32,
276 start_tilt_rad: f32,
277}
278
279impl Transition {
280 /// A transition in `Copter` with `config`. Until [`prime`](Self::prime) sets the arming
281 /// altitude it has no height reference, so it refuses `Plane` as `BelowMinAltitude`.
282 ///
283 /// # Panics
284 ///
285 /// If `config` is invalid ([`TransitionConfig::validate`]).
286 pub fn new(config: TransitionConfig) -> Self {
287 if let Err(error) = config.validate() {
288 panic!("invalid TransitionConfig: {error}");
289 }
290 let (forward_done_cosine, back_done_cosine) = done_cosines(&config);
291 Transition {
292 config,
293 forward_done_cosine,
294 back_done_cosine,
295 mode: FlightMode::Copter,
296 refusal: None,
297 gate: ForwardGate::new(),
298 elapsed_s: 0.0,
299 start_tilt_rad: 0.0,
300 }
301 }
302
303 /// Back to `Copter` with no refusal or timeout, and `state`'s altitude as the height
304 /// reference. Call when the vehicle arms.
305 pub fn prime(&mut self, state: &VehicleState) {
306 self.mode = FlightMode::Copter;
307 self.refusal = None;
308 self.elapsed_s = 0.0;
309 self.gate.prime(state);
310 }
311
312 /// Moves toward `requested` and returns this tick's mode and tilt target.
313 ///
314 /// # Panics
315 ///
316 /// If `dt` isn't positive and finite.
317 pub fn update(
318 &mut self,
319 dt: f32,
320 requested: FlightRegime,
321 state: &VehicleState,
322 ) -> TransitionStep {
323 assert_dt(dt);
324 let nose_up = nose_up_cosine(&state.attitude);
325 self.refusal = None;
326 let mut handoff = false;
327
328 match self.mode {
329 FlightMode::Copter => match requested {
330 FlightRegime::Plane => self.try_forward(state, nose_up),
331 FlightRegime::Copter => self.gate.clear(),
332 },
333 FlightMode::ToPlane => {
334 self.elapsed_s += dt;
335 if requested != FlightRegime::Plane {
336 self.mode = FlightMode::Copter;
337 } else if self.forward_done(state, nose_up) {
338 self.mode = FlightMode::Plane;
339 handoff = true;
340 } else if self.elapsed_s > self.config.timeout_s {
341 self.abandon(ModeRefusal::TransitionTimeout);
342 }
343 }
344 FlightMode::Plane => {
345 if requested != FlightRegime::Plane {
346 self.start(FlightMode::ToCopter, nose_up);
347 } else if self.gate.below(state, self.config.plane_min_height_m) {
348 self.start(FlightMode::ToCopter, nose_up);
349 self.gate.abandon(ModeRefusal::BelowPlaneMinAltitude);
350 self.refusal = Some(ModeRefusal::BelowPlaneMinAltitude);
351 }
352 }
353 FlightMode::ToCopter => {
354 self.elapsed_s += dt;
355 let plane_requested = requested == FlightRegime::Plane;
356 if plane_requested && !self.gate.fallen_back() {
357 self.mode = FlightMode::Plane;
358 } else if nose_up >= self.back_done_cosine || self.elapsed_s > self.config.timeout_s
359 {
360 self.mode = FlightMode::Copter;
361 handoff = true;
362 }
363 if plane_requested {
364 self.refusal = self.gate.fallback();
365 }
366 }
367 }
368
369 TransitionStep {
370 mode: self.mode,
371 tilt_target_rad: self.tilt_target_rad(),
372 handoff,
373 }
374 }
375
376 /// Cuts a transition short for `refusal` (e.g. [`ModeRefusal::RollError`], from a check the
377 /// caller makes), returning the step to fly this tick instead of the one
378 /// [`update`](Self::update) gave: a forward transition is abandoned to `Copter`, held
379 /// refused until `Copter` is requested (like a timeout); a back transition completes to
380 /// `Copter` with a handoff. Outside a transition it returns the current mode, unchanged.
381 ///
382 /// # Examples
383 ///
384 /// ```
385 /// use stable_flight::guidance::vtol::{Transition, TransitionConfig};
386 /// use stable_flight::{FlightMode, FlightRegime, ModeRefusal, Vec3, VehicleState};
387 ///
388 /// let mut transition = Transition::new(TransitionConfig::default());
389 /// transition.prime(&VehicleState::default());
390 /// let high = VehicleState { position_m: Vec3::new(0.0, 0.0, 10.0), ..Default::default() };
391 /// transition.update(0.01, FlightRegime::Plane, &high);
392 ///
393 /// let step = transition.cut_short(ModeRefusal::RollError);
394 /// assert_eq!(step.mode, FlightMode::Copter);
395 /// assert_eq!(transition.report().refusal, Some(ModeRefusal::RollError));
396 /// ```
397 pub fn cut_short(&mut self, refusal: ModeRefusal) -> TransitionStep {
398 let handoff = match self.mode {
399 FlightMode::ToPlane => {
400 self.abandon(refusal);
401 false
402 }
403 FlightMode::ToCopter => {
404 self.mode = FlightMode::Copter;
405 true
406 }
407 _ => false,
408 };
409 TransitionStep {
410 mode: self.mode,
411 tilt_target_rad: self.tilt_target_rad(),
412 handoff,
413 }
414 }
415
416 /// Gives up a forward transition: back to `Copter`, refused for `refusal` until `Copter`
417 /// is requested.
418 fn abandon(&mut self, refusal: ModeRefusal) {
419 self.mode = FlightMode::Copter;
420 self.gate.abandon(refusal);
421 self.refusal = Some(refusal);
422 }
423
424 /// The mode the last [`update`](Self::update) flew, and why it isn't the requested regime
425 /// when it can't be: what a VTOL guidance reports as its
426 /// [`flight_mode`](crate::Guidance::flight_mode).
427 pub fn report(&self) -> FlightModeReport {
428 FlightModeReport {
429 mode: self.mode,
430 refusal: self.refusal,
431 }
432 }
433
434 /// Whether a fallback holds `Plane` refused until `Copter` is requested.
435 pub(super) fn fallen_back(&self) -> bool {
436 self.gate.fallen_back()
437 }
438
439 /// Starts `ToPlane` from `Copter`, or reports why it can't.
440 fn try_forward(&mut self, state: &VehicleState, nose_up: f32) {
441 let needed_m = self.config.min_height_m.max(self.config.plane_min_height_m);
442 self.refusal = self.gate.refusal(state, needed_m);
443 if self.refusal.is_none() {
444 self.start(FlightMode::ToPlane, nose_up);
445 }
446 }
447
448 /// Enters a transition `mode`, ramping from the vehicle's tilt (hover for a NaN attitude
449 /// going forward, level flight going back).
450 fn start(&mut self, mode: FlightMode, nose_up: f32) {
451 let fallback = if mode == FlightMode::ToPlane {
452 0.0
453 } else {
454 FRAC_PI_2
455 };
456 self.mode = mode;
457 self.elapsed_s = 0.0;
458 self.start_tilt_rad = if nose_up.is_finite() {
459 libm::acosf(nose_up.clamp(-1.0, 1.0))
460 } else {
461 fallback
462 };
463 }
464
465 /// Whether `ToPlane` has tilted far enough, with enough airspeed when it's measured. A
466 /// NaN tilt never completes.
467 fn forward_done(&self, state: &VehicleState, nose_up: f32) -> bool {
468 let tilted = nose_up <= self.forward_done_cosine;
469 let fast_enough = state
470 .valid_airspeed_mps()
471 .is_none_or(|airspeed_mps| airspeed_mps >= self.config.min_airspeed_mps);
472 tilted && fast_enough
473 }
474
475 /// The ramped tilt target while transitioning.
476 fn tilt_target_rad(&self) -> Option<f32> {
477 match self.mode {
478 FlightMode::ToPlane => Some(
479 (self.start_tilt_rad + self.config.forward_rate_radps * self.elapsed_s)
480 .min(self.config.forward_max_tilt_rad.max(self.start_tilt_rad)),
481 ),
482 FlightMode::ToCopter => {
483 Some((self.start_tilt_rad - self.config.back_rate_radps * self.elapsed_s).max(0.0))
484 }
485 _ => None,
486 }
487 }
488}
489
490impl Configurable for Transition {
491 type Config = TransitionConfig;
492
493 fn config(&self) -> &TransitionConfig {
494 &self.config
495 }
496
497 /// Validates with [`TransitionConfig::validate`]. A running transition keeps its mode,
498 /// start tilt, and elapsed time, and follows the new rates, angles, and timeout from the
499 /// next tick.
500 fn set_config(&mut self, config: TransitionConfig) -> Result<(), InvalidConfig> {
501 config.validate()?;
502 self.config = config;
503 (self.forward_done_cosine, self.back_done_cosine) = done_cosines(&config);
504 Ok(())
505 }
506}
507
508/// What starts a forward transition, shared by [`Transition`] and [`LiftTransition`]: height
509/// above the arming altitude, and no fallback waiting on a `Copter` request.
510#[derive(Debug, Clone, Copy, PartialEq)]
511struct ForwardGate {
512 /// The altitude at [`prime`](Self::prime); NaN before it, which no height clears.
513 home_altitude_m: f32,
514 /// Why the last forward transition was abandoned or plane flight fell back, held until
515 /// `Copter` is requested.
516 abandoned: Option<ModeRefusal>,
517}
518
519impl ForwardGate {
520 fn new() -> Self {
521 ForwardGate {
522 home_altitude_m: f32::NAN,
523 abandoned: None,
524 }
525 }
526
527 /// `state`'s altitude as the height reference, and no abandoned transition.
528 fn prime(&mut self, state: &VehicleState) {
529 self.home_altitude_m = state.position_m.z;
530 self.abandoned = None;
531 }
532
533 /// Why a forward transition can't start in `state`, needing `min_height_m`: the
534 /// fallback's refusal first, then `BelowMinAltitude`; `None` when it can.
535 fn refusal(&self, state: &VehicleState, min_height_m: f32) -> Option<ModeRefusal> {
536 let height_m = self.height_m(state);
537 // A NaN height isn't high enough.
538 let high_enough = height_m.is_finite() && height_m >= min_height_m;
539 if self.abandoned.is_some() {
540 self.abandoned
541 } else if !high_enough {
542 Some(ModeRefusal::BelowMinAltitude)
543 } else {
544 None
545 }
546 }
547
548 /// Whether `state` is below `floor_m` above the arming altitude, with `floor_m` positive
549 /// (0 is off). A NaN height isn't: an unknown height falls back on nothing.
550 fn below(&self, state: &VehicleState, floor_m: f32) -> bool {
551 floor_m > 0.0 && self.height_m(state) < floor_m
552 }
553
554 /// `state`'s height above the arming altitude, in m; NaN before [`prime`](Self::prime).
555 fn height_m(&self, state: &VehicleState) -> f32 {
556 state.position_m.z - self.home_altitude_m
557 }
558
559 /// Holds `refusal` against forward transitions until [`clear`](Self::clear).
560 fn abandon(&mut self, refusal: ModeRefusal) {
561 self.abandoned = Some(refusal);
562 }
563
564 /// The fallback holding forward transitions refused, if any.
565 fn fallback(&self) -> Option<ModeRefusal> {
566 self.abandoned
567 }
568
569 /// Whether a fallback holds forward transitions refused.
570 fn fallen_back(&self) -> bool {
571 self.abandoned.is_some()
572 }
573
574 /// `Copter` was requested: an abandoned transition no longer holds.
575 fn clear(&mut self) {
576 self.abandoned = None;
577 }
578}
579
580/// Where copter flight hovers after a fallback (see [Modes](self#modes)), shared by
581/// [`TailsitterGuidance`] and [`QuadPlaneGuidance`]: in place of a waypoint, the point where
582/// the vehicle was on the fallback's first copter tick flying one, held until the fallback
583/// clears. The waypoint may be a distant plane leg's, which the copter would otherwise chase
584/// at the plane leg's speed (#453). Other input (sticks, offboard attitudes and rates, land)
585/// is flown as given, as PX4 keeps flying its manual modes after a quadchute (PX4
586/// `commander/failsafe/failsafe.cpp:619-625`). On a waypoint ArduPilot lands where a forward
587/// transition failed (`QLAND`, `ArduPlane/quadplane.cpp:1503-1506`) and PX4 returns home by
588/// default (`COM_QC_ACT`, `commander_params.yaml:198-207`); holding leaves that choice to the
589/// commander: `Land` or `Copter` clears the fallback.
590#[derive(Debug, Clone, Copy, Default, PartialEq)]
591struct FallbackHold {
592 /// The latched hover point; `None` outside a fallback.
593 point: Option<WaypointCommand>,
594}
595
596impl FallbackHold {
597 /// What copter flight flies this tick: `input`, or while `fallen_back` and `input` is a
598 /// waypoint, the hold over where `state` was on the first such tick.
599 fn input(
600 &mut self,
601 fallen_back: bool,
602 input: &ControlInput,
603 state: &VehicleState,
604 ) -> ControlInput {
605 if !fallen_back {
606 self.point = None;
607 return *input;
608 }
609 let ControlInput::Waypoint(_) = input else {
610 return *input;
611 };
612 let point = *self.point.get_or_insert_with(|| WaypointCommand {
613 position_m: state.position_m.xy(),
614 altitude_m: state.position_m.z,
615 ..WaypointCommand::default()
616 });
617 ControlInput::Waypoint(point)
618 }
619
620 /// No hold latched: call when the vehicle arms.
621 fn clear(&mut self) {
622 self.point = None;
623 }
624}
625
626/// The cosines of the forward and back completion tilts, which [`Transition`] compares the
627/// nose's [`nose_up_cosine`] against instead of taking its `acos` every tick.
628fn done_cosines(config: &TransitionConfig) -> (f32, f32) {
629 (
630 libm::cosf(config.forward_done_rad),
631 libm::cosf(config.back_done_rad),
632 )
633}
634
635/// Blends thrust from its value when control passed between controllers to the incoming
636/// controller's demand, linearly over a fixed time, so the handoff steps moments but not
637/// thrust.
638///
639/// # Examples
640///
641/// ```
642/// use stable_flight::guidance::vtol::ThrustHandoff;
643///
644/// let mut handoff = ThrustHandoff::new(0.5);
645/// handoff.start(0.8); // the outgoing controller's last thrust
646/// let first = handoff.apply(0.25, 0.4);
647/// assert!((first - 0.6).abs() < 1e-6); // halfway
648/// assert_eq!(handoff.apply(0.25, 0.4), 0.4); // done
649/// assert!(!handoff.active());
650/// ```
651#[derive(Debug, Clone, Copy, PartialEq)]
652pub struct ThrustHandoff {
653 duration_s: f32,
654 from: f32,
655 elapsed_s: f32,
656}
657
658impl ThrustHandoff {
659 /// A handoff that blends over `duration_s` seconds, inactive until
660 /// [`start`](Self::start). Zero passes the demand straight through.
661 ///
662 /// # Panics
663 ///
664 /// If `duration_s` is negative or not finite.
665 pub fn new(duration_s: f32) -> Self {
666 if let Err(error) = check_limit("duration_s", duration_s) {
667 panic!("invalid ThrustHandoff: {error}");
668 }
669 ThrustHandoff {
670 duration_s,
671 from: 0.0,
672 elapsed_s: duration_s,
673 }
674 }
675
676 /// Starts blending from `from` (the outgoing controller's last thrust, `[0, 1]`; NaN
677 /// counts as 0).
678 pub fn start(&mut self, from: f32) {
679 self.from = saturate_throttle(from);
680 self.elapsed_s = 0.0;
681 }
682
683 /// Whether a blend is running.
684 pub fn active(&self) -> bool {
685 self.elapsed_s < self.duration_s
686 }
687
688 /// This tick's thrust: `demanded` (saturated to `[0, 1]`, NaN as 0) once the blend is
689 /// done, otherwise the blend from the start value toward it.
690 ///
691 /// # Panics
692 ///
693 /// If `dt` isn't positive and finite.
694 pub fn apply(&mut self, dt: f32, demanded: f32) -> f32 {
695 assert_dt(dt);
696 let demanded = saturate_throttle(demanded);
697 if !self.active() {
698 return demanded;
699 }
700 self.elapsed_s += dt;
701 let weight = (self.elapsed_s / self.duration_s).min(1.0);
702 self.from + (demanded - self.from) * weight
703 }
704}