stable_flight/mixers/table.rs
1//! A table-driven [`Mixer`]: one row per motor or servo, each output a weighted sum of the
2//! roll, pitch, and yaw moments, plus collective thrust for motors.
3//!
4//! Presets cover the common frames ([`TableMixer::quad_x`], [`TableMixer::hex_x`],
5//! [`TableMixer::tri`], ...; see [`presets`](self#presets)); [`TableMixer::new`] takes a custom
6//! table.
7//!
8//! # Mixing
9//!
10//! Moments are saturated to `[-1, 1]` and thrust to `[0, 1]` (NaN → neutral), then:
11//!
12//! - **Motor rows** get `thrust · thrust_factor` plus `headroom · (roll · r + pitch · p)` and
13//! `headroom · yaw_ratio · yaw · y`, where `r`, `p`, `y` are the row's factors and
14//! `headroom = 1 − thrust_factor` ([`MixerConfig`]). All motor rows are then desaturated
15//! together into `[0, 1]`, airmode-style: the moments are kept and collective thrust gives
16//! way; moments too large to fit at all are scaled down, keeping their ratios. Shifting up is
17//! limited to twice the collective, so it fades out toward idle, and at zero thrust motors
18//! below zero are clipped.
19//! - **Servo rows** get `roll · r + pitch · p + yaw · y` over their full range, with no thrust
20//! term, each clamped to `[-1, 1]` on its own.
21//! - **Pusher rows** (a lift+cruise VTOL's forward motor) get the cruise thrust over their
22//! full range and no moments: `thrust_factor` is headroom for the lift motors' moments, which
23//! a pusher doesn't carry, as ArduPlane's throttle spans 0–100% (`THR_MAX`,
24//! `ArduPlane/config.h`). They aren't desaturated with the lift motors.
25//!
26//! On a lift+cruise VTOL the stabilizer sets [`ControlOutput::cruise`]: motor rows then fly
27//! `thrust` and `moments`, and pusher and servo rows fly the cruise thrust and moments. Without
28//! it, servo rows take `moments` and pusher rows stay at 0.
29//!
30//! [`Mixer::saturation`] reports `mixer_thrust` when the motors were shifted down, and
31//! `mixer_moments` when the motor moments were scaled down or clipped, or a servo was clamped.
32//!
33//! # Presets
34//!
35//! Factors follow the frame contract: a positive roll moment rolls right, pitch raises the
36//! nose, yaw turns the nose right. Motor roll and pitch factors are normalized per axis so the
37//! largest is 1, so gains carry across frames. On multirotors, yaw comes from prop drag: a positive yaw moment
38//! speeds up the counterclockwise props (seen from above), whose reaction torque is clockwise
39//! (flight-checked in RealFlight on the quad, #62).
40//!
41//! Motors are numbered clockwise seen from above, starting from the motor on the nose, or the
42//! front-left one when none is on the nose; coaxial frames number the top layer, then the
43//! bottom. [`TableMixer::quad_x`] is the exception: it keeps the order the RealFlight
44//! QuadCopterX airframe maps (front-left, front-right, rear-left, rear-right). Motor 0 spins
45//! clockwise and spin alternates around the frame; on coaxial frames the top and bottom props
46//! of each arm spin opposite ways. Each preset's rustdoc has its diagram.
47//!
48//! | Preset | Motors | Servos |
49//! |--------|--------|--------|
50//! | [`quad_x`](TableMixer::quad_x) | 0 FL, 1 FR, 2 RL, 3 RR | |
51//! | [`quad_plus`](TableMixer::quad_plus) | 0 F, 1 R, 2 B, 3 L | |
52//! | [`hex_x`](TableMixer::hex_x) | 0 FL, 1 FR, 2 R, 3 RR, 4 RL, 5 L | |
53//! | [`hex_plus`](TableMixer::hex_plus) | 0 F, 1 FR, 2 RR, 3 B, 4 RL, 5 FL | |
54//! | [`octo_x`](TableMixer::octo_x) | 0–7 from just left of the nose | |
55//! | [`y6`](TableMixer::y6) | top 0 FL, 1 FR, 2 B; bottom 3–5 under them | |
56//! | [`x8`](TableMixer::x8) | top 0 FL, 1 FR, 2 RR, 3 RL; bottom 4–7 under them | |
57//! | [`tri`](TableMixer::tri) | 0 FL, 1 FR, 2 B | 0 tail tilt (yaw) |
58//! | [`bi`](TableMixer::bi) | 0 L, 1 R | 0 left tilt, 1 right tilt |
59//! | [`tailsitter_2p`](TableMixer::tailsitter_2p) | 0 L, 1 R | 0 left elevon, 1 right elevon |
60//! | [`plane`](TableMixer::plane) | 0 nose | 0 ailerons, 1 elevator, 2 rudder |
61//! | [`quadplane`](TableMixer::quadplane) | lift 0 FL, 1 FR, 2 RL, 3 RR; 4 pusher | 0 ailerons, 1 elevator, 2 rudder |
62//! | [`quadplane_vtail`](TableMixer::quadplane_vtail) | lift 0 FL, 1 FR, 2 RL, 3 RR; 4 pusher | 0 ailerons, 1 left, 2 right ruddervator |
63
64use thiserror::Error;
65
66use crate::math::{desaturate, saturate_throttle, saturate_unit};
67use crate::{ActuatorCommand, ControlOutput, Mixer, Saturation, Vec3};
68
69mod presets;
70#[cfg(test)]
71mod tests;
72
73/// One [`ActuatorCommand`] slot a [`MixRow`] drives.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum Slot {
76 /// `motors[i]`, in `[0, 1]`.
77 Motor(u8),
78 /// `servos[i]`, in `[-1, 1]`.
79 Servo(u8),
80}
81
82/// One output of a [`TableMixer`]: the slot it drives and how much each moment moves it.
83///
84/// # Examples
85///
86/// ```
87/// use stable_flight::mixers::MixRow;
88///
89/// // Front-left motor of an X quad, spinning clockwise.
90/// let front_left = MixRow::motor(0, 1.0, 1.0, -1.0);
91/// // A tricopter's tail tilt servo: yaw only.
92/// let tail = MixRow::servo(0, 0.0, 0.0, 1.0);
93/// ```
94#[derive(Debug, Clone, Copy, PartialEq)]
95pub struct MixRow {
96 slot: Slot,
97 roll: f32,
98 pitch: f32,
99 yaw: f32,
100 pusher: bool,
101}
102
103impl MixRow {
104 /// A motor row: collective thrust plus the weighted moments, desaturated with the other
105 /// motors. A table's `m` motor rows drive `motors[0..m]`, in any row order.
106 pub const fn motor(index: u8, roll: f32, pitch: f32, yaw: f32) -> Self {
107 MixRow {
108 slot: Slot::Motor(index),
109 roll,
110 pitch,
111 yaw,
112 pusher: false,
113 }
114 }
115
116 /// A servo row: the weighted moments, clamped to `[-1, 1]`.
117 pub const fn servo(index: u8, roll: f32, pitch: f32, yaw: f32) -> Self {
118 MixRow {
119 slot: Slot::Servo(index),
120 roll,
121 pitch,
122 yaw,
123 pusher: false,
124 }
125 }
126
127 /// A lift+cruise VTOL's pusher (forward motor) on `motors[index]`: the cruise thrust
128 /// ([`ControlOutput::cruise`]), no moments, not desaturated with the motor rows. Its slot
129 /// comes after every motor row's.
130 ///
131 /// # Examples
132 ///
133 /// ```
134 /// use stable_flight::mixers::{MixRow, Slot};
135 ///
136 /// let pusher = MixRow::pusher(4);
137 /// assert_eq!(pusher.slot(), Slot::Motor(4));
138 /// assert!(pusher.is_pusher());
139 /// ```
140 pub const fn pusher(index: u8) -> Self {
141 MixRow {
142 slot: Slot::Motor(index),
143 roll: 0.0,
144 pitch: 0.0,
145 yaw: 0.0,
146 pusher: true,
147 }
148 }
149
150 /// The slot this row drives.
151 pub const fn slot(&self) -> Slot {
152 self.slot
153 }
154
155 /// How much a roll moment moves this output.
156 pub const fn roll(&self) -> f32 {
157 self.roll
158 }
159
160 /// How much a pitch moment moves this output.
161 pub const fn pitch(&self) -> f32 {
162 self.pitch
163 }
164
165 /// How much a yaw moment moves this output.
166 pub const fn yaw(&self) -> f32 {
167 self.yaw
168 }
169
170 /// Whether this is a [`pusher`](Self::pusher) row.
171 pub const fn is_pusher(&self) -> bool {
172 self.pusher
173 }
174
175 /// This row with its yaw factor negated: the same output, its prop spinning the other way.
176 pub const fn with_reversed_yaw(self) -> Self {
177 MixRow {
178 yaw: -self.yaw,
179 ..self
180 }
181 }
182
183 fn moment(&self, moments: Vec3) -> f32 {
184 self.roll * moments.x + self.pitch * moments.y + self.yaw * moments.z
185 }
186
187 fn is_finite(&self) -> bool {
188 self.roll.is_finite() && self.pitch.is_finite() && self.yaw.is_finite()
189 }
190}
191
192/// How a [`TableMixer`] splits each motor's range between thrust and moments.
193#[derive(Debug, Clone, Copy, PartialEq)]
194pub struct MixerConfig {
195 /// Share of each motor's range given to collective thrust, in `(0, 1)`; the rest
196 /// (`1 − thrust_factor`) is headroom for roll and pitch. Pusher rows carry no moments and
197 /// use their full range.
198 pub thrust_factor: f32,
199 /// Yaw's motor factor relative to roll and pitch's (finite, `≥ 0`). Above 1 because prop
200 /// drag gives far less yaw authority than differential thrust gives roll and pitch.
201 pub yaw_ratio: f32,
202}
203
204impl Default for MixerConfig {
205 /// Thrust factor 0.9, yaw ratio 2.5: motor moments of 0.1 for roll and pitch, 0.25 for yaw.
206 fn default() -> Self {
207 MixerConfig {
208 thrust_factor: 0.9,
209 yaw_ratio: 2.5,
210 }
211 }
212}
213
214/// Why [`TableMixer::new`] rejected a table or config.
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
216#[non_exhaustive]
217pub enum MixerError {
218 /// The table has no rows.
219 #[error("mixer table is empty")]
220 Empty,
221 /// A row's slot index is past the [`ActuatorCommand`] arrays ([`ActuatorCommand::SLOTS`]).
222 #[error("mixer slot {0:?} is out of range")]
223 SlotOutOfRange(Slot),
224 /// Two rows drive the same slot.
225 #[error("mixer slot {0:?} appears twice")]
226 DuplicateSlot(Slot),
227 /// Motor slots skip an index: `m` motor and pusher rows must drive `motors[0..m]` (the
228 /// backend's mapping, not the table, picks each motor's channel).
229 #[error("mixer slot {0:?} leaves a gap in the motor slots")]
230 MotorGap(Slot),
231 /// A pusher row's slot comes before a motor row's: pushers follow the motors.
232 #[error("mixer pusher slot {0:?} comes before a motor slot")]
233 PusherBeforeMotor(Slot),
234 /// A row has a NaN or infinite factor.
235 #[error("mixer slot {0:?} has a non-finite factor")]
236 NonFiniteFactor(Slot),
237 /// [`MixerConfig::thrust_factor`] is not in `(0, 1)`.
238 #[error("mixer thrust factor must be in (0, 1)")]
239 ThrustFactor,
240 /// [`MixerConfig::yaw_ratio`] is negative or not finite.
241 #[error("mixer yaw ratio must be finite and non-negative")]
242 YawRatio,
243}
244
245/// A table-driven mixer for multirotors and other thrust-and-surface frames: `N` rows, each
246/// driving one motor or servo slot (see the [module docs](self) for the mixing rules and
247/// presets).
248///
249/// # Examples
250///
251/// A preset:
252///
253/// ```
254/// use stable_flight::mixers::TableMixer;
255/// use stable_flight::{ControlOutput, Mixer, Vec3};
256///
257/// let mut mixer = TableMixer::quad_x();
258/// let output = mixer.mix(&ControlOutput::new(0.5, Vec3::new(0.2, 0.0, 0.0)));
259/// // Rolling right: the left motors (0 and 2) push harder than the right ones.
260/// assert!(output.motors[0] > output.motors[1]);
261/// assert!(output.motors[2] > output.motors[3]);
262/// ```
263///
264/// A tricopter yaws with its tail servo:
265///
266/// ```
267/// use stable_flight::mixers::TableMixer;
268/// use stable_flight::{ControlOutput, Mixer, Vec3};
269///
270/// let mut mixer = TableMixer::tri();
271/// let output = mixer.mix(&ControlOutput::new(0.5, Vec3::new(0.0, 0.0, 0.3)));
272/// assert_eq!(output.servos[0], 0.3);
273/// assert_eq!(output.motors[0], output.motors[1]);
274/// ```
275///
276/// A custom table, with its own scaling:
277///
278/// ```
279/// use stable_flight::mixers::{MixRow, MixerConfig, TableMixer};
280///
281/// // Two motors side by side, each tilted by its own servo (a bicopter, numbered by hand).
282/// let rows = [
283/// MixRow::motor(0, 1.0, 0.0, 0.0),
284/// MixRow::motor(1, -1.0, 0.0, 0.0),
285/// MixRow::servo(0, 0.0, 1.0, -1.0),
286/// MixRow::servo(1, 0.0, 1.0, 1.0),
287/// ];
288/// let config = MixerConfig { thrust_factor: 0.8, ..MixerConfig::default() };
289/// let mixer = TableMixer::new(rows, config).expect("valid table");
290/// ```
291#[derive(Debug, Clone, Copy, PartialEq)]
292pub struct TableMixer<const N: usize> {
293 rows: [MixRow; N],
294 config: MixerConfig,
295 /// Motor rows (not pushers), which drive slots `0..motor_count`.
296 motor_count: usize,
297 /// What the last [`mix`](Mixer::mix) gave up.
298 saturation: Saturation,
299}
300
301impl<const N: usize> TableMixer<N> {
302 /// A mixer over `rows`, scaled by `config`.
303 ///
304 /// # Errors
305 ///
306 /// [`MixerError`] when the table is empty, a slot index is 8 or more, two rows share a
307 /// slot, the motor slots skip an index, a pusher comes before a motor, a factor is not
308 /// finite, or `config` is out of range.
309 pub fn new(rows: [MixRow; N], config: MixerConfig) -> Result<Self, MixerError> {
310 validate_rows(&rows)?;
311 validate_config(&config)?;
312 Ok(Self::from_valid(rows, config))
313 }
314
315 /// The thrust factor and yaw ratio this mixer scales by.
316 ///
317 /// # Examples
318 ///
319 /// ```
320 /// use stable_flight::mixers::{MixerConfig, TableMixer};
321 ///
322 /// assert_eq!(TableMixer::quad_x().config(), MixerConfig::default());
323 /// ```
324 pub fn config(&self) -> MixerConfig {
325 self.config
326 }
327
328 /// This mixer with `config` instead (e.g. a preset with another thrust factor).
329 ///
330 /// # Errors
331 ///
332 /// [`MixerError::ThrustFactor`] or [`MixerError::YawRatio`] when `config` is out of range.
333 pub fn with_config(self, config: MixerConfig) -> Result<Self, MixerError> {
334 validate_config(&config)?;
335 Ok(Self { config, ..self })
336 }
337
338 /// This mixer with every motor row's yaw factor negated: the same frame with every prop
339 /// spinning the other way (a model whose props turn opposite to the preset's). Servo rows
340 /// keep theirs: a rudder or a tilt servo turns the same way whichever way the props spin.
341 ///
342 /// # Examples
343 ///
344 /// ```
345 /// use stable_flight::mixers::TableMixer;
346 ///
347 /// // quad_x motor 0 spins clockwise (yaw -1); reversed, counterclockwise.
348 /// let reversed = TableMixer::quad_x().with_reversed_yaw();
349 /// assert_eq!(reversed.rows()[0].yaw(), 1.0);
350 /// assert_eq!(reversed.rows()[0].roll(), 1.0);
351 ///
352 /// // A quadplane's rudder (servo 2, row 7) still turns the nose right.
353 /// let quadplane = TableMixer::quadplane().with_reversed_yaw();
354 /// assert_eq!(quadplane.rows()[7].yaw(), 1.0);
355 /// ```
356 pub fn with_reversed_yaw(self) -> Self {
357 Self {
358 rows: self.rows.map(|row| match row.slot {
359 Slot::Motor(_) => row.with_reversed_yaw(),
360 Slot::Servo(_) => row,
361 }),
362 ..self
363 }
364 }
365
366 /// The table's rows, e.g. for a simulator that derives each motor's torque from them.
367 ///
368 /// # Examples
369 ///
370 /// ```
371 /// use stable_flight::mixers::{Slot, TableMixer};
372 ///
373 /// // quad_x motor 0 is front-left: more thrust there rolls right and pitches up.
374 /// let front_left = TableMixer::quad_x().rows()[0];
375 /// assert_eq!(front_left.slot(), Slot::Motor(0));
376 /// assert_eq!((front_left.roll(), front_left.pitch()), (1.0, 1.0));
377 /// ```
378 pub const fn rows(&self) -> &[MixRow; N] {
379 &self.rows
380 }
381
382 /// Rows and config already known valid (the presets; a test runs each through `new`).
383 fn from_valid(rows: [MixRow; N], config: MixerConfig) -> Self {
384 let motor_count = motor_count(&rows, false);
385 TableMixer {
386 rows,
387 config,
388 motor_count,
389 saturation: Saturation::default(),
390 }
391 }
392}
393
394impl<const N: usize> Mixer for TableMixer<N> {
395 /// Mixes thrust (`[0, 1]`) and moments (`[-1, 1]`) into motors in `[0, 1]` and servos in
396 /// `[-1, 1]`, per the [module docs](self).
397 fn mix(&mut self, command: &ControlOutput) -> ActuatorCommand {
398 // Out-of-range or NaN inputs saturate rather than panic (see `crate::math`).
399 let thrust = saturate_throttle(command.thrust);
400 let moments = command.moments.map(saturate_unit);
401 // Without a cruise output, servos fly the moments and pushers stay stopped.
402 let (cruise_thrust, surface_moments) = command.cruise.map_or((0.0, moments), |cruise| {
403 (
404 saturate_throttle(cruise.thrust),
405 cruise.moments.map(saturate_unit),
406 )
407 });
408
409 let MixerConfig {
410 thrust_factor,
411 yaw_ratio,
412 } = self.config;
413 let collective = thrust * thrust_factor;
414 let headroom = 1.0 - thrust_factor;
415 let motor_moments = Vec3::new(
416 moments.x * headroom,
417 moments.y * headroom,
418 moments.z * headroom * yaw_ratio,
419 );
420
421 let mut command = ActuatorCommand::default();
422 let mut servo_clamped = false;
423 for row in &self.rows {
424 match row.slot {
425 Slot::Motor(index) => {
426 if let Some(motor) = command.motors.get_mut(usize::from(index)) {
427 *motor = if row.pusher {
428 cruise_thrust
429 } else {
430 collective + row.moment(motor_moments)
431 };
432 }
433 }
434 Slot::Servo(index) => {
435 let value = row.moment(surface_moments);
436 servo_clamped |= value.abs() > 1.0;
437 if let Some(servo) = command.servos.get_mut(usize::from(index)) {
438 *servo = value.clamp(-1.0, 1.0);
439 }
440 }
441 }
442 }
443 // Motor slots are `0..motor_count`, pushers after them (validated), so the slice holds
444 // exactly the motors.
445 let desaturation = command
446 .motors
447 .get_mut(..self.motor_count)
448 .map(|motors| desaturate(motors, collective))
449 .unwrap_or_default();
450
451 self.saturation = Saturation {
452 mixer_thrust: desaturation.lowered,
453 mixer_moments: desaturation.moments_lost || servo_clamped,
454 ..Saturation::default()
455 };
456 command
457 }
458
459 /// `mixer_thrust` when the motors were shifted down (collective gave way), and
460 /// `mixer_moments` when the motor moments were scaled down or clipped, or a servo clamped.
461 fn saturation(&self) -> Saturation {
462 self.saturation
463 }
464}
465
466/// Rows driving a motor slot, pushers included when `pushers`.
467fn motor_count(rows: &[MixRow], pushers: bool) -> usize {
468 rows.iter()
469 .filter(|row| matches!(row.slot, Slot::Motor(_)) && (pushers || !row.pusher))
470 .count()
471}
472
473fn validate_rows(rows: &[MixRow]) -> Result<(), MixerError> {
474 if rows.is_empty() {
475 return Err(MixerError::Empty);
476 }
477 for (i, row) in rows.iter().enumerate() {
478 let (Slot::Motor(index) | Slot::Servo(index)) = row.slot;
479 if usize::from(index) >= ActuatorCommand::SLOTS {
480 return Err(MixerError::SlotOutOfRange(row.slot));
481 }
482 if rows[..i].iter().any(|earlier| earlier.slot == row.slot) {
483 return Err(MixerError::DuplicateSlot(row.slot));
484 }
485 if !row.is_finite() {
486 return Err(MixerError::NonFiniteFactor(row.slot));
487 }
488 }
489 // With unique indices, the motors fill `0..count` exactly when none is `count` or above.
490 let slot_count = motor_count(rows, true);
491 if let Some(row) = rows
492 .iter()
493 .find(|row| matches!(row.slot, Slot::Motor(index) if usize::from(index) >= slot_count))
494 {
495 return Err(MixerError::MotorGap(row.slot));
496 }
497 // Pushers follow the motors, so the motors alone fill `0..motors` for desaturation.
498 let lift_count = motor_count(rows, false);
499 if let Some(row) = rows.iter().find(
500 |row| matches!(row.slot, Slot::Motor(index) if row.pusher && usize::from(index) < lift_count),
501 ) {
502 return Err(MixerError::PusherBeforeMotor(row.slot));
503 }
504 Ok(())
505}
506
507fn validate_config(config: &MixerConfig) -> Result<(), MixerError> {
508 // Comparisons are false for NaN, so NaN fails both.
509 if !(config.thrust_factor > 0.0 && config.thrust_factor < 1.0) {
510 return Err(MixerError::ThrustFactor);
511 }
512 if !(config.yaw_ratio >= 0.0 && config.yaw_ratio.is_finite()) {
513 return Err(MixerError::YawRatio);
514 }
515 Ok(())
516}