1use crate::body::Body;
2use crate::close_encounter::CloseEncounter;
3use crate::force::{self, ForceMethod};
4use crate::integrator::{self, Integrator, leap_frog};
5use crate::system::System;
6use crate::vec3::Vec3;
7use crate::vec6::Vec6;
8use std::collections::HashMap;
9
10#[derive(Clone, Debug)]
11pub enum TimestepMethod {
12 Constant(f64),
13 }
15
16pub fn constant_step(system: &mut System, dt: f64, tmp: &mut Vec<Body>) -> bool {
17 let n = system.bodies.len();
18 let bodies = &system.bodies;
19 let solve = &mut system.integrator;
20 let force_method = &system.force_method;
21 let close_encounter = &system.close_encounter;
22 let cache = &mut system.cache;
23 let mut proceed = true;
24 for id in 0..n {
25 let body = &bodies[id];
26 let m = body.m;
27 let a = body.a;
28 let w = body.to_vec6();
29 let wdot_func = |w: Vec6, use_cache: bool| {
30 let dummy = Body::new(id, m, w.r, w.v, None);
31 calc_wdot(
32 &dummy,
33 bodies,
34 force_method,
35 close_encounter,
36 cache,
37 use_cache,
38 )
39 };
40 let sol = match solve {
41 Integrator::Euler => integrator::euler(w, dt, wdot_func),
42 Integrator::RK4 => integrator::rk4(w, dt, wdot_func),
43 Integrator::BS => integrator::bs(w, dt, wdot_func),
44 Integrator::LeapFrog(state) => {
45 let s = integrator::lf(w, dt, wdot_func, *state);
46 if id == n - 1 {
47 state.next();
48 }
49 if *state == leap_frog::State::SecondDrift {
50 proceed = true;
51 } else {
52 proceed = false;
53 }
54 s
55 }
56 };
57 let (w_new, a_new) = sol.unzip();
58 let new_body = Body::new(id, m, w_new.r, w_new.v, a_new.or(Some(a)));
59 tmp.push(new_body);
60 }
61 system.clear_cache();
62 system.bodies = std::mem::take(tmp);
63 proceed
64}
65
66pub fn calc_wdot(
67 body: &Body,
68 bodies: &Vec<Body>,
69 force_method: &ForceMethod,
70 close_encounter: &CloseEncounter,
71 cache: &mut HashMap<(usize, usize), Vec3>,
72 use_cache: bool,
73) -> Vec6 {
74 let cache = if use_cache { Some(cache) } else { None };
75 let vdot = force::calc(body, bodies, force_method, close_encounter, cache);
76 let rdot = body.v;
77 Vec6::new(rdot, vdot)
78}