use nalgebra::UnitQuaternion;
use crate::controllers::{InvalidConfig, check, check_positive, check_unit_interval};
use crate::math::{DEG, assert_dt, euler_angles, twist_angle_rad, wrap_angle};
use crate::{AbsoluteAttitudeCommand, AbsoluteRateCommand, ControlInput, VehicleState};
mod path;
mod segment;
#[cfg(test)]
mod tests;
use path::PathHold;
pub use path::{Path, PathConfig};
pub use segment::{
Axis, DEFAULT_DOUBLET_HALF_S, DOUBLET_PAUSE_S, MAX_SEGMENTS, Maneuver, ManeuverError, RateLaw,
Segment, SegmentEnd, Thrust,
};
use segment::{UNUSED, positive};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RecoveryConfig {
pub pitch_rad: f32,
pub thrust: f32,
pub level_band_rad: f32,
pub max_body_rate_radps: f32,
pub settle_s: f32,
pub timeout_s: f32,
}
impl Default for RecoveryConfig {
fn default() -> Self {
RecoveryConfig {
pitch_rad: 0.0,
thrust: 1.0,
level_band_rad: 10.0 * DEG,
max_body_rate_radps: 20.0 * DEG,
settle_s: 0.5,
timeout_s: 10.0,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ManeuverConfig {
pub thrust: f32,
pub cruise_thrust: f32,
pub timeout_factor: f32,
pub path: PathConfig,
pub recovery: RecoveryConfig,
}
impl Default for ManeuverConfig {
fn default() -> Self {
ManeuverConfig {
thrust: 1.0,
cruise_thrust: 0.5,
timeout_factor: 2.0,
path: PathConfig::default(),
recovery: RecoveryConfig::default(),
}
}
}
impl ManeuverConfig {
pub fn validate(&self) -> Result<(), InvalidConfig> {
check_unit_interval("thrust", self.thrust)?;
check_unit_interval("cruise_thrust", self.cruise_thrust)?;
check(
"timeout_factor",
self.timeout_factor >= 1.0 && self.timeout_factor.is_finite(),
"at least 1 and finite",
)?;
self.path
.validate()
.map_err(|e: InvalidConfig| e.in_section("path"))?;
let recovery = &self.recovery;
let section = |e: InvalidConfig| e.in_section("recovery");
check(
"pitch_rad",
(-core::f32::consts::FRAC_PI_2..=core::f32::consts::FRAC_PI_2)
.contains(&recovery.pitch_rad),
"in [-π/2, π/2]",
)
.map_err(section)?;
check_unit_interval("thrust", recovery.thrust).map_err(section)?;
check_positive("level_band_rad", recovery.level_band_rad).map_err(section)?;
check_positive("max_body_rate_radps", recovery.max_body_rate_radps).map_err(section)?;
check_positive("settle_s", recovery.settle_s).map_err(section)?;
check_positive("timeout_s", recovery.timeout_s).map_err(section)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ManeuverPhase {
Idle,
Rotation {
segment: usize,
},
Recovery,
Done,
}
#[derive(Clone, Copy, Debug)]
struct SegmentProgress {
start_inverse: UnitQuaternion<f32>,
last_twist_rad: f32,
turned_rad: f32,
elapsed_s: f32,
limit_s: f32,
path: PathHold,
}
impl SegmentProgress {
fn new(segment: &Segment, state: &VehicleState, timeout_factor: f32) -> Self {
let limit_s = match *segment {
Segment::Pause { duration_s, .. } => duration_s,
Segment::Rotate {
end: SegmentEnd::Duration { s },
..
} => s,
Segment::Rotate {
rate,
end: SegmentEnd::Angle { rad },
..
} => {
let radps = rate.radps(state).abs();
if positive(radps) {
rad / radps * timeout_factor
} else {
0.0
}
}
};
SegmentProgress {
start_inverse: state.attitude.inverse(),
last_twist_rad: 0.0,
turned_rad: 0.0,
elapsed_s: 0.0,
limit_s,
path: PathHold::new(segment, state),
}
}
fn ended(&mut self, segment: &Segment, state: &VehicleState) -> bool {
if self.elapsed_s >= self.limit_s {
return true;
}
let Segment::Rotate {
axis,
rate,
end: SegmentEnd::Angle { rad },
..
} = *segment
else {
return false;
};
let rotation = self.start_inverse * state.attitude;
let twist_rad = twist_angle_rad(&rotation, &axis.unit());
let step_rad = wrap_angle(twist_rad - self.last_twist_rad);
if step_rad.is_finite() {
self.turned_rad += step_rad;
self.last_twist_rad = twist_rad;
}
self.turned_rad * rate.direction() >= rad
}
}
#[derive(Clone, Copy, Debug, Default)]
struct Recovery {
elapsed_s: f32,
level_s: f32,
}
impl Recovery {
fn next(
&mut self,
config: &RecoveryConfig,
dt: f32,
state: &VehicleState,
) -> Option<ControlInput> {
let (roll_rad, pitch_rad, _) = euler_angles(&state.attitude);
let level = roll_rad.abs() <= config.level_band_rad
&& (pitch_rad - config.pitch_rad).abs() <= config.level_band_rad
&& state.angular_velocity_radps.norm() <= config.max_body_rate_radps;
self.level_s = if level { self.level_s + dt } else { 0.0 };
if self.level_s >= config.settle_s || self.elapsed_s >= config.timeout_s {
return None;
}
self.elapsed_s += dt;
Some(ControlInput::AbsoluteAttitude(AbsoluteAttitudeCommand {
roll_rad: 0.0,
pitch_rad: config.pitch_rad,
heading_rad: f32::NAN,
thrust: config.thrust,
}))
}
}
#[derive(Clone, Debug)]
pub struct ManeuverRunner {
config: ManeuverConfig,
maneuver: Option<Maneuver>,
phase: ManeuverPhase,
progress: SegmentProgress,
recovery: Recovery,
}
impl Default for ManeuverRunner {
fn default() -> Self {
ManeuverRunner::new(ManeuverConfig::default())
}
}
impl ManeuverRunner {
pub fn new(config: ManeuverConfig) -> Self {
if let Err(error) = config.validate() {
panic!("invalid ManeuverConfig: {error}");
}
ManeuverRunner {
config,
maneuver: None,
phase: ManeuverPhase::Idle,
progress: SegmentProgress::new(&UNUSED, &VehicleState::default(), 1.0),
recovery: Recovery::default(),
}
}
pub fn config(&self) -> &ManeuverConfig {
&self.config
}
pub fn start(&mut self, maneuver: Maneuver, state: &VehicleState) {
self.maneuver = Some(maneuver);
self.begin(0, state);
}
pub fn abort(&mut self) {
if matches!(self.phase, ManeuverPhase::Rotation { .. }) {
self.recover();
}
}
pub fn phase(&self) -> ManeuverPhase {
self.phase
}
pub fn is_active(&self) -> bool {
matches!(
self.phase,
ManeuverPhase::Rotation { .. } | ManeuverPhase::Recovery
)
}
pub fn next(&mut self, dt: f32, state: &VehicleState) -> Option<ControlInput> {
assert_dt(dt);
loop {
match self.phase {
ManeuverPhase::Idle | ManeuverPhase::Done => return None,
ManeuverPhase::Rotation { segment: index } => {
let segment = self.segment(index)?;
if self.progress.ended(&segment, state) {
self.begin(index + 1, state);
continue;
}
self.progress.elapsed_s += dt;
return Some(self.rates(&segment, state));
}
ManeuverPhase::Recovery => {
let command = self.recovery.next(&self.config.recovery, dt, state);
if command.is_none() {
self.phase = ManeuverPhase::Done;
}
return command;
}
}
}
}
fn segment(&self, index: usize) -> Option<Segment> {
self.maneuver.as_ref()?.segments().get(index).copied()
}
fn begin(&mut self, index: usize, state: &VehicleState) {
let Some(segment) = self.segment(index) else {
self.recover();
return;
};
self.phase = ManeuverPhase::Rotation { segment: index };
self.progress = SegmentProgress::new(&segment, state, self.config.timeout_factor);
}
fn recover(&mut self) {
self.phase = ManeuverPhase::Recovery;
self.recovery = Recovery::default();
}
fn rates(&self, segment: &Segment, state: &VehicleState) -> ControlInput {
let (axis, radps, thrust) = match *segment {
Segment::Rotate {
axis, rate, thrust, ..
} => (Some(axis), rate.radps(state), thrust),
Segment::Pause { thrust, .. } => (None, 0.0, thrust),
};
let correction_radps = self
.progress
.path
.correction_radps(&self.config.path, state);
let rate = |about: Axis| {
let own_radps = if axis == Some(about) { radps } else { 0.0 };
own_radps + correction_radps.dot(&about.unit())
};
ControlInput::AbsoluteRate(AbsoluteRateCommand {
roll_radps: rate(Axis::Roll),
pitch_radps: rate(Axis::Pitch),
yaw_radps: rate(Axis::Yaw),
thrust: match thrust {
Thrust::Maneuver => self.config.thrust,
Thrust::Cruise => self.config.cruise_thrust,
},
})
}
}