use crcbl_core::logarithm::ln_1p;
use glam::DVec3;
use crate::GravityForce;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FlightConfig {
pub gravity: DVec3,
pub max_substep: f64,
pub max_substeps: u32,
}
impl FlightConfig {
pub const DEFAULT: Self = Self {
gravity: GravityForce::EARTH.acceleration,
max_substep: 1.0 / 240.0,
max_substeps: 256,
};
#[must_use]
pub fn is_valid(&self) -> bool {
self.gravity.is_finite()
&& self.max_substep.is_finite()
&& self.max_substep > 0.0
&& self.max_substeps > 0
}
}
impl Default for FlightConfig {
fn default() -> Self {
Self::DEFAULT
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Flight {
pub position: DVec3,
pub velocity: DVec3,
pub quadratic_drag: f64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FlightSegment {
pub start: DVec3,
pub end: DVec3,
pub start_velocity: DVec3,
pub end_velocity: DVec3,
pub duration: f64,
}
impl Flight {
#[must_use = "the segments are the path to sweep for collisions"]
pub fn advance(&mut self, duration: f64, config: &FlightConfig) -> Vec<FlightSegment> {
let mut segments = Vec::new();
self.advance_into(duration, config, &mut segments);
segments
}
pub fn advance_into(
&mut self,
duration: f64,
config: &FlightConfig,
segments: &mut Vec<FlightSegment>,
) {
if !self.can_fly(duration, config) {
return;
}
let steps = (duration / config.max_substep)
.ceil()
.clamp(1.0, f64::from(config.max_substeps));
let dt = duration / steps;
let count = steps as usize;
segments.reserve(count);
for _ in 0..count {
segments.push(self.step(dt, config.gravity));
}
}
pub fn advance_one_segment(
&mut self,
max_duration: f64,
config: &FlightConfig,
) -> Option<FlightSegment> {
self.can_fly(max_duration, config)
.then(|| self.step(max_duration.min(config.max_substep), config.gravity))
}
fn can_fly(&self, duration: f64, config: &FlightConfig) -> bool {
duration.is_finite()
&& duration > 0.0
&& config.is_valid()
&& self.position.is_finite()
&& self.velocity.is_finite()
&& self.quadratic_drag.is_finite()
&& self.quadratic_drag >= 0.0
}
fn step(&mut self, dt: f64, gravity: DVec3) -> FlightSegment {
let start = self.position;
let start_velocity = self.velocity;
let drag = self.quadratic_drag * start_velocity.length();
let reach = if drag > 0.0 {
ln_1p(drag * dt) / drag
} else {
dt
};
let end = start + start_velocity * reach + gravity * (0.5 * dt * dt);
let end_velocity = start_velocity / (1.0 + drag * dt) + gravity * dt;
self.position = end;
self.velocity = end_velocity;
FlightSegment {
start,
end,
start_velocity,
end_velocity,
duration: dt,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const TOLERANCE: f64 = 1e-9;
#[expect(
clippy::disallowed_methods,
reason = "an independent reference for the engine's ln_1p"
)]
fn platform_ln(x: f64) -> f64 {
x.ln()
}
fn bullet(drag: f64) -> Flight {
Flight {
position: DVec3::new(1.0, 2.0, 3.0),
velocity: DVec3::new(800.0, 0.0, 0.0),
quadratic_drag: drag,
}
}
#[test]
fn without_drag_it_follows_the_parabola() {
let mut flight = bullet(0.0);
let start = flight;
let t = 0.73;
let segments = flight.advance(t, &FlightConfig::DEFAULT);
let g = FlightConfig::DEFAULT.gravity;
let want = start.position + start.velocity * t + g * (0.5 * t * t);
assert!(
flight.position.distance(want) < TOLERANCE,
"{} vs {want}",
flight.position
);
assert!(flight.velocity.distance(start.velocity + g * t) < TOLERANCE);
assert_eq!(segments.len(), (t * 240.0).ceil() as usize);
}
#[test]
fn drag_alone_lands_on_the_closed_form() {
let config = FlightConfig {
gravity: DVec3::ZERO,
..FlightConfig::DEFAULT
};
let k = 1e-3;
let mut flight = bullet(k);
let (p0, v0) = (flight.position, flight.velocity.x);
let t = 0.9;
let _ = flight.advance(t, &config);
let speed = v0 / (1.0 + k * v0 * t);
let distance = platform_ln(1.0 + k * v0 * t) / k;
assert!(
(flight.velocity.x - speed).abs() < 1e-9,
"{} vs {speed}",
flight.velocity.x
);
assert!(
(flight.position.x - (p0.x + distance)).abs() < 1e-9,
"{} vs {}",
flight.position.x,
p0.x + distance
);
assert_eq!(flight.position.y, p0.y);
}
#[test]
fn the_segments_join_up_and_add_up() {
let mut flight = bullet(5e-4);
let start = flight;
let segments = flight.advance(0.1, &FlightConfig::DEFAULT);
assert_eq!(segments[0].start, start.position);
assert_eq!(segments[0].start_velocity, start.velocity);
for pair in segments.windows(2) {
assert_eq!(pair[0].end, pair[1].start);
assert_eq!(pair[0].end_velocity, pair[1].start_velocity);
}
let last = segments.last().unwrap();
assert_eq!(
(last.end, last.end_velocity),
(flight.position, flight.velocity)
);
let total: f64 = segments.iter().map(|s| s.duration).sum();
assert!((total - 0.1).abs() < 1e-15);
assert!(flight.velocity.x < start.velocity.x, "drag slowed it");
assert!(flight.velocity.y < 0.0, "gravity pulled it down");
}
#[test]
fn the_work_is_bounded() {
let config = FlightConfig::DEFAULT;
let mut flight = bullet(1e-3);
let segments = flight.advance(10.0, &config);
assert_eq!(segments.len(), config.max_substeps as usize);
assert!((segments[0].duration - 10.0 / 256.0).abs() < 1e-15);
let one = flight.advance_one_segment(1.0, &config).unwrap();
assert_eq!(one.duration, config.max_substep);
let short = flight.advance_one_segment(1e-4, &config).unwrap();
assert_eq!(short.duration, 1e-4);
}
#[test]
fn bad_input_steps_nothing() {
let config = FlightConfig::DEFAULT;
let mut flight = bullet(1e-3);
let before = flight;
assert!(flight.advance(0.0, &config).is_empty());
assert!(flight.advance(f64::NAN, &config).is_empty());
let broken = FlightConfig {
max_substeps: 0,
..config
};
assert!(flight.advance(1.0, &broken).is_empty());
assert!(flight.advance_one_segment(1.0, &broken).is_none());
assert_eq!(flight, before);
let mut negative = bullet(-1.0);
assert!(negative.advance(1.0, &config).is_empty());
}
}