summaryrefslogtreecommitdiffstats
path: root/src/solar_system.rs
blob: 81567d0613ac47a8ca424acd29567ae2dd642b2b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
pub mod orbit;
pub mod ship;

use serde::{Deserialize};
use crate::known_stars::*;
use crate::solar_system::orbit::*;
use crate::solar_system::ship::*;
use crate::timeman::Second;
use std::error::Error;

const GRAVITATIONAL_CONSTANT: f64 = 6.67408e-20;

pub type Kilograms = f64;
pub type Kilometers = f64;
pub type Percentage = f64;
pub type Angle = f64;

pub type BodyId = usize;
pub type SystemId = usize;

#[derive(Debug, Deserialize)]
pub struct CSVOrbitalBody
{
    name: String,
    orbits: Option<BodyId>,
    mass: Kilograms,
    radius: Kilometers,

    eccentricity: Percentage,
    inclination: Angle,
    long_asc_node: Angle,
    long_periapsis: Angle,
    sgp: f64,
    mean_long: Angle,

    semi_major_axis: Kilometers,
}

pub struct OrbitalBody
{
    name: String,
    mass: Kilograms,
    radius: Kilometers,
    sgp: f64,

    orbit: Option<StaticOrbit>,
    position: Option<cgmath::Vector3<Kilometers>>
}

pub struct SolarSystem
{
    id: SystemId,
    name: String,
 
    bodies: Vec<OrbitalBody>,
    ships: Vec<Ship>
}

impl SolarSystem
{
    pub fn new_from_csv(
        id: SystemId,
        data: &'static str)
    -> Result<Self, Box<dyn Error>> {
        let data_reader = stringreader::StringReader::new(data);
        let mut body_reader = csv::Reader::from_reader(data_reader);
        
        let mut bodies = Vec::<OrbitalBody>::new();

        for result in body_reader.deserialize() {
            let mut record: CSVOrbitalBody = result?;

            match record.orbits {
                Some(orbits) => {
                    if record.sgp == 0.0 {
                        record.sgp = (bodies[orbits].mass + record.mass) * GRAVITATIONAL_CONSTANT;
                    }
                }
                None => {}
            }
            if record.radius == 0.0 { continue; }
            println!("New body: {:?}", record);

            bodies.push(OrbitalBody { 
                name: record.name,
                mass: record.mass,
                radius: record.radius,
                sgp: record.sgp,
                orbit: Some(StaticOrbit {
                    parent: record.orbits,
                    eccentricity: record.eccentricity,
                    inclination: record.inclination,
                    long_asc_node: record.long_asc_node,
                    long_periapsis: record.long_periapsis,
                    mean_long: record.mean_long,
                    semi_major_axis: record.semi_major_axis
                }),
                position: None
            });
        }

        Ok(Self {
            id: id,
            name: bodies[0].name().clone(),
            bodies: bodies,
            ships: vec![]
        })
    }

    pub fn new_from_known_star(
        id: SystemId,
        star: &'static str)
    -> Result<Self, Box<dyn Error>> {
        let star_csv = match KNOWN_STARS.get(star).copied() {
            Some(csv) => csv,
            None => return Err(Box::new(StarNotFoundError { star: star }))
        };
        SolarSystem::new_from_csv(id, star_csv)
    }

    pub fn id(&self) -> SystemId { self.id }

    pub fn name(&self) -> &String { &self.name }

    pub fn bodies(&self)
        -> &[OrbitalBody]
    {
        self.bodies.as_slice()
    }

    pub fn body_position(
        &self,
        body: &OrbitalBody)
    -> cgmath::Vector3<Kilometers>
    {
        match &body.orbit {
            Some(orbit) => {
                match orbit.parent {
                    Some(parent) => {
                        let this_pos = body.position();
                        let parent_pos = self.bodies[parent].position();
                        this_pos + parent_pos
                    },
                    None => body.position()
                }
            },
            None => body.position()
        }
    }

    pub fn update(
        &mut self,
        time: Second)
    {
        self.bodies.iter_mut().for_each(|body| {
            body.position = Some(body.calculate_orbit_at(time));
        });
    }
}

impl OrbitalBody
{
    pub fn name(&self) -> &String { &self.name }
    pub fn radius(&self) -> f32 { self.radius as f32 }
    pub fn position(&self) -> cgmath::Vector3<f64> { self.position.unwrap() }
    pub fn does_orbit(&self) -> bool {
        match &self.orbit {
            Some(orbit) => orbit.parent.is_some(),
            None => false
        }
    }
    pub fn get_orbits(&self) -> Option<BodyId> {
        match &self.orbit {
            Some(orbit) => orbit.parent(),
            None => None
        }
    }

    pub fn orbital_period(&self) -> Second
    {
        match &self.orbit {
            Some(v) => v.period(self),
            None => return 0
        }
    }

    pub fn calculate_orbit_at(
        &self,
        time: Second)
    -> cgmath::Vector3<Kilometers>
    {
        match &self.orbit {
            Some(orbit) => orbit.calculate_position_at(self, time),
            None => cgmath::vec3(0.0, 0.0, 0.0)
        }
    }
}