use crcbl_core::WorldPos;
use crate::frames::State;
const MAX_NEWTON_STEPS: u32 = 64;
const CHI_TOLERANCE: f64 = 1.0e-12;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Orbit {
pub semi_major_axis: f64,
pub eccentricity: f64,
pub semi_latus_rectum: f64,
pub specific_energy: f64,
}
impl Orbit {
#[must_use]
pub fn from_state(mu: f64, state: State) -> Self {
assert!(mu > 0.0, "a gravitational parameter is positive, got {mu}");
let position = state.position.delta(WorldPos::ORIGIN);
let velocity = state.velocity;
let radius = position.length();
assert!(
radius > 0.0,
"a body at the centre of attraction is not on an orbit"
);
let speed_squared = velocity.length_squared();
let specific_energy = 0.5 * speed_squared - mu / radius;
let semi_major_axis = 1.0 / inverse_semi_major_axis(mu, radius, speed_squared);
let eccentricity = eccentricity_vector(mu, position, velocity).length();
let semi_latus_rectum = position.cross(velocity).length_squared() / mu;
Self {
semi_major_axis,
eccentricity,
semi_latus_rectum,
specific_energy,
}
}
#[inline]
#[must_use]
pub fn is_closed(&self) -> bool {
self.semi_major_axis > 0.0 && self.semi_major_axis.is_finite()
}
#[inline]
#[must_use]
pub fn periapsis(&self) -> f64 {
self.semi_latus_rectum / (1.0 + self.eccentricity)
}
#[must_use]
pub fn apoapsis(&self) -> Option<f64> {
self.is_closed()
.then_some(self.semi_major_axis * (1.0 + self.eccentricity))
}
#[must_use]
pub fn period(&self, mu: f64) -> Option<f64> {
self.is_closed().then(|| {
std::f64::consts::TAU
* (self.semi_major_axis * self.semi_major_axis * self.semi_major_axis / mu).sqrt()
})
}
}
#[must_use]
pub fn eccentricity_vector(mu: f64, position: glam::DVec3, velocity: glam::DVec3) -> glam::DVec3 {
let radius = position.length();
((velocity.length_squared() - mu / radius) * position - position.dot(velocity) * velocity) / mu
}
#[must_use]
pub fn propagate(mu: f64, state: State, dt: f64) -> State {
assert!(mu > 0.0, "a gravitational parameter is positive, got {mu}");
assert!(dt.is_finite(), "cannot propagate by {dt} seconds");
let position = state.position.delta(WorldPos::ORIGIN);
let velocity = state.velocity;
let radius = position.length();
assert!(
radius > 0.0,
"a body at the centre of attraction is not on an orbit"
);
let root_mu = mu.sqrt();
let alpha = inverse_semi_major_axis(mu, radius, velocity.length_squared());
let sigma = position.dot(velocity) / root_mu;
let dt = match period_of(mu, alpha) {
Some(period) => dt % period,
None => dt,
};
if dt == 0.0 {
return state;
}
let chi = solve_universal_anomaly(root_mu, radius, sigma, alpha, dt);
let psi = chi * chi * alpha;
let (c2, c3) = stumpff(psi);
let f = 1.0 - chi * chi * c2 / radius;
let g = dt - chi * chi * chi * c3 / root_mu;
let new_position = f * position + g * velocity;
let new_radius = new_position.length();
let f_dot = root_mu * chi * (psi * c3 - 1.0) / (new_radius * radius);
let g_dot = 1.0 - chi * chi * c2 / new_radius;
State::new(
WorldPos::from_offset(new_position),
f_dot * position + g_dot * velocity,
)
}
fn inverse_semi_major_axis(mu: f64, radius: f64, speed_squared: f64) -> f64 {
2.0 / radius - speed_squared / mu
}
fn period_of(mu: f64, alpha: f64) -> Option<f64> {
(alpha > 0.0).then(|| {
let a = 1.0 / alpha;
std::f64::consts::TAU * (a * a * a / mu).sqrt()
})
}
fn solve_universal_anomaly(root_mu: f64, radius: f64, sigma: f64, alpha: f64, dt: f64) -> f64 {
let target = root_mu * dt;
let residual = |chi: f64| {
let psi = chi * chi * alpha;
let (c2, c3) = stumpff(psi);
let flight =
chi * chi * chi * c3 + sigma * chi * chi * c2 + radius * chi * (1.0 - psi * c3);
let slope = chi * chi * c2 + sigma * chi * (1.0 - psi * c3) + radius * (1.0 - psi * c2);
(flight - target, slope)
};
let (mut low, mut high) = bracket(&residual, alpha, dt);
let mut chi = if alpha > 0.0 {
(root_mu * dt * alpha).clamp(low, high)
} else {
0.5 * (low + high)
};
for _ in 0..MAX_NEWTON_STEPS {
let (value, slope) = residual(chi);
if value > 0.0 {
high = chi
} else {
low = chi
}
let step = if slope > 0.0 {
value / slope
} else {
f64::INFINITY
};
let next = chi - step;
let next = if next > low && next < high {
next
} else {
0.5 * (low + high)
};
let moved = (next - chi).abs();
chi = next;
if moved <= CHI_TOLERANCE * chi.abs().max(1.0) {
break;
}
}
chi
}
fn bracket(residual: &impl Fn(f64) -> (f64, f64), alpha: f64, dt: f64) -> (f64, f64) {
if alpha > 0.0 {
let revolution = std::f64::consts::TAU / alpha.sqrt();
return if dt < 0.0 {
(-revolution, 0.0)
} else {
(0.0, revolution)
};
}
let mut edge = dt.signum();
while residual(edge).0.signum() == residual(0.0).0.signum() {
edge *= 2.0;
assert!(
edge.is_finite(),
"no universal anomaly brackets a flight time of {dt} seconds"
);
}
if edge < 0.0 { (edge, 0.0) } else { (0.0, edge) }
}
#[expect(
clippy::disallowed_methods,
reason = "crcbl_core::trig saturates past a million radians, which a long propagate's \
anomaly passes, and no hyperbolic functions are constructed yet; \
docs/backlog.md carries both"
)]
fn stumpff(psi: f64) -> (f64, f64) {
const SERIES_BELOW: f64 = 1.0e-6;
if psi > SERIES_BELOW {
let root = psi.sqrt();
((1.0 - root.cos()) / psi, (root - root.sin()) / (root * psi))
} else if psi < -SERIES_BELOW {
let root = (-psi).sqrt();
(
(root.cosh() - 1.0) / -psi,
(root.sinh() - root) / (root * -psi),
)
} else {
(
0.5 - psi / 24.0 + psi * psi / 720.0,
1.0 / 6.0 - psi / 120.0 + psi * psi / 5040.0,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use glam::DVec3;
const EARTH_MU: f64 = 3.986_004_418e14;
fn circular(radius: f64) -> State {
State::new(
WorldPos::from_offset(DVec3::new(radius, 0.0, 0.0)),
DVec3::new(0.0, (EARTH_MU / radius).sqrt(), 0.0),
)
}
fn transfer(low: f64, high: f64) -> State {
let a = 0.5 * (low + high);
State::new(
WorldPos::from_offset(DVec3::new(low, 0.0, 0.0)),
DVec3::new(0.0, (EARTH_MU * (2.0 / low - 1.0 / a)).sqrt(), 0.0),
)
}
fn radius_of(state: State) -> f64 {
state.position.delta(WorldPos::ORIGIN).length()
}
#[test]
fn the_period_of_a_geostationary_orbit_is_a_sidereal_day() {
const SIDEREAL_DAY: f64 = 86_164.090_5;
let orbit = Orbit::from_state(EARTH_MU, circular(42_164_170.0));
let period = orbit.period(EARTH_MU).expect("a circular orbit closes");
assert!(
(period - SIDEREAL_DAY).abs() <= SIDEREAL_DAY * 0.001,
"the geostationary period came out {period} s against a sidereal day of {SIDEREAL_DAY} s"
);
}
#[test]
fn a_circular_orbit_comes_a_quarter_turn_in_a_quarter_period() {
const RADIUS: f64 = 7_000_000.0;
let start = circular(RADIUS);
let orbit = Orbit::from_state(EARTH_MU, start);
assert!(
orbit.eccentricity < 1.0e-12,
"a circular orbit has no eccentricity to speak of, and nothing may \
divide by it, but it came out {}",
orbit.eccentricity
);
let period = orbit.period(EARTH_MU).expect("a circular orbit closes");
let quarter = propagate(EARTH_MU, start, period / 4.0);
let position = quarter.position.delta(WorldPos::ORIGIN);
let expected = DVec3::new(0.0, RADIUS, 0.0);
assert!(
(position - expected).length() < 1.0e-3,
"a quarter period should reach {expected:?}, came out {position:?}"
);
assert!(
(quarter.velocity.length() - start.velocity.length()).abs() < 1.0e-6,
"speed is constant on a circle"
);
let half = propagate(EARTH_MU, start, period / 2.0);
let position = half.position.delta(WorldPos::ORIGIN);
assert!(
(position - DVec3::new(-RADIUS, 0.0, 0.0)).length() < 1.0e-3,
"half a period should reach the far side, came out {position:?}"
);
}
#[test]
fn a_transfer_orbit_reaches_the_apoapsis_it_reports() {
const LOW: f64 = 6_571_000.0;
const HIGH: f64 = 46_371_000.0;
let start = transfer(LOW, HIGH);
let orbit = Orbit::from_state(EARTH_MU, start);
assert!((orbit.periapsis() - LOW).abs() < 1.0e-3, "{:?}", orbit);
let apoapsis = orbit.apoapsis().expect("a transfer orbit closes");
assert!((apoapsis - HIGH).abs() < 1.0e-3, "{apoapsis}");
assert!(
orbit.eccentricity > 0.0 && orbit.eccentricity < 1.0,
"a transfer orbit is an ellipse, got e = {}",
orbit.eccentricity
);
let period = orbit.period(EARTH_MU).expect("a transfer orbit closes");
let arrived = radius_of(propagate(EARTH_MU, start, period / 2.0));
assert!(
(arrived - HIGH).abs() < 1.0e-3,
"half a period should arrive at apoapsis {HIGH} m, came out {arrived} m"
);
let elsewhere = propagate(EARTH_MU, start, period / 3.0);
let radius = radius_of(elsewhere);
assert!(
radius > LOW * 1.01 && radius < HIGH * 0.99,
"the sample point must be off both apsides, and it is at {radius} m"
);
let same = Orbit::from_state(EARTH_MU, elsewhere);
assert!(
(same.eccentricity - orbit.eccentricity).abs() < 1.0e-9,
"read from {radius} m the eccentricity became {} against {}",
same.eccentricity,
orbit.eccentricity
);
assert!(
(same.periapsis() - LOW).abs() < 1.0e-3,
"read from off-apsis the periapsis became {} m",
same.periapsis()
);
assert!(
(same.apoapsis().expect("still closed") - HIGH).abs() < 1.0e-3,
"read from off-apsis the apoapsis became {:?} m",
same.apoapsis()
);
}
#[test]
fn ten_thousand_revolutions_leave_the_orbit_where_it_was() {
const STEPS: u32 = 10_000;
const STEP_FRACTION: f64 = 0.37;
const RADIUS: f64 = 42_164_170.0;
const DRIFT: f64 = 1.0e-6;
const PHASE: f64 = 1.0e-2;
let start = circular(RADIUS);
let before = Orbit::from_state(EARTH_MU, start);
let step = before.period(EARTH_MU).expect("a circular orbit closes") * STEP_FRACTION;
let mut chained = start;
for _ in 0..STEPS {
chained = propagate(EARTH_MU, chained, step);
}
let after = Orbit::from_state(EARTH_MU, chained);
let energy_drift =
(after.specific_energy - before.specific_energy).abs() / before.specific_energy.abs();
assert!(
energy_drift < DRIFT,
"specific energy drifted by {energy_drift} of itself over {STEPS} propagations"
);
let size_drift =
(after.semi_major_axis - before.semi_major_axis).abs() / before.semi_major_axis;
assert!(
size_drift < DRIFT,
"the semi-major axis drifted by {size_drift} of itself"
);
assert!(
after.eccentricity < DRIFT,
"a circle stayed a circle only to e = {}",
after.eccentricity
);
let radius = radius_of(chained);
assert!(
(radius - RADIUS).abs() < RADIUS * DRIFT,
"after {STEPS} propagations the circular radius is {radius} m, not {RADIUS} m"
);
let period = before.period(EARTH_MU).expect("a circular orbit closes");
let far = propagate(EARTH_MU, start, f64::from(STEPS) * period + period / 4.0);
let quarter = propagate(EARTH_MU, start, period / 4.0);
let apart = far.position.distance(quarter.position);
assert!(
apart < PHASE,
"{STEPS} periods and a quarter landed {apart} m from a quarter period"
);
}
#[test]
fn an_escape_trajectory_has_no_period_and_reverses_exactly() {
const PERIAPSIS: f64 = 6_571_000.0;
let escape = State::new(
WorldPos::from_offset(DVec3::new(PERIAPSIS, 0.0, 0.0)),
DVec3::new(0.0, 1.5 * (2.0 * EARTH_MU / PERIAPSIS).sqrt(), 0.0),
);
let orbit = Orbit::from_state(EARTH_MU, escape);
assert!(orbit.eccentricity > 1.0, "e = {}", orbit.eccentricity);
assert!(!orbit.is_closed());
assert_eq!(orbit.period(EARTH_MU), None);
assert_eq!(orbit.apoapsis(), None);
assert!(
(orbit.periapsis() - PERIAPSIS).abs() < 1.0e-3,
"a hyperbola still has a periapsis, got {}",
orbit.periapsis()
);
let day = 86_400.0;
let out = propagate(EARTH_MU, escape, day);
assert!(
radius_of(out) > radius_of(escape) * 10.0,
"a day of escape should be a long way out, got {} m",
radius_of(out)
);
let back = propagate(EARTH_MU, out, -day);
let error = back.position.distance(escape.position);
assert!(
error < radius_of(out) * 1.0e-9,
"out and back over {} m of hyperbola came home {error} m adrift",
radius_of(out)
);
}
#[test]
fn a_backwards_step_on_a_near_parabolic_orbit_does_not_go_the_long_way() {
const PERIAPSIS: f64 = 6_571_000.0;
let escape_speed = (2.0 * EARTH_MU / PERIAPSIS).sqrt();
let barely = State::new(
WorldPos::from_offset(DVec3::new(PERIAPSIS, 0.0, 0.0)),
DVec3::new(0.0, escape_speed * (1.0 - 1.0e-9), 0.0),
);
let orbit = Orbit::from_state(EARTH_MU, barely);
assert!(
orbit.is_closed() && orbit.eccentricity > 0.999,
"the fixture must be a barely-closed orbit, got e = {}",
orbit.eccentricity
);
assert!(
(orbit.periapsis() - PERIAPSIS).abs() < 1.0e-3,
"a barely-closed orbit still has a periapsis at {PERIAPSIS} m, got {} m",
orbit.periapsis()
);
let hour = 3_600.0;
let out = propagate(EARTH_MU, barely, hour);
let back = propagate(EARTH_MU, out, -hour);
let error = back.position.distance(barely.position);
assert!(
error < 1.0e-3,
"an hour out and back came home {error} m adrift"
);
}
#[test]
fn a_radial_trajectory_has_an_apoapsis_where_it_stops() {
const HEIGHT: f64 = 7_000_000.0;
let dropped = State::new(
WorldPos::from_offset(DVec3::new(0.0, HEIGHT, 0.0)),
DVec3::ZERO,
);
let orbit = Orbit::from_state(EARTH_MU, dropped);
assert!(
orbit.is_closed(),
"a body dropped from rest comes back down"
);
let apoapsis = orbit.apoapsis().expect("a closed orbit has an apoapsis");
assert!(
(apoapsis - HEIGHT).abs() < 1.0e-6,
"a body at rest is at its own apoapsis, and this one reports {apoapsis} m"
);
assert!(
orbit.periapsis() < 1.0e-6,
"a radial fall reaches the centre, and this one stops at {} m",
orbit.periapsis()
);
let thrown = State::new(
WorldPos::from_offset(DVec3::new(0.0, HEIGHT, 0.0)),
DVec3::new(0.0, 1_000.0, 0.0),
);
let orbit = Orbit::from_state(EARTH_MU, thrown);
let apoapsis = orbit.apoapsis().expect("it comes back");
assert!(
apoapsis.is_finite(),
"a vertical throw has a finite top, not {apoapsis}"
);
assert!(
apoapsis > HEIGHT,
"thrown upwards it should stop above {HEIGHT} m, and it reports {apoapsis} m"
);
let expected = -EARTH_MU / orbit.specific_energy;
assert!(
(apoapsis - expected).abs() < expected * 1.0e-9,
"the apoapsis {apoapsis} m disagrees with where the energy runs out, {expected} m"
);
}
#[test]
fn a_whole_revolution_returns_the_state_it_started_from() {
let start = circular(7_000_000.0);
let period = Orbit::from_state(EARTH_MU, start)
.period(EARTH_MU)
.expect("a circular orbit closes");
let round = propagate(EARTH_MU, start, period);
assert_eq!(round.position, start.position);
assert_eq!(round.velocity, start.velocity);
}
#[test]
#[should_panic(expected = "a body at the centre of attraction is not on an orbit")]
fn a_body_on_the_centre_of_attraction_is_refused() {
let _ = propagate(EARTH_MU, State::AT_ORIGIN, 1.0);
}
#[test]
#[should_panic(expected = "cannot propagate by NaN seconds")]
fn a_non_finite_flight_time_is_refused() {
let _ = propagate(EARTH_MU, circular(7_000_000.0), f64::NAN);
}
}