1use crate::body::Body;
2use crate::close_encounter::CloseEncounter;
3use crate::vec3::{Vec3, ZERO_VEC3};
4use std::collections::HashMap;
5
6#[derive(Clone, Debug)]
7pub enum ForceMethod {
8 Direct,
9 Octree,
10}
11
12impl ForceMethod {
13 pub fn new_octree() -> ForceMethod {
14 ForceMethod::Octree
15 }
16}
17
18pub fn gravity(b1: &Body, b2: &Body, close_encounter: &CloseEncounter) -> Vec3 {
23 let r = b2.r - b1.r;
24 let rhat = r.hat();
25 let r2 = r.norm_2();
26 let divisor = match close_encounter {
27 CloseEncounter::Regularized => r2,
28 CloseEncounter::Soften(s) => r2 + s * s,
29 CloseEncounter::Truncated(s) => r2.max(s * s),
30 };
31 let value = b1.m * b2.m / divisor;
32 value * rhat
33}
34
35pub fn direct(
36 body: &Body,
37 bodies: &Vec<Body>,
38 close_encounter: &CloseEncounter,
39 mut cache: Option<&mut HashMap<(usize, usize), Vec3>>,
40) -> Vec3 {
41 let mut total_force = ZERO_VEC3;
42
43 for other in bodies.iter() {
44 if body.id == other.id {
45 continue;
46 }
47
48 if let Some(cache_ref) = cache.as_ref() {
50 if let Some(force) = cache_ref.get(&(body.id, other.id)) {
51 total_force += *force;
52 continue;
53 }
54 }
55
56 let force = gravity(body, other, close_encounter);
57 total_force += force;
58
59 if let Some(cache_ref) = cache.as_mut() {
61 cache_ref.insert((other.id, body.id), -1. * force);
62 cache_ref.insert((body.id, other.id), force);
63 }
64 }
65
66 total_force / body.m
67}
68
69pub fn calc(
70 body: &Body,
71 bodies: &Vec<Body>,
72 force_method: &ForceMethod,
73 close_encounter: &CloseEncounter,
74 cache: Option<&mut HashMap<(usize, usize), Vec3>>,
75) -> Vec3 {
76 match force_method {
77 ForceMethod::Direct => direct(body, bodies, close_encounter, cache),
78 ForceMethod::Octree => todo!(),
79 }
80}