mod builder;
mod edit;
mod player;
mod segment;
mod stats;
use alloc::borrow::Cow;
use alloc::vec::Vec;
use core::{error, fmt};
pub use builder::{TrajectoryBuilder, TrajectoryBuilderError};
pub use edit::LandingError;
pub use player::{TrajectoryPlayer, TrajectoryPlayerState};
pub use segment::TrajectorySegment;
pub use stats::{
LandingStats, TakeoffStats, TrajectoryStatComponents, TrajectoryStats,
TrajectoryStatsCalculator, TrajectoryStatsError,
};
use crate::basic_types::{BoundingBox, Interval, Vector3WithYaw};
use crate::formats::binary::{BinaryBlockType, BinaryFile, BinaryFileError};
use crate::parsing::read_i16;
use crate::poly::Poly;
use segment::{coords_length, msec_to_sec};
const HEADER_LENGTH: usize = 9;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TrajectoryError {
Corrupted,
File(BinaryFileError),
}
impl fmt::Display for TrajectoryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Corrupted => f.write_str("the trajectory is malformed"),
Self::File(_) => f.write_str("the show file could not be read"),
}
}
}
impl error::Error for TrajectoryError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Self::Corrupted => None,
Self::File(err) => Some(err),
}
}
}
impl From<BinaryFileError> for TrajectoryError {
fn from(err: BinaryFileError) -> Self {
Self::File(err)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Trajectory<'a> {
bytes: Cow<'a, [u8]>,
start: Vector3WithYaw,
scale: f32,
header_length: usize,
}
impl Default for Trajectory<'static> {
fn default() -> Self {
Self::new()
}
}
impl Trajectory<'static> {
#[must_use]
pub const fn new() -> Self {
Self {
bytes: Cow::Owned(Vec::new()),
start: Vector3WithYaw {
x: 0.0,
y: 0.0,
z: 0.0,
yaw: 0.0,
},
scale: 1.0,
header_length: 0,
}
}
pub fn from_vec(bytes: Vec<u8>) -> Result<Self, TrajectoryError> {
Self::from_cow(Cow::Owned(bytes))
}
}
impl<'a> Trajectory<'a> {
pub fn from_buffer(bytes: &'a [u8]) -> Result<Self, TrajectoryError> {
Self::from_cow(Cow::Borrowed(bytes))
}
pub fn from_binary_file(file: &BinaryFile<'a>) -> Result<Option<Self>, TrajectoryError> {
file.find_first_block_by_type(BinaryBlockType::TRAJECTORY)?
.map(|block| Self::from_buffer(block.body))
.transpose()
}
fn from_cow(bytes: Cow<'a, [u8]>) -> Result<Self, TrajectoryError> {
validate(&bytes)?;
let scale = f32::from(scale_of(bytes.first().copied().unwrap_or_default()));
let coordinate = |offset| f32::from(read_i16(&bytes, offset).unwrap_or_default()) * scale;
let start = Vector3WithYaw {
x: coordinate(1),
y: coordinate(3),
z: coordinate(5),
yaw: 0.0,
};
Ok(Self {
bytes,
start,
scale,
header_length: HEADER_LENGTH,
})
}
#[must_use]
pub fn into_owned(self) -> Trajectory<'static> {
Trajectory {
bytes: Cow::Owned(self.bytes.into_owned()),
start: self.start,
scale: self.scale,
header_length: self.header_length,
}
}
#[must_use]
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.bytes.first().is_none_or(|&flags| scale_of(flags) == 0)
}
#[must_use]
pub const fn scale(&self) -> f32 {
self.scale
}
pub(crate) const fn start(&self) -> Vector3WithYaw {
self.start
}
pub(crate) const fn header_length(&self) -> usize {
self.header_length
}
#[must_use]
pub fn start_position(&self) -> Vector3WithYaw {
TrajectoryPlayer::new(self).position_at(0.0)
}
#[must_use]
pub fn end_position(&self) -> Vector3WithYaw {
TrajectoryPlayer::new(self).position_at(f32::INFINITY)
}
#[must_use]
pub fn total_duration_msec(&self) -> u32 {
TrajectoryPlayer::new(self).total_duration_msec()
}
#[must_use]
pub fn total_duration_sec(&self) -> f32 {
msec_to_sec(self.total_duration_msec())
}
#[must_use]
pub fn segment_at(&self, time_sec: f32) -> (TrajectoryPlayerState, f32) {
let mut player = TrajectoryPlayer::new(self);
let rel_time = player.seek_to_time(time_sec);
let segment = player.current_segment();
segment.dpoly();
segment.ddpoly();
(player.save_state(), rel_time)
}
#[must_use]
pub fn axis_aligned_bounding_box(&self) -> BoundingBox {
let empty = Interval {
min: f32::INFINITY,
max: f32::NEG_INFINITY,
};
let mut result = BoundingBox {
x: empty,
y: empty,
z: empty,
};
let mut player = TrajectoryPlayer::new(self);
while player.has_more_segments() {
let poly = *player.current_segment().poly();
for (interval, poly) in [
(&mut result.x, &poly.x),
(&mut result.y, &poly.y),
(&mut result.z, &poly.z),
] {
let extrema = extrema_of(poly);
if extrema.min < interval.min {
interval.min = extrema.min;
}
if extrema.max > interval.max {
interval.max = extrema.max;
}
}
player.build_next_segment();
}
result
}
}
fn extrema_of(poly: &Poly) -> Interval {
poly.extrema()
.unwrap_or_else(|_| control_point_bounds(poly))
}
fn control_point_bounds(poly: &Poly) -> Interval {
let coeffs = poly.coeffs();
let n = coeffs.len().saturating_sub(1);
let mut result = Interval {
min: f32::INFINITY,
max: f32::NEG_INFINITY,
};
for k in 0..=n {
let mut point = 0.0;
for (i, &coeff) in coeffs.iter().enumerate().take(k + 1) {
point += binomial(k, i) / binomial(n, i) * coeff;
}
if point < result.min {
result.min = point;
}
if point > result.max {
result.max = point;
}
}
result
}
#[expect(
clippy::cast_precision_loss,
reason = "binomials of numbers up to the maximum degree are small"
)]
fn binomial(n: usize, k: usize) -> f32 {
let mut result: u32 = 1;
for i in 0..k.min(n) {
let (Ok(numerator), Ok(denominator)) = (u32::try_from(n - i), u32::try_from(i + 1)) else {
return f32::NAN;
};
result = result.saturating_mul(numerator) / denominator;
}
result as f32
}
const fn scale_of(flags: u8) -> u8 {
flags & 0x7f
}
fn validate(bytes: &[u8]) -> Result<(), TrajectoryError> {
if bytes.len() < HEADER_LENGTH {
return Err(TrajectoryError::Corrupted);
}
if bytes.first().is_some_and(|&flags| scale_of(flags) == 0) {
return Ok(());
}
let mut rest = bytes.get(HEADER_LENGTH..).unwrap_or_default();
while let Some(&header) = rest.first() {
if rest.len() < 3 {
return Err(TrajectoryError::Corrupted);
}
rest = rest
.get(3 + coords_length(header)..)
.ok_or(TrajectoryError::Corrupted)?;
}
Ok(())
}