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