use core::f32::consts::FRAC_PI_2;
use crate::controllers::{InvalidConfig, check, check_limit, check_positive};
use crate::math::{assert_dt, nose_up_cosine, saturate_throttle};
use crate::{
Configurable, ControlInput, FlightMode, FlightModeReport, FlightRegime, ModeRefusal,
VehicleState, WaypointCommand,
};
mod forward;
mod lift;
mod off_nose;
mod params;
mod quadplane;
mod tailsitter;
pub use forward::{ForwardSplit, ForwardThrust, ForwardThrustConfig};
pub use lift::{
DEFAULT_FORWARD_PITCH_MAX_RAD, LiftTransition, LiftTransitionConfig, LiftTransitionStep,
};
pub use off_nose::{
DEFAULT_OFF_NOSE_FREE_RAD, DEFAULT_OFF_NOSE_FULL_RAD, DEFAULT_OFF_NOSE_SPEED_MPS,
DEFAULT_OFF_NOSE_TAIL_FIRST_DIVISOR, OffNoseSpeed, OffNoseSpeedConfig,
};
pub use quadplane::{QuadPlaneGuidance, QuadPlaneGuidanceConfig};
pub use tailsitter::{TailsitterGuidance, TailsitterGuidanceConfig};
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TransitionConfig {
pub forward_rate_radps: f32,
pub forward_done_rad: f32,
pub forward_max_tilt_rad: f32,
pub min_airspeed_mps: f32,
pub back_rate_radps: f32,
pub back_done_rad: f32,
pub timeout_s: f32,
pub min_height_m: f32,
pub plane_min_height_m: f32,
pub forward_thrust: f32,
pub back_thrust: f32,
pub back_sink_limit_mps: f32,
pub back_sink_gain: f32,
pub handoff_s: f32,
pub roll_limit_rad: f32,
}
impl TransitionConfig {
pub fn validate(&self) -> Result<(), InvalidConfig> {
let in_quarter_turn = |value: f32| value > 0.0 && value < FRAC_PI_2;
check_positive("forward_rate_radps", self.forward_rate_radps)?;
check(
"forward_done_rad",
in_quarter_turn(self.forward_done_rad),
"in (0, π/2) rad",
)?;
check(
"forward_max_tilt_rad",
self.forward_max_tilt_rad > 0.0 && self.forward_max_tilt_rad <= FRAC_PI_2,
"in (0, π/2] rad",
)?;
check_limit("min_airspeed_mps", self.min_airspeed_mps)?;
check_positive("back_rate_radps", self.back_rate_radps)?;
check(
"back_done_rad",
in_quarter_turn(self.back_done_rad),
"in (0, π/2) rad",
)?;
check_positive("timeout_s", self.timeout_s)?;
check_limit("min_height_m", self.min_height_m)?;
check_limit("plane_min_height_m", self.plane_min_height_m)?;
let unit = |value: f32| (0.0..=1.0).contains(&value);
check("forward_thrust", unit(self.forward_thrust), "in [0, 1]")?;
check("back_thrust", unit(self.back_thrust), "in [0, 1]")?;
check_limit("back_sink_limit_mps", self.back_sink_limit_mps)?;
check_limit("back_sink_gain", self.back_sink_gain)?;
check_limit("handoff_s", self.handoff_s)?;
check(
"roll_limit_rad",
self.roll_limit_rad > 0.0 && self.roll_limit_rad <= core::f32::consts::PI,
"in (0, π] rad",
)
}
}
impl Default for TransitionConfig {
fn default() -> Self {
TransitionConfig {
forward_rate_radps: 50.0_f32.to_radians(),
forward_done_rad: 45.0_f32.to_radians(),
forward_max_tilt_rad: 80.0_f32.to_radians(),
min_airspeed_mps: 0.0,
back_rate_radps: 50.0_f32.to_radians(),
back_done_rad: 45.0_f32.to_radians(),
timeout_s: 15.0,
min_height_m: 5.0,
plane_min_height_m: 0.0,
forward_thrust: 0.5,
back_thrust: 0.5,
back_sink_limit_mps: 1.0,
back_sink_gain: 0.4,
handoff_s: 0.5,
roll_limit_rad: 45.0_f32.to_radians(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TransitionStep {
pub mode: FlightMode,
pub tilt_target_rad: Option<f32>,
pub handoff: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Transition {
config: TransitionConfig,
forward_done_cosine: f32,
back_done_cosine: f32,
mode: FlightMode,
refusal: Option<ModeRefusal>,
gate: ForwardGate,
elapsed_s: f32,
start_tilt_rad: f32,
}
impl Transition {
pub fn new(config: TransitionConfig) -> Self {
if let Err(error) = config.validate() {
panic!("invalid TransitionConfig: {error}");
}
let (forward_done_cosine, back_done_cosine) = done_cosines(&config);
Transition {
config,
forward_done_cosine,
back_done_cosine,
mode: FlightMode::Copter,
refusal: None,
gate: ForwardGate::new(),
elapsed_s: 0.0,
start_tilt_rad: 0.0,
}
}
pub fn prime(&mut self, state: &VehicleState) {
self.mode = FlightMode::Copter;
self.refusal = None;
self.elapsed_s = 0.0;
self.gate.prime(state);
}
pub fn update(
&mut self,
dt: f32,
requested: FlightRegime,
state: &VehicleState,
) -> TransitionStep {
assert_dt(dt);
let nose_up = nose_up_cosine(&state.attitude);
self.refusal = None;
let mut handoff = false;
match self.mode {
FlightMode::Copter => match requested {
FlightRegime::Plane => self.try_forward(state, nose_up),
FlightRegime::Copter => self.gate.clear(),
},
FlightMode::ToPlane => {
self.elapsed_s += dt;
if requested != FlightRegime::Plane {
self.mode = FlightMode::Copter;
} else if self.forward_done(state, nose_up) {
self.mode = FlightMode::Plane;
handoff = true;
} else if self.elapsed_s > self.config.timeout_s {
self.abandon(ModeRefusal::TransitionTimeout);
}
}
FlightMode::Plane => {
if requested != FlightRegime::Plane {
self.start(FlightMode::ToCopter, nose_up);
} else if self.gate.below(state, self.config.plane_min_height_m) {
self.start(FlightMode::ToCopter, nose_up);
self.gate.abandon(ModeRefusal::BelowPlaneMinAltitude);
self.refusal = Some(ModeRefusal::BelowPlaneMinAltitude);
}
}
FlightMode::ToCopter => {
self.elapsed_s += dt;
let plane_requested = requested == FlightRegime::Plane;
if plane_requested && !self.gate.fallen_back() {
self.mode = FlightMode::Plane;
} else if nose_up >= self.back_done_cosine || self.elapsed_s > self.config.timeout_s
{
self.mode = FlightMode::Copter;
handoff = true;
}
if plane_requested {
self.refusal = self.gate.fallback();
}
}
}
TransitionStep {
mode: self.mode,
tilt_target_rad: self.tilt_target_rad(),
handoff,
}
}
pub fn cut_short(&mut self, refusal: ModeRefusal) -> TransitionStep {
let handoff = match self.mode {
FlightMode::ToPlane => {
self.abandon(refusal);
false
}
FlightMode::ToCopter => {
self.mode = FlightMode::Copter;
true
}
_ => false,
};
TransitionStep {
mode: self.mode,
tilt_target_rad: self.tilt_target_rad(),
handoff,
}
}
fn abandon(&mut self, refusal: ModeRefusal) {
self.mode = FlightMode::Copter;
self.gate.abandon(refusal);
self.refusal = Some(refusal);
}
pub fn report(&self) -> FlightModeReport {
FlightModeReport {
mode: self.mode,
refusal: self.refusal,
}
}
pub(super) fn fallen_back(&self) -> bool {
self.gate.fallen_back()
}
fn try_forward(&mut self, state: &VehicleState, nose_up: f32) {
let needed_m = self.config.min_height_m.max(self.config.plane_min_height_m);
self.refusal = self.gate.refusal(state, needed_m);
if self.refusal.is_none() {
self.start(FlightMode::ToPlane, nose_up);
}
}
fn start(&mut self, mode: FlightMode, nose_up: f32) {
let fallback = if mode == FlightMode::ToPlane {
0.0
} else {
FRAC_PI_2
};
self.mode = mode;
self.elapsed_s = 0.0;
self.start_tilt_rad = if nose_up.is_finite() {
libm::acosf(nose_up.clamp(-1.0, 1.0))
} else {
fallback
};
}
fn forward_done(&self, state: &VehicleState, nose_up: f32) -> bool {
let tilted = nose_up <= self.forward_done_cosine;
let fast_enough = state
.valid_airspeed_mps()
.is_none_or(|airspeed_mps| airspeed_mps >= self.config.min_airspeed_mps);
tilted && fast_enough
}
fn tilt_target_rad(&self) -> Option<f32> {
match self.mode {
FlightMode::ToPlane => Some(
(self.start_tilt_rad + self.config.forward_rate_radps * self.elapsed_s)
.min(self.config.forward_max_tilt_rad.max(self.start_tilt_rad)),
),
FlightMode::ToCopter => {
Some((self.start_tilt_rad - self.config.back_rate_radps * self.elapsed_s).max(0.0))
}
_ => None,
}
}
}
impl Configurable for Transition {
type Config = TransitionConfig;
fn config(&self) -> &TransitionConfig {
&self.config
}
fn set_config(&mut self, config: TransitionConfig) -> Result<(), InvalidConfig> {
config.validate()?;
self.config = config;
(self.forward_done_cosine, self.back_done_cosine) = done_cosines(&config);
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct ForwardGate {
home_altitude_m: f32,
abandoned: Option<ModeRefusal>,
}
impl ForwardGate {
fn new() -> Self {
ForwardGate {
home_altitude_m: f32::NAN,
abandoned: None,
}
}
fn prime(&mut self, state: &VehicleState) {
self.home_altitude_m = state.position_m.z;
self.abandoned = None;
}
fn refusal(&self, state: &VehicleState, min_height_m: f32) -> Option<ModeRefusal> {
let height_m = self.height_m(state);
let high_enough = height_m.is_finite() && height_m >= min_height_m;
if self.abandoned.is_some() {
self.abandoned
} else if !high_enough {
Some(ModeRefusal::BelowMinAltitude)
} else {
None
}
}
fn below(&self, state: &VehicleState, floor_m: f32) -> bool {
floor_m > 0.0 && self.height_m(state) < floor_m
}
fn height_m(&self, state: &VehicleState) -> f32 {
state.position_m.z - self.home_altitude_m
}
fn abandon(&mut self, refusal: ModeRefusal) {
self.abandoned = Some(refusal);
}
fn fallback(&self) -> Option<ModeRefusal> {
self.abandoned
}
fn fallen_back(&self) -> bool {
self.abandoned.is_some()
}
fn clear(&mut self) {
self.abandoned = None;
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
struct FallbackHold {
point: Option<WaypointCommand>,
}
impl FallbackHold {
fn input(
&mut self,
fallen_back: bool,
input: &ControlInput,
state: &VehicleState,
) -> ControlInput {
if !fallen_back {
self.point = None;
return *input;
}
let ControlInput::Waypoint(_) = input else {
return *input;
};
let point = *self.point.get_or_insert_with(|| WaypointCommand {
position_m: state.position_m.xy(),
altitude_m: state.position_m.z,
..WaypointCommand::default()
});
ControlInput::Waypoint(point)
}
fn clear(&mut self) {
self.point = None;
}
}
fn done_cosines(config: &TransitionConfig) -> (f32, f32) {
(
libm::cosf(config.forward_done_rad),
libm::cosf(config.back_done_rad),
)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ThrustHandoff {
duration_s: f32,
from: f32,
elapsed_s: f32,
}
impl ThrustHandoff {
pub fn new(duration_s: f32) -> Self {
if let Err(error) = check_limit("duration_s", duration_s) {
panic!("invalid ThrustHandoff: {error}");
}
ThrustHandoff {
duration_s,
from: 0.0,
elapsed_s: duration_s,
}
}
pub fn start(&mut self, from: f32) {
self.from = saturate_throttle(from);
self.elapsed_s = 0.0;
}
pub fn active(&self) -> bool {
self.elapsed_s < self.duration_s
}
pub fn apply(&mut self, dt: f32, demanded: f32) -> f32 {
assert_dt(dt);
let demanded = saturate_throttle(demanded);
if !self.active() {
return demanded;
}
self.elapsed_s += dt;
let weight = (self.elapsed_s / self.duration_s).min(1.0);
self.from + (demanded - self.from) * weight
}
}