stable_flight/guidance/plane.rs
1//! Fixed-wing guidance: [`PlaneGuidance`] turns pilot sticks and offboard commands into
2//! [`Setpoint::Plane`] and [`Setpoint::PlaneRate`] for a
3//! [`PlaneStabilizer`](crate::stabilizers::plane::PlaneStabilizer).
4//!
5//! | Control input | Setpoint |
6//! |---|---|
7//! | [`ControlInput::Attitude`] | [`Setpoint::Plane`]: roll stick × [`max_bank_rad`](PlaneGuidanceConfig::max_bank_rad), pitch stick × [`max_pitch_up_rad`](PlaneGuidanceConfig::max_pitch_up_rad) or [`max_pitch_down_rad`](PlaneGuidanceConfig::max_pitch_down_rad), throttle as thrust (ArduPlane's FBWA); turns coordinated, yaw stick unused |
8//! | [`ControlInput::Rate`] | [`Setpoint::PlaneRate`]: sticks × [`max_rate_radps`](PlaneGuidanceConfig::max_rate_radps) (acro: rolls, loops), throttle as thrust |
9//! | [`ControlInput::AbsoluteAttitude`] | [`Setpoint::Plane`]: roll, pitch, and thrust as given (heading unused) |
10//! | [`ControlInput::AbsoluteRate`] | [`Setpoint::PlaneRate`]: rates and thrust as given |
11//! | [`ControlInput::Waypoint`] | [`Setpoint::Plane`]: with a leg velocity, L1 along the line through the waypoint in its direction; without one (a route's final hold, an offboard point), a clockwise loiter of [`loiter_radius_m`](PlaneGuidanceConfig::loiter_radius_m) around it; bank `atan(a/g)` capped at [`max_bank_rad`](PlaneGuidanceConfig::max_bank_rad). Pitch and thrust hold the waypoint's altitude and its `cruise_speed_mps` as airspeed by total energy control ([`TecsConfig`]: thrust for the total energy, pitch for its balance); without an airspeed or a speed target, pitch holds the altitude (a PI loop) and thrust is [`cruise_thrust`](PlaneGuidanceConfig::cruise_thrust) plus a climb's share |
12//! | [`ControlInput::Land`] | Neutral (level, zero thrust): a plane doesn't land here; a VTOL lands as a copter |
13//!
14//! Sticks and angles saturate (NaN as centered or level), throttle to `[0, 1]` (NaN as
15//! none). It flies only [`FlightRegime::Plane`], and reports a `Copter` request as
16//! [`ModeRefusal::Unsupported`](crate::ModeRefusal::Unsupported)
17//! ([`FlightModeReport::plane_only`]).
18
19use crate::controllers::{InvalidConfig, check, check_limit, check_positive};
20use crate::math::{DEG, all_finite, assert_dt, clamp_symmetric, saturate_throttle, saturate_unit};
21use crate::{
22 BodyRateSetpoint, Configurable, ControlInput, FlightModeReport, FlightRegime, Guidance,
23 PlaneSetpoint, Setpoint, Vec3, VehicleState, WaypointCommand,
24};
25
26mod navigation;
27mod params;
28mod tecs;
29#[cfg(test)]
30mod tests;
31
32use navigation::{PiLoop, bank_for_accel_rad, loiter_accel_mps2, track_accel_mps2};
33pub use tecs::TecsConfig;
34use tecs::{Limits, Tecs};
35
36/// [`PlaneGuidance`] settings.
37#[derive(Clone, Copy, Debug, PartialEq)]
38pub struct PlaneGuidanceConfig {
39 /// Bank at full roll stick, in radians.
40 pub max_bank_rad: f32,
41 /// Pitch at full back stick, in radians.
42 pub max_pitch_up_rad: f32,
43 /// Pitch (down) at full forward stick, in radians, positive.
44 pub max_pitch_down_rad: f32,
45 /// Body rates at full stick in rate (acro) flight, roll/pitch/yaw, in rad/s.
46 pub max_rate_radps: Vec3,
47 /// Pitch for wings-level cruise, in radians.
48 pub trim_pitch_rad: f32,
49 /// Throttle for wings-level cruise at the trim airspeed, `[0, 1]`: total energy control's
50 /// thrust at a steady energy.
51 pub cruise_thrust: f32,
52 /// L1 period, in seconds: how quickly the path is captured (shorter is tighter).
53 pub l1_period_s: f32,
54 /// L1 damping ratio.
55 pub l1_damping: f32,
56 /// Radius of the loiter around a waypoint with no leg, in meters.
57 pub loiter_radius_m: f32,
58 /// Without an airspeed: pitch per meter of altitude error, rad/m.
59 pub altitude_p: f32,
60 /// Without an airspeed: pitch per meter-second of accumulated altitude error.
61 pub altitude_i: f32,
62 /// Without an airspeed: the altitude loop's integral limit, in m·s.
63 pub altitude_max_integral: f32,
64 /// Total energy control of altitude and airspeed, with an airspeed and a speed target.
65 pub tecs: TecsConfig,
66 /// Least thrust waypoint flight commands, `[0, 1]`.
67 pub min_thrust: f32,
68 /// Most thrust waypoint flight commands, `[0, 1]`.
69 pub max_thrust: f32,
70 /// Without an airspeed: thrust added per radian of pitch up (a climb needs more).
71 pub climb_thrust_per_rad: f32,
72}
73
74impl Default for PlaneGuidanceConfig {
75 /// ArduPlane's FBWA limits (45° bank, +20°/−25° pitch, `mode_fbwa.cpp`), its acro rates
76 /// (180°/s roll and pitch, yaw stick unused), level trim, and half throttle to cruise;
77 /// for waypoints, ArduPilot's L1 damping (0.75) with a shorter period than its 17 s (12 s,
78 /// for a small airframe), a 40 m loiter, ArduPilot's total energy control defaults
79 /// ([`TecsConfig::default`]), and starting gains for the altitude loop without an airspeed
80 /// (an airframe tunes its own).
81 fn default() -> Self {
82 PlaneGuidanceConfig {
83 max_bank_rad: 45.0 * DEG,
84 max_pitch_up_rad: 20.0 * DEG,
85 max_pitch_down_rad: 25.0 * DEG,
86 max_rate_radps: Vec3::new(180.0 * DEG, 180.0 * DEG, 0.0),
87 trim_pitch_rad: 0.0,
88 cruise_thrust: 0.5,
89 l1_period_s: 12.0,
90 l1_damping: 0.75,
91 loiter_radius_m: 40.0,
92 altitude_p: 0.05,
93 altitude_i: 0.01,
94 altitude_max_integral: 20.0,
95 tecs: TecsConfig::default(),
96 min_thrust: 0.2,
97 max_thrust: 1.0,
98 climb_thrust_per_rad: 0.5,
99 }
100 }
101}
102
103impl PlaneGuidanceConfig {
104 /// `Ok` when the angle limits are in `[0, π/2]`, the rates non-negative, the trim pitch in
105 /// `[−π/2, π/2]`, the cruise thrust in `[0, 1]`, and [`TecsConfig::validate`] passes.
106 ///
107 /// # Errors
108 ///
109 /// [`InvalidConfig`] naming the first field out of range.
110 pub fn validate(&self) -> Result<(), InvalidConfig> {
111 let quarter_turn = |angle: f32| (0.0..=core::f32::consts::FRAC_PI_2).contains(&angle);
112 let in_range = "in [0, π/2] rad";
113 check("max_bank_rad", quarter_turn(self.max_bank_rad), in_range)?;
114 check(
115 "max_pitch_up_rad",
116 quarter_turn(self.max_pitch_up_rad),
117 in_range,
118 )?;
119 check(
120 "max_pitch_down_rad",
121 quarter_turn(self.max_pitch_down_rad),
122 in_range,
123 )?;
124 check_limit("max_rate_radps.x", self.max_rate_radps.x)?;
125 check_limit("max_rate_radps.y", self.max_rate_radps.y)?;
126 check_limit("max_rate_radps.z", self.max_rate_radps.z)?;
127 let half = core::f32::consts::FRAC_PI_2;
128 check(
129 "trim_pitch_rad",
130 (-half..=half).contains(&self.trim_pitch_rad),
131 "in [−π/2, π/2] rad",
132 )?;
133 let unit = |value: f32| (0.0..=1.0).contains(&value);
134 check("cruise_thrust", unit(self.cruise_thrust), "in [0, 1]")?;
135 check_positive("l1_period_s", self.l1_period_s)?;
136 check_positive("l1_damping", self.l1_damping)?;
137 check_positive("loiter_radius_m", self.loiter_radius_m)?;
138 check_limit("altitude_p", self.altitude_p)?;
139 check_limit("altitude_i", self.altitude_i)?;
140 check_limit("altitude_max_integral", self.altitude_max_integral)?;
141 self.tecs.validate().map_err(|e| e.in_section("tecs"))?;
142 check("min_thrust", unit(self.min_thrust), "in [0, 1]")?;
143 check("max_thrust", unit(self.max_thrust), "in [0, 1]")?;
144 check_limit("climb_thrust_per_rad", self.climb_thrust_per_rad)
145 }
146}
147
148/// Fixed-wing guidance for piloted and offboard flight. See the [module docs](self).
149///
150/// # Examples
151///
152/// ```
153/// use stable_flight::guidance::plane::{PlaneGuidance, PlaneGuidanceConfig};
154/// use stable_flight::{AttitudeCommand, ControlInput, FlightRegime, Guidance, Setpoint, VehicleState};
155///
156/// let mut guidance = PlaneGuidance::new(PlaneGuidanceConfig::default());
157/// let full_right = ControlInput::Attitude(AttitudeCommand {
158/// throttle: 0.7,
159/// roll: 1.0,
160/// ..Default::default()
161/// });
162/// let state = VehicleState::default();
163/// let Setpoint::Plane(setpoint) = guidance.guide(0.01, FlightRegime::Plane, &full_right, &state)
164/// else {
165/// unreachable!("sticks give a plane attitude");
166/// };
167/// assert_eq!(setpoint.roll_rad, 45f32.to_radians());
168/// assert_eq!(setpoint.thrust, 0.7);
169/// ```
170#[derive(Clone, Debug, PartialEq)]
171pub struct PlaneGuidance {
172 config: PlaneGuidanceConfig,
173 requested: FlightRegime,
174 /// Waypoint flight without an airspeed: altitude (→ pitch).
175 altitude: PiLoop,
176 /// Waypoint flight with an airspeed: total energy control.
177 tecs: Tecs,
178}
179
180impl PlaneGuidance {
181 /// Guidance with `config`.
182 ///
183 /// # Panics
184 ///
185 /// If `config` is invalid ([`PlaneGuidanceConfig::validate`]).
186 pub fn new(config: PlaneGuidanceConfig) -> Self {
187 if let Err(error) = config.validate() {
188 panic!("invalid PlaneGuidanceConfig: {error}");
189 }
190 PlaneGuidance {
191 config,
192 requested: FlightRegime::Plane,
193 altitude: PiLoop::default(),
194 tecs: Tecs::default(),
195 }
196 }
197
198 /// [`Guidance::guide`], with waypoint flight's pitch held within `pitch_cap_rad` either
199 /// way when given: the forward transition's limits, so the energy control's pitch integral
200 /// stops where the transition stops the pitch (`ArduPlane/quadplane.cpp:4791-4793`).
201 pub(crate) fn guide_capped(
202 &mut self,
203 dt: f32,
204 regime: FlightRegime,
205 input: &ControlInput,
206 state: &VehicleState,
207 pitch_cap_rad: Option<f32>,
208 ) -> Setpoint {
209 assert_dt(dt);
210 self.requested = regime;
211 if !matches!(input, ControlInput::Waypoint(_)) {
212 // The navigation loops are idle: clear them so waypoint flight starts fresh.
213 self.altitude = PiLoop::default();
214 self.tecs.reset();
215 }
216 let config = &self.config;
217 match input {
218 ControlInput::Attitude(sticks) => {
219 Setpoint::Plane(self.sticks(sticks.roll, sticks.pitch, sticks.throttle))
220 }
221 ControlInput::Rate(sticks) => Setpoint::PlaneRate(BodyRateSetpoint {
222 roll_radps: saturate_unit(sticks.roll_rate) * config.max_rate_radps.x,
223 pitch_radps: saturate_unit(sticks.pitch_rate) * config.max_rate_radps.y,
224 yaw_radps: saturate_unit(sticks.yaw_rate) * config.max_rate_radps.z,
225 thrust: saturate_throttle(sticks.throttle),
226 idle: false,
227 }),
228 ControlInput::AbsoluteAttitude(command) => Setpoint::Plane(PlaneSetpoint {
229 roll_rad: command.roll_rad,
230 pitch_rad: command.pitch_rad,
231 thrust: saturate_throttle(command.thrust),
232 transition: false,
233 }),
234 ControlInput::AbsoluteRate(command) => {
235 let mut rates = BodyRateSetpoint::from(command);
236 rates.thrust = saturate_throttle(command.thrust);
237 Setpoint::PlaneRate(rates)
238 }
239 ControlInput::Waypoint(waypoint) => {
240 Setpoint::Plane(self.navigate(dt, waypoint, state, pitch_cap_rad))
241 }
242 ControlInput::Land(_) => Setpoint::Plane(PlaneSetpoint::default()),
243 }
244 }
245
246 /// Waypoint flight: bank from L1 along the leg (or a loiter without one); pitch and thrust
247 /// from total energy control, or without an airspeed or a speed target, pitch from the
248 /// altitude loop and thrust from cruise and the pitch.
249 fn navigate(
250 &mut self,
251 dt: f32,
252 waypoint: &WaypointCommand,
253 state: &VehicleState,
254 pitch_cap_rad: Option<f32>,
255 ) -> PlaneSetpoint {
256 let config = &self.config;
257 let cap = |limit_rad: f32| pitch_cap_rad.map_or(limit_rad, |cap| limit_rad.min(cap));
258 let (pitch_up_rad, pitch_down_rad) =
259 (cap(config.max_pitch_up_rad), cap(config.max_pitch_down_rad));
260 let (position_m, velocity_mps) = (state.position_m.xy(), state.velocity_mps.xy());
261 let (period_s, damping) = (config.l1_period_s, config.l1_damping);
262 let leg = waypoint.velocity_mps.filter(all_finite);
263 let accel_mps2 = match leg {
264 Some(leg) => track_accel_mps2(
265 position_m,
266 velocity_mps,
267 waypoint.position_m,
268 leg,
269 period_s,
270 damping,
271 ),
272 None => loiter_accel_mps2(
273 position_m,
274 velocity_mps,
275 waypoint.position_m,
276 config.loiter_radius_m,
277 period_s,
278 damping,
279 ),
280 };
281 let roll_rad = clamp_symmetric(bank_for_accel_rad(accel_mps2), config.max_bank_rad);
282
283 let (low, high) = (config.min_thrust, config.max_thrust.max(config.min_thrust));
284 let trim = config.trim_pitch_rad;
285 let target_mps = Some(waypoint.cruise_speed_mps).filter(|speed| *speed > 0.0);
286 let (pitch_rad, thrust) = match (target_mps, state.valid_airspeed_mps()) {
287 (Some(target_mps), Some(airspeed_mps)) => {
288 self.altitude = PiLoop::default();
289 let limits = Limits {
290 pitch_up_rad,
291 pitch_down_rad,
292 trim_pitch_rad: trim,
293 min_thrust: low,
294 max_thrust: high,
295 cruise_thrust: config.cruise_thrust,
296 };
297 self.tecs.step(
298 dt,
299 &config.tecs,
300 &limits,
301 (waypoint.altitude_m, target_mps),
302 airspeed_mps,
303 state,
304 )
305 }
306 _ => {
307 self.tecs.reset();
308 // Pitch around trim, within the pitch limits; cruise thrust plus what a climb
309 // needs.
310 let pitch_rad = trim
311 + self.altitude.step(
312 dt,
313 waypoint.altitude_m - state.position_m.z,
314 config.altitude_p,
315 config.altitude_i,
316 config.altitude_max_integral,
317 (-pitch_down_rad - trim, pitch_up_rad - trim),
318 0.0,
319 );
320 let thrust = (config.cruise_thrust
321 + config.climb_thrust_per_rad * (pitch_rad - trim))
322 .clamp(low, high);
323 (pitch_rad, thrust)
324 }
325 };
326 PlaneSetpoint {
327 roll_rad,
328 pitch_rad,
329 thrust,
330 transition: false,
331 }
332 }
333
334 /// FBWA: sticks to bank and pitch, pitch asymmetric.
335 fn sticks(&self, roll: f32, pitch: f32, throttle: f32) -> PlaneSetpoint {
336 let config = &self.config;
337 let pitch = saturate_unit(pitch);
338 let pitch_limit = if pitch >= 0.0 {
339 config.max_pitch_up_rad
340 } else {
341 config.max_pitch_down_rad
342 };
343 PlaneSetpoint {
344 roll_rad: saturate_unit(roll) * config.max_bank_rad,
345 pitch_rad: pitch * pitch_limit,
346 thrust: saturate_throttle(throttle),
347 transition: false,
348 }
349 }
350}
351
352impl Configurable for PlaneGuidance {
353 type Config = PlaneGuidanceConfig;
354
355 fn config(&self) -> &PlaneGuidanceConfig {
356 &self.config
357 }
358
359 /// Validates with [`PlaneGuidanceConfig::validate`]; applies from the next tick.
360 fn set_config(&mut self, config: PlaneGuidanceConfig) -> Result<(), InvalidConfig> {
361 config.validate()?;
362 self.config = config;
363 Ok(())
364 }
365}
366
367impl Guidance for PlaneGuidance {
368 fn guide(
369 &mut self,
370 dt: f32,
371 regime: FlightRegime,
372 input: &ControlInput,
373 state: &VehicleState,
374 ) -> Setpoint {
375 self.guide_capped(dt, regime, input, state, None)
376 }
377
378 /// Clears the navigation loops: integrals, demands, and underspeed.
379 fn prime(&mut self, _state: &VehicleState) {
380 self.altitude = PiLoop::default();
381 self.tecs.reset();
382 }
383
384 /// Always plane; a `Copter` request is refused as unsupported.
385 fn flight_mode(&self) -> Option<FlightModeReport> {
386 Some(FlightModeReport::plane_only(self.requested))
387 }
388}