stable_flight/stabilizers/copter.rs
1//! Basic controller for a vehicle that does not transition between different flight modes such as copter and plane.
2//!
3//! A reference model for such a vehicle is the QuadCopter X.
4//! Reference model: <https://github.com/ArduPilot/SITL_Models/tree/master/RealFlight/Released_Models/Multicopters/QuadCopterX>
5//!
6//! # Control Architecture
7//!
8//! This implements a modular cascaded control system with configurable control loops:
9//!
10//! 1. **Inner Loop: Rate Control**
11//! - Controls angular rates (roll rate, pitch rate, yaw rate)
12//! - Fast update frequency (typically 400-1000Hz)
13//! - PID controllers with feed-forward terms for each axis
14//! - Directly commands motor mixing algorithm
15//! - Always active as the core control layer
16//!
17//! 2. **Middle Loop: Attitude Control (Optional)**
18//! - Controls orientation angles (roll angle, pitch angle, yaw angle)
19//! - Moderate update frequency (typically 100-250Hz)
20//! - Outputs desired angular rates to inner loop
21//! - Implements angle limiting for safety
22//! - Can be used without outer position loops for manual flight modes
23//!
24//! The outer position loops (altitude and lateral position) are guidance, not stabilization:
25//! they live in [`CopterGuidance`](crate::guidance::copter::CopterGuidance), which turns
26//! commands into the [`Setpoint`] this stabilizer tracks.
27//!
28//! # Setpoints
29//!
30//! - [`Setpoint::Rate`]: rate loop only (acro); the idle attitude and heading loops are
31//! cleared, so attitude flight resumes from fresh state.
32//! - [`Setpoint::Attitude`]: attitude and heading loops feeding the rate loop.
33
34use crate::{Vec2, Vec3};
35
36use crate::{
37 AttitudeSetpoint, Configurable, ControlOutput, RateSetpoint, Saturation, Setpoint, Stabilizer,
38 VehicleState,
39};
40
41use crate::controllers::*;
42use crate::controllers::{check_limit, check_positive};
43use crate::math::{assert_dt, euler_angles, saturate_throttle, saturate_unit};
44
45mod params;
46#[cfg(test)]
47mod tests;
48
49/// Configuration for the [CopterStabilizer]: gains and limits for the inner control loops and
50/// the thrust mapping.
51///
52/// Plain data: [`CopterStabilizer::new`] validates it, and the stabilizer passes it to its
53/// controllers every tick.
54#[derive(Clone, Copy, Debug, PartialEq)]
55pub struct CopterStabilizerConfig {
56 /// Body-rate (inner) loop.
57 pub body_rate: BodyRateControllerConfig,
58 /// Roll/pitch attitude loop ([`Setpoint::Attitude`] only).
59 pub attitude: AttitudeControllerConfig,
60 /// Heading-hold loop ([`Setpoint::Attitude`] only).
61 pub yaw: YawControllerConfig,
62 /// Body rates (roll, pitch, yaw) in rad/s that a full-scale [`RateSetpoint`] maps to. Each
63 /// component must be non-negative and finite: an infinite or NaN scale makes even a neutral
64 /// stick a non-finite rate, which zeroes that axis's moment.
65 pub full_scale_rates_radps: Vec3,
66 /// Exponent of the thrust curve applied to the linear thrust setpoint. Must be positive
67 /// and finite: a negative exponent maps zero throttle to full thrust.
68 pub thrust_curve_exponent: f32,
69}
70
71impl Default for CopterStabilizerConfig {
72 /// Untuned starting values; airframes override them with flight-checked sets.
73 fn default() -> Self {
74 CopterStabilizerConfig {
75 body_rate: BodyRateControllerConfig::default(),
76 attitude: AttitudeControllerConfig::default(),
77 yaw: YawControllerConfig::default(),
78 full_scale_rates_radps: Vec3::new(3.0, 3.0, 3.0),
79 thrust_curve_exponent: 2.0,
80 }
81 }
82}
83
84impl CopterStabilizerConfig {
85 /// Checks every controller config ([`BodyRateControllerConfig::validate`],
86 /// [`AttitudeControllerConfig::validate`], [`YawControllerConfig::validate`]; errors carry
87 /// the loop as their `section`), that each `full_scale_rates_radps` component is
88 /// non-negative and finite, and that `thrust_curve_exponent` is positive and finite.
89 ///
90 /// # Examples
91 ///
92 /// ```
93 /// use stable_flight::stabilizers::copter::CopterStabilizerConfig;
94 ///
95 /// let mut config = CopterStabilizerConfig::default();
96 /// assert!(config.validate().is_ok());
97 /// config.yaw.max_rate_radps = -1.0;
98 /// assert!(config.validate().is_err());
99 /// ```
100 pub fn validate(&self) -> Result<(), InvalidConfig> {
101 self.body_rate
102 .validate()
103 .map_err(|e| e.in_section("body_rate"))?;
104 self.attitude
105 .validate()
106 .map_err(|e| e.in_section("attitude"))?;
107 self.yaw.validate().map_err(|e| e.in_section("yaw"))?;
108 let scales = &self.full_scale_rates_radps;
109 check_limit("full_scale_rates_radps.x", scales.x)?;
110 check_limit("full_scale_rates_radps.y", scales.y)?;
111 check_limit("full_scale_rates_radps.z", scales.z)?;
112 check_positive("thrust_curve_exponent", self.thrust_curve_exponent)
113 }
114}
115
116/// The inner loop for vehicles like quadcopters, implementing a cascaded control system.
117///
118/// This controller supports rate and attitude control loops, with configurable gains for
119/// each loop. It tracks a [`Setpoint`] ([`RateSetpoint`] or [`AttitudeSetpoint`]) and
120/// generates motor control outputs ([`ControlOutput`]).
121///
122/// # Examples
123///
124/// ```
125/// use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
126/// use stable_flight::{AttitudeSetpoint, Setpoint, Stabilizer, VehicleState};
127///
128/// let mut stabilizer = CopterStabilizer::new(CopterStabilizerConfig::default());
129/// let hover = Setpoint::Attitude(AttitudeSetpoint { thrust: 0.5, ..Default::default() });
130///
131/// let output = stabilizer.stabilize(0.004, &hover, &VehicleState::default());
132/// assert_eq!(output.thrust, 0.25); // 0.5 through the default quadratic thrust curve
133/// ```
134pub struct CopterStabilizer {
135 /// Gains and limits, passed into each controller every tick.
136 config: CopterStabilizerConfig,
137
138 body_rate: BodyRateController,
139 attitude: AttitudeController,
140 yaw: YawController,
141
142 /// What the last `stabilize` call clipped.
143 saturation: Saturation,
144}
145
146impl CopterStabilizer {
147 /// Creates a new [CopterStabilizer] with the specified configuration.
148 ///
149 /// # Arguments
150 ///
151 /// * `config` - Configuration for the controller, including PID gains and thrust curve exponent.
152 ///
153 /// # Panics
154 ///
155 /// If `config` is invalid ([`CopterStabilizerConfig::validate`]).
156 pub fn new(config: CopterStabilizerConfig) -> Self {
157 if let Err(error) = config.validate() {
158 panic!("invalid CopterStabilizerConfig: {error}");
159 }
160 CopterStabilizer {
161 config,
162 body_rate: BodyRateController::default(),
163 attitude: AttitudeController::default(),
164 yaw: YawController::default(),
165 saturation: Saturation::default(),
166 }
167 }
168}
169
170impl Configurable for CopterStabilizer {
171 type Config = CopterStabilizerConfig;
172
173 fn config(&self) -> &CopterStabilizerConfig {
174 &self.config
175 }
176
177 /// Validates with [`CopterStabilizerConfig::validate`].
178 fn set_config(&mut self, config: CopterStabilizerConfig) -> Result<(), InvalidConfig> {
179 config.validate()?;
180 let old = &self.config;
181 self.body_rate
182 .rescale_integral(&old.body_rate, &config.body_rate);
183 self.attitude
184 .rescale_integral(&old.attitude, &config.attitude);
185 self.yaw.rescale_integral(&old.yaw, &config.yaw);
186 self.config = config;
187 Ok(())
188 }
189}
190
191impl Stabilizer for CopterStabilizer {
192 /// Tracks a setpoint and generates motor control outputs based on the current vehicle state.
193 ///
194 /// # Arguments
195 ///
196 /// * `dt` - Time step since the last update in seconds (must be positive and finite).
197 /// * `setpoint` - The attitude or rate target.
198 /// * `estimated_state` - The current state of the vehicle (attitude, angular rates, etc.).
199 ///
200 /// # Returns
201 ///
202 /// A [ControlOutput] containing the normalized thrust (0.0 to 1.0) and moments (roll, pitch, yaw) in N·m.
203 fn stabilize(
204 &mut self,
205 dt: f32,
206 setpoint: &Setpoint,
207 estimated_state: &VehicleState,
208 ) -> ControlOutput {
209 assert_dt(dt);
210 self.saturation = Saturation::default();
211
212 let output = match setpoint {
213 Setpoint::Attitude(attitude) => self.track_attitude(dt, attitude, estimated_state),
214 Setpoint::Rate(rates) => {
215 // The attitude and heading loops are idle: clear them so a switch back to
216 // attitude flight carries no stale integral or derivative history (#70).
217 self.attitude = AttitudeController::default();
218 self.yaw = YawController::default();
219 self.track_rates(dt, rates, estimated_state)
220 }
221 };
222
223 // The rate loop clamps each moment to [-1, 1]; landing on a bound means it clipped.
224 self.saturation.moments = output.moments.map(|m| m.abs() >= 1.0).into();
225 output
226 }
227
228 /// Clears the body-rate, attitude, and yaw controller state (integrals and derivative
229 /// history), so control after arming starts from zero.
230 fn prime(&mut self, _state: &VehicleState) {
231 self.body_rate = BodyRateController::default();
232 self.attitude = AttitudeController::default();
233 self.yaw = YawController::default();
234 self.saturation = Saturation::default();
235 }
236
237 /// `tilt` when an attitude setpoint's roll or pitch was beyond
238 /// [`max_angles_rad`](AttitudeControllerConfig::max_angles_rad), `thrust` when the
239 /// setpoint's thrust was outside `[0, 1]`, and `moments` per axis when the rate loop's
240 /// output hit ±1.
241 fn saturation(&self) -> Saturation {
242 self.saturation
243 }
244}
245
246impl CopterStabilizer {
247 /// Tracks an [AttitudeSetpoint].
248 ///
249 /// Converts the desired roll, pitch, and heading into angular rates using the attitude and
250 /// yaw controllers, then passes the rates to the rate controller to generate moments.
251 ///
252 /// # Arguments
253 ///
254 /// * `dt` - Time step since the last update in seconds (must be positive and finite).
255 /// * `setpoint` - The desired roll, pitch, and heading (radians), and linear thrust.
256 /// * `estimated_state` - The current state of the vehicle (attitude, angular rates, etc.).
257 ///
258 /// # Returns
259 ///
260 /// A `ControlOutput` containing the normalized thrust (0.0 to 1.0) and moments (roll, pitch, yaw) in N·m.
261 fn track_attitude(
262 &mut self,
263 dt: f32,
264 setpoint: &AttitudeSetpoint,
265 estimated_state: &VehicleState,
266 ) -> ControlOutput {
267 // Roll/pitch saturate inside the attitude controller, thrust in the thrust curve (see
268 // `crate::math`).
269 let desired_angles_rad = Vec2::new(setpoint.roll_rad, setpoint.pitch_rad);
270 let max_angles_rad = self.config.attitude.max_angles_rad;
271 // `>` is false for NaN, which the attitude controller treats as level.
272 self.saturation.tilt = desired_angles_rad.x.abs() > max_angles_rad.x
273 || desired_angles_rad.y.abs() > max_angles_rad.y;
274 // The quaternion is the canonical attitude; `euler_angles` is NaN-safe.
275 let (roll, pitch, current_heading) = euler_angles(&estimated_state.attitude);
276 let current_angles = Vec2::new(roll, pitch);
277
278 let config = &self.config;
279 let desired_rates =
280 self.attitude
281 .control(&config.attitude, dt, desired_angles_rad, current_angles);
282
283 let desired_yaw_rate =
284 self.yaw
285 .control(&config.yaw, dt, setpoint.heading_rad, current_heading);
286
287 let current_rates = Vec3::new(
288 estimated_state.angular_velocity_radps.x,
289 estimated_state.angular_velocity_radps.y,
290 estimated_state.angular_velocity_radps.z,
291 );
292
293 let desired_rates = Vec3::new(desired_rates.x, desired_rates.y, desired_yaw_rate);
294
295 let moments = self
296 .body_rate
297 .control(&config.body_rate, dt, desired_rates, current_rates);
298
299 ControlOutput {
300 thrust: self.fit_to_thrust_curve(setpoint.thrust),
301 moments,
302 }
303 }
304
305 /// Tracks a [RateSetpoint], bypassing the attitude controller.
306 ///
307 /// # Arguments
308 ///
309 /// * `dt` - Time step since the last update in seconds (must be positive and finite).
310 /// * `setpoint` - The desired roll, pitch, yaw rates (normalized) and linear thrust.
311 /// * `estimated_state` - The current state of the vehicle (angular rates, etc.).
312 ///
313 /// # Returns
314 ///
315 /// A `ControlOutput` containing the normalized thrust (0.0 to 1.0) and moments (roll, pitch, yaw) in N·m.
316 fn track_rates(
317 &mut self,
318 dt: f32,
319 setpoint: &RateSetpoint,
320 estimated_state: &VehicleState,
321 ) -> ControlOutput {
322 // Per-component saturation: `clamp` alone passes NaN, which would zero that axis's
323 // moment (no damping) instead of meaning "hold zero rate".
324 let desired_rates = Vec3::new(
325 saturate_unit(setpoint.roll_rate),
326 saturate_unit(setpoint.pitch_rate),
327 saturate_unit(setpoint.yaw_rate),
328 )
329 .component_mul(&self.config.full_scale_rates_radps);
330
331 let current_rates = Vec3::new(
332 estimated_state.angular_velocity_radps.x,
333 estimated_state.angular_velocity_radps.y,
334 estimated_state.angular_velocity_radps.z,
335 );
336
337 let moments =
338 self.body_rate
339 .control(&self.config.body_rate, dt, desired_rates, current_rates);
340
341 ControlOutput {
342 thrust: self.fit_to_thrust_curve(setpoint.thrust),
343 moments,
344 }
345 }
346
347 /// Applies a nonlinear thrust curve to a linear thrust command.
348 ///
349 /// Maps a linear thrust value (0.0 to 1.0) to a nonlinear output using the configured thrust curve exponent.
350 /// This compensates for nonlinear motor responses. Out-of-range input saturates (flagging
351 /// `thrust`) and NaN becomes 0 (motors off), per the input policy.
352 ///
353 /// # Arguments
354 ///
355 /// * `linear_thrust` - Linear thrust command (0.0 to 1.0).
356 ///
357 /// # Returns
358 ///
359 /// Nonlinear thrust command (0.0 to 1.0).
360 fn fit_to_thrust_curve(&mut self, linear_thrust: f32) -> f32 {
361 self.saturation.thrust = !(0.0..=1.0).contains(&linear_thrust) && !linear_thrust.is_nan();
362 let nonlinear_thrust = libm::powf(
363 saturate_throttle(linear_thrust),
364 self.config.thrust_curve_exponent,
365 );
366 nonlinear_thrust.clamp(0.0, 1.0)
367 }
368}