Skip to main content

crcbl_phys/
frames.rs

1//! A hierarchy of reference frames, and the sphere-of-influence crossings that
2//! move a body between them.
3//!
4//! The physics plan, whose rules are in `docs/notes/simulation.md`: "bodies
5//! parent to dominant gravity source (galaxy
6//! → star → planet → moon → vehicle). Simulation runs in the local frame; the
7//! frame itself moves on-rails. Frame transitions (sphere-of-influence
8//! crossing) are explicit events."
9//!
10//! # Why a hierarchy at all
11//!
12//! Gravity is an n-body problem and nothing here pretends otherwise; what a
13//! hierarchy buys is that **one** body dominates at any given place, so the
14//! motion is a two-body problem plus small perturbations. That is the patched
15//! conic approximation, and it is why a spacecraft's trajectory can be
16//! propagated analytically for a thousand orbits instead of integrated: inside
17//! a sphere of influence there is one attractor, and at its boundary the body
18//! is handed to the next frame out or in.
19//!
20//! # Why the positions are [`WorldPos`]
21//!
22//! A frame conversion is an addition, and at these distances an addition in
23//! plain `f64` is where a seam comes from: at Jupiter's orbit an `f64` metre
24//! coordinate has about 128 m between representable values, so a body would
25//! visibly snap as it crossed. [`WorldPos`] carries the large part as an
26//! integer sector index and the small part as an offset below `2^20` m, where
27//! the spacing is a fraction of a nanometre — so the crossing is exact and
28//! [`Frames::convert`] round-trips bit for bit. That is what
29//! `06-orbit.md`'s "no visible seam or jitter" asks for, and
30//! `a_crossing_far_from_the_origin_keeps_millimetres` is what measures it: a
31//! millimetre held 10^15 m from the root, which a plain `f64` metre coordinate
32//! cannot represent at all.
33//!
34//! # What drove it
35//!
36//! `docs/plan/sample/06-orbit.md` milestone 3 — the moon transfer, which is an
37//! SOI transition and a sector crossing at once.
38
39use crcbl_core::WorldPos;
40use glam::{DVec3, I64Vec3};
41
42/// A frame's handle in a [`Frames`] hierarchy.
43///
44/// A plain index rather than the generational id [`crate::ColliderId`] is,
45/// because frames are not removed: a hierarchy is the star, planets and moons
46/// of a scene, built once. With no recycling there is no slot to confuse, and
47/// an id from one [`Frames`] used against another is the only misuse left —
48/// which panics on the bounds check rather than reading a neighbour.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50pub struct FrameId(u32);
51
52impl FrameId {
53    /// The index this id names, for subscripting a caller's own per-frame
54    /// array.
55    #[inline]
56    #[must_use]
57    pub fn index(self) -> usize {
58        self.0 as usize
59    }
60}
61
62/// A position and velocity, read in some frame.
63///
64/// Which frame is not carried here: a state is only ever handled together with
65/// the [`FrameId`] it belongs to, and pairing them in one struct would invite
66/// [`Frames::convert`] to be called with a frame the state is not actually in
67/// and quietly agree.
68#[derive(Debug, Clone, Copy, PartialEq)]
69pub struct State {
70    /// Position relative to the frame's origin.
71    pub position: WorldPos,
72    /// Velocity relative to the frame, in m/s.
73    pub velocity: DVec3,
74}
75
76impl State {
77    /// A state at a frame's origin, at rest in it.
78    pub const AT_ORIGIN: Self = Self {
79        position: WorldPos::ORIGIN,
80        velocity: DVec3::ZERO,
81    };
82
83    /// Builds a state.
84    #[inline]
85    #[must_use]
86    pub fn new(position: WorldPos, velocity: DVec3) -> Self {
87        Self { position, velocity }
88    }
89}
90
91/// One frame of the hierarchy.
92#[derive(Debug)]
93struct Frame {
94    parent: Option<FrameId>,
95    children: Vec<FrameId>,
96    depth: u32,
97    mu: f64,
98    soi_radius: f64,
99    /// Where this frame's origin sits in its parent's frame.
100    origin: WorldPos,
101    /// How fast this frame moves through its parent's, in m/s.
102    velocity: DVec3,
103}
104
105/// A tree of reference frames: a root, and bodies parented to whatever
106/// dominates them.
107///
108/// Build it once with [`new`](Self::new) and [`add`](Self::add), move frames
109/// with [`set_state`](Self::set_state) as they orbit, read a body's state in
110/// another frame with [`convert`](Self::convert), and ask
111/// [`transition`](Self::transition) whether a body has left the frame it was
112/// being simulated in.
113///
114/// Nothing here integrates or propagates anything. A frame's motion is set by
115/// its caller — today by whatever is stepping the scene, later by the on-rails
116/// Kepler propagator, which changes nothing about the conversions.
117#[derive(Debug)]
118pub struct Frames {
119    frames: Vec<Frame>,
120}
121
122impl Frames {
123    /// Builds a hierarchy with a single root frame of gravitational parameter
124    /// `mu` (`GM`, in m³/s²).
125    ///
126    /// The root has no parent and an infinite sphere of influence: nothing is
127    /// outside it, which is what makes [`transition`](Self::transition)
128    /// terminate.
129    #[must_use]
130    pub fn new(mu: f64) -> Self {
131        Self {
132            frames: vec![Frame {
133                parent: None,
134                children: Vec::new(),
135                depth: 0,
136                mu,
137                soi_radius: f64::INFINITY,
138                origin: WorldPos::ORIGIN,
139                velocity: DVec3::ZERO,
140            }],
141        }
142    }
143
144    /// The root frame's id, which is always the first one added.
145    #[inline]
146    #[must_use]
147    pub fn root(&self) -> FrameId {
148        FrameId(0)
149    }
150
151    /// How many frames the hierarchy holds, the root included.
152    #[inline]
153    #[must_use]
154    pub fn len(&self) -> usize {
155        self.frames.len()
156    }
157
158    /// Always false — a hierarchy always has its root. Present because clippy
159    /// asks for it wherever `len` is, and answering honestly is cheaper than
160    /// explaining the exception.
161    #[inline]
162    #[must_use]
163    pub fn is_empty(&self) -> bool {
164        false
165    }
166
167    /// Adds a frame under `parent`, at `origin` in the parent's frame and
168    /// moving at `velocity` through it.
169    ///
170    /// `mu` is the body's gravitational parameter `GM` in m³/s², and
171    /// `soi_radius` the radius in metres beyond which the parent dominates —
172    /// [`sphere_of_influence`] computes the usual one.
173    ///
174    /// # Panics
175    ///
176    /// If `soi_radius` is not positive. A frame nothing can be inside cannot
177    /// be transitioned into and would sit in the tree as a body that silently
178    /// exerts no influence.
179    pub fn add(
180        &mut self,
181        parent: FrameId,
182        mu: f64,
183        soi_radius: f64,
184        origin: WorldPos,
185        velocity: DVec3,
186    ) -> FrameId {
187        assert!(
188            soi_radius > 0.0,
189            "a frame's sphere of influence must have a positive radius, got {soi_radius}"
190        );
191        let id = FrameId(u32::try_from(self.frames.len()).expect("frame count fits in u32"));
192        let depth = self.frames[parent.index()].depth + 1;
193        self.frames.push(Frame {
194            parent: Some(parent),
195            children: Vec::new(),
196            depth,
197            mu,
198            soi_radius,
199            origin: origin.normalize(),
200            velocity,
201        });
202        self.frames[parent.index()].children.push(id);
203        id
204    }
205
206    /// This frame's parent, or `None` for the root.
207    #[inline]
208    #[must_use]
209    pub fn parent(&self, id: FrameId) -> Option<FrameId> {
210        self.frames[id.index()].parent
211    }
212
213    /// The frames parented directly to `id`.
214    #[inline]
215    #[must_use]
216    pub fn children(&self, id: FrameId) -> &[FrameId] {
217        &self.frames[id.index()].children
218    }
219
220    /// This frame's gravitational parameter `GM`, in m³/s².
221    #[inline]
222    #[must_use]
223    pub fn mu(&self, id: FrameId) -> f64 {
224        self.frames[id.index()].mu
225    }
226
227    /// The radius of this frame's sphere of influence, in metres. Infinite for
228    /// the root.
229    #[inline]
230    #[must_use]
231    pub fn soi_radius(&self, id: FrameId) -> f64 {
232        self.frames[id.index()].soi_radius
233    }
234
235    /// Where this frame's origin sits in its parent's frame, and how fast it
236    /// moves through it. Both are zero for the root.
237    #[inline]
238    #[must_use]
239    pub fn state_in_parent(&self, id: FrameId) -> State {
240        let frame = &self.frames[id.index()];
241        State::new(frame.origin, frame.velocity)
242    }
243
244    /// Moves a frame within its parent.
245    ///
246    /// This is how a moon orbits: whatever is propagating it — an integrator
247    /// now, the Kepler propagator later — writes the new state here each tick,
248    /// and every conversion through it follows.
249    ///
250    /// # Panics
251    ///
252    /// If `id` is the root, whose origin is the definition of the hierarchy's
253    /// coordinates and cannot move without moving everything with it.
254    pub fn set_state(&mut self, id: FrameId, state: State) {
255        assert!(
256            self.frames[id.index()].parent.is_some(),
257            "the root frame's origin is what every other frame is measured from and cannot move"
258        );
259        let frame = &mut self.frames[id.index()];
260        frame.origin = state.position.normalize();
261        frame.velocity = state.velocity;
262    }
263
264    /// The deepest frame that is an ancestor of both `a` and `b`, or one of
265    /// them if it is an ancestor of the other.
266    ///
267    /// Every pair has one, because every frame descends from the root.
268    #[must_use]
269    pub fn common_ancestor(&self, a: FrameId, b: FrameId) -> FrameId {
270        let (mut a, mut b) = (a, b);
271        // Lift the deeper one until they are level, then step both up together.
272        // The parent of a non-root frame always exists, so neither unwrap can
273        // fire before the two meet at the root.
274        while self.frames[a.index()].depth > self.frames[b.index()].depth {
275            a = self.frames[a.index()]
276                .parent
277                .expect("a deeper frame has a parent");
278        }
279        while self.frames[b.index()].depth > self.frames[a.index()].depth {
280            b = self.frames[b.index()]
281                .parent
282                .expect("a deeper frame has a parent");
283        }
284        while a != b {
285            a = self.frames[a.index()]
286                .parent
287                .expect("frames level and unequal are not the root");
288            b = self.frames[b.index()]
289                .parent
290                .expect("frames level and unequal are not the root");
291        }
292        a
293    }
294
295    /// Reads a state given in frame `from` as it stands in frame `to`.
296    ///
297    /// Exact in position: every step is a sector-and-offset addition, which
298    /// loses nothing, so converting out and back returns the position bit for
299    /// bit. Velocity is a plain `f64` sum of the frames' velocities and is as
300    /// exact as those are.
301    #[must_use]
302    pub fn convert(&self, state: State, from: FrameId, to: FrameId) -> State {
303        let meeting = self.common_ancestor(from, to);
304
305        let mut state = state;
306        let mut up = from;
307        while up != meeting {
308            let frame = &self.frames[up.index()];
309            state.position = compose(frame.origin, state.position);
310            state.velocity += frame.velocity;
311            up = frame.parent.expect("the walk stops at the common ancestor");
312        }
313
314        // The way down is the same steps in reverse, so collect them first.
315        let mut down = Vec::new();
316        let mut cursor = to;
317        while cursor != meeting {
318            down.push(cursor);
319            cursor = self.frames[cursor.index()]
320                .parent
321                .expect("the walk stops at the common ancestor");
322        }
323        for id in down.into_iter().rev() {
324            let frame = &self.frames[id.index()];
325            state.position = decompose(state.position, frame.origin);
326            state.velocity -= frame.velocity;
327        }
328
329        state
330    }
331
332    /// The frame a body at `state` in `frame` should be simulated in next, or
333    /// `None` if it is already in the right one.
334    ///
335    /// One step: a body that has fallen through two boundaries in a tick — a
336    /// tick long enough to cross a whole sphere of influence — needs the answer
337    /// applied and the question asked again. The caller does that rather than a
338    /// loop here, because a malformed hierarchy is the one thing that could
339    /// make such a loop run for ever, and a caller that has counted its steps
340    /// notices.
341    ///
342    /// **Entering a child wins over leaving for the parent.** In a well-formed
343    /// hierarchy the two cannot both be true, because a child's sphere of
344    /// influence lies inside its parent's; where a hand-built one says
345    /// otherwise, the deeper frame is the better approximation.
346    #[must_use]
347    pub fn transition(&self, state: State, frame: FrameId) -> Option<FrameId> {
348        let here = &self.frames[frame.index()];
349        for &child in &here.children {
350            let inside = &self.frames[child.index()];
351            if state.position.distance(inside.origin) < inside.soi_radius {
352                return Some(child);
353            }
354        }
355        // `>=` so the boundary itself belongs to the parent, which is the same
356        // side the child test above puts it on: exactly one frame claims a body
357        // standing on the line.
358        if state.position.distance(WorldPos::ORIGIN) >= here.soi_radius {
359            return here.parent;
360        }
361        None
362    }
363}
364
365/// The radius of a body's sphere of influence, in metres.
366///
367/// The Laplace sphere of influence of the patched-conic approximation
368/// (Bate, Mueller & White, *Fundamentals of Astrodynamics*, §7.4):
369///
370/// ```text
371/// r_soi = a · (m / M)^(2/5)
372/// ```
373///
374/// where `a` is the semi-major axis of the body's orbit about its primary and
375/// `m / M` the mass ratio between them. It is given here in gravitational
376/// parameters because `G` cancels — `mu = GM`, so `mu / primary_mu` is that
377/// same ratio — and because `mu` is what is actually published to eight
378/// figures for a body while its mass is not.
379///
380/// It is not a physical surface. It is where the primary's perturbation of a
381/// two-body orbit about the body first exceeds the body's perturbation of a
382/// two-body orbit about the primary, which is the point at which it is cheaper
383/// to be wrong the other way round.
384///
385/// # Panics
386///
387/// If `primary_mu` is not positive, which would make the ratio meaningless, or
388/// if `semi_major_axis` or `mu` is negative.
389#[must_use]
390#[expect(
391    clippy::disallowed_methods,
392    reason = "no constructed power exists yet; a sphere of influence is set up once \
393              per frame rather than stepped, and docs/backlog.md carries it"
394)]
395pub fn sphere_of_influence(semi_major_axis: f64, mu: f64, primary_mu: f64) -> f64 {
396    assert!(
397        semi_major_axis >= 0.0,
398        "a semi-major axis is not negative, got {semi_major_axis}"
399    );
400    assert!(
401        mu >= 0.0,
402        "a gravitational parameter is not negative, got {mu}"
403    );
404    assert!(
405        primary_mu > 0.0,
406        "the primary must have mass for a sphere of influence to be defined, got {primary_mu}"
407    );
408    semi_major_axis * (mu / primary_mu).powf(0.4)
409}
410
411// ---------------------------------------------------------------------------
412// Sector-exact offsets
413// ---------------------------------------------------------------------------
414//
415// A frame's origin in its parent is a *displacement*, and one that can be
416// larger than a sector needs the same integer-plus-offset form a position does
417// — so it is carried as a `WorldPos` and chained by adding the two parts. The
418// alternative, `WorldPos::delta` down to a `DVec3` and back, would round the
419// sum to whatever `f64` can hold at that magnitude, which is the seam this
420// whole module exists to avoid.
421
422/// `origin` displaced by `offset`: reading a position given in a frame as it
423/// stands in that frame's parent.
424fn compose(origin: WorldPos, offset: WorldPos) -> WorldPos {
425    WorldPos::new(
426        saturating_add(origin.sector, offset.sector),
427        origin.local + offset.local,
428    )
429}
430
431/// The inverse of [`compose`]: reading a position given in a parent as it
432/// stands in the child whose origin is at `origin`.
433fn decompose(position: WorldPos, origin: WorldPos) -> WorldPos {
434    WorldPos::new(
435        saturating_sub(position.sector, origin.sector),
436        position.local - origin.local,
437    )
438}
439
440/// Sector addition that clamps at the edge of the addressable volume rather
441/// than wrapping to the far side of it, matching what
442/// [`WorldPos::normalize`] already does with a carry.
443fn saturating_add(a: I64Vec3, b: I64Vec3) -> I64Vec3 {
444    I64Vec3::new(
445        a.x.saturating_add(b.x),
446        a.y.saturating_add(b.y),
447        a.z.saturating_add(b.z),
448    )
449}
450
451/// Sector subtraction, clamping for the same reason [`saturating_add`] does.
452fn saturating_sub(a: I64Vec3, b: I64Vec3) -> I64Vec3 {
453    I64Vec3::new(
454        a.x.saturating_sub(b.x),
455        a.y.saturating_sub(b.y),
456        a.z.saturating_sub(b.z),
457    )
458}
459
460// ---------------------------------------------------------------------------
461// Tests
462// ---------------------------------------------------------------------------
463
464#[cfg(test)]
465mod tests {
466    use super::*;
467
468    /// Gravitational parameters as published by JPL (DE440, `GM` in m³/s²) —
469    /// the values the spheres of influence below are computed from.
470    const SUN_MU: f64 = 1.327_124_400_18e20;
471    const EARTH_MU: f64 = 3.986_004_418e14;
472    const MOON_MU: f64 = 4.902_800_118e12;
473
474    /// Semi-major axes in metres: Earth about the Sun, and the Moon about
475    /// Earth.
476    const EARTH_ORBIT: f64 = 1.495_978_707e11;
477    const MOON_ORBIT: f64 = 3.844_00e8;
478
479    /// A hierarchy of Sun → Earth → Moon, with the Moon out along `+x` and
480    /// Earth far enough from the origin that a naive `f64` sum would lose
481    /// metres.
482    fn solar_system() -> (Frames, FrameId, FrameId, FrameId) {
483        let mut frames = Frames::new(SUN_MU);
484        let sun = frames.root();
485        let earth = frames.add(
486            sun,
487            EARTH_MU,
488            sphere_of_influence(EARTH_ORBIT, EARTH_MU, SUN_MU),
489            WorldPos::from_offset(DVec3::new(EARTH_ORBIT, 0.0, 0.0)),
490            DVec3::new(0.0, 29_780.0, 0.0),
491        );
492        let moon = frames.add(
493            earth,
494            MOON_MU,
495            sphere_of_influence(MOON_ORBIT, MOON_MU, EARTH_MU),
496            WorldPos::from_offset(DVec3::new(MOON_ORBIT, 0.0, 0.0)),
497            DVec3::new(0.0, 1_022.0, 0.0),
498        );
499        (frames, sun, earth, moon)
500    }
501
502    /// **The formula against the published radii**, not against numbers this
503    /// file chose: Earth's sphere of influence is about 924 000 km and the
504    /// Moon's about 66 100 km. Both are quoted to three figures in the
505    /// literature, so 1% is the tolerance the sources support.
506    #[test]
507    fn the_spheres_of_influence_match_the_published_radii() {
508        let earth = sphere_of_influence(EARTH_ORBIT, EARTH_MU, SUN_MU);
509        let published = 9.24e8;
510        assert!(
511            (earth - published).abs() <= published * 0.01,
512            "Earth's SOI came out {earth} m, published {published} m"
513        );
514
515        let moon = sphere_of_influence(MOON_ORBIT, MOON_MU, EARTH_MU);
516        let published = 6.61e7;
517        assert!(
518            (moon - published).abs() <= published * 0.01,
519            "the Moon's SOI came out {moon} m, published {published} m"
520        );
521
522        // The exponent is what makes it a Laplace radius rather than any other
523        // power law, so pin it: quadrupling the mass ratio must multiply the
524        // radius by 4^(2/5), which no neighbouring exponent gives.
525        let base = sphere_of_influence(1.0, 1.0, 1.0e6);
526        let quadrupled = sphere_of_influence(1.0, 4.0, 1.0e6);
527        let ratio = quadrupled / base;
528        #[expect(
529            clippy::disallowed_methods,
530            reason = "the platform's power is the oracle"
531        )]
532        let expected = 4.0f64.powf(0.4);
533        assert!(
534            (ratio - expected).abs() < 1e-12,
535            "four times the mass must give {expected} times the radius, got {ratio}"
536        );
537    }
538
539    /// A conversion out and back is the identity, to the bit.
540    ///
541    /// This is the claim [`Frames::convert`] makes, and it is only true because
542    /// the walk adds sector indices as integers. The state used sits a long way
543    /// from every origin involved, where an `f64` sum would already have lost
544    /// the low bits.
545    #[test]
546    fn a_conversion_out_and_back_returns_the_state_exactly() {
547        let (frames, sun, _earth, moon) = solar_system();
548        let start = State::new(
549            WorldPos::from_offset(DVec3::new(1.0e7, -2.5e6, 3.25e6)),
550            DVec3::new(-900.0, 120.5, 7.25),
551        );
552
553        let out = frames.convert(start, moon, sun);
554        let back = frames.convert(out, sun, moon);
555        assert_eq!(
556            back.position, start.position,
557            "a round trip through the hierarchy must return the same position"
558        );
559        assert_eq!(back.velocity, start.velocity);
560    }
561
562    /// **The seam test.** A millimetre at the far side of the solar system
563    /// survives a frame conversion.
564    ///
565    /// Earth's frame sits 1.496 × 10¹¹ m from the root here, where an `f64`
566    /// metre coordinate has about 30 μm between neighbouring values — a
567    /// millimetre still survives that, so the test places the pair a further
568    /// 10¹⁵ m out, where the spacing is about a quarter of a metre and a naive
569    /// sum would collapse the two positions onto each other or fling them
570    /// apart. What is asserted is the *separation*, because that is what a
571    /// viewer sees: a seam is two points that were a millimetre apart landing
572    /// somewhere else relative to one another.
573    #[test]
574    fn a_crossing_far_from_the_origin_keeps_millimetres() {
575        const FAR: f64 = 1.0e15;
576        const MILLIMETRE: f64 = 1.0e-3;
577
578        let mut frames = Frames::new(SUN_MU);
579        let sun = frames.root();
580        let far = frames.add(
581            sun,
582            EARTH_MU,
583            1.0e9,
584            WorldPos::from_offset(DVec3::new(FAR, FAR, FAR)),
585            DVec3::ZERO,
586        );
587
588        let a = State::new(
589            WorldPos::from_offset(DVec3::new(1.0e8, 0.0, 0.0)),
590            DVec3::ZERO,
591        );
592        // Displaced from `a` rather than built from `1.0e8 + 1.0e-3`, which is
593        // not a representable `f64` and would start the pair seven nanometres
594        // off the millimetre before anything under test had run. Added to a
595        // normalized position it lands on the small local offset, where it is
596        // exact — which is the whole reason a position is held this way.
597        let b = State::new(a.position.translated(DVec3::X * MILLIMETRE), DVec3::ZERO);
598        let before = a.position.distance(b.position);
599        assert!(
600            (before - MILLIMETRE).abs() < MILLIMETRE * 1e-6,
601            "the two should start about a millimetre apart, got {before} m"
602        );
603
604        let converted_a = frames.convert(a, far, sun);
605        let converted_b = frames.convert(b, far, sun);
606        let after = converted_a.position.distance(converted_b.position);
607        // A conversion is one `f64` addition per axis on a coordinate below
608        // `SECTOR_SIZE`, so it can move a separation by at most an ulp there —
609        // `2^20` has an ulp of `2^-32` m, under a quarter of a nanometre.
610        const SEAM: f64 = 1.0e-9;
611        assert!(
612            (after - before).abs() < SEAM,
613            "a millimetre {FAR} m from the origin came back as {after} m, from {before} m"
614        );
615
616        // And that this is worth doing: the same two points held as plain `f64`
617        // metres from the root are the same point.
618        let naive_a = FAR + 1.0e8;
619        let naive_b = FAR + 1.0e8 + MILLIMETRE;
620        assert_eq!(
621            naive_b - naive_a,
622            0.0,
623            "an `f64` metre coordinate at {FAR} m cannot hold a millimetre at all, \
624             which is what the sector split is for"
625        );
626    }
627
628    /// Between two frames neither of which contains the other, the walk goes up
629    /// to the common ancestor and back down — and lands where the geometry
630    /// says.
631    #[test]
632    fn a_state_converts_between_siblings_through_their_common_ancestor() {
633        let (mut frames, sun, earth, moon) = solar_system();
634        let mars = frames.add(
635            sun,
636            4.282_837e13,
637            1.0e9,
638            WorldPos::from_offset(DVec3::new(0.0, 2.279_39e11, 0.0)),
639            DVec3::ZERO,
640        );
641        assert_eq!(frames.common_ancestor(moon, mars), sun);
642        assert_eq!(frames.common_ancestor(moon, earth), earth);
643        assert_eq!(frames.common_ancestor(earth, earth), earth);
644
645        // A body sitting exactly on the Moon's origin is, seen from Mars, at
646        // whatever vector separates the two origins.
647        let seen = frames.convert(State::AT_ORIGIN, moon, mars);
648        let expected = DVec3::new(EARTH_ORBIT + MOON_ORBIT, -2.279_39e11, 0.0);
649        let error = (seen.position.delta(WorldPos::ORIGIN) - expected).length();
650        assert!(
651            error < 1.0e-6,
652            "the Moon seen from Mars should be at {expected:?}, came out {:?}",
653            seen.position.delta(WorldPos::ORIGIN)
654        );
655
656        // And its velocity is its own plus Earth's, since Mars is not moving in
657        // this hierarchy.
658        assert_eq!(seen.velocity, DVec3::new(0.0, 29_780.0 + 1_022.0, 0.0));
659    }
660
661    /// Past the boundary the body belongs to the parent; inside a child's, to
662    /// the child; and in between, to neither.
663    #[test]
664    fn a_body_crossing_a_boundary_is_handed_to_the_frame_that_now_dominates() {
665        let (frames, sun, earth, moon) = solar_system();
666        let moon_soi = frames.soi_radius(moon);
667
668        let inside = State::new(
669            WorldPos::from_offset(DVec3::new(moon_soi * 0.5, 0.0, 0.0)),
670            DVec3::ZERO,
671        );
672        assert_eq!(
673            frames.transition(inside, moon),
674            None,
675            "a body well inside the Moon's sphere of influence stays in it"
676        );
677
678        let outside = State::new(
679            WorldPos::from_offset(DVec3::new(moon_soi * 1.5, 0.0, 0.0)),
680            DVec3::ZERO,
681        );
682        assert_eq!(
683            frames.transition(outside, moon),
684            Some(earth),
685            "past the Moon's sphere of influence, Earth dominates"
686        );
687
688        // The same body read in Earth's frame is inside the Moon's SOI again
689        // only if it is near the Moon; put one there and Earth must hand it
690        // over.
691        let near_moon = frames.convert(inside, moon, earth);
692        assert_eq!(
693            frames.transition(near_moon, earth),
694            Some(moon),
695            "a body inside the Moon's sphere of influence is handed to the Moon"
696        );
697
698        // Halfway out to the Moon it is Earth's and nobody else's.
699        let between = State::new(
700            WorldPos::from_offset(DVec3::new(MOON_ORBIT * 0.5, 0.0, 0.0)),
701            DVec3::ZERO,
702        );
703        assert_eq!(frames.transition(between, earth), None);
704
705        // Nothing leaves the root: its sphere of influence is everything.
706        let anywhere = State::new(WorldPos::from_offset(DVec3::splat(1.0e18)), DVec3::ZERO);
707        assert_eq!(frames.transition(anywhere, sun), None);
708    }
709
710    /// **A transition changes the description, not the body.**
711    ///
712    /// The state that comes out the other side of a hand-over, read back in the
713    /// root, is the state that went in — so nothing accelerates, teleports or
714    /// jitters at the boundary, which is what `06-orbit.md` means by an
715    /// invisible crossing.
716    #[test]
717    fn a_transition_leaves_the_physical_state_untouched() {
718        let (frames, sun, earth, moon) = solar_system();
719        let moon_soi = frames.soi_radius(moon);
720
721        // Sat exactly on the boundary, moving outward.
722        let leaving = State::new(
723            WorldPos::from_offset(DVec3::new(moon_soi, 0.0, 0.0)),
724            DVec3::new(310.0, -40.0, 5.0),
725        );
726        assert_eq!(frames.transition(leaving, moon), Some(earth));
727
728        let handed_over = frames.convert(leaving, moon, earth);
729        assert_eq!(
730            frames.convert(handed_over, earth, sun),
731            frames.convert(leaving, moon, sun),
732            "the same body seen from the root must not move when it changes frame"
733        );
734
735        // And it is still on the boundary: its distance from the Moon's origin,
736        // now measured in Earth's frame, is the radius it crossed.
737        let moon_origin = frames.state_in_parent(moon).position;
738        let still_there = handed_over.position.distance(moon_origin);
739        assert!(
740            (still_there - moon_soi).abs() < 1.0e-6,
741            "the body was {moon_soi} m from the Moon and is now {still_there} m from it"
742        );
743
744        // The velocity it is handed over with differs from the one it had by
745        // exactly the Moon's own — no more, no less.
746        assert_eq!(
747            handed_over.velocity - leaving.velocity,
748            frames.state_in_parent(moon).velocity
749        );
750    }
751
752    /// A frame that moves takes everything in it along.
753    #[test]
754    fn moving_a_frame_moves_what_is_measured_through_it() {
755        let (mut frames, sun, _earth, moon) = solar_system();
756        let before = frames.convert(State::AT_ORIGIN, moon, sun);
757
758        let shifted = frames.state_in_parent(moon);
759        frames.set_state(
760            moon,
761            State::new(
762                shifted.position.translated(DVec3::new(0.0, 1.0e6, 0.0)),
763                shifted.velocity,
764            ),
765        );
766
767        let after = frames.convert(State::AT_ORIGIN, moon, sun);
768        let moved = after.position.delta(before.position);
769        assert!(
770            (moved - DVec3::new(0.0, 1.0e6, 0.0)).length() < 1.0e-6,
771            "moving the Moon a megametre should move a body sitting on it the same, got {moved:?}"
772        );
773    }
774}