atmosim 0.1.0

A library for calculating most efficient gas bombs in Space Station 14 game
Documentation
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! This handles simulation of specifically tank explosion logic (not gas reactions).
//! You probably don't want to touch this unless they've changed this logic or you're fixing a bug.

use core::{f32::consts::PI, fmt::Display};

use log::{error, trace};

#[cfg(not(feature = "std"))]
use num_traits::Float;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::{
    Atmosim,
    config::{ONE_ATMOSPHERE, R},
    gases::GasMixture,
    reactions::ATMOS_TICKRATE,
};

// 2 fucking hours. You don't need more.
const HARD_TICK_LIMIT: usize = 15000;

#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct GasContainerPrototype {
    pub volume: f32,
    pub max_integrity: i8,
    pub normal_pressure: f32,
    pub logic: GasContainerLogic,
}

// realistically this should be done via traits and generics
// practically they've touched maxcap logic once in 10 years
// and likely aren't gonna touch it again so who cares
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum GasContainerLogic {
    Modern {
        container: ContainerType,
        release_area: f32,
        safety_pressure: f32,
        overpressure: f32,
        explosion_slope: f32,
        explosion_max_intensity: f32,
    },
    TankOld {
        fragment_pressure: f32,
        rupture_pressure: f32,
        leak_pressure: f32,
        fragment_scale: f32,
    },
}

#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ContainerType {
    Tank,
    Canister,
}

impl GasContainerPrototype {
    #[must_use]
    pub(crate) fn default_tank() -> Self {
        Self {
            volume: 5.,
            max_integrity: 5,
            normal_pressure: ONE_ATMOSPHERE * 10.,
            logic: GasContainerLogic::Modern {
                container: ContainerType::Tank,
                release_area: 0.0001,
                safety_pressure: ONE_ATMOSPHERE * 15.,
                overpressure: ONE_ATMOSPHERE * 20.,
                explosion_max_intensity: 20.,
                explosion_slope: 1.,
            },
        }
    }

    #[must_use]
    pub(crate) fn default_canister() -> Self {
        Self {
            volume: 1500.,
            max_integrity: 25,
            normal_pressure: 4500.,
            logic: GasContainerLogic::Modern {
                container: ContainerType::Canister,
                release_area: 0.05,
                safety_pressure: 5066.25,
                overpressure: 15198.75,
                explosion_max_intensity: 100.,
                explosion_slope: 1.,
            },
        }
    }

    #[must_use]
    pub(crate) fn old_default_tank() -> Self {
        Self {
            max_integrity: 3,
            logic: GasContainerLogic::TankOld {
                fragment_pressure: 50. * ONE_ATMOSPHERE,
                rupture_pressure: 40. * ONE_ATMOSPHERE,
                leak_pressure: 30. * ONE_ATMOSPHERE,
                fragment_scale: 2.25 * ONE_ATMOSPHERE,
            },
            ..Self::default_tank()
        }
    }
}

impl Atmosim {
    #[must_use]
    pub(crate) fn container(&self) -> GasContainerPrototype {
        self.game.container
    }
}

impl Default for GasContainerPrototype {
    fn default() -> Self {
        Self::default_tank()
    }
}

#[derive(Debug)]
pub struct GasContainer<'a> {
    pub(crate) mix: GasMixture<'a>,
    state: GasContainerState,
    integrity: i8,
    lifetime: usize,
    valve_open: bool,
}

impl Display for GasContainer<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.mix.fmt(f)?;
        writeln!(f, ", P = {} kPa", self.pressure())?;
        write!(f, "State: {:?}", self.state)
    }
}

impl<'a> GasContainer<'a> {
    #[must_use]
    /// Inherits proto from the mix engine gameconfig
    pub fn new(mix: GasMixture<'a>) -> Self {
        Self {
            mix,
            state: GasContainerState::Idle,
            integrity: mix.engine.game.container.max_integrity,
            lifetime: 0,
            valve_open: false,
        }
    }

    #[must_use]
    pub fn proto(&self) -> GasContainerPrototype {
        self.mix.engine.container()
    }

    #[must_use]
    pub fn mixture(&'_ self) -> &'_ GasMixture<'_> {
        &self.mix
    }

    #[must_use]
    pub fn volume(&self) -> f32 {
        self.proto().volume
    }

    #[must_use]
    pub fn ticks(&self) -> usize {
        self.lifetime
    }

    #[must_use]
    pub fn state(&self) -> GasContainerState {
        self.state
    }

    /// Keeps the moles relative ratios and temperature, but adjusts
    /// mole amounts so the pressure is equal to normal pressure of the tank
    #[must_use]
    pub fn normalized(mut self) -> Self {
        let ratio = self.proto().normal_pressure / self.pressure(); // mul by that
        self.mix.modify_moles_each(|mole| mole * ratio);
        self
    }

    #[must_use]
    pub fn pressure(&self) -> f32 {
        self.mix.total_moles() * R * self.mix.temperature() / self.volume()
    }

    // TODO: should return true even if no gases reacted but tank state changed (gas bleed etc)
    pub fn step(&mut self) -> GasContainerState {
        self.lifetime += 1;

        match self.proto().logic {
            GasContainerLogic::Modern { .. } => {
                if self.check_status() {
                    self.device_updated();
                }
            }
            GasContainerLogic::TankOld { .. } => {
                if self.mix.react() {
                    self.state = GasContainerState::Reacting;
                } else {
                    self.state = GasContainerState::Idle;
                }
                self.check_status();
            }
        }

        trace!(
            "Container stepped, currently contains {:?} at {}K ({} kPa), integrity = {}.",
            self.mix.moles(),
            self.mix.temperature(),
            self.pressure(),
            self.integrity
        );

        self.state
    }

    pub fn step_n(&mut self, n: usize) {
        for _ in 0..n {
            if self.step() != GasContainerState::Reacting {
                break;
            }
        }
    }

    pub fn step_all(&mut self) {
        self.step_n(HARD_TICK_LIMIT);
        if self.state() == GasContainerState::Reacting {
            error!("Gas mixture {self} went into an infinite loop.");
        }
    }

    pub(crate) fn get_over_pressure(&self, other: Option<GasContainer>) -> f32 {
        (self.pressure()
            - if let Some(container) = other {
                container.pressure()
            } else {
                0.
            })
            * self.proto().volume
    }

    /// Whether the container survived
    fn check_status(&mut self) -> bool {
        // Same for tanks and canisters
        match self.proto().logic {
            GasContainerLogic::Modern {
                safety_pressure,
                overpressure,
                explosion_slope,
                explosion_max_intensity,
                ..
            } => {
                let pressure = self.pressure();
                if pressure > overpressure * f32::from(self.integrity + 1) {
                    self.state = GasContainerState::Exploded {
                        radius: intensity_to_radius(
                            self.get_over_pressure(None).sqrt(),
                            explosion_slope,
                            explosion_max_intensity,
                        ),
                    };
                    return false;
                }

                if pressure > overpressure {
                    self.integrity -= 1;
                } else if self.integrity < self.proto().max_integrity {
                    self.integrity += 1;
                }

                if pressure > safety_pressure {
                    self.valve_open = true;
                }

                true
            }
            GasContainerLogic::TankOld {
                rupture_pressure,
                fragment_pressure,
                leak_pressure,
                fragment_scale,
            } => {
                match self.pressure() {
                    p if p > fragment_pressure => {
                        for _ in 0..3 {
                            self.mix.react(); // not step bc that would be infinite recursion
                        }
                        self.state = GasContainerState::Exploded {
                            radius: ((self.pressure() - fragment_pressure) / fragment_scale).sqrt(),
                        }
                    }
                    p if p > rupture_pressure && self.integrity <= 0 => {
                        self.state = GasContainerState::Ruptured;
                    }
                    p if p > leak_pressure && self.integrity <= 0 => {
                        self.mix.remove_ratio(0.25);
                    }
                    p if p > leak_pressure || p > rupture_pressure => self.integrity -= 1,
                    _ if self.integrity < 3 => self.integrity += 1, // yes it's hardcoded 3 lmao
                    _ => (),
                }

                false // we don't care about the return type for old case
            }
        }
    }

    fn device_updated(&mut self) {
        match self.proto().logic {
            // for whatever reason tanks first release, then react
            // but canisters do the opposite
            GasContainerLogic::Modern {
                container: ContainerType::Tank,
                ..
            } => {
                if self.valve_open {
                    self.release_gas();
                }

                self.state = if self.mix.react() {
                    GasContainerState::Reacting
                } else {
                    GasContainerState::Idle
                };
            }
            GasContainerLogic::Modern {
                container: ContainerType::Canister,
                safety_pressure,
                ..
            } => {
                self.state = if self.mix.react() {
                    GasContainerState::Reacting
                } else {
                    GasContainerState::Idle
                };

                if self.valve_open {
                    self.release_gas();
                }

                // canister specific: close the valve if the pressure is now safe
                if self.pressure() < safety_pressure {
                    self.valve_open = false;
                }
            }
            GasContainerLogic::TankOld { .. } => {
                // Ideally this should be compiler-enforced but whatever, see reason somewhere above
                unreachable!("Old tanks shouldn't call device_updated.")
            }
        }
    }

    fn release_gas(&mut self) {
        if let GasContainerLogic::Modern {
            release_area,
            safety_pressure,
            ..
        } = self.proto().logic
        {
            let pressure = self.pressure();
            // there's no way I'm bothering with simulating outer pressure, but setting it to zero makes us ready for the worse
            let environment_air_pressure = 0.;

            let delta_p = pressure - environment_air_pressure;
            assert!(delta_p.is_sign_positive());

            // basically if we are below safety pressure we can just set output pressure to 0 and never leak
            if pressure >= safety_pressure {
                // The original code has 10 nested callbacks for no reason
                let volume = ATMOS_TICKRATE
                    * release_area
                    * (2. * delta_p * self.volume() / self.mix.get_mass()).sqrt();
                let moles_needed = delta_p * volume / (R * self.mix.temperature());

                self.mix.remove(moles_needed);
            }
        }
    }
}

// i literally have no idea how this works, this just does what the game does
fn intensity_to_radius(total_intensity: f32, slope: f32, max_intensity: f32) -> f32 {
    let r0 = max_intensity / slope;
    let v0 = slope * PI / 3. * r0.powi(3);

    if total_intensity < v0 {
        (3. * total_intensity / (slope * PI)).cbrt()
    } else {
        r0 * ((12. * total_intensity / v0 - 3.).sqrt() / 6. + 0.5)
    }
}

#[derive(Debug, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum GasContainerState {
    Reacting,
    Idle,
    Exploded {
        radius: f32,
    },
    /// Old only
    Ruptured,
}