use core::f32::consts::FRAC_PI_2;
use crate::math::clamp_symmetric;
use crate::{GRAVITY, Vec2};
#[cfg(test)]
mod tests;
const MIN_GROUND_SPEED_MPS: f32 = 1.0;
const MAX_CAPTURE_RAD: f32 = core::f32::consts::FRAC_PI_4;
fn l1(ground_speed_mps: f32, period_s: f32, damping: f32) -> (f32, f32) {
let distance_m = damping * period_s * ground_speed_mps / core::f32::consts::PI;
(distance_m, 4.0 * damping * damping)
}
fn cross(a: Vec2, b: Vec2) -> f32 {
a.x * b.y - a.y * b.x
}
pub(crate) fn track_accel_mps2(
position_m: Vec2,
velocity_mps: Vec2,
point_m: Vec2,
direction: Vec2,
period_s: f32,
damping: f32,
) -> f32 {
let Some(direction) = direction.try_normalize(1e-6) else {
return 0.0;
};
let speed_mps = velocity_mps.norm();
if speed_mps.is_nan() || speed_mps < MIN_GROUND_SPEED_MPS {
return 0.0;
}
let (distance_m, gain) = l1(speed_mps, period_s, damping);
let cross_track_m = cross(direction, position_m - point_m);
let capture_rad = libm::asinf((cross_track_m / distance_m).clamp(-1.0, 1.0))
.clamp(-MAX_CAPTURE_RAD, MAX_CAPTURE_RAD);
let course_rad = libm::atan2f(cross(direction, velocity_mps), direction.dot(&velocity_mps));
let eta_rad = clamp_symmetric(-capture_rad - course_rad, FRAC_PI_2);
let accel = gain * speed_mps * speed_mps / distance_m * libm::sinf(eta_rad);
if accel.is_finite() { accel } else { 0.0 }
}
pub(crate) fn loiter_accel_mps2(
position_m: Vec2,
velocity_mps: Vec2,
center_m: Vec2,
radius_m: f32,
period_s: f32,
damping: f32,
) -> f32 {
let speed_mps = velocity_mps.norm();
let slow = speed_mps.is_nan() || speed_mps < MIN_GROUND_SPEED_MPS;
if slow || radius_m.is_nan() || radius_m <= 0.0 {
return 0.0;
}
let centripetal = speed_mps * speed_mps / radius_m;
let Some(outward) = (position_m - center_m).try_normalize(1e-3) else {
return centripetal;
};
let tangent = Vec2::new(-outward.y, outward.x);
let nearest_m = center_m + outward * radius_m;
centripetal
+ track_accel_mps2(
position_m,
velocity_mps,
nearest_m,
tangent,
period_s,
damping,
)
}
pub(crate) fn bank_for_accel_rad(accel_mps2: f32) -> f32 {
let bank = libm::atanf(accel_mps2 / GRAVITY);
if bank.is_finite() { bank } else { 0.0 }
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct PiLoop {
integral: f32,
}
impl PiLoop {
#[allow(
clippy::too_many_arguments,
reason = "a PI loop's gains and limits, inline"
)]
pub(crate) fn step(
&mut self,
dt: f32,
error: f32,
p: f32,
i: f32,
max_integral: f32,
(low, high): (f32, f32),
fallback: f32,
) -> f32 {
if !error.is_finite() {
return fallback;
}
let high = high.max(low);
let unclamped = p * error + i * self.integral;
let pinned = (unclamped >= high && error > 0.0) || (unclamped <= low && error < 0.0);
if !pinned {
self.integral = clamp_symmetric(self.integral + error * dt, max_integral);
}
(p * error + i * self.integral).clamp(low, high)
}
}