use super::WingModel;
use crate::controllers::{InvalidConfig, RateGains, check, check_positive};
use crate::stabilizers::plane::PlaneAxisGains;
use crate::tuning::{StepConfig, StepMetrics, StepProbe, StepStatus};
#[cfg(test)]
mod tests;
const MODEL_DT: f32 = 0.004;
const P_GRID: [f32; 16] = [
0.005, 0.0083, 0.0138, 0.0229, 0.0381, 0.0632, 0.105, 0.175, 0.29, 0.482, 0.8, 1.33, 2.21,
3.67, 6.09, 10.0,
];
const I_GRID: [f32; 12] = [
0.0, 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.63, 1.26, 2.51, 5.01, 10.0,
];
const CELLS: usize = P_GRID.len() * I_GRID.len();
const TAU_RATIO: f32 = 1.05;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WingDesignConfig {
pub amplitude_rad: f32,
pub step_duration_s: f32,
pub max_rate_radps: f32,
pub max_moment: f32,
pub max_integral: f32,
pub static_trim: f32,
pub max_overshoot: f32,
pub max_saturated_s: f32,
pub time_constant_range_s: [f32; 2],
pub rise_per_time_constant: f32,
}
impl WingDesignConfig {
pub fn validate(&self) -> Result<(), InvalidConfig> {
check_positive("amplitude_rad", self.amplitude_rad)?;
check_positive("step_duration_s", self.step_duration_s)?;
check_positive("max_rate_radps", self.max_rate_radps)?;
check(
"max_moment",
self.max_moment > 0.0 && self.max_moment <= 1.0,
"in (0, 1]",
)?;
check_positive("max_integral", self.max_integral)?;
check("static_trim", self.static_trim.abs() <= 1.0, "in [-1, 1]")?;
check(
"max_overshoot",
self.max_overshoot >= 0.0 && self.max_overshoot.is_finite(),
"non-negative and finite",
)?;
check(
"max_saturated_s",
self.max_saturated_s >= 0.0 && self.max_saturated_s.is_finite(),
"non-negative and finite",
)?;
let [least, most] = self.time_constant_range_s;
check_positive("time_constant_range_s[0]", least)?;
check(
"time_constant_range_s[1]",
most > least && most.is_finite(),
"finite and above time_constant_range_s[0]",
)?;
check_positive("rise_per_time_constant", self.rise_per_time_constant)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WingDesignStatus {
Running,
Done(PlaneAxisGains),
Failed,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WingDesign {
model: WingModel,
config: WingDesignConfig,
min_i: f32,
phase: Phase,
}
const TRIM_INTEGRAL_SHARE: f32 = 0.5;
#[derive(Clone, Copy, Debug, PartialEq)]
enum Phase {
Bisect {
tau_s: f32,
cell: usize,
passing_tau_s: Option<f32>,
failing_tau_s: f32,
},
Map {
tau_s: f32,
cell: usize,
passes: [bool; CELLS],
},
Done(WingDesignStatus),
}
impl WingDesign {
pub fn new(model: WingModel, config: WingDesignConfig) -> Self {
if let Err(error) = config.validate() {
panic!("invalid WingDesignConfig: {error}");
}
let stiff = model.stiffness_per_s2 > 0.0;
let usable = model.control_radps2 > 0.0
&& (model.damping_per_s > 0.0 || stiff)
&& model.feedforward().is_finite();
let model = WingModel {
damping_per_s: model.damping_per_s.max(0.0),
..model
};
let [least_s, most_s] = config.time_constant_range_s;
let phase = if usable {
Phase::Bisect {
tau_s: most_s,
cell: 0,
passing_tau_s: None,
failing_tau_s: least_s / TAU_RATIO,
}
} else {
Phase::Done(WingDesignStatus::Failed)
};
let integral_trim = (model.trim_moment - config.static_trim).abs();
Self {
model,
config,
min_i: integral_trim / (TRIM_INTEGRAL_SHARE * config.max_integral),
phase,
}
}
pub fn advance(&mut self, candidates: usize) -> WingDesignStatus {
for _ in 0..candidates {
if let Phase::Done(status) = self.phase {
return status;
}
self.phase = self.next_phase();
}
match self.phase {
Phase::Done(status) => status,
_ => WingDesignStatus::Running,
}
}
fn next_phase(&self) -> Phase {
match self.phase {
Phase::Bisect {
tau_s,
cell,
passing_tau_s,
failing_tau_s,
} => {
if self.passes(cell, tau_s) {
self.bisected(failing_tau_s, Some(tau_s))
} else if cell + 1 < CELLS {
Phase::Bisect {
tau_s,
cell: cell + 1,
passing_tau_s,
failing_tau_s,
}
} else if passing_tau_s.is_none() {
Phase::Done(WingDesignStatus::Failed)
} else {
self.bisected(tau_s, passing_tau_s)
}
}
Phase::Map {
tau_s,
cell,
mut passes,
} => {
passes[cell] = self.passes(cell, tau_s);
if cell + 1 < CELLS {
Phase::Map {
tau_s,
cell: cell + 1,
passes,
}
} else {
Phase::Done(self.pick(tau_s, &passes))
}
}
Phase::Done(status) => Phase::Done(status),
}
}
fn bisected(&self, failing_tau_s: f32, passing_tau_s: Option<f32>) -> Phase {
let passing_tau_s = passing_tau_s.unwrap_or_else(|| unreachable!("bisected after a pass"));
if passing_tau_s <= failing_tau_s * TAU_RATIO {
let most_s = self.config.time_constant_range_s[1];
return Phase::Map {
tau_s: (passing_tau_s * TAU_MARGIN).min(most_s),
cell: 0,
passes: [false; CELLS],
};
}
Phase::Bisect {
tau_s: libm::sqrtf(failing_tau_s * passing_tau_s),
cell: 0,
passing_tau_s: Some(passing_tau_s),
failing_tau_s,
}
}
fn pick(&self, tau_s: f32, passes: &[bool; CELLS]) -> WingDesignStatus {
let passing = |p: isize, i: isize| {
let inside =
(0..P_GRID.len() as isize).contains(&p) && (0..I_GRID.len() as isize).contains(&i);
inside && passes[p as usize * I_GRID.len() + i as usize]
};
let depth = |p: isize, i: isize| {
(1..)
.take_while(|&d| {
[(d, 0), (-d, 0), (0, d), (0, -d)]
.iter()
.all(|&(dp, di)| passing(p + dp, i + di))
})
.count()
};
let best = (0..CELLS)
.filter(|&cell| passes[cell])
.map(|cell| {
let (p, i) = (
(cell / I_GRID.len()) as isize,
(cell % I_GRID.len()) as isize,
);
(cell, depth(p, i))
})
.fold(
None,
|best: Option<(usize, usize)>, (cell, depth)| match best {
Some((_, kept)) if kept >= depth => best,
_ => Some((cell, depth)),
},
);
match best {
Some((cell, _)) => WingDesignStatus::Done(self.gains(cell, tau_s)),
None => WingDesignStatus::Failed,
}
}
fn gains(&self, cell: usize, tau_s: f32) -> PlaneAxisGains {
PlaneAxisGains {
rate: RateGains {
p: P_GRID[cell / I_GRID.len()],
i: I_GRID[cell % I_GRID.len()],
ff: self.model.feedforward(),
},
time_constant_s: tau_s,
}
}
fn passes(&self, cell: usize, tau_s: f32) -> bool {
let gains = self.gains(cell, tau_s);
if gains.rate.i < self.min_i {
return false;
}
model_step(&self.model, gains, &self.config)
.is_some_and(|metrics| meets_targets(&metrics, tau_s, &self.config))
}
}
const TAU_MARGIN: f32 = 1.15;
pub(crate) fn meets_targets(metrics: &StepMetrics, tau_s: f32, config: &WingDesignConfig) -> bool {
let max_rise_s = config.rise_per_time_constant * tau_s;
metrics.overshoot <= config.max_overshoot
&& metrics.settling_time_s.is_some()
&& metrics.saturated_s <= config.max_saturated_s
&& metrics
.rise_time_s
.is_some_and(|rise_s| rise_s <= max_rise_s)
}
fn model_step(
model: &WingModel,
gains: PlaneAxisGains,
config: &WingDesignConfig,
) -> Option<StepMetrics> {
let RateGains { p, i, ff } = gains.rate;
let surface_share = MODEL_DT / (MODEL_DT + model.lag_s);
let delay_ticks = libm::roundf(model.delay_s / MODEL_DT) as usize;
let mut probe = StepProbe::new(StepConfig {
amplitude: config.amplitude_rad,
duration_s: config.step_duration_s,
settle_band: 0.1,
filter_hz: 0.0,
});
let mut queue = [0.0f32; MAX_MODEL_DELAY_TICKS];
let delay_ticks = delay_ticks.min(MAX_MODEL_DELAY_TICKS);
let (mut angle_rad, mut rate_radps, mut alpha_rad) = (0.0f32, 0.0f32, 0.0f32);
let (mut surface, mut integral, mut clipped) = (0.0f32, 0.0f32, false);
let peak_limit = 1.0 + config.max_overshoot;
let mut tick = 0usize;
loop {
let target_rad = probe.step(MODEL_DT, angle_rad, clipped);
match probe.status() {
StepStatus::Running { .. } => {}
StepStatus::Done(metrics) => return Some(metrics),
StepStatus::Aborted(_) => return None,
}
if angle_rad > peak_limit * config.amplitude_rad {
return None;
}
let rate_target_radps = ((target_rad - angle_rad) / gains.time_constant_s)
.clamp(-config.max_rate_radps, config.max_rate_radps);
let error_radps = rate_target_radps - rate_radps;
integral =
(integral + error_radps * MODEL_DT).clamp(-config.max_integral, config.max_integral);
let raw = p * error_radps + i * integral + ff * rate_target_radps;
let moment = raw.clamp(-config.max_moment, config.max_moment);
clipped = raw.abs() > config.max_moment;
let felt = if delay_ticks == 0 {
moment
} else {
let slot = tick % delay_ticks;
core::mem::replace(&mut queue[slot], moment)
};
surface += surface_share * (felt - surface);
let accel_radps2 = -model.stiffness_per_s2 * alpha_rad - model.damping_per_s * rate_radps
+ model.control_radps2 * surface;
alpha_rad += (rate_radps - model.path_turn_per_s * alpha_rad) * MODEL_DT;
angle_rad += rate_radps * MODEL_DT;
rate_radps += accel_radps2 * MODEL_DT;
tick += 1;
}
}
const MAX_MODEL_DELAY_TICKS: usize = 25;