use core::fmt;
use core::ops::{Add, AddAssign, Sub, SubAssign};
use glam::{DVec3, I64Vec3, Vec3};
pub const SECTOR_SIZE_LOG2: u32 = 20;
pub const SECTOR_SIZE: f64 = (1u64 << SECTOR_SIZE_LOG2) as f64;
const LOCAL_MAX: f64 = f64::from_bits(SECTOR_SIZE.to_bits() - 1);
pub const EXACT_SECTOR_DELTA: i64 = 1 << 53;
#[derive(Clone, Copy, PartialEq, Default)]
pub struct WorldPos {
pub sector: I64Vec3,
pub local: DVec3,
}
impl WorldPos {
pub const ORIGIN: Self = Self {
sector: I64Vec3::ZERO,
local: DVec3::ZERO,
};
#[inline]
#[must_use]
pub fn new(sector: I64Vec3, local: DVec3) -> Self {
Self { sector, local }.normalize()
}
#[inline]
#[must_use]
pub fn from_offset(offset: DVec3) -> Self {
Self::new(I64Vec3::ZERO, offset)
}
#[inline]
#[must_use]
pub const fn from_sector(sector: I64Vec3) -> Self {
Self {
sector,
local: DVec3::ZERO,
}
}
#[inline]
#[must_use]
pub fn normalize(self) -> Self {
debug_assert!(
self.local.is_finite(),
"WorldPos::local must be finite, got {}",
self.local
);
let (sx, lx) = normalize_axis(self.sector.x, self.local.x);
let (sy, ly) = normalize_axis(self.sector.y, self.local.y);
let (sz, lz) = normalize_axis(self.sector.z, self.local.z);
Self {
sector: I64Vec3::new(sx, sy, sz),
local: DVec3::new(lx, ly, lz),
}
}
#[inline]
pub fn rebase(&mut self) {
*self = self.normalize();
}
#[inline]
#[must_use]
pub fn is_normalized(&self) -> bool {
let inside = |v: f64| (0.0..SECTOR_SIZE).contains(&v);
inside(self.local.x) && inside(self.local.y) && inside(self.local.z)
}
#[inline]
#[must_use]
pub fn delta(self, origin: Self) -> DVec3 {
DVec3::new(
delta_axis(self.sector.x, self.local.x, origin.sector.x, origin.local.x),
delta_axis(self.sector.y, self.local.y, origin.sector.y, origin.local.y),
delta_axis(self.sector.z, self.local.z, origin.sector.z, origin.local.z),
)
}
#[inline]
#[must_use]
pub fn distance(self, other: Self) -> f64 {
self.delta(other).length()
}
#[inline]
#[must_use]
pub fn distance_squared(self, other: Self) -> f64 {
self.delta(other).length_squared()
}
#[inline]
#[must_use]
pub fn relative_to(self, origin: Self) -> Vec3 {
self.delta(origin).as_vec3()
}
#[inline]
#[must_use]
pub fn translated(self, offset: DVec3) -> Self {
Self {
sector: self.sector,
local: self.local + offset,
}
.normalize()
}
}
#[inline]
fn normalize_axis(sector: i64, local: f64) -> (i64, f64) {
let mut carry = (local / SECTOR_SIZE).floor();
let mut rest = local - carry * SECTOR_SIZE;
if rest >= SECTOR_SIZE {
carry += 1.0;
rest = 0.0;
} else if rest < 0.0 {
rest = 0.0;
}
let carried = sector as i128 + carry as i128;
if carried < i64::MIN as i128 {
(i64::MIN, 0.0)
} else if carried > i64::MAX as i128 {
(i64::MAX, LOCAL_MAX)
} else {
(carried as i64, rest)
}
}
#[inline]
fn delta_axis(sector: i64, local: f64, origin_sector: i64, origin_local: f64) -> f64 {
let sectors = sector as i128 - origin_sector as i128;
sectors as f64 * SECTOR_SIZE + (local - origin_local)
}
impl Add<DVec3> for WorldPos {
type Output = Self;
#[inline]
fn add(self, offset: DVec3) -> Self {
self.translated(offset)
}
}
impl AddAssign<DVec3> for WorldPos {
#[inline]
fn add_assign(&mut self, offset: DVec3) {
*self = self.translated(offset);
}
}
impl Sub<DVec3> for WorldPos {
type Output = Self;
#[inline]
fn sub(self, offset: DVec3) -> Self {
self.translated(-offset)
}
}
impl SubAssign<DVec3> for WorldPos {
#[inline]
fn sub_assign(&mut self, offset: DVec3) {
*self = self.translated(-offset);
}
}
impl Sub<WorldPos> for WorldPos {
type Output = DVec3;
#[inline]
fn sub(self, origin: Self) -> DVec3 {
self.delta(origin)
}
}
impl fmt::Debug for WorldPos {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"WorldPos(sector [{}, {}, {}], local [{}, {}, {}] m)",
self.sector.x, self.sector.y, self.sector.z, self.local.x, self.local.y, self.local.z
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
const METRES_PER_LIGHT_YEAR: f64 = 9_460_730_472_580_800.0;
#[test]
fn constructors_agree_and_rebase_matches_normalize() {
assert_eq!(WorldPos::ORIGIN, WorldPos::default());
assert_eq!(WorldPos::ORIGIN.sector, I64Vec3::ZERO);
assert!(WorldPos::ORIGIN.is_normalized());
let offset = DVec3::new(SECTOR_SIZE * 1.5, -1.0, 42.0);
let from_offset = WorldPos::from_offset(offset);
assert_eq!(from_offset.sector, I64Vec3::new(1, -1, 0));
assert_eq!(from_offset - WorldPos::ORIGIN, offset);
assert_eq!(WorldPos::ORIGIN.translated(offset), from_offset);
assert_eq!(WorldPos::ORIGIN + offset, from_offset);
let sector = I64Vec3::new(-4, 5, 6);
assert_eq!(WorldPos::from_sector(sector).sector, sector);
assert_eq!(WorldPos::from_sector(sector).local, DVec3::ZERO);
assert_eq!(
WorldPos::new(sector, offset),
WorldPos::from_sector(sector) + offset
);
let mut raw = WorldPos {
sector,
local: offset,
};
let normalized = raw.normalize();
raw.rebase();
assert_eq!(raw, normalized);
assert!(
!WorldPos {
sector,
local: offset
}
.is_normalized()
);
assert_eq!(
from_offset.distance_squared(WorldPos::ORIGIN),
offset.length_squared()
);
assert!(format!("{from_offset:?}").starts_with("WorldPos(sector [1, -1, 0]"));
}
#[test]
fn sector_size_is_a_power_of_two() {
assert_eq!(SECTOR_SIZE, 1_048_576.0);
assert_eq!(SECTOR_SIZE, (1u64 << SECTOR_SIZE_LOG2) as f64);
assert_eq!(
SECTOR_SIZE.to_bits() & ((1 << 52) - 1),
0,
"mantissa must be all zeroes"
);
assert_eq!(LOCAL_MAX, SECTOR_SIZE.next_down());
for sectors in [
1i128,
-1,
12_345_678,
EXACT_SECTOR_DELTA as i128,
i64::MIN as i128,
] {
let scaled = sectors as f64 * SECTOR_SIZE;
assert_eq!(
scaled as i128,
sectors << SECTOR_SIZE_LOG2,
"{sectors} sectors did not scale exactly"
);
}
}
#[test]
fn documented_precision_and_extent_hold() {
let edge = SECTOR_SIZE.next_down();
let ulp = edge - edge.next_down();
assert_eq!(
ulp,
1.0 / 8_589_934_592.0,
"worst-case local ULP should be 2^-33 m"
);
assert!(
(ulp - 0.116e-9).abs() < 0.001e-9,
"sector-edge precision should be ~0.116 nm, got {ulp} m"
);
let f32_ulp_at_1km = (1000.0f32.next_up() - 1000.0f32) as f64;
assert!(
(f32_ulp_at_1km / ulp - 524_288.0).abs() < 1.0,
"should be ~524 000x finer than render space, got {}x",
f32_ulp_at_1km / ulp
);
const EARTH_DIAMETER_M: f64 = 12_742_000.0;
let earth_cells = EARTH_DIAMETER_M / SECTOR_SIZE;
assert!(
(12.0..13.0).contains(&earth_cells),
"Earth should span ~12 sectors, got {earth_cells}"
);
const {
assert!(
4_000.0 < SECTOR_SIZE,
"an FPS map should fit inside one sector"
)
};
let sectors = (i64::MAX as f64 - i64::MIN as f64) + 1.0;
let extent_ly = sectors * SECTOR_SIZE / METRES_PER_LIGHT_YEAR;
assert!(
(2.03e9..2.06e9).contains(&extent_ly),
"extent should be ~2.04 billion ly, got {extent_ly}"
);
assert!(extent_ly > 1e5, "the Milky Way must fit many times over");
let corner = WorldPos::from_sector(I64Vec3::splat(i64::MAX));
let opposite = WorldPos::from_sector(I64Vec3::splat(i64::MIN));
assert!(corner.distance(opposite).is_finite());
assert!(corner.distance_squared(opposite).is_finite());
}
#[test]
fn delta_is_exact_out_to_two_to_the_fifty_three_sectors() {
assert_eq!(EXACT_SECTOR_DELTA as f64 as i64, EXACT_SECTOR_DELTA);
assert_ne!(
(EXACT_SECTOR_DELTA + 1) as f64 as i64,
EXACT_SECTOR_DELTA + 1,
"2^53 + 1 is the first integer f64 cannot hold — the boundary is here"
);
let a = WorldPos::from_sector(I64Vec3::new(EXACT_SECTOR_DELTA, 0, 0));
let b = WorldPos::ORIGIN;
let delta = a - b;
assert_eq!(
delta.x as i128,
(EXACT_SECTOR_DELTA as i128) << SECTOR_SIZE_LOG2
);
assert_eq!((a + DVec3::X) - b, delta + DVec3::X);
let reach_ly = delta.x / METRES_PER_LIGHT_YEAR;
assert!(
(998_000.0..999_000.0).contains(&reach_ly),
"exact-delta reach should be ~998 000 ly, got {reach_ly}"
);
let corner = WorldPos::from_sector(I64Vec3::new(i64::MAX, 0, 0));
let opposite = WorldPos::from_sector(I64Vec3::new(i64::MIN, 0, 0));
let full = (corner - opposite).x;
assert!(full.is_finite() && full > 0.0);
let quantum = full - full.next_down();
assert_eq!(
quantum, 2_147_483_648.0,
"quantization at the full addressable span should be 2^31 m"
);
}
#[test]
fn normalize_pulls_local_into_range() {
let pos = WorldPos {
sector: I64Vec3::new(1, 1, 1),
local: DVec3::splat(SECTOR_SIZE * 2.5),
}
.normalize();
assert_eq!(pos.sector, I64Vec3::new(3, 3, 3));
assert_eq!(pos.local, DVec3::splat(SECTOR_SIZE * 0.5));
assert!(pos.is_normalized());
}
#[test]
fn normalize_handles_negative_offsets() {
let pos = WorldPos {
sector: I64Vec3::ZERO,
local: DVec3::new(-1.0, -SECTOR_SIZE, 0.0),
}
.normalize();
assert_eq!(pos.sector, I64Vec3::new(-1, -1, 0));
assert_eq!(pos.local, DVec3::new(SECTOR_SIZE - 1.0, 0.0, 0.0));
assert!(pos.is_normalized());
}
#[test]
fn normalize_keeps_the_half_open_range_at_the_boundary() {
let pos = WorldPos {
sector: I64Vec3::ZERO,
local: DVec3::new(-1e-300, -1.0, 0.0),
}
.normalize();
assert!(pos.is_normalized(), "{pos:?}");
assert_eq!(pos.sector, I64Vec3::new(0, -1, 0));
assert_eq!(pos.local.x, 0.0);
}
#[test]
fn out_of_range_saturates_instead_of_wrapping() {
let far = WorldPos {
sector: I64Vec3::splat(i64::MAX),
local: DVec3::splat(SECTOR_SIZE * 4.0),
}
.normalize();
assert_eq!(far.sector, I64Vec3::splat(i64::MAX));
assert!(far.is_normalized());
assert_eq!(far, far.normalize(), "saturation must be idempotent");
let near = WorldPos {
sector: I64Vec3::splat(i64::MIN),
local: DVec3::splat(-SECTOR_SIZE),
}
.normalize();
assert_eq!(near.sector, I64Vec3::splat(i64::MIN));
assert_eq!(near.local, DVec3::ZERO);
assert_eq!(near, near.normalize());
}
#[test]
fn non_finite_local_survives_normalization_without_inventing_a_position() {
let (sector, local) = normalize_axis(7, f64::NAN);
assert_eq!(sector, 7);
assert!(local.is_nan());
let (sector, local) = normalize_axis(0, f64::INFINITY);
assert_eq!(sector, i64::MAX, "infinity saturates rather than wraps");
assert_eq!(local, LOCAL_MAX);
}
#[test]
fn delta_is_exact_across_a_sector_boundary() {
let a = WorldPos::new(I64Vec3::ZERO, DVec3::new(SECTOR_SIZE - 1.0, 0.0, 0.0));
let b = a + DVec3::new(2.0, 0.0, 0.0);
assert_eq!(b.sector, I64Vec3::new(1, 0, 0));
assert_eq!(b.local.x, 1.0);
assert_eq!(b - a, DVec3::new(2.0, 0.0, 0.0));
assert_eq!(a.distance(b), 2.0);
}
#[test]
fn delta_does_not_wrap_between_opposite_corners() {
let a = WorldPos::from_sector(I64Vec3::new(i64::MAX, 0, 0));
let b = WorldPos::from_sector(I64Vec3::new(i64::MIN, 0, 0));
let delta = a - b;
assert!(delta.x > 0.0, "i64 subtraction would have wrapped negative");
assert_eq!(delta.x, (i64::MAX as f64 - i64::MIN as f64) * SECTOR_SIZE);
}
#[test]
fn relative_to_is_the_render_space_conversion() {
let camera = WorldPos::new(I64Vec3::new(12, -3, 7), DVec3::new(1000.0, 2000.0, 3000.0));
let object = camera + DVec3::new(1.5, -2.5, 0.25);
assert_eq!(object.relative_to(camera), Vec3::new(1.5, -2.5, 0.25));
let far = WorldPos::new(I64Vec3::splat(1_000_000), DVec3::splat(SECTOR_SIZE - 10.0));
let far_object = far + DVec3::new(1.5, -2.5, 0.25);
assert_eq!(far_object.relative_to(far), Vec3::new(1.5, -2.5, 0.25));
}
#[test]
fn assign_operators_match_the_value_forms() {
let base = WorldPos::new(I64Vec3::new(2, 2, 2), DVec3::splat(10.0));
let offset = DVec3::new(3.0, -4.0, 5.0);
let mut moved = base;
moved += offset;
assert_eq!(moved, base + offset);
moved -= offset;
assert_eq!(moved, base);
assert_eq!(base - offset, base + -offset);
}
fn any_pos() -> impl Strategy<Value = WorldPos> {
(
-1_000_000i64..1_000_000,
-1_000_000i64..1_000_000,
-1_000_000i64..1_000_000,
0.0..SECTOR_SIZE,
0.0..SECTOR_SIZE,
0.0..SECTOR_SIZE,
)
.prop_map(|(sx, sy, sz, lx, ly, lz)| {
WorldPos::new(I64Vec3::new(sx, sy, sz), DVec3::new(lx, ly, lz))
})
}
fn step_bound(offset: DVec3) -> f64 {
(SECTOR_SIZE + offset.abs().max_element()) * f64::EPSILON
}
fn any_offset() -> impl Strategy<Value = DVec3> {
let axis = prop_oneof![
-1e-3..1e-3f64,
-1e3..1e3f64,
-1e9..1e9f64,
-4.0 * SECTOR_SIZE..4.0 * SECTOR_SIZE,
];
(axis.clone(), axis.clone(), axis).prop_map(|(x, y, z)| DVec3::new(x, y, z))
}
proptest! {
#[test]
fn prop_normalize_is_idempotent(pos in any_pos(), offset in any_offset()) {
let raw = WorldPos { sector: pos.sector, local: pos.local + offset };
let once = raw.normalize();
prop_assert!(once.is_normalized(), "{once:?}");
prop_assert_eq!(once, once.normalize());
}
#[test]
fn prop_normalize_does_not_move_the_point(pos in any_pos(), offset in any_offset()) {
let raw = WorldPos { sector: pos.sector, local: pos.local + offset };
prop_assert_eq!(raw.normalize().delta(raw), DVec3::ZERO);
}
#[test]
fn prop_normalize_is_exact_at_interstellar_offsets(
sector in -1_000_000_000i64..1_000_000_000,
local in -1e21..1e21f64,
) {
let raw = WorldPos { sector: I64Vec3::splat(sector), local: DVec3::splat(local) };
let normalized = raw.normalize();
prop_assert!(normalized.is_normalized(), "{normalized:?}");
prop_assert_eq!(normalized.delta(raw), DVec3::ZERO);
}
#[test]
fn prop_add_then_sub_returns_the_offset(pos in any_pos(), offset in any_offset()) {
let recovered = (pos + offset) - pos;
let tolerance = step_bound(offset);
prop_assert!(
(recovered - offset).abs().max_element() <= tolerance,
"recovered {recovered} vs {offset}, tolerance {tolerance}"
);
}
#[test]
fn prop_delta_is_antisymmetric(a in any_pos(), b in any_pos()) {
prop_assert_eq!(a - b, -(b - a));
prop_assert_eq!(a.distance(b), b.distance(a));
}
#[test]
fn prop_distance_matches_delta_length(a in any_pos(), b in any_pos()) {
prop_assert_eq!(a.distance(b), (a - b).length());
let d2 = a.distance_squared(b);
prop_assert!((d2 - a.distance(b).powi(2)).abs() <= d2 * 1e-12);
}
#[test]
fn prop_random_walk_matches_single_step(
start in any_pos(),
steps in proptest::collection::vec(-1e6..1e6f64, 3..90),
) {
let steps: Vec<DVec3> = steps
.as_chunks::<3>().0.iter()
.map(|c| DVec3::new(c[0], c[1], c[2]))
.collect();
let mut walked = start;
for step in &steps {
walked += *step;
}
let mut total = DVec3::ZERO;
for step in &steps {
total += *step;
}
let jumped = start + total;
let drift = (walked - jumped).abs().max_element();
let bound: f64 = steps.iter().copied().map(step_bound).sum::<f64>()
+ step_bound(total);
prop_assert!(drift <= bound, "drift {drift} m over {} steps", steps.len());
}
#[test]
fn prop_walk_and_back_returns_home(
start in any_pos(),
steps in proptest::collection::vec(any_offset(), 1..24),
) {
let mut pos = start;
for step in &steps {
pos += *step;
}
for step in steps.iter().rev() {
pos -= *step;
}
let drift = (pos - start).abs().max_element();
let bound: f64 = 2.0 * steps.iter().copied().map(step_bound).sum::<f64>();
prop_assert!(drift <= bound, "drift {drift} m, bound {bound}");
}
#[test]
fn prop_relative_to_agrees_with_delta(a in any_pos(), offset in any_offset()) {
let b = a + offset;
prop_assert_eq!(b.relative_to(a), (b - a).as_vec3());
}
}
}