stable_flight/guidance/vtol/off_nose.rs
1//! [`OffNoseSpeed`]: a quadplane's copter-flight speed cut while its nose is off the way to its
2//! waypoint, so it doesn't fly fast sideways or tail first.
3
4use crate::controllers::{InvalidConfig, check, check_limit};
5use crate::math::{DEG, wrap_angle};
6use crate::{Configurable, VehicleState, WaypointCommand};
7use core::f32::consts::PI;
8
9mod params;
10#[cfg(test)]
11mod tests;
12
13/// Default [`OffNoseSpeedConfig::speed_mps`], in m/s: its 5 m/s tail first is ArduPilot's
14/// quadplane waypoint speed (`Q_WP_SPD`, in `ArduPlane/quadplane.cpp`'s `defaults_table`) and
15/// the speed the RealFlight Titan Cobra flies legs behind it cleanly (#433). On the sim
16/// quadplanes it holds an uncapped leg's turnaround within 1° of the tilt cap, where uncapped
17/// it overshoots by up to 12° (#437).
18pub const DEFAULT_OFF_NOSE_SPEED_MPS: f32 = 15.0;
19
20/// Default [`OffNoseSpeedConfig::free_rad`], in rad: ArduPilot's
21/// `QuadPlane::get_scaled_wp_speed`.
22pub const DEFAULT_OFF_NOSE_FREE_RAD: f32 = 20.0 * DEG;
23
24/// Default [`OffNoseSpeedConfig::full_rad`], in rad (ArduPilot, as above).
25pub const DEFAULT_OFF_NOSE_FULL_RAD: f32 = 160.0 * DEG;
26
27/// Default [`OffNoseSpeedConfig::tail_first_divisor`] (ArduPilot, as above).
28pub const DEFAULT_OFF_NOSE_TAIL_FIRST_DIVISOR: f32 = 3.0;
29
30/// [`OffNoseSpeed`] settings.
31#[derive(Debug, Clone, Copy, PartialEq)]
32pub struct OffNoseSpeedConfig {
33 /// Speed, in m/s, that the cut divides: the cap just past `free_rad` off the nose,
34 /// divided by `tail_first_divisor` from `full_rad`; `0` is off. Non-negative and finite.
35 /// Defaults to [`DEFAULT_OFF_NOSE_SPEED_MPS`].
36 pub speed_mps: f32,
37 /// Heading error, from the nose to the bearing to the waypoint, up to which the speed isn't
38 /// cut, in rad, in `[0, π)`. Higher: flies faster further off the nose.
39 pub free_rad: f32,
40 /// Heading error at and past which the speed is cut the most, in rad, in `(0, π]`; at or
41 /// below `free_rad`, the whole cut applies just past `free_rad`. Higher: eases into the
42 /// cut over a wider turn.
43 pub full_rad: f32,
44 /// What `speed_mps` is divided by from `full_rad` (tail first), at least 1; the divisor
45 /// rises linearly from 1 at `free_rad`. Higher: slower tail first.
46 pub tail_first_divisor: f32,
47}
48
49impl OffNoseSpeedConfig {
50 /// `Ok` when the speed is non-negative and finite, the free angle in `[0, π)`, the full
51 /// angle in `(0, π]`, and the divisor at least 1 and finite.
52 ///
53 /// # Errors
54 ///
55 /// [`InvalidConfig`] naming the first field out of range.
56 pub fn validate(&self) -> Result<(), InvalidConfig> {
57 check_limit("speed_mps", self.speed_mps)?;
58 check(
59 "free_rad",
60 (0.0..PI).contains(&self.free_rad),
61 "in [0, π) rad",
62 )?;
63 check(
64 "full_rad",
65 self.full_rad > 0.0 && self.full_rad <= PI,
66 "in (0, π] rad",
67 )?;
68 check(
69 "tail_first_divisor",
70 self.tail_first_divisor >= 1.0 && self.tail_first_divisor.is_finite(),
71 "at least 1, finite",
72 )
73 }
74}
75
76impl Default for OffNoseSpeedConfig {
77 /// [`DEFAULT_OFF_NOSE_SPEED_MPS`], uncut within 20°, a third from 160°: ArduPilot's
78 /// quadplane's.
79 fn default() -> Self {
80 OffNoseSpeedConfig {
81 speed_mps: DEFAULT_OFF_NOSE_SPEED_MPS,
82 free_rad: DEFAULT_OFF_NOSE_FREE_RAD,
83 full_rad: DEFAULT_OFF_NOSE_FULL_RAD,
84 tail_first_divisor: DEFAULT_OFF_NOSE_TAIL_FIRST_DIVISOR,
85 }
86 }
87}
88
89/// Caps a quadplane's waypoint speed in copter flight by how far the nose is off the bearing to
90/// the waypoint, as ArduPilot's quadplane does (`QuadPlane::get_scaled_wp_speed`): uncut
91/// within [`free_rad`](OffNoseSpeedConfig::free_rad) (20°), then
92/// [`speed_mps`](OffNoseSpeedConfig::speed_mps) divided by a factor rising linearly from 1
93/// there to [`tail_first_divisor`](OffNoseSpeedConfig::tail_first_divisor) (3) at
94/// [`full_rad`](OffNoseSpeedConfig::full_rad) (160°) and past it. The waypoint's own cruise
95/// speed still applies when lower.
96///
97/// A quadplane's wing and tail push it around flying sideways or tail first: tail first at
98/// 15 m/s the RealFlight Titan Cobra pitched past what its lift rotors hold and flipped (#437).
99/// Turning the nose along the leg (copter guidance's
100/// [`waypoint_yaw_radps`](crate::guidance::copter::CopterGuidanceConfig::waypoint_yaw_radps))
101/// leaves the turnarounds, an overshoot flown back along the leg, and legs with the turn off.
102///
103/// # Examples
104///
105/// ```
106/// use stable_flight::guidance::vtol::{OffNoseSpeed, OffNoseSpeedConfig};
107/// use stable_flight::{Vec2, VehicleState, WaypointCommand};
108///
109/// let off_nose = OffNoseSpeed::new(OffNoseSpeedConfig {
110/// speed_mps: 15.0,
111/// ..OffNoseSpeedConfig::default()
112/// });
113/// let behind = WaypointCommand { position_m: Vec2::new(-100.0, 0.0), ..Default::default() };
114/// let capped = off_nose.cap(&behind, &VehicleState::default()); // heading north
115/// assert_eq!(capped.cruise_speed_mps, 5.0);
116/// ```
117#[derive(Debug, Clone, Copy, PartialEq)]
118pub struct OffNoseSpeed {
119 config: OffNoseSpeedConfig,
120}
121
122impl OffNoseSpeed {
123 /// The cut with `config`.
124 ///
125 /// # Panics
126 ///
127 /// If `config` is invalid ([`OffNoseSpeedConfig::validate`]).
128 pub fn new(config: OffNoseSpeedConfig) -> Self {
129 if let Err(error) = config.validate() {
130 panic!("invalid OffNoseSpeedConfig: {error}");
131 }
132 OffNoseSpeed { config }
133 }
134
135 /// `waypoint` with its cruise speed lowered to the cap for the vehicle's heading and
136 /// position; unchanged when off, within `free_rad` of the nose, or below the cap already. A
137 /// non-finite position or heading leaves it unchanged (input policy).
138 pub fn cap(&self, waypoint: &WaypointCommand, state: &VehicleState) -> WaypointCommand {
139 let to_m = waypoint.position_m - state.position_m.xy();
140 let bearing_rad = libm::atan2f(to_m.y, to_m.x);
141 let cap_mps = self.cap_mps(wrap_angle(bearing_rad - state.heading_rad).abs());
142 // `>` is false for NaN: an unknown cap, or no cruise speed, takes the cap.
143 let cruise_mps = waypoint.cruise_speed_mps;
144 if !cap_mps.is_finite() || (cruise_mps > 0.0 && cruise_mps <= cap_mps) {
145 return *waypoint;
146 }
147 WaypointCommand {
148 cruise_speed_mps: cap_mps,
149 ..*waypoint
150 }
151 }
152
153 /// The speed cap, in m/s, `error_rad` off the nose: infinite when off, within `free_rad`,
154 /// or for a NaN error.
155 fn cap_mps(&self, error_rad: f32) -> f32 {
156 let OffNoseSpeedConfig {
157 speed_mps,
158 free_rad,
159 full_rad,
160 tail_first_divisor,
161 } = self.config;
162 // `>` is false for NaN.
163 if !(speed_mps > 0.0 && error_rad > free_rad) {
164 return f32::INFINITY;
165 }
166 // A full angle at or below the free one is a step to the whole cut.
167 let span_rad = full_rad - free_rad;
168 let share = if span_rad > 0.0 {
169 ((error_rad - free_rad) / span_rad).min(1.0)
170 } else {
171 1.0
172 };
173 speed_mps / (1.0 + (tail_first_divisor - 1.0) * share)
174 }
175}
176
177impl Configurable for OffNoseSpeed {
178 type Config = OffNoseSpeedConfig;
179
180 fn config(&self) -> &OffNoseSpeedConfig {
181 &self.config
182 }
183
184 /// Validates with [`OffNoseSpeedConfig::validate`]; applies from the next tick.
185 fn set_config(&mut self, config: OffNoseSpeedConfig) -> Result<(), InvalidConfig> {
186 config.validate()?;
187 self.config = config;
188 Ok(())
189 }
190}