Skip to main content

stable_flight/
lib.rs

1//! [![github]](https://github.com/wboayue/stable-flight) [![crates-io]](https://crates.io/crates/stable-flight) [![license]](https://opensource.org/licenses/MIT)
2//!
3//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5//! [license]: https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge&labelColor=555555
6//!
7//! <br>
8//!
9//! Flight-control core for the Stable Flight controller: the pipeline traits ([`Commander`],
10//! [`StateSource`] + [`Actuator`] = [`Vehicle`], [`Guidance`], [`Stabilizer`], [`Mixer`],
11//! [`TelemetryPublisher`]), the data passed between them, copter guidance, the cascaded-PID
12//! stabilizers, the mixers, and [`FlightLoop`], which sequences one control tick.
13//!
14//! This crate is `no_std` and has no simulator, I/O, or timing dependencies, so the same code
15//! runs in software-in-the-loop simulation
16//! ([`stable-flight-sitl`](https://crates.io/crates/stable-flight-sitl)) and, later, on flight
17//! hardware. See the
18//! [architecture overview](https://github.com/wboayue/stable-flight/blob/main/architecture.md).
19
20#![cfg_attr(not(test), no_std)]
21
22pub mod commanders;
23pub mod composition;
24pub mod controllers;
25pub mod estimation;
26pub mod flight_loop;
27pub mod guidance;
28mod math;
29pub mod mixers;
30pub mod params;
31pub mod stabilizers;
32#[cfg(any(test, feature = "testing"))]
33pub mod testing;
34pub mod timing;
35pub mod tuning;
36pub mod view;
37
38use core::time::Duration;
39
40#[doc(inline)]
41pub use composition::ComposedVehicle;
42#[doc(inline)]
43pub use flight_loop::FlightLoop;
44pub use view::View;
45
46use nalgebra::UnitQuaternion;
47
48pub use estimation::wind::WindEstimate;
49pub use math::{euler_angles, wrap_angle};
50
51/// Re-export of the [`nalgebra`] version this crate's public types use; depend on it through
52/// here so the versions can't diverge.
53///
54/// # Examples
55///
56/// ```
57/// use stable_flight::VehicleState;
58/// use stable_flight::nalgebra::UnitQuaternion;
59///
60/// let state = VehicleState {
61///     attitude: UnitQuaternion::from_euler_angles(0.0, 0.1, 0.0),
62///     ..Default::default()
63/// };
64/// assert!(state.attitude.angle() > 0.0);
65/// ```
66pub use nalgebra;
67
68/// 2D vector used throughout the pipeline (waypoint positions, tilt, controller limits).
69///
70/// # Examples
71///
72/// ```
73/// use stable_flight::Vec2;
74///
75/// let tilt = Vec2::new(0.3, -0.1);
76/// assert_eq!(tilt.component_mul(&Vec2::new(2.0, 2.0)), Vec2::new(0.6, -0.2));
77/// ```
78pub type Vec2 = nalgebra::Vector2<f32>;
79
80/// 3D vector used throughout the pipeline (state vectors, moments, rates). Element-wise
81/// products are `component_mul`; `*` between two vectors is a matrix product.
82///
83/// # Examples
84///
85/// ```
86/// use stable_flight::Vec3;
87///
88/// let rates = Vec3::new(3.0, 4.0, 0.0);
89/// assert_eq!(rates.norm(), 5.0);
90/// ```
91pub type Vec3 = nalgebra::Vector3<f32>;
92
93/// Standard gravity, in m/s².
94pub const GRAVITY: f32 = 9.806_65;
95
96// Commanders
97
98/// Represents an entity that produces flight control commands.
99///
100/// The `Commander` trait is responsible for producing the next flight control command given the elapsed time (dt) and the current vehicle state (current_state).
101/// This allows for time-dependent and state-dependent command generation, such as ramping values, coordinating timed sequences, or adjusting commands based on the aircraft’s position or velocity.
102///
103/// Implementors of this trait may include:
104/// - **User input handlers**: Translate joystick/keyboard inputs into manual commands (e.g., [ControlInput::Attitude] or [ControlInput::Rate]).
105/// - **Navigation systems**: Generate waypoint commands (e.g., [ControlInput::Waypoint]) for autonomous flight to specific locations.
106/// - **Mission controllers**: Produce commands based on predefined flight plans or mission objectives.
107/// - **Formation controllers**: Maintain relative positioning between multiple aircraft in a formation.
108///
109/// # Examples
110///
111/// Implementing a simple `Commander` that always returns a constant `Attitude` command:
112/// ```
113/// use stable_flight::VehicleState;
114/// use stable_flight::{AttitudeCommand, Command, Commander, ControlInput};
115///
116/// struct ConstantAttitudeCommander;
117///
118/// impl Commander for ConstantAttitudeCommander {
119///     fn next_command(&mut self, dt: f32, current_state: &VehicleState) -> Command {
120///         Command::armed(ControlInput::Attitude(AttitudeCommand {
121///             throttle: 0.5,  // 50% throttle
122///             roll: 0.0,      // No roll
123///             pitch: 0.0,     // No pitch
124///             yaw: 0.0,       // No yaw
125///         }))
126///     }
127/// }
128/// ```
129pub trait Commander {
130    /// Produces the next command to be executed by the flight control system.
131    ///
132    /// # Parameters
133    ///
134    /// - `dt`: The time elapsed since the last command was generated in seconds.
135    ///   This allows for time-dependent command generation, such as ramping up values
136    ///   gradually or handling timed sequences.
137    /// - `current_state`: The current state of the vehicle, as a `VehicleState`.
138    ///   Typically includes information like position, velocity, attitude, and other
139    ///   relevant data, allowing the commander to generate state-dependent commands.
140    ///
141    /// # Returns
142    ///
143    /// A [`Command`]: whether the vehicle should be armed, and the [`ControlInput`] to fly.
144    /// `arm` is a level, not an event: return the desired state every tick.
145    fn next_command(&mut self, dt: f32, current_state: &VehicleState) -> Command;
146
147    /// Which commander a failsafe let fly on the last [`next_command`](Self::next_command)
148    /// call, for a commander that has one
149    /// ([`FailsafeCommander`](crate::commanders::FailsafeCommander)). [`FlightLoop`] puts it in
150    /// the tick's [`TelemetryRecord::failsafe`]. The default reports none, so a commander that
151    /// wraps another must forward this to report the inner one's.
152    fn failsafe(&self) -> Option<FailsafeState> {
153        None
154    }
155}
156
157/// Which commander a [`FailsafeCommander`](crate::commanders::FailsafeCommander) let fly: its
158/// link-fed primary, or the fallback after the link went stale.
159///
160/// # Examples
161///
162/// ```
163/// use stable_flight::FailsafeState;
164///
165/// let link_ok = |state: Option<FailsafeState>| state != Some(FailsafeState::Fallback);
166/// assert!(link_ok(Some(FailsafeState::Primary)));
167/// assert!(link_ok(Some(FailsafeState::AwaitingSticks))); // heard, not yet in control
168/// assert!(link_ok(None)); // no failsafe: nothing to report
169/// assert!(!link_ok(Some(FailsafeState::Fallback)));
170/// ```
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
173#[non_exhaustive]
174pub enum FailsafeState {
175    /// The primary (link-fed) commander flies.
176    Primary,
177    /// The primary went stale, or hasn't been heard yet; the fallback flies.
178    Fallback,
179    /// The primary is fresh again, but flies sticks over an armed vehicle: the fallback flies
180    /// until a stick moves, so a forgotten joystick can't take over.
181    AwaitingSticks,
182}
183
184/// One tick's command from a [`Commander`]: whether the vehicle should be armed, which
185/// [`FlightRegime`] to fly in, and what to fly.
186///
187/// `arm` is vehicle-level and applies to every [`ControlInput`]. It is a level, not an event:
188/// a commander returns the desired state every tick (an edge-triggered source, such as a
189/// MAVLink arm request, latches it in the commander). While `arm` is `false`,
190/// [`FlightLoop`] holds the actuators at [`ActuatorCommand::default`] (motors off) and
191/// doesn't run guidance or the stabilizer; on the tick it turns `true`, it re-primes them so
192/// integrators start from zero.
193///
194/// `regime` is a level too: the regime the commander wants, every tick. Guidance owns the
195/// regime actually flown and moves toward the request ([`FlightModeReport`]), so repeating a
196/// request can't restart a transition. It is orthogonal to `input`: the input says what to
197/// fly, the regime how.
198///
199/// # Examples
200///
201/// ```
202/// use stable_flight::{AttitudeCommand, Command, ControlInput, FlightRegime};
203///
204/// let hover = Command::armed(ControlInput::Attitude(AttitudeCommand {
205///     throttle: 0.5,
206///     ..Default::default()
207/// }));
208/// assert!(hover.arm);
209/// assert_eq!(hover.regime, FlightRegime::Copter);
210///
211/// let switch_off = false;
212/// assert!(!Command::new(switch_off, hover.input).arm);
213///
214/// let cruise = hover.with_regime(FlightRegime::Plane);
215/// assert_eq!(cruise.regime, FlightRegime::Plane);
216/// ```
217#[derive(Debug, Default, Clone, Copy, PartialEq)]
218#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
219pub struct Command {
220    /// `true` to arm (motors may run), `false` to disarm (motors held off). Defaults to
221    /// `false`.
222    pub arm: bool,
223
224    /// The regime to fly in. Defaults to [`FlightRegime::Copter`].
225    pub regime: FlightRegime,
226
227    /// What to fly while armed. Ignored while disarmed.
228    pub input: ControlInput,
229}
230
231impl Command {
232    /// A command with the given arm state, in [`FlightRegime::Copter`].
233    pub fn new(arm: bool, input: ControlInput) -> Self {
234        Command {
235            arm,
236            regime: FlightRegime::default(),
237            input,
238        }
239    }
240
241    /// An armed command: fly `input`.
242    pub fn armed(input: ControlInput) -> Self {
243        Command::new(true, input)
244    }
245
246    /// A disarmed command: motors held off; `input` is carried for telemetry only.
247    pub fn disarmed(input: ControlInput) -> Self {
248        Command::new(false, input)
249    }
250
251    /// This command, requesting `regime`.
252    pub fn with_regime(self, regime: FlightRegime) -> Self {
253        Command { regime, ..self }
254    }
255}
256
257/// How the vehicle flies: hovering on its rotors, or wing-borne. Requested by a [`Command`];
258/// what is actually flown, including transitions, is a [`FlightMode`].
259///
260/// A copter-only stack flies [`Copter`](FlightRegime::Copter) whatever is requested and
261/// reports a `Plane` request as [`ModeRefusal::Unsupported`].
262#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
263#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
264#[non_exhaustive]
265pub enum FlightRegime {
266    /// Rotor-borne: hover and copter-style flight. Takeoff and landing are flown here.
267    #[default]
268    Copter,
269    /// Wing-borne forward flight.
270    Plane,
271}
272
273/// The regime guidance is actually flying, including the transitions between regimes. Owned
274/// by [`Guidance`] and reported in a [`FlightModeReport`].
275///
276/// Not to be confused with [`ControlMode`], the kind of the commanded [`ControlInput`]: the
277/// input says what to fly, the flight mode how it's being flown.
278#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
279#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
280#[non_exhaustive]
281pub enum FlightMode {
282    /// Flying in [`FlightRegime::Copter`].
283    #[default]
284    Copter,
285    /// Flying in [`FlightRegime::Plane`].
286    Plane,
287    /// Transitioning from copter to plane flight.
288    ToPlane,
289    /// Transitioning from plane to copter flight.
290    ToCopter,
291}
292
293impl FlightMode {
294    /// The regime this mode flies in or is heading to.
295    ///
296    /// # Examples
297    ///
298    /// ```
299    /// use stable_flight::{FlightMode, FlightRegime};
300    ///
301    /// assert_eq!(FlightMode::ToPlane.target(), FlightRegime::Plane);
302    /// assert_eq!(FlightMode::Copter.target(), FlightRegime::Copter);
303    /// ```
304    pub fn target(&self) -> FlightRegime {
305        match self {
306            FlightMode::Copter | FlightMode::ToCopter => FlightRegime::Copter,
307            FlightMode::Plane | FlightMode::ToPlane => FlightRegime::Plane,
308        }
309    }
310}
311
312/// Why guidance isn't flying, or stopped moving toward, the requested [`FlightRegime`].
313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
314#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
315#[non_exhaustive]
316pub enum ModeRefusal {
317    /// This guidance can't fly the requested regime (`Plane` on a copter, `Copter` on a
318    /// plane).
319    Unsupported,
320    /// The vehicle is on the ground; transitions start only in the air.
321    OnGround,
322    /// Too low to start a transition safely.
323    BelowMinAltitude,
324    /// A transition didn't complete in time and was abandoned.
325    TransitionTimeout,
326    /// A transition rolled too far off its target and was abandoned or cut short.
327    RollError,
328    /// Plane flight sank below its minimum height and fell back to copter flight (a
329    /// quadchute).
330    BelowPlaneMinAltitude,
331}
332
333/// The flight mode guidance is flying, and why it isn't the requested regime when it can't
334/// be. From [`Guidance::flight_mode`] (or [`copter_only`](Self::copter_only)); [`FlightLoop`] puts it in
335/// [`TelemetryRecord::flight_mode`].
336///
337/// # Examples
338///
339/// ```
340/// use stable_flight::{FlightMode, FlightModeReport, ModeRefusal};
341///
342/// let refused = FlightModeReport {
343///     mode: FlightMode::Copter,
344///     refusal: Some(ModeRefusal::Unsupported),
345/// };
346/// assert_ne!(refused, FlightModeReport::default());
347/// ```
348#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
349#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
350pub struct FlightModeReport {
351    /// What guidance flies this tick.
352    pub mode: FlightMode,
353    /// Why the requested regime isn't being flown or approached; `None` when it is (or a
354    /// transition toward it is under way).
355    pub refusal: Option<ModeRefusal>,
356}
357
358impl FlightModeReport {
359    /// What a copter-only guidance flies when `requested`: copter, refusing a plane request
360    /// as [`ModeRefusal::Unsupported`].
361    ///
362    /// # Examples
363    ///
364    /// ```
365    /// use stable_flight::{FlightMode, FlightModeReport, FlightRegime, ModeRefusal};
366    ///
367    /// assert_eq!(FlightModeReport::copter_only(FlightRegime::Copter), FlightModeReport::default());
368    /// let refused = FlightModeReport::copter_only(FlightRegime::Plane);
369    /// assert_eq!(refused.mode, FlightMode::Copter);
370    /// assert_eq!(refused.refusal, Some(ModeRefusal::Unsupported));
371    /// ```
372    pub fn copter_only(requested: FlightRegime) -> Self {
373        FlightModeReport {
374            mode: FlightMode::Copter,
375            refusal: (requested != FlightRegime::Copter).then_some(ModeRefusal::Unsupported),
376        }
377    }
378    /// What a plane-only guidance flies when `requested`: plane, refusing a copter request
379    /// as [`ModeRefusal::Unsupported`].
380    ///
381    /// # Examples
382    ///
383    /// ```
384    /// use stable_flight::{FlightMode, FlightModeReport, FlightRegime, ModeRefusal};
385    ///
386    /// let report = FlightModeReport::plane_only(FlightRegime::Plane);
387    /// assert_eq!((report.mode, report.refusal), (FlightMode::Plane, None));
388    /// let refused = FlightModeReport::plane_only(FlightRegime::Copter);
389    /// assert_eq!(refused.refusal, Some(ModeRefusal::Unsupported));
390    /// ```
391    pub fn plane_only(requested: FlightRegime) -> Self {
392        FlightModeReport {
393            mode: FlightMode::Plane,
394            refusal: (requested != FlightRegime::Plane).then_some(ModeRefusal::Unsupported),
395        }
396    }
397}
398
399/// The control input part of a [`Command`]: what the flight system should fly.
400///
401/// The `ControlInput` enum encapsulates different types of commands that can be issued
402/// to control an aircraft:
403///
404/// * `Manual` - Low-level direct control inputs typically generated from user input devices.
405///   This includes:
406///   - `Attitude`: Controls the aircraft's orientation (roll, pitch, yaw).
407///   - `Rate`: Controls the aircraft's rotational rates (rate of change of roll, pitch, yaw).
408/// * `AbsoluteAttitude` - An absolute roll, pitch, and heading with collective thrust, from an
409///   offboard app (e.g. MAVLink `SET_ATTITUDE_TARGET`).
410/// * `AbsoluteRate` - Absolute body rates with collective thrust, from an offboard app or a
411///   maneuver script.
412/// * `Waypoint` - High-level navigational commands used for autonomous flight.
413/// * `Land` - Descend in place until touchdown.
414///
415/// This separation allows the flight control system to handle both manual piloting
416/// and automated navigation with a unified command interface.
417///
418/// # Examples
419///
420/// Creating a manual attitude command:
421/// ```
422/// use stable_flight::{ControlInput, AttitudeCommand};
423///
424/// let manual_cmd = ControlInput::Attitude(AttitudeCommand {
425///     throttle: 0.75,  // 75% throttle
426///     roll: 0.1,       // Slight right bank
427///     pitch: -0.05,    // Slight nose down
428///     yaw: 0.0,        // No yaw input
429///     ..Default::default()
430/// });
431/// ```
432///
433/// Creating a manual rate command:
434/// ```
435/// use stable_flight::{ControlInput, RateCommand};
436///
437/// let rate_cmd = ControlInput::Rate(RateCommand {
438///     throttle: 0.5,   // 50% throttle
439///     roll_rate: 0.2,  // Moderate roll rate
440///     pitch_rate: 0.1, // Moderate pitch rate
441///     yaw_rate: 0.0,   // No yaw rate
442///     ..Default::default()
443/// });
444/// ```
445///
446/// Creating a waypoint command:
447/// ```
448/// use stable_flight::{ControlInput, Vec2, WaypointCommand};
449///
450/// let waypoint_cmd = ControlInput::Waypoint(WaypointCommand {
451///     position_m: Vec2::new(1000.0, 2000.0),    // Target position in world coordinates
452///     velocity_mps: Some(Vec2::new(15.0, 0.0)), // Optional velocity to fly through it with
453///     altitude_m: 500.0,                        // Target altitude in meters
454///     cruise_speed_mps: 25.0,                   // Speed cap on the way
455///     heading_rad: None,                        // Heading as guidance picks it
456/// });
457/// ```
458///
459/// # Notes
460/// - A [`WaypointCommand`] with `velocity_mps: None` stops on the waypoint.
461/// - `#[non_exhaustive]`: new command kinds (e.g. fixed-wing) can be added without a breaking
462///   change. A [`Guidance`] that can't fly a variant must fall back to neutral, not panic (see
463///   [`Guidance::guide`]).
464#[derive(Debug, Clone, Copy, PartialEq)]
465#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
466#[non_exhaustive]
467pub enum ControlInput {
468    /// Direct manual control inputs for the aircraft's attitude (orientation).
469    ///
470    /// These values typically range from -1.0 to 1.0 (or 0.0 to 1.0 for throttle)
471    /// and directly influence the aircraft's roll, pitch, and yaw orientation.
472    /// The ranges are conventional and may not be enforced by the system.
473    Attitude(AttitudeCommand),
474
475    /// Direct manual control inputs for the aircraft's rotational rate.
476    ///
477    /// These values typically range from -1.0 to 1.0 (or 0.0 to 1.0 for throttle)
478    /// and directly influence the rate of change of roll, pitch, and yaw.
479    /// The ranges are conventional and may not be enforced by the system.
480    Rate(RateCommand),
481
482    /// Autonomous navigation command specifying a destination point.
483    ///
484    /// This command provides high-level navigational instructions that are translated
485    /// into appropriate control surface and throttle settings by the flight controller.
486    Waypoint(WaypointCommand),
487
488    /// An absolute attitude in radians and collective thrust, typically from an offboard app.
489    ///
490    /// Unlike [`ControlInput::Attitude`], the angles are not stick positions: roll and pitch
491    /// are flown as given (the stabilizer saturates them to its maximum tilt), and the heading
492    /// is an angle, not a rate.
493    AbsoluteAttitude(AbsoluteAttitudeCommand),
494
495    /// Hold a horizontal position and descend at a steady rate until the ground stops the
496    /// vehicle. Guidance only descends; deciding it has touched down and disarming is the
497    /// commander's job ([`TouchdownDetector`](crate::commanders::TouchdownDetector)).
498    Land(LandCommand),
499
500    /// Absolute body rates in rad/s and collective thrust, typically from an offboard app or a
501    /// maneuver script (a flip, a roll, a loop). Unlike [`ControlInput::Rate`], the rates are
502    /// not stick fractions: they are flown as given, at any attitude.
503    AbsoluteRate(AbsoluteRateCommand),
504}
505
506/// Zero-throttle, centered-stick [`ControlInput::Attitude`].
507impl Default for ControlInput {
508    fn default() -> Self {
509        ControlInput::Attitude(AttitudeCommand::default())
510    }
511}
512
513impl ControlInput {
514    /// Whether this is pilot stick input (attitude or rate). After a link outage, the
515    /// failsafe hands an armed vehicle back to sticks only once they move, so a stick left
516    /// deflected can't take over unattended. Sticks are also a [stream](Self::is_stream).
517    ///
518    /// # Examples
519    ///
520    /// ```
521    /// use stable_flight::ControlInput;
522    ///
523    /// assert!(ControlInput::Attitude(Default::default()).is_sticks());
524    /// assert!(ControlInput::Rate(Default::default()).is_sticks());
525    /// assert!(!ControlInput::AbsoluteAttitude(Default::default()).is_sticks());
526    /// assert!(!ControlInput::Waypoint(Default::default()).is_sticks());
527    /// assert!(!ControlInput::Land(Default::default()).is_sticks());
528    /// ```
529    pub fn is_sticks(&self) -> bool {
530        matches!(self, ControlInput::Attitude(_) | ControlInput::Rate(_))
531    }
532
533    /// Whether this input is a stream that must keep arriving to stay valid (sticks and
534    /// absolute attitudes and rates), unlike a waypoint or a land, which stays valid until replaced. A link-fed
535    /// commander treats a stream as stale once commands stop, even if other messages arrive.
536    ///
537    /// # Examples
538    ///
539    /// ```
540    /// use stable_flight::ControlInput;
541    ///
542    /// assert!(ControlInput::Attitude(Default::default()).is_stream());
543    /// assert!(ControlInput::Rate(Default::default()).is_stream());
544    /// assert!(ControlInput::AbsoluteAttitude(Default::default()).is_stream());
545    /// assert!(ControlInput::AbsoluteRate(Default::default()).is_stream());
546    /// assert!(!ControlInput::Waypoint(Default::default()).is_stream());
547    /// assert!(!ControlInput::Land(Default::default()).is_stream());
548    /// ```
549    pub fn is_stream(&self) -> bool {
550        self.is_sticks()
551            || matches!(
552                self,
553                ControlInput::AbsoluteAttitude(_) | ControlInput::AbsoluteRate(_)
554            )
555    }
556
557    /// Which kind of input this is, without its values: the flight mode a ground station shows.
558    ///
559    /// # Examples
560    ///
561    /// ```
562    /// use stable_flight::{ControlInput, ControlMode};
563    ///
564    /// assert_eq!(ControlInput::Attitude(Default::default()).mode(), ControlMode::Attitude);
565    /// assert_eq!(ControlInput::Rate(Default::default()).mode(), ControlMode::Rate);
566    /// assert_eq!(ControlInput::Waypoint(Default::default()).mode(), ControlMode::Waypoint);
567    /// assert_eq!(
568    ///     ControlInput::AbsoluteAttitude(Default::default()).mode(),
569    ///     ControlMode::AbsoluteAttitude,
570    /// );
571    /// assert_eq!(ControlInput::Land(Default::default()).mode(), ControlMode::Land);
572    /// assert_eq!(
573    ///     ControlInput::AbsoluteRate(Default::default()).mode(),
574    ///     ControlMode::AbsoluteRate,
575    /// );
576    /// ```
577    pub fn mode(&self) -> ControlMode {
578        match self {
579            ControlInput::Attitude(_) => ControlMode::Attitude,
580            ControlInput::Rate(_) => ControlMode::Rate,
581            ControlInput::Waypoint(_) => ControlMode::Waypoint,
582            ControlInput::AbsoluteAttitude(_) => ControlMode::AbsoluteAttitude,
583            ControlInput::Land(_) => ControlMode::Land,
584            ControlInput::AbsoluteRate(_) => ControlMode::AbsoluteRate,
585        }
586    }
587}
588
589/// The kind of a [`ControlInput`], one variant per input variant: the flight mode, compact
590/// enough for a heartbeat. From [`ControlInput::mode`].
591///
592/// `#[non_exhaustive]` like [`ControlInput`]: a new input kind adds a mode, and a consumer
593/// that doesn't know it reports no mode.
594///
595/// The variant order is on the link's wire (`stable-flight-link`'s heartbeat): changing it is
596/// a protocol change, which bumps that crate's `PROTOCOL_VERSION`.
597#[derive(Debug, Clone, Copy, PartialEq, Eq)]
598#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
599#[non_exhaustive]
600pub enum ControlMode {
601    /// Stick inputs command attitude ([`ControlInput::Attitude`]).
602    Attitude,
603    /// Stick inputs command body rates ([`ControlInput::Rate`]).
604    Rate,
605    /// Autonomous flight to a waypoint ([`ControlInput::Waypoint`]).
606    Waypoint,
607    /// An offboard app commands an absolute attitude ([`ControlInput::AbsoluteAttitude`]).
608    AbsoluteAttitude,
609    /// Autonomous descent to touchdown ([`ControlInput::Land`]).
610    Land,
611    /// An offboard app or script commands absolute body rates ([`ControlInput::AbsoluteRate`]).
612    AbsoluteRate,
613}
614
615/// Represents direct manual control of an aircraft's attitude (orientation).
616///
617/// This struct encapsulates pilot inputs from control devices like joysticks,
618/// yokes, or keyboard/mouse combinations to control the aircraft's orientation
619/// (roll, pitch, yaw) and throttle. It is typically used within a `ControlInput::Attitude`
620/// variant to issue manual flight commands to the flight system.
621///
622/// # Value Ranges
623///
624/// - `throttle`: `0.0` (idle) to `1.0` (full power)
625/// - `roll`: `-1.0` (full left bank) to `1.0` (full right bank)
626/// - `pitch`: `-1.0` (full nose down) to `1.0` (full nose up)
627/// - `yaw`: `-1.0` (full left turn) to `1.0` (full right turn)
628///
629/// Note: The specified ranges are conventional and recommended for typical use.
630/// Values outside these ranges may be clamped, ignored, or cause undefined behavior
631/// depending on the flight system's implementation.
632///
633/// # Examples
634///
635/// Creating an `AttitudeCommand` for a slight climb with a right bank:
636/// ```
637/// use stable_flight::AttitudeCommand;
638///
639/// let cmd = AttitudeCommand {
640///     throttle: 0.75,  // 75% throttle
641///     roll: 0.1,       // Slight right bank
642///     pitch: 0.05,     // Slight nose up
643///     yaw: 0.0,        // No yaw input
644/// };
645/// ```
646///
647/// # Default Implementation
648///
649/// The `Default` trait is implemented for `AttitudeCommand`, providing the following
650/// default values:
651/// - `throttle`: `0.0`
652/// - `roll`: `0.0`
653/// - `pitch`: `0.0`
654/// - `yaw`: `0.0`
655#[derive(Debug, Default, Clone, Copy, PartialEq)]
656#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
657pub struct AttitudeCommand {
658    /// Controls the engine power output, ranging from `0.0` (idle) to `1.0` (maximum).
659    pub throttle: f32,
660
661    /// Controls the aircraft's roll/bank angle, ranging from `-1.0` (full left bank)
662    /// to `1.0` (full right bank).
663    pub roll: f32,
664
665    /// Controls the aircraft's pitch angle, ranging from `-1.0` (full nose down)
666    /// to `1.0` (full nose up).
667    pub pitch: f32,
668
669    /// Controls the aircraft's yaw rotation, ranging from `-1.0` (full left turn)
670    /// to `1.0` (full right turn).
671    pub yaw: f32,
672}
673
674/// Represents direct manual control of an aircraft's rotational rates.
675///
676/// This struct encapsulates pilot inputs from control devices like joysticks,
677/// yokes, or keyboard/mouse combinations to control the aircraft's rate of rotation
678/// (roll rate, pitch rate, yaw rate) and throttle. It is typically used within a
679/// `ControlInput::Rate` variant to issue manual flight commands to the flight system.
680///
681/// The "rate" refers to the speed of rotation around each axis, typically measured
682/// in a normalized range where `-1.0` and `1.0` represent the maximum rates supported
683/// by the flight system (e.g., radians per second, scaled to system limits).
684///
685/// # Value Ranges
686///
687/// - `throttle`: `0.0` (idle) to `1.0` (full power)
688/// - `roll_rate`: `-1.0` (maximum left roll rate) to `1.0` (maximum right roll rate)
689/// - `pitch_rate`: `-1.0` (maximum nose-down rate) to `1.0` (maximum nose-up rate)
690/// - `yaw_rate`: `-1.0` (maximum left yaw rate) to `1.0` (maximum right yaw rate)
691///
692/// Note: The specified ranges are conventional and recommended for typical use.
693/// Values outside these ranges may be clamped, ignored, or cause undefined behavior
694/// depending on the flight system's implementation.
695///
696/// # Examples
697///
698/// Creating a `RateCommand` for a moderate right roll and slight nose-up rate:
699/// ```
700/// use stable_flight::RateCommand;
701///
702/// let cmd = RateCommand {
703///     throttle: 0.6,    // 60% throttle
704///     roll_rate: 0.3,   // Moderate right roll rate
705///     pitch_rate: 0.1,  // Slight nose-up rate
706///     yaw_rate: 0.0,    // No yaw rate
707/// };
708/// ```
709///
710/// # Default Implementation
711///
712/// The `Default` trait is implemented for `RateCommand`, providing the following
713/// default values:
714/// - `throttle`: `0.0`
715/// - `roll_rate`: `0.0`
716/// - `pitch_rate`: `0.0`
717/// - `yaw_rate`: `0.0`
718#[derive(Debug, Default, Clone, Copy, PartialEq)]
719#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
720pub struct RateCommand {
721    /// Controls the engine power output, ranging from `0.0` (idle) to `1.0` (maximum).
722    pub throttle: f32,
723
724    /// Controls the aircraft's roll rate, ranging from `-1.0` (maximum left roll rate)
725    /// to `1.0` (maximum right roll rate).
726    pub roll_rate: f32,
727
728    /// Controls the aircraft's pitch rate, ranging from `-1.0` (maximum nose-down rate)
729    /// to `1.0` (maximum nose-up rate).
730    pub pitch_rate: f32,
731
732    /// Controls the aircraft's yaw rate, ranging from `-1.0` (maximum left yaw rate)
733    /// to `1.0` (maximum right yaw rate).
734    pub yaw_rate: f32,
735}
736
737/// Represents a navigational waypoint for autonomous flight.
738///
739/// A `WaypointCommand` instructs the aircraft to navigate to a specific position
740/// in 2D space at a given altitude, at up to a cruise speed, optionally flying through it
741/// with a given velocity. This struct is
742/// typically used within a `ControlInput::Waypoint` variant to issue autonomous navigation
743/// commands to the flight system.
744///
745/// # Value Ranges
746///
747/// - `position_m`: X, Y coordinates in 2D space (units and coordinate system depend on the flight system, typically meters in world coordinates)
748/// - `velocity_mps`: Optional velocity vector in meters per second (north, east), fed forward while flying to the waypoint
749/// - `altitude_m`: Target altitude in meters (typically non-negative; negative values may be interpreted as ground level or cause undefined behavior)
750/// - `cruise_speed_mps`: Speed cap in meters per second while flying to the waypoint; zero, negative, or NaN means no cap
751/// - `heading_rad`: Optional heading in radians from north; any angle, wrapped by guidance
752///
753/// Note: The specified ranges are conventional and recommended for typical use.
754/// Values outside these ranges may be clamped, ignored, or cause undefined behavior
755/// depending on the flight system's implementation.
756///
757/// # Examples
758///
759/// Creating a `WaypointCommand` to navigate to a position with a specific altitude and speed:
760/// ```
761/// use stable_flight::{Vec2, WaypointCommand};
762///
763/// let cmd = WaypointCommand {
764///     position_m: Vec2::new(1000.0, 2000.0),    // Target position (X=1000m, Y=2000m)
765///     velocity_mps: Some(Vec2::new(15.0, 0.0)), // Fly through it northward at 15 m/s
766///     altitude_m: 500.0,                        // Target altitude of 500 meters
767///     cruise_speed_mps: 25.0,                   // At most 25 m/s on the way
768///     heading_rad: Some(0.5),                   // Face 0.5 rad east of north
769/// };
770/// ```
771///
772/// # Behavior of Optional Fields
773///
774/// - If `velocity_mps` is `None`, the aircraft stops on the waypoint.
775///   [`WaypointFollower`](crate::commanders::WaypointFollower) fills it in along each leg so
776///   a route is flown at cruise speed.
777///
778/// # Default Implementation
779///
780/// The `Default` trait is implemented for `WaypointCommand`, providing the following
781/// default values:
782/// - `position_m`: zero
783/// - `velocity_mps`: `None`
784/// - `altitude_m`: `0.0`
785/// - `cruise_speed_mps`: `0.0`
786/// - `heading_rad`: `None`
787#[derive(Debug, Default, Clone, Copy, PartialEq)]
788#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
789pub struct WaypointCommand {
790    /// The target position in 2D space (X, Y coordinates).
791    ///
792    /// The coordinate system and units depend on the flight system implementation
793    /// (typically meters in world coordinates).
794    pub position_m: Vec2,
795
796    /// Optional velocity, in meters per second (north, east), to fly through the waypoint
797    /// with.
798    ///
799    /// Guidance feeds it forward while flying to the waypoint (added to the position loop's
800    /// demand, then capped at `cruise_speed_mps`), so the aircraft passes the waypoint
801    /// instead of stopping on it. `None` stops on the waypoint.
802    /// [`WaypointFollower`](crate::commanders::WaypointFollower) fills it in along each leg
803    /// when it's `None`.
804    pub velocity_mps: Option<Vec2>,
805
806    /// Target altitude in meters.
807    ///
808    /// Typically non-negative; negative values may be interpreted as ground level
809    /// or cause undefined behavior depending on the flight system.
810    pub altitude_m: f32,
811
812    /// Cruise speed in meters per second: the most guidance asks for while flying to the
813    /// waypoint. Zero, negative, or NaN means no cap (the guidance's tilt limit still
814    /// bounds the speed).
815    pub cruise_speed_mps: f32,
816
817    /// Optional heading to hold, in radians from north.
818    ///
819    /// Copter guidance turns its heading-hold target to it at
820    /// [`heading_rate_radps`](crate::guidance::copter::CopterGuidanceConfig::heading_rate_radps),
821    /// instead of along the leg, and never yields it; on a tailsitter it is the hover frame's
822    /// heading, the direction the belly faces. `None` (or NaN) leaves the heading to guidance.
823    /// Plane guidance ignores it.
824    pub heading_rad: Option<f32>,
825}
826
827/// An absolute attitude and collective thrust, for [`ControlInput::AbsoluteAttitude`]: what
828/// an offboard app (e.g. MAVLink `SET_ATTITUDE_TARGET`) asks for, as opposed to the normalized
829/// stick positions of an [`AttitudeCommand`].
830///
831/// Per the input policy, nothing is rejected: the stabilizer saturates roll and pitch to its
832/// maximum tilt and flies NaN as level, a NaN heading holds the current heading-hold target,
833/// and thrust saturates to `[0, 1]` (NaN means none).
834///
835/// # Examples
836///
837/// A 10° right bank, holding north, at 45% thrust:
838/// ```
839/// use stable_flight::{AbsoluteAttitudeCommand, ControlInput};
840///
841/// let input = ControlInput::AbsoluteAttitude(AbsoluteAttitudeCommand {
842///     roll_rad: 10.0_f32.to_radians(),
843///     pitch_rad: 0.0,
844///     heading_rad: 0.0,
845///     thrust: 0.45,
846/// });
847/// ```
848#[derive(Debug, Default, Clone, Copy, PartialEq)]
849#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
850pub struct AbsoluteAttitudeCommand {
851    /// Roll in radians, right positive, per the
852    /// [frame contract](VehicleState#frame-contract)'s `roll_rad`.
853    pub roll_rad: f32,
854    /// Pitch in radians, nose up positive, per the
855    /// [frame contract](VehicleState#frame-contract)'s `pitch_rad`.
856    pub pitch_rad: f32,
857    /// Absolute heading in radians, in the
858    /// [frame contract](VehicleState#frame-contract)'s `heading_rad` convention; any value,
859    /// wrapped by guidance.
860    pub heading_rad: f32,
861    /// Collective thrust along the body axis, `0.0` to `1.0`. Unlike an [`AttitudeCommand`]'s
862    /// throttle, it is not boosted for tilt: the sender owns that compensation.
863    pub thrust: f32,
864}
865
866/// Absolute body rates and collective thrust, for [`ControlInput::AbsoluteRate`]: what a
867/// maneuver or an offboard app (e.g. MAVLink `SET_ATTITUDE_TARGET` body rates) asks for, as
868/// opposed to the stick fractions of a [`RateCommand`].
869///
870/// Per the input policy, nothing is rejected: the stabilizer saturates the rates to its
871/// limits (NaN as zero) and thrust to `[0, 1]` (NaN means none).
872///
873/// # Examples
874///
875/// A full-rate roll to the right at 60% thrust:
876/// ```
877/// use stable_flight::{AbsoluteRateCommand, ControlInput};
878///
879/// let input = ControlInput::AbsoluteRate(AbsoluteRateCommand {
880///     roll_radps: 360.0_f32.to_radians(),
881///     thrust: 0.6,
882///     ..Default::default()
883/// });
884/// ```
885#[derive(Debug, Default, Clone, Copy, PartialEq)]
886#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
887pub struct AbsoluteRateCommand {
888    /// Roll rate about body `x` in rad/s, right positive.
889    pub roll_radps: f32,
890    /// Pitch rate about body `y` in rad/s, nose up positive.
891    pub pitch_radps: f32,
892    /// Yaw rate about body `z` in rad/s, nose right positive.
893    pub yaw_radps: f32,
894    /// Collective thrust, `0.0` to `1.0`.
895    pub thrust: f32,
896}
897
898/// Where to land, for [`ControlInput::Land`]: guidance holds `position_m` while it descends.
899///
900/// # Examples
901///
902/// ```
903/// use stable_flight::{ControlInput, LandCommand, Vec2};
904///
905/// let input = ControlInput::Land(LandCommand { position_m: Vec2::new(10.0, -5.0) });
906/// ```
907#[derive(Debug, Default, Clone, Copy, PartialEq)]
908#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
909pub struct LandCommand {
910    /// Horizontal position to hold, in meters, in the same frame as
911    /// [`WaypointCommand::position_m`].
912    pub position_m: Vec2,
913}
914
915/// Represents the high-level control outputs from the stabilization system.
916///
917/// This struct encapsulates the desired thrust and moments to be applied to the
918/// vehicle, which are later translated to specific actuator commands by a `Mixer`.
919///
920/// Most vehicles fly one set of actuators per output: `thrust` and `moments` reach every
921/// motor and servo the mixer drives. A lift+cruise VTOL (quadplane) flies two at once, its
922/// lift rotors on `thrust` and `moments` and its pusher and control surfaces on
923/// [`cruise`](Self::cruise).
924///
925/// # Examples
926///
927/// Creating a control output for a simple hover command:
928/// ```
929/// use stable_flight::{ControlOutput, Vec3};
930///
931/// let output = ControlOutput::new(
932///     0.5, // 50% thrust
933///     Vec3::zeros() // No roll, pitch, or yaw moments
934/// );
935/// ```
936///
937/// A quadplane in cruise: lift rotors stopped, the pusher and surfaces flying.
938/// ```
939/// use stable_flight::{ControlOutput, CruiseOutput, Vec3};
940///
941/// let output = ControlOutput {
942///     cruise: Some(CruiseOutput { thrust: 0.6, moments: Vec3::new(0.1, 0.0, 0.0) }),
943///     ..Default::default()
944/// };
945/// ```
946#[derive(Debug, Default, Clone, Copy, PartialEq)]
947#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
948pub struct ControlOutput {
949    /// Normalized thrust value, typically ranging from 0.0 (no thrust) to 1.0 (maximum thrust).
950    /// On a lift+cruise VTOL, the lift rotors' collective.
951    pub thrust: f32,
952
953    /// Control moments in roll (x), pitch (y), and yaw (z) axes.
954    /// Values are typically normalized between -1.0 and 1.0, where the magnitude
955    /// represents the proportion of maximum control authority in each axis.
956    /// On a lift+cruise VTOL, the lift rotors' moments only.
957    pub moments: Vec3,
958
959    /// A lift+cruise VTOL's cruise actuators, flown alongside the lift rotors: the pusher's
960    /// thrust and the control surfaces' moments. `None` for every other vehicle, whose servos
961    /// take [`moments`](Self::moments).
962    pub cruise: Option<CruiseOutput>,
963}
964
965impl ControlOutput {
966    /// Creates a new `ControlOutput` with the specified thrust and control moments, and no
967    /// [`cruise`](Self::cruise) output.
968    ///
969    /// # Parameters
970    ///
971    /// - `thrust`: Normalized thrust value, typically between 0.0 and 1.0.
972    /// - `moments`: Control moments as a 3D vector (roll, pitch, yaw).
973    ///
974    /// # Returns
975    ///
976    /// A new `ControlOutput` instance with the specified parameters.
977    pub fn new(thrust: f32, moments: Vec3) -> ControlOutput {
978        ControlOutput {
979            thrust,
980            moments,
981            cruise: None,
982        }
983    }
984}
985
986/// A lift+cruise VTOL's cruise output ([`ControlOutput::cruise`]): what its pusher and
987/// control surfaces fly while the lift rotors fly [`ControlOutput::thrust`] and
988/// [`ControlOutput::moments`].
989///
990/// # Examples
991///
992/// ```
993/// use stable_flight::{CruiseOutput, Vec3};
994///
995/// // Pusher at 60%, ailerons rolling right.
996/// let cruise = CruiseOutput { thrust: 0.6, moments: Vec3::new(0.2, 0.0, 0.0) };
997/// ```
998#[derive(Debug, Default, Clone, Copy, PartialEq)]
999#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1000pub struct CruiseOutput {
1001    /// The pusher's normalized thrust, in `[0, 1]`.
1002    pub thrust: f32,
1003    /// The control surfaces' roll (x), pitch (y), and yaw (z) moments, each in `[-1, 1]`.
1004    pub moments: Vec3,
1005}
1006
1007/// Represents the physical state of a vehicle in 3D space.
1008///
1009/// This struct encapsulates all the key state information needed for flight control,
1010/// including position, velocity, acceleration, attitude, and angular velocity.
1011/// Quantities are plain SI `f32`s; field names carry the unit (`position_m`, `velocity_mps`, …).
1012///
1013/// # Frame contract
1014///
1015/// This table is the reference for how every [`StateSource`] reports state; a backend
1016/// converts from its native frames at its boundary, and `testing::conformance` (`testing`
1017/// feature) checks it.
1018///
1019/// Two frames are involved. Attitude follows aerospace convention: the NED world frame
1020/// (`x` north, `y` east, `z` down) and the FRD body frame (`x` forward, `y` right, `z` down).
1021/// Translation uses the same north and east axes but flips `z` to point **up**, so altitude
1022/// and climb rate are positive: `position_m`/`velocity_mps`/`acceleration_mps2` `z` is NED `z`
1023/// negated.
1024///
1025/// | Quantity | Frame | Units | Positive |
1026/// |---|---|---|---|
1027/// | `position_m` | `x` north, `y` east, `z` up | m | `z` is altitude above the backend's datum (e.g. sea level) |
1028/// | `velocity_mps`, `acceleration_mps2` | as `position_m` | m/s, m/s² | `z` climbing |
1029/// | `attitude` | NED world → FRD body, ZYX (yaw, pitch, roll); `UnitQuaternion::from_euler_angles(roll, pitch, heading)` | — | [`euler_angles`] of it match the fields below |
1030/// | `roll_rad` | about body `x` | rad | right wing down |
1031/// | `pitch_rad` | about body `y` | rad | nose up |
1032/// | `heading_rad` | about NED `z` | rad | clockwise from north (east = π/2); any range, e.g. [0, 2π) or [-π, π) |
1033/// | `angular_velocity_radps` | FRD body: `x` roll, `y` pitch, `z` yaw | rad/s | roll right, nose up, nose right |
1034/// | `airspeed_mps` | speed relative to the air mass (any frame) | m/s | non-negative; `None` without an air-data source |
1035///
1036/// Near ±90° pitch the Euler fields are degenerate: roll and heading turn about the same axis,
1037/// so only their sum (or difference) means anything, and [`euler_angles`] picks one split.
1038/// `attitude` and `angular_velocity_radps` stay well defined, so code that must work there (a
1039/// tailsitter's nose-up hover) uses them, not the Euler fields.
1040///
1041/// # Examples
1042///
1043/// Creating a default vehicle state:
1044/// ```
1045/// use stable_flight::VehicleState;
1046///
1047/// let state = VehicleState::default();
1048/// ```
1049#[derive(Debug, Clone, Default, PartialEq)]
1050#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1051pub struct VehicleState {
1052    /// World position (north, east, up); see the [frame contract](VehicleState#frame-contract).
1053    pub position_m: Vec3,
1054
1055    /// World velocity (north, east, up).
1056    pub velocity_mps: Vec3,
1057
1058    /// World acceleration (north, east, up).
1059    pub acceleration_mps2: Vec3,
1060
1061    /// Orientation quaternion representing the vehicle's attitude.
1062    /// The quaternion represents the rotation from world frame to body frame.
1063    pub attitude: UnitQuaternion<f32>,
1064
1065    /// Body angular velocity in roll (x), pitch (y), and yaw (z), in radians per second.
1066    pub angular_velocity_radps: Vec3,
1067
1068    /// Current roll angle in radians, right wing down positive.
1069    pub roll_rad: f32,
1070
1071    /// Current pitch angle in radians, nose up positive.
1072    pub pitch_rad: f32,
1073
1074    /// Current heading (yaw) angle in radians.
1075    /// 0 is north, with positive values rotating clockwise.
1076    pub heading_rad: f32,
1077
1078    /// Speed relative to the air mass in meters per second, or `None` without an air-data
1079    /// source (e.g. no pitot). A magnitude, so it doesn't depend on the body frame. Consumers
1080    /// read it through [`valid_airspeed_mps`](Self::valid_airspeed_mps), which treats a NaN
1081    /// or negative value as `None` (input policy).
1082    pub airspeed_mps: Option<f32>,
1083}
1084
1085impl VehicleState {
1086    /// [`airspeed_mps`](Self::airspeed_mps) when it is usable: `None` without air data, and
1087    /// for a NaN or negative reading (input policy).
1088    ///
1089    /// # Examples
1090    ///
1091    /// ```
1092    /// use stable_flight::VehicleState;
1093    ///
1094    /// // (reported, usable)
1095    /// let cases = [
1096    ///     (Some(12.0), Some(12.0)),
1097    ///     (Some(0.0), Some(0.0)),
1098    ///     (None, None),
1099    ///     (Some(f32::NAN), None),
1100    ///     (Some(-1.0), None),
1101    /// ];
1102    /// for (airspeed_mps, usable) in cases {
1103    ///     let state = VehicleState { airspeed_mps, ..Default::default() };
1104    ///     assert_eq!(state.valid_airspeed_mps(), usable, "{airspeed_mps:?}");
1105    /// }
1106    /// ```
1107    pub fn valid_airspeed_mps(&self) -> Option<f32> {
1108        self.airspeed_mps
1109            .filter(|airspeed_mps| *airspeed_mps >= 0.0)
1110    }
1111
1112    /// This state in another body frame: `rotation` is the new body frame expressed in the old
1113    /// one (a constant mount or view rotation).
1114    ///
1115    /// The attitude becomes `attitude · rotation`, the body rates `rotation⁻¹ · ω` (the same
1116    /// rotation seen in the new axes), and the Euler fields are recomputed from the new
1117    /// attitude. World position, velocity, acceleration, and airspeed don't depend on the body
1118    /// frame and are unchanged.
1119    ///
1120    /// # Examples
1121    ///
1122    /// ```
1123    /// use core::f32::consts::FRAC_PI_2;
1124    /// use stable_flight::nalgebra::UnitQuaternion;
1125    /// use stable_flight::VehicleState;
1126    ///
1127    /// // A tailsitter hovering nose up, seen in a frame rotated −90° in pitch, reads level.
1128    /// let nose_up = VehicleState {
1129    ///     attitude: UnitQuaternion::from_euler_angles(0.0, FRAC_PI_2, 0.0),
1130    ///     ..Default::default()
1131    /// };
1132    /// let view = nose_up.rotate_body(&UnitQuaternion::from_euler_angles(0.0, -FRAC_PI_2, 0.0));
1133    /// assert!(view.pitch_rad.abs() < 1e-6);
1134    /// ```
1135    pub fn rotate_body(&self, rotation: &UnitQuaternion<f32>) -> Self {
1136        let attitude = self.attitude * rotation;
1137        let (roll_rad, pitch_rad, heading_rad) = euler_angles(&attitude);
1138        VehicleState {
1139            attitude,
1140            angular_velocity_radps: rotation.inverse_transform_vector(&self.angular_velocity_radps),
1141            roll_rad,
1142            pitch_rad,
1143            heading_rad,
1144            ..self.clone()
1145        }
1146    }
1147}
1148
1149/// Represents a physical vehicle that can be controlled by the flight system.
1150///
1151/// A `Vehicle` is anything that is both a [`StateSource`] and an [`Actuator`]; the blanket
1152/// impl below provides it automatically, so implement those two traits rather than this one.
1153/// The split mirrors hardware, where sensing (IMU, estimator) and actuation (ESC/servo output)
1154/// are usually separate drivers, while a simulator bridge can implement both on one type.
1155///
1156/// Examples: a simulator bridge such as `RealFlightVehicle`, a hardware IMU/estimator paired
1157/// with an ESC driver (see [`ComposedVehicle`]), or a test double such as
1158/// `testing::NullVehicle` (`testing` feature).
1159///
1160/// # Timing contract
1161///
1162/// [`FlightLoop::step`] calls [`StateSource::state`] once, then
1163/// [`Actuator::actuate`] once, every tick. A backend must:
1164///
1165/// - report state in the [`VehicleState` frame contract](VehicleState#frame-contract);
1166/// - talk to its simulator or hardware at most once per call, and should not block for longer
1167///   than a tick (document it if a blocking link can);
1168/// - document how old the state from `state` is relative to the last `actuate`. A
1169///   backend whose link sends controls and returns state in one round-trip exchanges in
1170///   `actuate` and returns the cached result, so tick *n* stabilizes on state reported when
1171///   the simulator received tick *n − 1*'s controls. A backend with a separate sensor read
1172///   should read fresh state in `state`;
1173/// - produce real state on the priming call (`dt == Duration::ZERO`, made once by
1174///   [`FlightLoop::prime`] before any `actuate`), contacting the simulator if it must, and
1175///   document what it returns if that fails.
1176///
1177/// # Examples
1178///
1179/// ```
1180/// use std::time::Duration;
1181/// use stable_flight::{Actuator, ActuatorCommand, StateSource, Vehicle, VehicleState};
1182///
1183/// struct HoverSim {
1184///     state: VehicleState,
1185/// }
1186///
1187/// impl StateSource for HoverSim {
1188///     fn state(&mut self, _dt: Duration) -> VehicleState {
1189///         self.state.clone()
1190///     }
1191/// }
1192///
1193/// impl Actuator for HoverSim {
1194///     fn actuate(&mut self, _command: &ActuatorCommand) {}
1195/// }
1196///
1197/// fn requires_vehicle(_: &impl Vehicle) {}
1198/// requires_vehicle(&HoverSim { state: VehicleState::default() });
1199/// ```
1200pub trait Vehicle: StateSource + Actuator {}
1201
1202impl<T: StateSource + Actuator> Vehicle for T {}
1203
1204/// Where the flight loop's vehicle state comes from.
1205///
1206/// The name describes the role, not how the state is obtained. Implementors include:
1207/// - **Simulator backends** that report the simulator's true state (e.g. `RealFlightVehicle`);
1208/// - **Test doubles** that report a fixed state (`testing::NullVehicle`);
1209/// - **Estimators** that fuse sensor readings into an estimate (IMU, baro, mag, GNSS).
1210///
1211/// Every implementor reports in the [`VehicleState` frame contract](VehicleState#frame-contract).
1212pub trait StateSource {
1213    /// Returns the current vehicle state.
1214    ///
1215    /// Takes `&mut self` because sources typically advance internal state on each call
1216    /// (a filter's predict/update, a simulator exchange's bookkeeping).
1217    ///
1218    /// # Parameters
1219    /// - `dt`: Time elapsed since the previous call. The first call, made once before the
1220    ///   control loop starts, passes `Duration::ZERO`; implementations may use it to
1221    ///   initialize (see `RealFlightVehicle`).
1222    fn state(&mut self, dt: Duration) -> VehicleState;
1223}
1224
1225/// Component responsible for controlling the vehicle's actuators.
1226///
1227/// The `Actuator` trait defines the interface for components that translate
1228/// actuator commands into actual physical actions, such as moving control surfaces
1229/// or adjusting motor speeds.
1230///
1231/// Implementors of this trait may include:
1232/// - **Motor controllers**: Control electric motors for thrust
1233/// - **Servo drivers**: Position control surfaces like elevators and ailerons
1234/// - **Simulation interfaces**: Send control commands to physics engines
1235pub trait Actuator {
1236    /// Actuates the vehicle's control surfaces and/or motors based on the command.
1237    ///
1238    /// # Parameters
1239    ///
1240    /// - `actuator_command`: The command values to apply to the actuators.
1241    fn actuate(&mut self, actuator_command: &ActuatorCommand);
1242}
1243
1244/// What the [`Stabilizer`] should hold this tick, as produced by a [`Guidance`].
1245///
1246/// A [`ControlInput`] says what the operator or mission wants (stick positions, a waypoint);
1247/// a `Setpoint` is the inner-loop target derived from it. Attitude targets are physical
1248/// angles in radians; rates and thrust are normalized. The stabilizer owns the physical
1249/// limits (maximum tilt and rates) and the thrust curve, and saturates out-of-range or NaN
1250/// inputs per the input policy.
1251///
1252/// `#[non_exhaustive]`: new setpoint kinds (e.g. fixed-wing) can be added without a breaking
1253/// change. A [`Stabilizer`] that can't fly a variant must fall back to neutral, not panic (see
1254/// [`Stabilizer::stabilize`]).
1255///
1256/// # Examples
1257///
1258/// ```
1259/// use stable_flight::{AttitudeSetpoint, Setpoint};
1260///
1261/// // Level, north-facing hover at half linear thrust.
1262/// let hover = Setpoint::Attitude(AttitudeSetpoint { thrust: 0.5, ..Default::default() });
1263/// ```
1264#[derive(Debug, Clone, Copy, PartialEq)]
1265#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1266#[non_exhaustive]
1267pub enum Setpoint {
1268    /// Hold a roll/pitch attitude and an absolute heading.
1269    Attitude(AttitudeSetpoint),
1270    /// Hold body rates, as fractions of the stabilizer's maximum.
1271    Rate(RateSetpoint),
1272    /// Hold absolute body rates (rad/s): a copter stabilizer's acro and maneuvers.
1273    BodyRate(BodyRateSetpoint),
1274    /// Fly a wing-borne roll/pitch attitude, turns coordinated (no heading): a plane
1275    /// stabilizer's.
1276    Plane(PlaneSetpoint),
1277    /// Hold absolute body rates (rad/s) on the wing, at any attitude: a plane stabilizer's acro
1278    /// and maneuvers (rolls, loops).
1279    PlaneRate(BodyRateSetpoint),
1280    /// Fly a hover and a wing-borne attitude at once, the lift rotors carrying
1281    /// [`lift_share`](BlendSetpoint::lift_share) of theirs: a lift+cruise VTOL's transitions.
1282    Blend(BlendSetpoint),
1283}
1284
1285impl Setpoint {
1286    /// The linear thrust the setpoint carries; a [`Blend`](Self::Blend)'s hover thrust (the
1287    /// lift rotors', before their share).
1288    ///
1289    /// # Examples
1290    ///
1291    /// ```
1292    /// use stable_flight::{RateSetpoint, Setpoint};
1293    ///
1294    /// let setpoint = Setpoint::Rate(RateSetpoint { thrust: 0.4, ..Default::default() });
1295    /// assert_eq!(setpoint.thrust(), 0.4);
1296    /// ```
1297    pub fn thrust(&self) -> f32 {
1298        match self {
1299            Setpoint::Attitude(attitude) => attitude.thrust,
1300            Setpoint::Rate(rates) => rates.thrust,
1301            Setpoint::BodyRate(rates) | Setpoint::PlaneRate(rates) => rates.thrust,
1302            Setpoint::Plane(plane) => plane.thrust,
1303            Setpoint::Blend(blend) => blend.hover.thrust,
1304        }
1305    }
1306
1307    /// Whether guidance marked this setpoint ground idle (see
1308    /// [`AttitudeSetpoint::idle`]); a plane attitude never is, a blend when its hover is.
1309    ///
1310    /// # Examples
1311    ///
1312    /// ```
1313    /// use stable_flight::{PlaneSetpoint, RateSetpoint, Setpoint};
1314    ///
1315    /// assert!(Setpoint::Rate(RateSetpoint { idle: true, ..Default::default() }).idle());
1316    /// assert!(!Setpoint::Plane(PlaneSetpoint::default()).idle());
1317    /// ```
1318    pub fn idle(&self) -> bool {
1319        match self {
1320            Setpoint::Attitude(attitude) => attitude.idle,
1321            Setpoint::Rate(rates) => rates.idle,
1322            Setpoint::BodyRate(rates) | Setpoint::PlaneRate(rates) => rates.idle,
1323            Setpoint::Plane(_) => false,
1324            Setpoint::Blend(blend) => blend.hover.idle,
1325        }
1326    }
1327
1328    /// This setpoint with its [`thrust`](Self::thrust) replaced by `thrust`, its other fields
1329    /// (the [`idle`](Self::idle) mark included) kept.
1330    ///
1331    /// # Examples
1332    ///
1333    /// ```
1334    /// use stable_flight::{RateSetpoint, Setpoint};
1335    ///
1336    /// let setpoint = Setpoint::Rate(RateSetpoint { thrust: 0.4, ..Default::default() });
1337    /// assert_eq!(setpoint.with_thrust(0.7).thrust(), 0.7);
1338    /// ```
1339    pub fn with_thrust(self, thrust: f32) -> Self {
1340        match self {
1341            Setpoint::Attitude(attitude) => {
1342                Setpoint::Attitude(AttitudeSetpoint { thrust, ..attitude })
1343            }
1344            Setpoint::Rate(rates) => Setpoint::Rate(RateSetpoint { thrust, ..rates }),
1345            Setpoint::BodyRate(rates) => Setpoint::BodyRate(BodyRateSetpoint { thrust, ..rates }),
1346            Setpoint::Plane(plane) => Setpoint::Plane(PlaneSetpoint { thrust, ..plane }),
1347            Setpoint::PlaneRate(rates) => Setpoint::PlaneRate(BodyRateSetpoint { thrust, ..rates }),
1348            Setpoint::Blend(blend) => Setpoint::Blend(BlendSetpoint {
1349                hover: AttitudeSetpoint {
1350                    thrust,
1351                    ..blend.hover
1352                },
1353                ..blend
1354            }),
1355        }
1356    }
1357}
1358
1359/// Absolute body-rate target, for [`Setpoint::BodyRate`] (copter) and [`Setpoint::PlaneRate`]
1360/// (plane). The stabilizer saturates each rate to its limit (NaN as zero).
1361#[derive(Debug, Default, Clone, Copy, PartialEq)]
1362#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1363pub struct BodyRateSetpoint {
1364    /// Roll rate about body `x` in rad/s, right positive.
1365    pub roll_radps: f32,
1366    /// Pitch rate about body `y` in rad/s, nose up positive.
1367    pub pitch_radps: f32,
1368    /// Yaw rate about body `z` in rad/s, nose right positive.
1369    pub yaw_radps: f32,
1370    /// Linear collective thrust, `0.0` to `1.0`, before the stabilizer's thrust curve.
1371    pub thrust: f32,
1372    /// Ground idle, as [`AttitudeSetpoint::idle`]; a plane stabilizer ignores it.
1373    pub idle: bool,
1374}
1375
1376/// The rates of an [`AbsoluteRateCommand`], as given.
1377///
1378/// # Examples
1379///
1380/// ```
1381/// use stable_flight::{AbsoluteRateCommand, BodyRateSetpoint};
1382///
1383/// let command = AbsoluteRateCommand { roll_radps: 2.0, thrust: 0.5, ..Default::default() };
1384/// assert_eq!(BodyRateSetpoint::from(&command).roll_radps, 2.0);
1385/// ```
1386impl From<&AbsoluteRateCommand> for BodyRateSetpoint {
1387    fn from(command: &AbsoluteRateCommand) -> Self {
1388        // Exhaustive destructuring: a new field fails to compile here until it is mapped.
1389        let AbsoluteRateCommand {
1390            roll_radps,
1391            pitch_radps,
1392            yaw_radps,
1393            thrust,
1394        } = *command;
1395        Self {
1396            roll_radps,
1397            pitch_radps,
1398            yaw_radps,
1399            thrust,
1400            idle: false,
1401        }
1402    }
1403}
1404
1405/// Wing-borne attitude target for a plane stabilizer, for [`Setpoint::Plane`], in the
1406/// [frame contract](VehicleState#frame-contract)'s body frame (a tailsitter's airplane
1407/// frame). Turns are coordinated, so there is no heading: the stabilizer derives the yaw rate
1408/// from bank and airspeed. The stabilizer saturates roll and pitch to its limits; NaN means
1409/// level.
1410#[derive(Debug, Default, Clone, Copy, PartialEq)]
1411#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1412pub struct PlaneSetpoint {
1413    /// Bank in radians, right wing down positive.
1414    pub roll_rad: f32,
1415    /// Pitch in radians, nose up positive.
1416    pub pitch_rad: f32,
1417    /// Linear throttle, `0.0` to `1.0`, before the stabilizer's thrust curve.
1418    pub thrust: f32,
1419    /// A tailsitter transition ramp: pitch saturates at ±π/2, not the stabilizer's limit, so
1420    /// the ramp reaches its handover whatever the cruise limit (ArduPilot's tailsitter ramps
1421    /// past its pitch limits, `tailsitter.cpp:957`).
1422    pub transition: bool,
1423}
1424
1425/// A hover and a wing-borne target flown together, for [`Setpoint::Blend`]: a lift+cruise
1426/// VTOL (quadplane) in transition, its lift rotors flying `hover` and its surfaces and pusher
1427/// flying `plane`.
1428///
1429/// The stabilizer weights the lift rotors' thrust and moments by `lift_share` and flies the
1430/// surfaces and pusher in full (PX4's standard VTOL,
1431/// `src/modules/vtol_att_control/standard.cpp:294-368`). A NaN share counts as 1, the lift
1432/// rotors carrying it all; others saturate to `[0, 1]`.
1433///
1434/// # Examples
1435///
1436/// ```
1437/// use stable_flight::{AttitudeSetpoint, BlendSetpoint, PlaneSetpoint, Setpoint};
1438///
1439/// // Halfway through handing the lift to the wing, the pusher at full throttle.
1440/// let blend = Setpoint::Blend(BlendSetpoint {
1441///     hover: AttitudeSetpoint { thrust: 0.5, ..Default::default() },
1442///     plane: PlaneSetpoint { thrust: 1.0, ..Default::default() },
1443///     lift_share: 0.5,
1444/// });
1445/// assert_eq!(blend.thrust(), 0.5);
1446/// ```
1447#[derive(Debug, Default, Clone, Copy, PartialEq)]
1448#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1449pub struct BlendSetpoint {
1450    /// The lift rotors' target, flown by the hover side.
1451    pub hover: AttitudeSetpoint,
1452    /// The surfaces' and pusher's target, flown by the plane side.
1453    pub plane: PlaneSetpoint,
1454    /// The share of hover lift the lift rotors carry, `0.0` to `1.0`.
1455    pub lift_share: f32,
1456}
1457
1458/// Attitude target for the [`Stabilizer`]; see [`Setpoint`].
1459#[derive(Debug, Default, Clone, Copy, PartialEq)]
1460#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1461pub struct AttitudeSetpoint {
1462    /// Roll target in radians, right positive, per the
1463    /// [frame contract](VehicleState#frame-contract)'s `roll_rad`. The stabilizer saturates it
1464    /// to its maximum tilt; NaN means level.
1465    pub roll_rad: f32,
1466    /// Pitch target in radians, nose up positive, per the
1467    /// [frame contract](VehicleState#frame-contract)'s `pitch_rad`. The stabilizer saturates it
1468    /// to its maximum tilt; NaN means level.
1469    pub pitch_rad: f32,
1470    /// Absolute heading target in radians, in the
1471    /// [frame contract](VehicleState#frame-contract)'s `heading_rad` convention.
1472    pub heading_rad: f32,
1473    /// Linear collective thrust, `0.0` to `1.0`, before the stabilizer's thrust curve.
1474    pub thrust: f32,
1475    /// A tailsitter transition ramp: pitch saturates at ±π/2, not the stabilizer's maximum
1476    /// tilt, so the ramp reaches its handover whatever the hover limit (ArduPilot's tailsitter
1477    /// ramps past its angle limit, `tailsitter.cpp:871`).
1478    pub transition: bool,
1479    /// Ground idle: guidance sets it while a piloted throttle is at or below
1480    /// [`IDLE_THROTTLE`](crate::guidance::copter::IDLE_THROTTLE) (or NaN), and a copter
1481    /// stabilizer then clears its integrals. A zero `thrust` alone (the altitude loop in
1482    /// flight) is not idle.
1483    pub idle: bool,
1484}
1485
1486/// Body-rate target for the [`Stabilizer`]; see [`Setpoint`].
1487#[derive(Debug, Default, Clone, Copy, PartialEq)]
1488#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1489pub struct RateSetpoint {
1490    /// Roll rate as a fraction of the stabilizer's maximum, `-1.0` to `1.0` (right positive).
1491    pub roll_rate: f32,
1492    /// Pitch rate as a fraction of the stabilizer's maximum, `-1.0` to `1.0` (nose up
1493    /// positive).
1494    pub pitch_rate: f32,
1495    /// Yaw rate as a fraction of the stabilizer's maximum, `-1.0` to `1.0` (nose right
1496    /// positive).
1497    pub yaw_rate: f32,
1498    /// Linear collective thrust, `0.0` to `1.0`, before the stabilizer's thrust curve.
1499    pub thrust: f32,
1500    /// Ground idle, as [`AttitudeSetpoint::idle`].
1501    pub idle: bool,
1502}
1503
1504/// Passes the sticks through as rates, with `throttle` as `thrust`.
1505///
1506/// # Examples
1507///
1508/// ```
1509/// use stable_flight::{RateCommand, RateSetpoint};
1510///
1511/// let command = RateCommand {
1512///     throttle: 0.6,
1513///     roll_rate: 0.1,
1514///     pitch_rate: -0.2,
1515///     yaw_rate: 0.3,
1516/// };
1517/// let setpoint = RateSetpoint::from(&command);
1518/// assert_eq!(
1519///     setpoint,
1520///     RateSetpoint { roll_rate: 0.1, pitch_rate: -0.2, yaw_rate: 0.3, thrust: 0.6, idle: false }
1521/// );
1522/// ```
1523impl From<&RateCommand> for RateSetpoint {
1524    fn from(command: &RateCommand) -> Self {
1525        // Exhaustive destructuring: a new field fails to compile here until it is mapped.
1526        let RateCommand {
1527            throttle,
1528            roll_rate,
1529            pitch_rate,
1530            yaw_rate,
1531        } = *command;
1532        Self {
1533            roll_rate,
1534            pitch_rate,
1535            yaw_rate,
1536            thrust: throttle,
1537            idle: false,
1538        }
1539    }
1540}
1541
1542/// Turns the commander's [`ControlInput`] into an inner-loop [`Setpoint`], in the requested
1543/// [`FlightRegime`].
1544///
1545/// Guidance only runs while the [`Command`] is armed, so it never sees `arm`. It owns the
1546/// flight mode: a guidance that flies more than one regime moves toward the requested one and
1547/// reports what it flies through [`flight_mode`](Self::flight_mode); a copter-only guidance
1548/// ignores the request and reports nothing, and [`FlightLoop`] reports it as
1549/// [`FlightModeReport::copter_only`].
1550///
1551/// Guidance is the outer loop: waypoint navigation (position and altitude hold), and the
1552/// interpretation of pilot sticks that needs memory, such as integrating yaw stick into a
1553/// heading-hold target. The [`Stabilizer`] then tracks the setpoint. [`FlightLoop`] calls both
1554/// every tick; a guidance that runs its loops slower paces them itself from `dt`. Why they are
1555/// split is in the
1556/// [architecture overview](https://github.com/wboayue/stable-flight/blob/main/architecture.md#core-components).
1557///
1558/// # Examples
1559///
1560/// A guidance that flies rate commands through unchanged, and otherwise levels out with
1561/// thrust cut:
1562///
1563/// ```
1564/// use stable_flight::{
1565///     AttitudeSetpoint, ControlInput, FlightRegime, Guidance, Setpoint, VehicleState,
1566/// };
1567///
1568/// struct RateOnly;
1569///
1570/// impl Guidance for RateOnly {
1571///     fn guide(
1572///         &mut self,
1573///         _dt: f32,
1574///         _regime: FlightRegime,
1575///         input: &ControlInput,
1576///         state: &VehicleState,
1577///     ) -> Setpoint {
1578///         match input {
1579///             ControlInput::Rate(rate) => Setpoint::Rate(rate.into()),
1580///             _ => Setpoint::Attitude(AttitudeSetpoint {
1581///                 heading_rad: state.heading_rad,
1582///                 ..Default::default()
1583///             }),
1584///         }
1585///     }
1586/// }
1587/// ```
1588pub trait Guidance {
1589    /// Produces this tick's inner-loop setpoint.
1590    ///
1591    /// # Parameters
1592    ///
1593    /// - `dt`: Time elapsed since the last guidance step in seconds. Must be positive and
1594    ///   finite; implementations may assert it (runners guarantee it).
1595    /// - `regime`: The commander's requested regime ([`Command::regime`]), repeated every
1596    ///   tick.
1597    /// - `input`: The commander's current control input.
1598    /// - `state`: The current estimated state of the vehicle.
1599    ///
1600    /// # Unsupported inputs
1601    ///
1602    /// [`ControlInput`] is `#[non_exhaustive]`. For a variant it can't fly, an implementation
1603    /// returns a neutral setpoint — level attitude, the current heading, zero thrust (what the
1604    /// input policy gives a NaN command) — and must not panic. A regime it can't fly is
1605    /// refused, not an error: it keeps flying the one it can and reports why
1606    /// ([`ModeRefusal`]).
1607    fn guide(
1608        &mut self,
1609        dt: f32,
1610        regime: FlightRegime,
1611        input: &ControlInput,
1612        state: &VehicleState,
1613    ) -> Setpoint;
1614
1615    /// Resets guidance and primes it from a known-good vehicle state.
1616    ///
1617    /// Clears runtime state (integrators, held outputs) and warms the rest (e.g. the
1618    /// heading-hold target) so guidance starts from where the vehicle is rather than from
1619    /// zero. [`FlightLoop`] calls it before the first tick and again each time the
1620    /// [`Command`] arms, since guidance doesn't run while disarmed. The default does
1621    /// nothing.
1622    fn prime(&mut self, _state: &VehicleState) {}
1623
1624    /// What the last [`guide`](Self::guide) call clipped to a limit. [`FlightLoop`] merges it
1625    /// into the tick's [`TelemetryRecord::saturation`]. The default reports nothing.
1626    fn saturation(&self) -> Saturation {
1627        Saturation::default()
1628    }
1629
1630    /// The flight mode the last [`guide`](Self::guide) call flew, for a guidance that flies
1631    /// more than one regime. [`FlightLoop`] puts it in an armed tick's
1632    /// [`TelemetryRecord::flight_mode`]. The default, `None`, means copter only: the loop
1633    /// reports [`FlightModeReport::copter_only`]. A guidance that wraps another forwards this.
1634    fn flight_mode(&self) -> Option<FlightModeReport> {
1635        None
1636    }
1637
1638    /// The wind this guidance estimates, if it estimates one. [`FlightLoop`] puts it in each
1639    /// tick's [`TelemetryRecord::wind`]. The default, `None`, estimates none. A guidance that
1640    /// wraps another forwards this.
1641    fn wind(&self) -> Option<WindEstimate> {
1642        None
1643    }
1644}
1645
1646/// Component responsible for flight control and stabilization: the inner loop.
1647///
1648/// The `Stabilizer` trait defines the interface for components that implement
1649/// control algorithms to track a [`Setpoint`] from [`Guidance`], producing the thrust and
1650/// moments that the [`Mixer`] turns into actuator commands.
1651///
1652/// Implementors of this trait may include:
1653/// - **PID controllers**: Simple feedback control for attitude stability
1654/// - **LQR controllers**: Optimal control for complex flight dynamics
1655/// - **Model predictive controllers**: Advanced control with future prediction
1656/// - **Cascaded control systems**: Hierarchical controllers for different aspects of flight
1657pub trait Stabilizer {
1658    /// Generates control outputs based on the current setpoint and vehicle state.
1659    ///
1660    /// # Parameters
1661    ///
1662    /// - `dt`: Time elapsed since the last control step in seconds. Must be positive and
1663    ///   finite; implementations may assert it (runners guarantee it).
1664    /// - `setpoint`: The attitude or rate target to track.
1665    /// - `state`: The current estimated state of the vehicle.
1666    ///
1667    /// # Returns
1668    ///
1669    /// A `ControlOutput` containing the desired thrust and control moments.
1670    ///
1671    /// # Unsupported setpoints
1672    ///
1673    /// [`Setpoint`] is `#[non_exhaustive]`. For a variant it can't fly, an implementation
1674    /// returns a neutral output — zero thrust and moments ([`ControlOutput::default`]) — and
1675    /// must not panic.
1676    fn stabilize(&mut self, dt: f32, setpoint: &Setpoint, state: &VehicleState) -> ControlOutput;
1677
1678    /// Resets the stabilizer and primes it from a known-good vehicle state.
1679    ///
1680    /// Clears runtime state (integrators, derivative history) and warms any filters so
1681    /// control starts from where the vehicle is. [`FlightLoop`] calls it before the first
1682    /// tick and again each time the [`Command`] arms, after [`Guidance::prime`]. The default
1683    /// does nothing.
1684    fn prime(&mut self, _state: &VehicleState) {}
1685
1686    /// What the last [`stabilize`](Self::stabilize) call clipped to a limit. [`FlightLoop`]
1687    /// merges it into the tick's [`TelemetryRecord::saturation`]. The default reports nothing.
1688    fn saturation(&self) -> Saturation {
1689        Saturation::default()
1690    }
1691}
1692
1693/// Which limits the pipeline hit on one tick, as reported by [`Guidance::saturation`],
1694/// [`Stabilizer::saturation`], and [`Mixer::saturation`], merged by [`FlightLoop`] into
1695/// [`TelemetryRecord::saturation`].
1696///
1697/// A saturated tick is not an error: limits are how the pipeline stays safe. Flags that stay
1698/// set across many ticks point at tuning or authority problems (e.g. a rate loop pinned at
1699/// full moment, or a mixer giving up collective to hold attitude). New flags may be added, so
1700/// the struct is `#[non_exhaustive]`; build one with [`Saturation::default`] and set fields.
1701///
1702/// # Examples
1703///
1704/// ```
1705/// use stable_flight::Saturation;
1706///
1707/// let mut guidance = Saturation::default();
1708/// guidance.tilt = true;
1709/// let mut mixer = Saturation::default();
1710/// mixer.mixer_thrust = true;
1711///
1712/// let tick = guidance.merge(mixer);
1713/// assert!(tick.tilt && tick.mixer_thrust && tick.any());
1714/// assert!(!Saturation::default().any());
1715/// ```
1716#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1717#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1718#[non_exhaustive]
1719pub struct Saturation {
1720    /// A requested tilt was capped: guidance's waypoint tilt limit, or the stabilizer's
1721    /// maximum roll/pitch angle.
1722    pub tilt: bool,
1723    /// Collective thrust was clipped to `[0, 1]` (the altitude loop, or the attitude-mode
1724    /// boost). The altitude loop's flag means its thrust sits on a bound, so it is also set
1725    /// when the tilt boost cuts thrust to 0 while inverted, and in a steady hover if
1726    /// `hover_thrust` is 1.
1727    pub thrust: bool,
1728    /// The rate loop's moment output hit ±1, per axis (roll, pitch, yaw).
1729    pub moments: [bool; 3],
1730    /// The mixer lowered collective thrust to keep the moments (a motor would pass full
1731    /// throttle).
1732    pub mixer_thrust: bool,
1733    /// The mixer couldn't deliver the moments in full: it scaled them down, its upward shift
1734    /// was limited near idle, or a motor was clipped. Expected while armed at idle on the
1735    /// ground, where any attitude error is clipped at zero thrust.
1736    pub mixer_moments: bool,
1737}
1738
1739impl Saturation {
1740    /// The union of two reports: a flag set in either is set.
1741    pub fn merge(self, other: Self) -> Self {
1742        // Exhaustive destructuring: a new flag fails to compile here until it is merged.
1743        let Saturation {
1744            tilt,
1745            thrust,
1746            moments,
1747            mixer_thrust,
1748            mixer_moments,
1749        } = other;
1750        Saturation {
1751            tilt: self.tilt || tilt,
1752            thrust: self.thrust || thrust,
1753            moments: [
1754                self.moments[0] || moments[0],
1755                self.moments[1] || moments[1],
1756                self.moments[2] || moments[2],
1757            ],
1758            mixer_thrust: self.mixer_thrust || mixer_thrust,
1759            mixer_moments: self.mixer_moments || mixer_moments,
1760        }
1761    }
1762
1763    /// True when any flag is set.
1764    pub fn any(&self) -> bool {
1765        // Exhaustive destructuring: a new flag fails to compile here until it is checked.
1766        let Saturation {
1767            tilt,
1768            thrust,
1769            moments,
1770            mixer_thrust,
1771            mixer_moments,
1772        } = *self;
1773        tilt || thrust || moments.iter().any(|&m| m) || mixer_thrust || mixer_moments
1774    }
1775}
1776
1777/// A pipeline component whose gains and limits can be read and replaced between ticks.
1778///
1779/// The config is plain `Copy` data that the component owns as its single source of truth;
1780/// [`set_config`](Self::set_config) is the one write point and validates before committing,
1781/// so a running loop can be retuned without ever flying an invalid config. Implemented by
1782/// [`CopterGuidance`](guidance::copter::CopterGuidance) and
1783/// [`CopterStabilizer`](stabilizers::copter::CopterStabilizer); [`FlightLoop`] reaches them
1784/// through [`set_guidance_config`](FlightLoop::set_guidance_config) and
1785/// [`set_stabilizer_config`](FlightLoop::set_stabilizer_config).
1786///
1787/// # Examples
1788///
1789/// ```
1790/// use stable_flight::Configurable;
1791/// use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
1792///
1793/// let mut stabilizer = CopterStabilizer::new(CopterStabilizerConfig::default());
1794///
1795/// let mut retuned = *stabilizer.config();
1796/// retuned.body_rate.roll_gains.p = 0.2;
1797/// assert!(stabilizer.set_config(retuned).is_ok());
1798///
1799/// retuned.body_rate.max_integral = -1.0;
1800/// assert!(stabilizer.set_config(retuned).is_err());
1801/// assert_eq!(stabilizer.config().body_rate.roll_gains.p, 0.2); // unchanged
1802/// ```
1803pub trait Configurable {
1804    /// The component's config.
1805    type Config: Copy;
1806
1807    /// The config the component flies.
1808    fn config(&self) -> &Self::Config;
1809
1810    /// Replaces the config if it is valid; otherwise keeps the current one and returns the
1811    /// error. Call it between ticks: the new config applies from the next tick, and runtime
1812    /// state (integrals, derivative history, timers) is kept. A changed integral gain rescales
1813    /// its integral so the I term carries over without a bump; across a zero gain the
1814    /// integral resets (`architecture.md#config-ownership`).
1815    fn set_config(&mut self, config: Self::Config) -> Result<(), controllers::InvalidConfig>;
1816}
1817
1818/// Component responsible for publishing telemetry data from the flight system.
1819///
1820/// The `TelemetryPublisher` trait defines the interface for components that send
1821/// flight data to external systems for logging, monitoring, or visualization.
1822/// This can include sending data to ground control stations, logging systems,
1823/// or other monitoring tools.
1824///
1825/// Implementors of this trait may include:
1826/// - **Mavlink publishers**: Send telemetry via the MAVLink protocol
1827/// - **Data loggers**: Record flight data for later analysis
1828/// - **Visualization interfaces**: Send data to real-time flight displays
1829pub trait TelemetryPublisher {
1830    /// Publishes one control-loop tick to external systems.
1831    ///
1832    /// Fire-and-forget: the flight loop cannot act on a telemetry failure, so implementations
1833    /// handle (log) their own errors instead of returning them.
1834    ///
1835    /// # Parameters
1836    ///
1837    /// - `record`: Everything the loop produced this tick; see [`TelemetryRecord`].
1838    fn publish(&mut self, record: &TelemetryRecord);
1839}
1840
1841/// One control-loop tick, as handed to a [`TelemetryPublisher`].
1842///
1843/// The loop assembles it after actuating, so every stage's output is available. Fields borrow
1844/// from the loop and live only for the tick; publishers copy what they need to keep. New
1845/// fields can be added without changing the `publish` signature (struct literals, as in tests,
1846/// need the new field; `testing::RecordedTick::as_record`, behind the `testing` feature,
1847/// builds one from an owned copy).
1848///
1849/// # Examples
1850///
1851/// ```
1852/// use std::time::Duration;
1853/// use stable_flight::{
1854///     ActuatorCommand, Command, ControlOutput, FlightModeReport, Saturation, Setpoint,
1855///     TelemetryPublisher, TelemetryRecord, VehicleState,
1856/// };
1857///
1858/// struct ThrustLogger;
1859///
1860/// impl TelemetryPublisher for ThrustLogger {
1861///     fn publish(&mut self, record: &TelemetryRecord) {
1862///         println!("{:?}: thrust {}", record.dt, record.control.thrust);
1863///     }
1864/// }
1865///
1866/// let command = Command::default();
1867/// let setpoint = Setpoint::Attitude(Default::default());
1868/// let state = VehicleState::default();
1869/// let control = ControlOutput::default();
1870/// let actuators = ActuatorCommand::default();
1871///
1872/// ThrustLogger.publish(&TelemetryRecord {
1873///     dt: Duration::from_millis(4),
1874///     command: &command,
1875///     setpoint: &setpoint,
1876///     state: &state,
1877///     control: &control,
1878///     actuators: &actuators,
1879///     saturation: Saturation::default(),
1880///     failsafe: None,
1881///     flight_mode: FlightModeReport::default(),
1882///     wind: None,
1883/// });
1884/// ```
1885#[derive(Debug, Clone, Copy)]
1886pub struct TelemetryRecord<'a> {
1887    /// Nominal loop period (`1 / target frequency`), not measured elapsed time.
1888    pub dt: Duration,
1889    /// Command the commander produced.
1890    pub command: &'a Command,
1891    /// Setpoint guidance derived from `command` (neutral while disarmed).
1892    pub setpoint: &'a Setpoint,
1893    /// Estimated vehicle state the stabilizer acted on.
1894    pub state: &'a VehicleState,
1895    /// Stabilizer output (thrust and moments; zero while disarmed).
1896    pub control: &'a ControlOutput,
1897    /// Mixer output sent to the actuators ([`ActuatorCommand::default`] while disarmed).
1898    pub actuators: &'a ActuatorCommand,
1899    /// Limits guidance, the stabilizer, and the mixer hit this tick, merged
1900    /// ([`Saturation::default`] while disarmed).
1901    pub saturation: Saturation,
1902    /// Which commander a failsafe let fly this tick ([`Commander::failsafe`]); `None` without
1903    /// a failsafe.
1904    pub failsafe: Option<FailsafeState>,
1905    /// The flight mode guidance flew this tick ([`Guidance::flight_mode`]), and why it isn't
1906    /// the requested [`Command::regime`] when it can't be. A disarmed tick, where guidance
1907    /// doesn't run, records [`FlightModeReport::copter_only`].
1908    pub flight_mode: FlightModeReport,
1909    /// Guidance's wind estimate ([`Guidance::wind`]); `None` without one.
1910    pub wind: Option<WindEstimate>,
1911}
1912
1913/// One tick's actuator outputs: motors and servos, as generic slots.
1914///
1915/// The [`Mixer`] decides what each slot does
1916/// ([`TableMixer::quad_x`](crate::mixers::TableMixer::quad_x)'s motor `0` is front-left; a
1917/// tricopter's servo `0` might be its tail tilt); the backend's mapping decides which output
1918/// channel each slot drives. Slots a mixer doesn't use stay at their default.
1919///
1920/// The default (all zeros: motors off, servos centered) is what [`FlightLoop`] actuates while
1921/// disarmed.
1922///
1923/// # Examples
1924///
1925/// A quadcopter uses the first four motors:
1926/// ```
1927/// use stable_flight::ActuatorCommand;
1928///
1929/// let mut cmd = ActuatorCommand::default();
1930/// cmd.motors[..4].copy_from_slice(&[0.5; 4]); // Four motors at 50% power
1931/// ```
1932///
1933/// A tricopter adds a tail servo for yaw:
1934/// ```
1935/// use stable_flight::ActuatorCommand;
1936///
1937/// let mut cmd = ActuatorCommand::default();
1938/// cmd.motors[..3].copy_from_slice(&[0.5; 3]);
1939/// cmd.servos[0] = 0.2; // Tail tilted for a slight yaw
1940/// ```
1941#[derive(Debug, Clone, Copy, Default, PartialEq)]
1942#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1943pub struct ActuatorCommand {
1944    /// Motor outputs, from 0.0 (off) to 1.0 (full power). The mixer sets which physical motor
1945    /// each index is.
1946    pub motors: [f32; ActuatorCommand::SLOTS],
1947
1948    /// Servo outputs, from -1.0 to 1.0, with 0.0 centered. The mixer sets what each index moves
1949    /// (a control surface, a tilt servo).
1950    pub servos: [f32; ActuatorCommand::SLOTS],
1951}
1952
1953impl ActuatorCommand {
1954    /// Slots per kind: `motors` and `servos` each hold this many.
1955    pub const SLOTS: usize = 8;
1956}
1957
1958// == Mixers ==
1959
1960/// Component responsible for converting control outputs to actuator commands.
1961///
1962/// The `Mixer` trait defines the interface for components that translate
1963/// generalized control outputs (thrust and moments) into specific actuator
1964/// commands appropriate for the vehicle configuration. It maps abstract control
1965/// concepts to physical actuator movements.
1966///
1967/// Implementors of this trait may include:
1968/// - **Quadcopter mixers**: Map controls to four motors in different configurations (X, +)
1969/// - **Hexacopter mixers**: Map controls to six motors
1970/// - **Fixed-wing mixers**: Map controls to a throttle motor and control-surface servos
1971pub trait Mixer {
1972    /// Transforms abstract control outputs into specific actuator commands.
1973    ///
1974    /// This method is the core functionality of the `Mixer` trait, providing the critical
1975    /// translation layer between the stabilization system's desired control effects and
1976    /// the actual physical actuator settings needed to achieve those effects.
1977    ///
1978    /// # Parameters
1979    ///
1980    /// * `controls` - Reference to a [`ControlOutput`] struct containing normalized thrust
1981    ///   and moment values that represent the desired control effect.
1982    ///
1983    /// # Returns
1984    ///
1985    /// An [`ActuatorCommand`] containing specific actuator settings appropriate for the
1986    /// vehicle's physical configuration. The mixer assigns each `motors` and `servos` slot its
1987    /// meaning; slots it doesn't use stay at their default:
1988    ///
1989    /// * For multicopters: the `motors` array
1990    /// * For fixed-wing: a throttle motor, with control surfaces on `servos`
1991    /// * For tilting or hybrid vehicles: both
1992    ///
1993    /// # Examples
1994    ///
1995    /// ```
1996    /// use stable_flight::{ControlOutput, Mixer, Vec3};
1997    /// use stable_flight::mixers::TableMixer;
1998    ///
1999    /// let mut mixer = TableMixer::quad_x();
2000    ///
2001    /// // Create control output with 70% thrust and slight roll right
2002    /// let control_output = ControlOutput::new(
2003    ///     0.7,                    // 70% thrust
2004    ///     Vec3::new(0.1, 0.0, 0.0)     // slight roll right, no pitch, no yaw
2005    /// );
2006    ///
2007    /// // Convert abstract controls into specific motor commands
2008    /// let actuator_command = mixer.mix(&control_output);
2009    ///
2010    /// // Now actuator_command contains specific motor values for a quadcopter
2011    /// ```
2012    fn mix(&mut self, controls: &ControlOutput) -> ActuatorCommand;
2013
2014    /// What the last [`mix`](Self::mix) call couldn't deliver in full. [`FlightLoop`] merges
2015    /// it into the tick's [`TelemetryRecord::saturation`]. The default reports nothing.
2016    fn saturation(&self) -> Saturation {
2017        Saturation::default()
2018    }
2019}