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//! - A PID per axis, no feedforward; D on the measured rate after the gyro low-pass
13//! (`STAB_GYRO_FLT`) and the optional notch
14//! - Outputs moments to the mixer
15//!
16//! 2. **Middle Loop: Attitude Control (Optional)**
17//! - Controls orientation angles (roll angle, pitch angle, yaw angle)
18//! - Outputs desired angular rates to inner loop
19//! - Saturates the angle setpoint to `max_angles_rad`
20//! - Can be used without outer position loops for manual flight modes
21//!
22//! Both loops run every tick; each loop's form is in
23//! [`controllers`](crate::controllers#loop-shapes).
24//!
25//! The outer position loops (altitude and lateral position) are guidance, not stabilization:
26//! they live in [`CopterGuidance`](crate::guidance::copter::CopterGuidance), which turns
27//! commands into the [`Setpoint`] this stabilizer tracks.
28//!
29//! # Setpoints
30//!
31//! - [`Setpoint::Rate`]: rate loop only (acro), at stick fractions of
32//! [`full_scale_rates_radps`](CopterStabilizerConfig::full_scale_rates_radps); the idle
33//! attitude and heading loops are cleared, so attitude flight resumes from fresh state.
34//! - [`Setpoint::BodyRate`]: the same, at absolute rates saturated to the full-scale rates
35//! (maneuvers, offboard rates).
36//! - [`Setpoint::Plane`], [`Setpoint::PlaneRate`]: a plane stabilizer's; [`Setpoint::Blend`]: a
37//! lift+cruise VTOL's; neutral output.
38//! - [`Setpoint::Attitude`]: attitude and heading loops feeding the rate loop. They act on the
39//! body-frame error from the attitude quaternion: the shortest tilt of the thrust axis onto
40//! the setpoint's (roll and pitch relative to the current heading), then the heading error,
41//! weighted by the cosine of the tilt (PX4 `mc_att_control`, reduced attitude). Near level
42//! that is the per-axis Euler difference; far over (a tailsitter's view in transition) it
43//! stays defined and gives body rates. Roll and pitch saturate to
44//! [`max_angles_rad`](AttitudeControllerConfig::max_angles_rad), pitch to ±π/2 for a
45//! [`transition`](crate::AttitudeSetpoint::transition) ramp.
46//!
47//! An [`idle`](Setpoint::idle) setpoint (guidance's ground idle) clears every loop's integral
48//! after the tick: on the ground there's nothing for the I terms to hold, and they'd wind up
49//! against the resting attitude. Zero thrust alone doesn't: in the air it is the altitude loop
50//! shedding a climb, and the I terms hold the trim.
51//!
52//! # Tuning
53//!
54//! An autotune stage ([`start_probe`](crate::tuning::Tunable::start_probe)) hands one loop to a
55//! [`Probe`](crate::tuning::Probe). Every controller still runs each tick; before
56//! the loop's controller runs, the probe sees its
57//! [`LoopSignals`](crate::tuning::LoopSignals) and replaces the loop's setpoint (a step, or an
58//! identification's square wave).
59//!
60//! | [`TunedLoop`] | Setpoint, error |
61//! |---|---|
62//! | `RollRate`, `PitchRate`, `YawRate` | desired body rate; desired − measured |
63//! | `Roll`, `Pitch` | saturated desired angle; that − estimated angle |
64//! | `Heading` | desired heading; wrapped heading error |
65//!
66//! The signals' `saturated` is the last tick's clip on the loop's path: the axis's moment, and
67//! for an angle or heading loop also its rate setpoint.
68//!
69//! - **Rate stages** replace the rate setpoint the angle loop sets, so the angle loop around
70//! the tested axis has no say while a step runs, and its integral holds: the step tilts or
71//! turns the vehicle away from that loop's setpoint, an error the loop isn't flying.
72//! An identification adds its square wave to that setpoint instead, so the angle loop still
73//! holds the attitude and integrates as usual.
74//! - **Handoff:** when the probe finishes, on [`stop_probe`](crate::tuning::Tunable::stop_probe),
75//! or when a [`Setpoint::Rate`] tick idles the angle or heading loop under test
76//! ([`ProbeStatus::Interrupted`](crate::tuning::ProbeStatus::Interrupted)), the loop
77//! restarts with no derivative history and keeps its I term, which a retune with the tuned
78//! gains rescales like any other (`docs/architecture/config.md#config-ownership`). On an interrupt the
79//! rate tick then clears the idle angle loops, so their I terms are dropped. An angle
80//! stage's identification runs on the rate loop under it, so a rate tick doesn't interrupt
81//! it.
82//! - The stage is runtime state, not config; [`prime`](crate::Stabilizer::prime) ends it.
83
84use crate::{Vec2, Vec3};
85
86use crate::{
87 AttitudeSetpoint, Configurable, ControlOutput, Saturation, Setpoint, Stabilizer, VehicleState,
88};
89
90use crate::controllers::gyro::GyroFilter;
91use crate::controllers::*;
92use crate::controllers::{GyroFilters, NotchConfig};
93use crate::controllers::{check_limit, check_positive};
94use crate::math::{
95 assert_dt, attitude_error, pitch_limit_rad, saturate_rates, saturate_unit, thrust_curve,
96};
97
98mod params;
99#[cfg(test)]
100mod tests;
101mod tuning;
102
103pub use tuning::TunedLoop;
104
105/// Configuration for the [CopterStabilizer]: gains and limits for the inner control loops and
106/// the thrust mapping.
107///
108/// Plain data: [`CopterStabilizer::new`] validates it, and the stabilizer passes it to its
109/// controllers every tick.
110#[derive(Clone, Copy, Debug, PartialEq)]
111pub struct CopterStabilizerConfig {
112 /// Body-rate (inner) loop.
113 pub body_rate: BodyRateControllerConfig,
114 /// Roll/pitch attitude loop ([`Setpoint::Attitude`] only).
115 pub attitude: AttitudeControllerConfig,
116 /// Heading-hold loop ([`Setpoint::Attitude`] only).
117 pub yaw: YawControllerConfig,
118 /// Body rates (roll, pitch, yaw) in rad/s that a full-scale [`RateSetpoint`](crate::RateSetpoint) maps to. Each
119 /// component must be non-negative and finite: an infinite or NaN scale makes even a neutral
120 /// stick a non-finite rate, which zeroes that axis's moment.
121 pub full_scale_rates_radps: Vec3,
122 /// Exponent of the thrust curve applied to the linear thrust setpoint. Must be positive
123 /// and finite: a negative exponent maps zero throttle to full thrust.
124 pub thrust_curve_exponent: f32,
125 /// Cutoff of the low-pass on the body rates the rate loop flies, in Hz; 0 turns it off,
126 /// and so does one at or past Nyquist. Non-negative and finite. Lower: less gyro noise
127 /// and vibration in the moments, more lag in the loop (about 5.6 ms at 40 Hz). The
128 /// default is PX4's `IMU_GYRO_CUTOFF`; on the sim's 0.1 rad/s vibration at 90 Hz, 40 Hz
129 /// passed the most robustness rows, 20 Hz (ArduPilot's `INS_GYRO_FILTER`) and 50 Hz and up
130 /// lost clean rows (#373).
131 pub gyro_cutoff_hz: f32,
132 /// A notch on the roll and pitch rates before the low-pass, for one vibration tone (a
133 /// motor's); off by default. The autotune's design models it with the low-pass. On the
134 /// sim's 0.1 rad/s at 90 Hz under `racer`'s 75 Hz low-pass, a notch at the tone (90 Hz,
135 /// 45 Hz wide, 40 dB) passed the robustness noise row, and flown on every row it changed
136 /// none. The yaw rate stays unnotched, though ArduPilot and PX4 notch all three axes: with
137 /// yaw notched too, `quad_x`'s yaw search overshot the step spec on one noise seed of five
138 /// from both starts (peaks 1.052 and 1.066 against 1.05), which roll and pitch alone
139 /// pass (#597).
140 pub gyro_notch: NotchConfig,
141}
142
143/// [`CopterStabilizerConfig::gyro_cutoff_hz`]'s default, in Hz.
144pub const DEFAULT_GYRO_CUTOFF_HZ: f32 = 40.0;
145
146impl Default for CopterStabilizerConfig {
147 /// Untuned starting values; airframes override them with flight-checked sets.
148 fn default() -> Self {
149 CopterStabilizerConfig {
150 body_rate: BodyRateControllerConfig::default(),
151 attitude: AttitudeControllerConfig::default(),
152 yaw: YawControllerConfig::default(),
153 full_scale_rates_radps: Vec3::new(3.0, 3.0, 3.0),
154 thrust_curve_exponent: 2.0,
155 gyro_cutoff_hz: DEFAULT_GYRO_CUTOFF_HZ,
156 gyro_notch: NotchConfig::default(),
157 }
158 }
159}
160
161impl CopterStabilizerConfig {
162 /// Checks every controller config ([`BodyRateControllerConfig::validate`],
163 /// [`AttitudeControllerConfig::validate`], [`YawControllerConfig::validate`]; errors carry
164 /// the loop as their `section`), that each `full_scale_rates_radps` component is
165 /// non-negative and finite, that `thrust_curve_exponent` is positive and finite, and that
166 /// `gyro_cutoff_hz` is non-negative and finite.
167 ///
168 /// # Examples
169 ///
170 /// ```
171 /// use stable_flight::stabilizers::copter::CopterStabilizerConfig;
172 ///
173 /// let mut config = CopterStabilizerConfig::default();
174 /// assert!(config.validate().is_ok());
175 /// config.yaw.max_rate_radps = -1.0;
176 /// assert!(config.validate().is_err());
177 /// ```
178 pub fn validate(&self) -> Result<(), InvalidConfig> {
179 self.body_rate
180 .validate()
181 .map_err(|e| e.in_section("body_rate"))?;
182 self.attitude
183 .validate()
184 .map_err(|e| e.in_section("attitude"))?;
185 self.yaw.validate().map_err(|e| e.in_section("yaw"))?;
186 let scales = &self.full_scale_rates_radps;
187 check_limit("full_scale_rates_radps.x", scales.x)?;
188 check_limit("full_scale_rates_radps.y", scales.y)?;
189 check_limit("full_scale_rates_radps.z", scales.z)?;
190 check_positive("thrust_curve_exponent", self.thrust_curve_exponent)?;
191 check_limit("gyro_cutoff_hz", self.gyro_cutoff_hz)?;
192 self.gyro_notch
193 .validate()
194 .map_err(|e| e.in_section("gyro_notch"))
195 }
196
197 /// The gyro filters body `axis` (0 roll, 1 pitch, 2 yaw) flies through: on roll and
198 /// pitch, [`gyro_notch`](Self::gyro_notch) then the low-pass at
199 /// [`gyro_cutoff_hz`](Self::gyro_cutoff_hz); on yaw, the low-pass alone.
200 pub fn gyro_filters_on(&self, axis: usize) -> GyroFilters {
201 let notch = if axis < 2 {
202 self.gyro_notch
203 } else {
204 NotchConfig::default()
205 };
206 GyroFilters {
207 cutoff_hz: self.gyro_cutoff_hz,
208 notch,
209 }
210 }
211}
212
213/// The inner loop for vehicles like quadcopters, implementing a cascaded control system.
214///
215/// This controller supports rate and attitude control loops, with configurable gains for
216/// each loop. It tracks a [`Setpoint`] ([`RateSetpoint`](crate::RateSetpoint) or [`AttitudeSetpoint`]) and
217/// generates motor control outputs ([`ControlOutput`]).
218///
219/// # Examples
220///
221/// ```
222/// use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
223/// use stable_flight::{AttitudeSetpoint, Setpoint, Stabilizer, VehicleState};
224///
225/// let mut stabilizer = CopterStabilizer::new(CopterStabilizerConfig::default());
226/// let hover = Setpoint::Attitude(AttitudeSetpoint { thrust: 0.5, ..Default::default() });
227///
228/// let output = stabilizer.stabilize(0.004, &hover, &VehicleState::default());
229/// assert_eq!(output.thrust, 0.25); // 0.5 through the default quadratic thrust curve
230/// ```
231pub struct CopterStabilizer {
232 /// Gains and limits, passed into each controller every tick.
233 config: CopterStabilizerConfig,
234
235 body_rate: BodyRateController,
236 attitude: AttitudeController,
237 yaw: YawController,
238
239 /// What the last `stabilize` call clipped.
240 saturation: Saturation,
241
242 /// The autotune stage, if one was started and not yet stopped.
243 stage: Option<tuning::Stage>,
244
245 /// What the last `stabilize` call clipped per axis, for a probe's
246 /// [`LoopSignals::saturated`](crate::tuning::LoopSignals::saturated).
247 clipped: Clipped,
248
249 /// The moments the last `stabilize` call commanded (roll, pitch, yaw), for a probe's
250 /// [`LoopSignals::last_moment`](crate::tuning::LoopSignals::last_moment).
251 last_moments: Vec3,
252
253 /// The low-pass per body rate (roll, pitch, yaw) at
254 /// [`gyro_cutoff_hz`](CopterStabilizerConfig::gyro_cutoff_hz).
255 gyro_filters: [GyroFilter; 3],
256}
257
258/// Per-axis clips (roll, pitch, yaw) of one tick.
259#[derive(Clone, Copy, Debug, Default, PartialEq)]
260struct Clipped {
261 /// The rate loop's moment hit ±1.
262 moments: [bool; 3],
263 /// The attitude or heading loop's rate setpoint hit its `max_rate_radps`.
264 rates: [bool; 3],
265}
266
267impl CopterStabilizer {
268 /// Creates a new [CopterStabilizer] with the specified configuration.
269 ///
270 /// # Arguments
271 ///
272 /// * `config` - Configuration for the controller, including PID gains and thrust curve exponent.
273 ///
274 /// # Panics
275 ///
276 /// If `config` is invalid ([`CopterStabilizerConfig::validate`]).
277 pub fn new(config: CopterStabilizerConfig) -> Self {
278 if let Err(error) = config.validate() {
279 panic!("invalid CopterStabilizerConfig: {error}");
280 }
281 CopterStabilizer {
282 config,
283 body_rate: BodyRateController::default(),
284 attitude: AttitudeController::default(),
285 yaw: YawController::default(),
286 saturation: Saturation::default(),
287 stage: None,
288 clipped: Clipped::default(),
289 last_moments: Vec3::zeros(),
290 gyro_filters: Default::default(),
291 }
292 }
293}
294
295impl Configurable for CopterStabilizer {
296 type Config = CopterStabilizerConfig;
297
298 fn config(&self) -> &CopterStabilizerConfig {
299 &self.config
300 }
301
302 /// Validates with [`CopterStabilizerConfig::validate`].
303 fn set_config(&mut self, config: CopterStabilizerConfig) -> Result<(), InvalidConfig> {
304 config.validate()?;
305 let old = &self.config;
306 self.attitude
307 .rescale_integral(&old.attitude, &config.attitude);
308 self.yaw.rescale_integral(&old.yaw, &config.yaw);
309 self.config = config;
310 Ok(())
311 }
312}
313
314impl Stabilizer for CopterStabilizer {
315 /// Tracks a setpoint and generates motor control outputs based on the current vehicle state.
316 ///
317 /// # Arguments
318 ///
319 /// * `dt` - Time step since the last update in seconds (must be positive and finite).
320 /// * `setpoint` - The attitude or rate target.
321 /// * `estimated_state` - The current state of the vehicle (attitude, angular rates, etc.).
322 ///
323 /// # Returns
324 ///
325 /// A [ControlOutput] containing the normalized thrust (0.0 to 1.0) and moments (roll, pitch, yaw) in N·m.
326 fn stabilize(
327 &mut self,
328 dt: f32,
329 setpoint: &Setpoint,
330 estimated_state: &VehicleState,
331 ) -> ControlOutput {
332 assert_dt(dt);
333 self.saturation = Saturation::default();
334
335 let output = match setpoint {
336 Setpoint::Attitude(attitude) => self.track_attitude(dt, attitude, estimated_state),
337 Setpoint::Rate(rates) => {
338 // Per-component saturation: `clamp` alone passes NaN, which would zero that
339 // axis's moment (no damping) instead of meaning "hold zero rate".
340 let fractions = Vec3::new(
341 saturate_unit(rates.roll_rate),
342 saturate_unit(rates.pitch_rate),
343 saturate_unit(rates.yaw_rate),
344 );
345 let desired = fractions.component_mul(&self.config.full_scale_rates_radps);
346 self.track_rates(dt, desired, rates.thrust, estimated_state)
347 }
348 Setpoint::BodyRate(rates) => {
349 let desired = saturate_rates(
350 Vec3::new(rates.roll_radps, rates.pitch_radps, rates.yaw_radps),
351 self.config.full_scale_rates_radps,
352 );
353 self.track_rates(dt, desired, rates.thrust, estimated_state)
354 }
355 // A plane stabilizer's setpoints: neutral (the trait's rule for unsupported ones).
356 Setpoint::Plane(_) | Setpoint::PlaneRate(_) | Setpoint::Blend(_) => {
357 ControlOutput::default()
358 }
359 };
360
361 // At ground idle the I terms can't act on anything and would wind up against a
362 // resting attitude, to kick at liftoff; clear them every such tick. ArduPilot decays
363 // its rate I terms at GROUND_IDLE instead (`ModeStabilize::run`,
364 // `reset_rate_controller_I_terms_smoothly`); which to follow is #397.
365 if setpoint.idle() {
366 self.body_rate.clear_integral();
367 self.attitude.clear_integral();
368 self.yaw.clear_integral();
369 }
370
371 // The rate loop clamps each moment to [-1, 1]; landing on a bound means it clipped.
372 self.saturation.moments = output.moments.map(|m| m.abs() >= 1.0).into();
373 self.clipped.moments = self.saturation.moments;
374 self.last_moments = output.moments;
375 self.finish_stage();
376 output
377 }
378
379 /// Clears the body-rate, attitude, and yaw controller state (integrals and derivative
380 /// history) and the gyro filters, so control after arming starts from zero, and ends any
381 /// tuning stage.
382 fn prime(&mut self, _state: &VehicleState) {
383 self.stage = None;
384 self.clipped = Clipped::default();
385 self.last_moments = Vec3::zeros();
386 self.gyro_filters = Default::default();
387 self.body_rate = BodyRateController::default();
388 self.attitude = AttitudeController::default();
389 self.yaw = YawController::default();
390 self.saturation = Saturation::default();
391 }
392
393 /// `tilt` when an attitude setpoint's roll or pitch was beyond
394 /// [`max_angles_rad`](AttitudeControllerConfig::max_angles_rad), `thrust` when the
395 /// setpoint's thrust was outside `[0, 1]`, and `moments` per axis when the rate loop's
396 /// output hit ±1.
397 fn saturation(&self) -> Saturation {
398 self.saturation
399 }
400}
401
402impl CopterStabilizer {
403 /// Tracks an [AttitudeSetpoint].
404 ///
405 /// Converts the desired roll, pitch, and heading into angular rates using the attitude and
406 /// yaw controllers, then passes the rates to the rate controller to generate moments.
407 ///
408 /// # Arguments
409 ///
410 /// * `dt` - Time step since the last update in seconds (must be positive and finite).
411 /// * `setpoint` - The desired roll, pitch, and heading (radians), and linear thrust.
412 /// * `estimated_state` - The current state of the vehicle (attitude, angular rates, etc.).
413 ///
414 /// # Returns
415 ///
416 /// A `ControlOutput` containing the normalized thrust (0.0 to 1.0) and moments (roll, pitch, yaw) in N·m.
417 fn track_attitude(
418 &mut self,
419 dt: f32,
420 setpoint: &AttitudeSetpoint,
421 estimated_state: &VehicleState,
422 ) -> ControlOutput {
423 // Roll/pitch saturate inside the attitude controller, thrust in the thrust curve (see
424 // `crate::math`).
425 let max_angles_rad = self.max_angles_rad(setpoint);
426 // `>` is false for NaN, which saturates to level.
427 self.saturation.tilt = setpoint.roll_rad.abs() > max_angles_rad.x
428 || setpoint.pitch_rad.abs() > max_angles_rad.y;
429 let attitude = &estimated_state.attitude;
430 let saturate_tilt = |roll_rad: f32, pitch_rad: f32, heading_rad: f32| {
431 let tilt = AttitudeController::saturate_setpoint(
432 max_angles_rad,
433 Vec2::new(roll_rad, pitch_rad),
434 );
435 Vec3::new(tilt.x, tilt.y, heading_rad)
436 };
437
438 // Roll, pitch, and heading setpoints; a probe on one of these loops may replace one.
439 // A NaN heading gives a NaN yaw error, which the yaw loop holds on (no yaw rate).
440 let mut desired =
441 saturate_tilt(setpoint.roll_rad, setpoint.pitch_rad, setpoint.heading_rad);
442 let error_for = |angles: &Vec3| attitude_error(attitude, angles.x, angles.y, angles.z);
443 let mut error = error_for(&desired);
444 let probed = desired;
445 // The raw rates: the identify fit models the airframe, without the gyro filter's lag.
446 self.probe_attitude(
447 dt,
448 &mut desired,
449 &error,
450 &estimated_state.angular_velocity_radps,
451 );
452 // `!=` is true for a NaN heading too; recomputing is harmless.
453 if desired != probed {
454 desired = saturate_tilt(desired.x, desired.y, desired.z);
455 error = error_for(&desired);
456 }
457
458 // The loops act on the body-frame rotation to the setpoint, so their outputs are body
459 // rates at any attitude (a tailsitter's view pitches far over in transition).
460 let [hold_roll, hold_pitch, hold_heading] = self.held_integrals();
461 let config = &self.config;
462 let desired_rates =
463 self.attitude
464 .control_error(&config.attitude, dt, error.xy(), [hold_roll, hold_pitch]);
465 let desired_yaw_rate = self
466 .yaw
467 .control_error(&config.yaw, dt, error.z, hold_heading);
468 // The controllers clamp their rate outputs; landing on a bound means they clipped.
469 let max_rates = config.attitude.max_rate_radps;
470 self.clipped.rates = [
471 desired_rates.x.abs() >= max_rates.x,
472 desired_rates.y.abs() >= max_rates.y,
473 desired_yaw_rate.abs() >= config.yaw.max_rate_radps,
474 ];
475
476 let desired_rates = Vec3::new(desired_rates.x, desired_rates.y, desired_yaw_rate);
477 let moments = self.track_body_rates(dt, desired_rates, estimated_state);
478
479 ControlOutput {
480 thrust: self.fit_to_thrust_curve(setpoint.thrust),
481 moments,
482 cruise: None,
483 }
484 }
485
486 /// The roll and pitch limits for `setpoint`: `max_angles_rad`, with pitch lifted to ±π/2
487 /// for a transition ramp.
488 fn max_angles_rad(&self, setpoint: &AttitudeSetpoint) -> Vec2 {
489 let limits_rad = self.config.attitude.max_angles_rad;
490 Vec2::new(
491 limits_rad.x,
492 pitch_limit_rad(limits_rad.y, setpoint.transition),
493 )
494 }
495
496 /// Tracks body rates in rad/s with linear `thrust`, bypassing the attitude controller.
497 fn track_rates(
498 &mut self,
499 dt: f32,
500 desired_rates_radps: Vec3,
501 thrust: f32,
502 estimated_state: &VehicleState,
503 ) -> ControlOutput {
504 // The attitude and heading loops are idle: a stage on one of them ends, and they are
505 // cleared so a switch back to attitude flight carries no stale integral or derivative
506 // history.
507 self.interrupt_attitude_stage();
508 self.attitude = AttitudeController::default();
509 self.yaw = YawController::default();
510 self.clipped.rates = [false; 3];
511
512 let moments = self.track_body_rates(dt, desired_rates_radps, estimated_state);
513 ControlOutput {
514 thrust: self.fit_to_thrust_curve(thrust),
515 moments,
516 cruise: None,
517 }
518 }
519
520 /// Runs the body-rate loop toward `desired_rates_radps` on the gyro-filtered rates; a stage
521 /// on a rate loop replaces that axis's rate setpoint.
522 fn track_body_rates(
523 &mut self,
524 dt: f32,
525 desired_rates_radps: Vec3,
526 estimated_state: &VehicleState,
527 ) -> Vec3 {
528 let current_rates = self.filter_rates(dt, estimated_state.angular_velocity_radps);
529 let mut desired_rates_radps = desired_rates_radps;
530 self.probe_rates(
531 dt,
532 &mut desired_rates_radps,
533 ¤t_rates,
534 &estimated_state.angular_velocity_radps,
535 );
536 self.body_rate.control(
537 &self.config.body_rate,
538 dt,
539 desired_rates_radps,
540 current_rates,
541 )
542 }
543
544 /// `rates_radps` (body frame, roll, pitch, yaw) through each axis's gyro filters
545 /// ([`CopterStabilizerConfig::gyro_filters_on`]).
546 fn filter_rates(&mut self, dt: f32, rates_radps: Vec3) -> Vec3 {
547 let config = self.config;
548 Vec3::from_fn(|axis, _| {
549 let filters = config.gyro_filters_on(axis);
550 self.gyro_filters[axis].apply(rates_radps[axis], dt, &filters)
551 })
552 }
553
554 /// Applies a nonlinear thrust curve to a linear thrust command.
555 ///
556 /// Maps a linear thrust value (0.0 to 1.0) to a nonlinear output using the configured thrust curve exponent.
557 /// This compensates for nonlinear motor responses. Out-of-range input saturates (flagging
558 /// `thrust`) and NaN becomes 0 (motors off), per the input policy.
559 ///
560 /// # Arguments
561 ///
562 /// * `linear_thrust` - Linear thrust command (0.0 to 1.0).
563 ///
564 /// # Returns
565 ///
566 /// Nonlinear thrust command (0.0 to 1.0).
567 fn fit_to_thrust_curve(&mut self, linear_thrust: f32) -> f32 {
568 self.saturation.thrust = !(0.0..=1.0).contains(&linear_thrust) && !linear_thrust.is_nan();
569 thrust_curve(linear_thrust, self.config.thrust_curve_exponent)
570 }
571}