use super::{ParticleSystem, Range};
const SIGMA: f32 = 5.670_374e-8;
const K_AIR: f32 = 0.057;
const NU_AIR: f32 = 1.0e-4;
const D_O2: f32 = 1.0e-4;
const RHO_O2: f32 = 0.27;
const HEAT_PER_O2: f32 = 6.9e6;
const CARBON_PER_O2: f32 = 0.75;
const E_OVER_R: f32 = 130_000.0 / 8.314;
const RATE: f32 = 5.0e6;
const PR_THIRD: f32 = 0.888;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Thermal {
pub initial: Range,
pub ambient: f32,
pub diameter: f32,
pub density: f32,
pub heat_capacity: f32,
pub emissivity: f32,
pub burning: bool,
pub contact: f32,
pub surface_temperature: f32,
}
impl Thermal {
pub fn ember(ambient: f32) -> Self {
Self {
initial: Range::new(1100.0, 1350.0),
ambient,
diameter: 0.05,
density: 400.0,
heat_capacity: 1000.0,
emissivity: 0.9,
burning: true,
contact: 0.0,
surface_temperature: ambient,
}
}
pub fn rates(&self, t: f32, d: f32, speed: f32, burning: bool, resting: bool) -> (f32, f32) {
let d = d.max(1e-5);
let area = std::f32::consts::PI * d * d;
let mass = self.density * std::f32::consts::PI * d * d * d / 6.0;
let re = speed * d / NU_AIR;
let nu = 2.0 + 0.6 * re.sqrt() * PR_THIRD;
let h = nu * K_AIR / d;
let ta = self.ambient;
let mut loss = area * (self.emissivity * SIGMA * (t.powi(4) - ta.powi(4)) + h * (t - ta));
if resting && self.contact > 0.0 {
loss += area * self.contact * (t - self.surface_temperature);
}
let mut gain = 0.0;
let mut shrink = 0.0;
if burning && !(resting && self.contact > 0.0) {
let diffusion = nu * D_O2 * RHO_O2 / d;
let reaction = RHO_O2 * RATE * (-E_OVER_R / t.max(1.0)).exp();
let flux = diffusion * reaction / (diffusion + reaction);
gain = area * HEAT_PER_O2 * flux;
shrink = 2.0 * CARBON_PER_O2 * flux / self.density;
}
((gain - loss) / (mass * self.heat_capacity), -shrink)
}
}
impl ParticleSystem {
pub(crate) fn heat(&mut self, dt: f32) {
let Some(th) = self.thermal else { return };
let n = self.particles.len();
let ps = &mut self.particles;
while ps.temperature.len() < n {
ps.temperature.push(th.initial.sample(&mut self.rng));
}
while ps.remaining.len() < n {
ps.remaining.push(1.0);
}
for i in 0..n {
let d0 = ps.size[i] * th.diameter;
let air = self
.air
.get(i)
.copied()
.filter(|a| !a.x.is_nan())
.unwrap_or(self.forces.wind);
let speed = (ps.velocity[i] - air).length();
let mut t = ps.temperature[i];
let mut r = ps.remaining[i];
let tau = th.density * d0.max(1e-5) * r * th.heat_capacity
/ (6.0
* (4.0 * th.emissivity * SIGMA * t.max(th.ambient).powi(3)
+ 3000.0f32.min(th.contact + 60.0)));
let steps = ((dt / (0.5 * tau.max(1e-5))).ceil() as usize).clamp(1, 64);
let h = dt / steps as f32;
for _ in 0..steps {
let (dt_dt, dd_dt) = th.rates(t, d0 * r, speed, th.burning, ps.resting[i]);
t = (t + dt_dt * h).max(th.ambient.min(th.surface_temperature));
r = (r + dd_dt * h / d0.max(1e-6)).max(0.0);
}
ps.temperature[i] = t;
ps.remaining[i] = r;
if r < 0.2 {
ps.age[i] = f32::INFINITY;
}
}
}
}