use super::numeric_traits::Flt;
use fixed::types::extra::{U11, U16};
use fixed::{FixedI16, FixedU16};
use nalgebra::{ComplexField, Vector2, Vector3};
pub type StarAx = FixedI16<U11>;
pub type QuadAx = FixedU16<U16>;
#[derive(
rkyv_08::Archive,
rkyv_08::Serialize,
rkyv_08::Deserialize,
serde::Serialize,
PartialEq,
Debug,
Clone,
Copy,
)]
#[rkyv(crate=rkyv_08)]
pub struct CoordCelestial<F>
where
F: Flt + serde::Serialize + for<'de2> serde::Deserialize<'de2>,
{
pub ra: F, pub dec: F, }
pub type CoordCartesian<F> = Vector2<F>;
pub type CoordUnitSphere<F> = Vector3<F>;
pub type CoordUnitSphereFP = [StarAx; 3];
impl<F: Flt> From<CoordUnitSphere<F>> for CoordCelestial<F> {
fn from(spherical: CoordUnitSphere<F>) -> Self {
let ra: F = spherical.y.atan2(spherical.x);
let ra: F = if ra < F::zero() {
ra + F::pi() + F::pi()
} else {
ra
};
let dec: F = num_traits::Float::asin(spherical.z);
CoordCelestial { ra, dec }
}
}
impl<F: Flt> From<&CoordUnitSphere<F>> for CoordCelestial<F> {
fn from(spherical: &CoordUnitSphere<F>) -> Self {
let ra: F = spherical.y.atan2(spherical.x);
let ra: F = if ra < F::zero() {
ra + (F::pi() + F::pi())
} else {
ra
};
let dec: F = num_traits::Float::asin(spherical.z);
CoordCelestial { ra, dec }
}
}
impl<F: Flt> Into<CoordUnitSphere<F>> for CoordCelestial<F> {
fn into(self) -> CoordUnitSphere<F> {
CoordUnitSphere::new(
num_traits::Float::cos(self.dec) * num_traits::Float::cos(self.ra),
num_traits::Float::cos(self.dec) * num_traits::Float::sin(self.ra),
num_traits::Float::sin(self.dec),
)
}
}
pub fn coord_unit_sphere_from_radec<F: Flt>(ra: F, dec: F) -> CoordUnitSphere<F> {
(CoordCelestial { ra, dec }).into()
}
pub fn get_midpoint<F: Flt + ComplexField>(
a: &CoordUnitSphere<F>,
b: &CoordUnitSphere<F>,
) -> CoordUnitSphere<F> {
(a + b).normalize()
}
pub fn tan_project<F: Flt>(
s: &CoordUnitSphere<F>,
r: &CoordUnitSphere<F>,
) -> Option<CoordCartesian<F>> {
let s_dot_r = s.dot(&r);
if s_dot_r < F::zero() {
return None;
}
Some(if num_traits::Float::abs(r.z - F::one()) < F::epsilon() {
CoordCartesian::new(s.x / s.z, s.y / s.z)
} else if num_traits::Float::abs(r.z + F::one()) < F::epsilon() {
CoordCartesian::new(-s.x / s.z, s.y / s.z)
} else {
let eta = Vector3::new(-r.y, r.x, F::zero());
let eta_scale_inv = eta.x * eta.x + num_traits::Float::sqrt(F::one() / (eta.y * eta.y));
let eta = eta * eta_scale_inv;
let xi = r.cross(&eta);
let inv_s_dot_r = F::one() / s_dot_r;
CoordCartesian::new(s.dot(&eta) * inv_s_dot_r, s.dot(&xi) * inv_s_dot_r)
})
}