use core::f32::consts::{PI, TAU};
use nalgebra::{SVector, UnitQuaternion};
use crate::{Vec2, Vec3};
#[cfg(test)]
mod tests;
#[track_caller]
pub(crate) fn assert_dt(dt: f32) {
assert!(dt > 0.0 && dt.is_finite(), "dt must be positive and finite");
}
const MAX_RAISE_PER_COLLECTIVE: f32 = 2.0;
pub(crate) fn desaturate(outputs: &mut [f32], collective: f32) -> Desaturation {
let (low, high) = outputs
.iter()
.fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), &o| {
(lo.min(o), hi.max(o))
});
let spread = high - low;
let scale = if spread > 1.0 { 1.0 / spread } else { 1.0 };
let scaled_low = collective + scale * (low - collective);
let scaled_high = collective + scale * (high - collective);
let shift = if scaled_high > 1.0 {
1.0 - scaled_high
} else if scaled_low < 0.0 {
(-scaled_low).min(MAX_RAISE_PER_COLLECTIVE * limit_or_zero(collective))
} else {
0.0
};
for output in outputs.iter_mut() {
*output = (collective + scale * (*output - collective) + shift).clamp(0.0, 1.0);
}
Desaturation {
lowered: shift < -CLIP_TOLERANCE,
moments_lost: scale < 1.0
|| scaled_low + shift < -CLIP_TOLERANCE
|| scaled_high + shift > 1.0 + CLIP_TOLERANCE,
}
}
const CLIP_TOLERANCE: f32 = 1e-6;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Desaturation {
pub(crate) lowered: bool,
pub(crate) moments_lost: bool,
}
pub(crate) fn cap_magnitude(v: Vec2, max: f32) -> Vec2 {
let length = v.norm();
if !length.is_finite() {
Vec2::zeros()
} else if length > max {
v * (max / length)
} else {
v
}
}
pub(crate) fn saturate_unit(value: f32) -> f32 {
saturate_symmetric(value, 1.0)
}
pub(crate) fn pitch_limit_rad(limit_rad: f32, transition: bool) -> f32 {
if transition {
core::f32::consts::FRAC_PI_2
} else {
limit_rad
}
}
pub(crate) fn saturate_symmetric(value: f32, limit: f32) -> f32 {
if value.is_nan() {
0.0
} else {
clamp_symmetric(value, limit)
}
}
pub(crate) fn clamp_symmetric(value: f32, limit: f32) -> f32 {
let limit = limit_or_zero(limit);
value.clamp(-limit, limit)
}
pub(crate) fn lagged(value: f32, target: f32, dt: f32, time_constant_s: f32) -> f32 {
value + (target - value) * (dt / time_constant_s).min(1.0)
}
pub(crate) fn limit_or_zero(limit: f32) -> f32 {
if limit >= 0.0 { limit } else { 0.0 }
}
pub(crate) fn clamp_symmetric_each<const D: usize>(
value: SVector<f32, D>,
limit: f32,
) -> SVector<f32, D> {
value.map(|component| clamp_symmetric(component, limit))
}
pub(crate) fn all_finite<const D: usize>(value: &SVector<f32, D>) -> bool {
value.iter().all(|component| component.is_finite())
}
pub(crate) fn neu_to_ned(v: Vec3) -> Vec3 {
Vec3::new(v.x, v.y, -v.z)
}
pub fn euler_angles(attitude: &UnitQuaternion<f32>) -> (f32, f32, f32) {
let (w, x, y, z) = (attitude.w, attitude.i, attitude.j, attitude.k);
let roll = libm::atan2f(2.0 * (y * z + w * x), w * w - x * x - y * y + z * z);
let pitch = libm::asinf(nose_up_cosine(attitude).clamp(-1.0, 1.0));
let yaw = libm::atan2f(2.0 * (x * y + w * z), w * w + x * x - y * y - z * z);
(roll, pitch, yaw)
}
const MIN_TILT_COSINE: f32 = 0.5;
const INVERTED_FADE_COSINE: f32 = 0.1;
pub(crate) fn tilt_boost(attitude: &UnitQuaternion<f32>) -> f32 {
let (x, y) = (attitude.i, attitude.j);
let cosine = 1.0 - 2.0 * (x * x + y * y);
if !cosine.is_finite() {
return 1.0;
}
let upright = (cosine / INVERTED_FADE_COSINE).clamp(0.0, 1.0);
upright / cosine.max(MIN_TILT_COSINE)
}
pub(crate) fn nose_up_cosine(attitude: &UnitQuaternion<f32>) -> f32 {
let (w, x, y, z) = (attitude.w, attitude.i, attitude.j, attitude.k);
2.0 * (w * y - x * z)
}
pub(crate) fn attitude_error(
current: &UnitQuaternion<f32>,
roll_rad: f32,
pitch_rad: f32,
heading_rad: f32,
) -> Vec3 {
if !current.coords.iter().all(|c| c.is_finite()) {
return Vec3::repeat(f32::NAN);
}
let rotation = current.to_rotation_matrix();
let m = rotation.matrix();
let (north, east) = (m[(0, 0)], m[(1, 0)]);
let current_heading_rad = libm::atan2f(east, north);
let horizontal = libm::sqrtf(north * north + east * east);
let (cos_h, sin_h) = if horizontal > 1e-6 {
(north / horizontal, east / horizontal)
} else {
(1.0, 0.0)
};
let (sin_r, cos_r) = (libm::sinf(roll_rad), libm::cosf(roll_rad));
let (sin_p, cos_p) = (libm::sinf(pitch_rad), libm::cosf(pitch_rad));
let desired_z = Vec3::new(
cos_h * sin_p * cos_r + sin_h * sin_r,
sin_h * sin_p * cos_r - cos_h * sin_r,
cos_p * cos_r,
);
let z = m.tr_mul(&desired_z);
let axis = Vec2::new(-z.y, z.x);
let sine = axis.norm();
let tilt = if sine < 1e-6 && z.z < 0.0 {
Vec2::new(PI, 0.0)
} else if sine < 1e-6 {
axis
} else {
axis * (libm::atan2f(sine, z.z) / sine)
};
let upright = m[(2, 2)].max(0.0);
Vec3::new(
tilt.x,
tilt.y,
wrap_angle(heading_rad - current_heading_rad) * upright,
)
}
pub(crate) const DEG: f32 = PI / 180.0;
pub(crate) fn saturate_rates(rates: Vec3, limits: Vec3) -> Vec3 {
Vec3::new(
saturate_symmetric(rates.x, limits.x),
saturate_symmetric(rates.y, limits.y),
saturate_symmetric(rates.z, limits.z),
)
}
pub(crate) fn thrust_curve(linear_thrust: f32, exponent: f32) -> f32 {
libm::powf(saturate_throttle(linear_thrust), exponent).clamp(0.0, 1.0)
}
pub(crate) fn bank_rad(attitude: &UnitQuaternion<f32>) -> f32 {
let m = attitude.to_rotation_matrix();
libm::atan2f(m[(2, 1)], m[(2, 2)])
}
pub(crate) fn twist_angle_rad(rotation: &UnitQuaternion<f32>, axis: &Vec3) -> f32 {
2.0 * libm::atan2f(rotation.imag().dot(axis), rotation.w)
}
pub(crate) fn saturate_throttle(value: f32) -> f32 {
if value.is_nan() {
0.0
} else {
value.clamp(0.0, 1.0)
}
}
pub(crate) fn guard_sink(thrust: f32, climb_mps: f32, limit_mps: f32, gain: f32) -> Option<f32> {
let excess_mps = -limit_mps - climb_mps;
(limit_mps > 0.0 && excess_mps > 0.0).then(|| saturate_throttle(thrust + gain * excess_mps))
}
pub(crate) fn shaped_closing_speed(distance_m: f32, p: f32, accel_mps2: f32) -> f32 {
if distance_m.is_nan() || distance_m <= 0.0 {
return 0.0;
}
let accel_mps2 = if accel_mps2 > 0.0 { accel_mps2 } else { 0.0 };
if p.is_nan() || p <= 0.0 {
return libm::sqrtf(2.0 * accel_mps2 * distance_m);
}
let linear_m = accel_mps2 / (p * p);
if accel_mps2 == 0.0 || distance_m <= linear_m {
return p * distance_m;
}
libm::sqrtf(2.0 * accel_mps2 * (distance_m - linear_m / 2.0))
}
pub fn wrap_angle(angle: f32) -> f32 {
rem_euclid(angle + PI, TAU) - PI
}
fn rem_euclid(value: f32, divisor: f32) -> f32 {
let remainder = value % divisor;
if remainder < 0.0 {
remainder + divisor
} else {
remainder
}
}