Files
airdef/airdef-mod/src/smoke.rs
T
chexit 1261c30724 Stage the cold launch and spool every interceptor's motor (#129)
The interceptor's launch is one sequence: the cap opens, the round is
thrown out unlit and slows under linear gas drag (`cold` ticks), the motor
lights where it has reached, it turns with a growing rate while thrust
spools up (`boost` ticks), and full guidance starts only at `cold + boost`.
A rail launch lights at once but spools over the same `boost` ticks; the
electric P1-SUN has no rocket spool or plume.

S-400/500 now hold the unlit ejection for 20/24 ticks (1.00/1.20 s at
20 Hz); IRIS-T/Tor keep shorter 8-tick throws. Ignition, its sound, flame
and recorded MotorIgnition event all use the missile's current position.
The RM48U strike follows the same 20-tick choreography, counts the throw
in its flight time and starts its recorded smoke at ignition.

Maximum speed, turn, accel, pk and every collision rule are unchanged.

Co-Authored-By: Kimi Code <noreply@kimi.com>
2026-11-06 13:35:35 +03:00

653 lines
22 KiB
Rust

//! Smoke for the HD renderer (`render.set-smoke`): exhaust trails of drones and missiles that leave
//! a clear tunnel in fog and cloud, smoke columns over fires, and the smoke of blasts. The game
//! derives everything from a segment's age, so the columns and blasts are a pure function of the
//! tick (nothing grows twice when a frame is shown again); trails are the only state, and they are
//! cut back when the tick goes backwards.
use crate::{
scene::{MoverKind, Snapshot},
sim::{Class, DroneKind},
};
use glam::DVec3;
use horizon_mod_sdk::render::SmokeSegment;
use std::collections::HashMap;
const MAX_TRAIL: usize = 2400;
const MAX_TOTAL: usize = 4000;
// A small optical-density lift for powered missile trails. Keep geometry and budgets unchanged.
const MISSILE_TRAIL_DENSITY: f32 = 1.12;
struct Trail {
seg: SmokeSegment,
}
#[derive(Default)]
pub struct Smoke {
trails: Vec<Trail>,
/// Where each flying thing last left a segment: (kind, id) -> (position, tick).
last: HashMap<(u8, u32), (DVec3, u64)>,
last_tick: u64,
next: u32,
/// The renderer draws the smoke (the answer of the last call).
pub hd: bool,
}
fn seg(id: u32, a: DVec3, b: DVec3, born: u64, life: u32) -> SmokeSegment {
SmokeSegment {
id,
ax: a.x,
ay: a.y,
az: a.z,
bx: b.x,
by: b.y,
bz: b.z,
born: born as f64,
life: life as f32,
radius_start: 1.0,
radius_end: 6.0,
density: 0.5,
heat: 0.0,
soot: 0.4,
rise: 0.2,
clear: 0.0,
}
}
/// The column over one fire up to `tick`: a puff every 15 ticks (90 for the weaker fires) that
/// rises, spreads and thins. A pure function of the tick.
fn fire_column(
out: &mut Vec<SmokeSegment>,
fire_id: u32,
at: DVec3,
start: u64,
size: f32,
shown: bool,
tick: u64,
level: &dyn Fn(u64) -> (f32, f32),
) {
// Only the strongest fires get a full column; the rest a thin puff now and then.
let step = if shown { 15 } else { 90 };
let first = start.max(tick.saturating_sub(520));
let mut k = first.div_ceil(step) * step;
while k <= tick && out.len() < MAX_TOTAL {
let (flame, smoke) = level(k);
if smoke > 0.05 && k >= start {
let id = 0x4000_0000 | (fire_id.wrapping_mul(131) ^ (k / step) as u32) & 0x3fff_ffff;
let at = at + DVec3::Y * 0.6;
let mut s = seg(id, at, at, k, 540);
s.radius_start = 1.0 * size;
s.radius_end = 8.0 * size + 2.0;
s.density = 2.6 * smoke * size.sqrt() * if shown { 1.0 } else { 0.5 };
s.heat = flame * 0.6;
s.soot = 0.85;
s.rise = 2.6;
out.push(s);
}
k += step;
}
}
/// Blasts: a billow of puffs going up, for 900 ticks after each.
fn blast_billows(out: &mut Vec<SmokeSegment>, blasts: &[crate::sim::Blast], tick: u64) {
for b in blasts {
let age = tick.saturating_sub(b.start);
if age > 900 {
continue;
}
for j in 0..6u64 {
let born = b.start + j * 3;
if born > tick {
break;
}
let h = b.size as f64 * (0.2 + 0.5 * j as f64);
let at = b.at + DVec3::Y * h;
let mut s = seg(
0x5000_0000 | (b.id.wrapping_mul(7) + j as u32) & 0x0fff_ffff,
at,
at,
born,
800,
);
s.radius_start = b.size * 0.6;
s.radius_end = b.size * 3.2 + 4.0;
s.density = 2.4 / (1.0 + j as f32 * 0.25);
s.heat = if j < 3 { 1.0 } else { 0.4 };
s.soot = 0.55;
s.rise = 4.0 - 0.3 * j as f32;
out.push(s);
}
}
}
/// How one kind of trail looks. One rule by engine: a propeller leaves a faint short grey haze,
/// a jet or a cruise missile a thin grey line, a rocket (supersonic, ballistic, interceptor) a white
/// line as thick as the missile is big. No trail has heat: the flame at the nozzle is separate.
#[derive(Clone, Copy, Debug)]
struct Look {
r0: f32,
r1: f32,
density: f32,
soot: f32,
clear: f32,
life: f32,
}
/// A rocket's white line, thicker for a bigger missile (`scale`: Pantsir 0.85, S-500 1.7).
fn rocket(scale: f32, density: f32, life: f32) -> Look {
let scale = scale.min(2.0);
Look {
r0: 0.25 * scale,
r1: 1.2 + 1.6 * scale,
density: density * MISSILE_TRAIL_DENSITY,
soot: 0.02,
clear: 0.8 + 1.2 * scale,
life: life + 250.0 * scale,
}
}
fn drone_look(class: Class, scale: f32) -> Look {
match class {
Class::Drone => Look {
r0: 0.4,
r1: 1.8,
density: 0.15,
soot: 0.3,
clear: 0.3,
life: 250.0,
},
Class::Jet => Look {
r0: 0.5,
r1: 2.5,
density: 0.5,
soot: 0.25,
clear: 1.5,
life: 500.0,
},
Class::Cruise => Look {
r0: 0.6,
r1: 3.0,
density: 0.6 * MISSILE_TRAIL_DENSITY,
soot: 0.3,
clear: 2.0,
life: 600.0,
},
Class::Supersonic => rocket(scale, 0.9, 400.0),
Class::Ballistic => rocket(scale, 1.1, 500.0),
}
}
/// `None`: no motor smoke at all (the electric P1-SUN).
fn missile_look(kind: crate::sim::MissileKind) -> Option<Look> {
kind.trail_scale().map(|k| rocket(k, 0.8, 250.0))
}
fn style(s: &mut SmokeSegment, l: Look) {
s.radius_start = l.r0;
s.radius_end = l.r1;
s.density = l.density;
s.heat = 0.0;
s.soot = l.soot;
s.clear = l.clear;
s.life = l.life;
}
/// Points between a replay trail segment's ends (a segment every `TRAIL_GRID * STEP` ticks).
const TRAIL_GRID: usize = 4;
/// Trail segments sit on a fixed grid of each recorded track's points.
fn recorded_trails(rec: &crate::sim::record::Recording, t: f64) -> Vec<SmokeSegment> {
use crate::sim::record::{STEP, What};
let tick = t.max(0.0) as u64;
let mut out: Vec<SmokeSegment> = Vec::new();
let stride = (TRAIL_GRID as u32 * STEP) as f64;
for (n, tr) in rec.tracks.iter().enumerate() {
let look = match tr.what {
What::Drone(kind) => {
let spec = kind.spec();
Some(drone_look(spec.class, spec.trail_scale()))
}
What::Missile(kind, _) => missile_look(kind),
// Legacy fixtures retain their cruise trail; physical carriers use a rocket trail.
What::StrikeCarrier(_) => missile_look(crate::sim::MissileKind::M48n6),
What::Strike => Some(drone_look(
Class::Cruise,
DroneKind::Kalibr.spec().trail_scale(),
)),
};
let Some(look) = look else { continue };
let life = look.life as f64;
// The segments whose end point has been reached and whose life is not over.
let lo = (((t - life - tr.first as f64) / stride).floor().max(0.0)) as usize;
let hi = (((t - tr.first as f64) / stride).floor().max(0.0)) as usize;
for g in lo.max(1)..=hi {
let (Some(mut a), Some(b)) = (
tr.sample(rec.origin, (g - 1) * TRAIL_GRID),
tr.sample(rec.origin, g * TRAIL_GRID),
) else {
break;
};
let born = tr.first as u64 + (g * TRAIL_GRID) as u64 * STEP as u64;
if born > tick
|| a.distance(b) >= 400.0
|| (matches!(tr.what, What::StrikeCarrier(_))
&& born < tr.first as u64 + crate::sim::strike::EJECT_TICKS)
|| (matches!(tr.what, What::Missile(kind, _) if !rec.missile_is_lit(tr, born as f64, kind.lit_after())))
{
continue;
}
let ignition = match tr.what {
What::StrikeCarrier(_) => Some(tr.first as f64 + crate::sim::strike::EJECT_TICKS as f64),
What::Missile(kind, _) => Some(rec.missile_ignition(tr.id).map_or(tr.first as f64 + kind.lit_after() as f64 + 1.0, |e| e.at as f64)),
_ => None,
};
if let Some(ignition) = ignition {
let segment_start = tr.first as f64 + (g - 1) as f64 * stride;
if segment_start < ignition { a = tr.at(rec.origin, ignition).unwrap_or(b); }
}
let mut s = seg(
0x2000_0000 | ((n as u32).wrapping_mul(7919) ^ g as u32) & 0x0fff_ffff,
a,
b,
born,
1200,
);
style(&mut s, look);
if (tick as f64) < born as f64 + s.life as f64 {
out.push(s);
}
}
}
if out.len() > MAX_TRAIL {
out.sort_by_key(|s| s.born as u64);
let cut = out.len() - MAX_TRAIL;
out.drain(..cut);
}
out
}
/// A recording's smoke is just another read-only scene view; seeking rebuilds the same segments
/// from its tracks, fire transitions and blasts without consulting the current simulation.
#[cfg(test)]
pub fn replay_smoke(rec: &crate::sim::record::Recording, t: f64) -> Vec<SmokeSegment> {
let context = crate::presentation::Context::playback(
crate::presentation::Mode::Replay,
1,
None,
0,
0,
t,
None,
1.0,
DVec3::ZERO,
true,
);
Smoke::default().segments(&Snapshot::at_context(
&context,
crate::scene::Source::Recorded(rec),
))
}
impl Smoke {
fn trail(&mut self, key: (u8, u32), at: DVec3, tick: u64, look: Look) {
let Some(&(from, when)) = self.last.get(&key) else {
self.last.insert(key, (at, tick));
return;
};
if at.distance(from) < 5.0 && tick - when < 10 {
return;
}
// A jump (a teleport, a respawn) is no trail.
if at.distance(from) < 400.0 {
self.next = self.next.wrapping_add(1);
let mut s = seg(self.next, from, at, tick, 1200);
style(&mut s, look);
self.trails.push(Trail { seg: s });
}
self.last.insert(key, (at, tick));
}
/// Follows the simulation one tick: new trail segments for what flies, old ones dropped.
pub fn update(&mut self, scene: &Snapshot<'_>) {
debug_assert_eq!(
scene.source(),
"live",
"incremental trails are sampled from live poses only"
);
let tick = scene.time().max(0.0) as u64;
if tick < self.last_tick {
self.trails.retain(|t| t.seg.born as u64 <= tick);
self.last.clear();
}
self.last_tick = tick;
let movers = scene.movers();
for mover in &movers {
match mover.kind {
MoverKind::Drone(kind) => {
let spec = kind.spec();
self.trail(
(mover.group, mover.id),
mover.pos,
tick,
drone_look(spec.class, spec.trail_scale()),
);
}
MoverKind::Missile { kind, engine_lit } => {
if !engine_lit { continue; }
if let Some(look) = missile_look(kind) {
self.trail((mover.group, mover.id), mover.pos, tick, look);
}
}
MoverKind::Strike {
physical,
engine_lit,
} => {
if engine_lit {
let look = if physical {
rocket(crate::sim::strike::ROUND_SCALE as f32, 0.8, 250.0)
} else {
drone_look(Class::Cruise, DroneKind::Kalibr.spec().trail_scale())
};
self.trail((mover.group, mover.id), mover.pos, tick, look);
}
}
}
}
// Forget what is gone.
if tick % 100 == 0 {
let alive: std::collections::HashSet<(u8, u32)> =
movers.iter().map(|m| (m.group, m.id)).collect();
self.last.retain(|k, _| alive.contains(k));
}
self.trails
.retain(|t| tick < t.seg.born as u64 + t.seg.life as u64);
if self.trails.len() > MAX_TRAIL {
let cut = self.trails.len() - MAX_TRAIL;
self.trails.drain(..cut);
}
}
/// Every segment alive at the simulation's tick: trails, fire columns, blast smoke.
pub fn segments(&self, scene: &Snapshot<'_>) -> Vec<SmokeSegment> {
let tick = scene.time().max(0.0) as u64;
let mut out = match scene.recording() {
Some(rec) => recorded_trails(rec, scene.time()),
None if scene.is_recorded_view() => Vec::new(),
None => self.trails.iter().map(|t| t.seg.clone()).collect(),
};
// The same fire and blast adapters serve live effects and seekable recorded effects.
let mut fires = scene.fires();
fires.sort_by(|a, b| {
b.size()
.total_cmp(&a.size())
.then(a.start().cmp(&b.start()))
});
for (rank, f) in fires.iter().enumerate() {
if f.quiet() && f.size() < 1.0 {
continue;
}
fire_column(
&mut out,
0x1000_0000 | f.key(),
f.at(),
f.start(),
f.size(),
f.shown() && rank < crate::sim::fires::MAX,
tick,
&|k| f.level(k),
);
}
blast_billows(&mut out, &scene.smoke_blasts(), tick);
out.truncate(MAX_TOTAL);
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::scene;
use crate::{
presentation::Context,
sim::{DroneKind, MissileKind, Sim},
};
fn live_scene(sim: &Sim) -> Snapshot<'_> {
let ctx = Context::live(1, None, 0, sim.tick, None, DVec3::ZERO);
Snapshot::at_context(&ctx, scene::Source::Live(sim))
}
#[test]
fn replay_smoke_has_trails_and_fire_columns_and_is_a_function_of_time() {
use crate::sim::record::{Event, EventKind, Recording, What};
let sim = Sim::new(1);
let mut rec = Recording::blank(160);
for id in 1..=2 {
let x = (id - 1) as f64 * 30.0;
rec.straight(
id,
What::Drone(DroneKind::Geran3),
0,
160,
DVec3::new(x, 80.0, 0.0),
DVec3::new(x, 80.0, 500.0),
);
}
assert_eq!(rec.tracks.len(), 2);
rec.events = vec![Event {
at: 40,
pos: DVec3::new(5.0, 70.0, 5.0),
kind: EventKind::Hit {
drone: 1,
kind: DroneKind::Geran3,
power: 2,
object: None,
sam: None,
},
}];
let live_state = (sim.tick, sim.fires.list.len());
let t = 130.0;
let a = replay_smoke(&rec, t);
assert!(a.iter().any(|s| s.clear > 0.0), "trails of both tracks");
assert!(a.iter().any(|s| s.soot > 0.8), "a column over the fire");
assert!(a.iter().any(|s| s.soot == 0.55), "the blast's billows");
let _ = replay_smoke(&rec, 10.0);
let _ = replay_smoke(&rec, 155.0);
let b = replay_smoke(&rec, t);
assert_eq!(
a.iter().map(|s| (s.id, s.born as u64)).collect::<Vec<_>>(),
b.iter().map(|s| (s.id, s.born as u64)).collect::<Vec<_>>()
);
assert!(a.iter().all(|s| s.born <= t));
assert!(replay_smoke(&rec, -5.0).is_empty());
let ctx = Context::playback(
crate::presentation::Mode::Replay,
1,
None,
0,
0,
400.0,
None,
1.0,
DVec3::ZERO,
true,
);
let scene = Snapshot::at_context(&ctx, crate::scene::Source::Recorded(&rec));
assert!(scene.blasts().is_empty(), "the visual flash has expired");
assert_eq!(
scene.smoke_blasts().len(),
1,
"smoke persists on the recording timeline"
);
assert!(replay_smoke(&rec, 400.0).iter().any(|s| s.soot == 0.55));
assert_eq!((sim.tick, sim.fires.list.len()), live_state);
}
#[test]
fn missing_recording_never_falls_back_to_cached_live_trails() {
let ctx = Context::playback(
crate::presentation::Mode::Replay,
2,
None,
0,
900,
40.0,
None,
0.5,
DVec3::ZERO,
true,
);
let scene = Snapshot::at_context(&ctx, scene::Source::Empty);
let mut smoke = Smoke::default();
smoke.trails.push(Trail {
seg: seg(1, DVec3::ZERO, DVec3::Z, 10, 1200),
});
assert!(scene.is_recorded_view());
assert_eq!(scene.time(), 40.0);
assert!(smoke.segments(&scene).is_empty());
}
#[test]
fn live_counter_strike_leaves_a_trail_and_releases_its_source() {
use crate::sim::sites::{LaunchSite, SiteClass};
use crate::sim::strike::{Estimate, Known, SiteState};
use glam::DVec2;
let mut sim = Sim::new(11);
let id = 1;
sim.sites.list.push(LaunchSite {
id,
side: 0,
sector: 0,
bearing: 0.0,
class: SiteClass::Ramp,
pos: DVec3::new(0.0, 64.0, 300.0),
range: 300.0,
water: false,
stock: 0,
planned: 0,
alive: true,
next_free: 0,
offmap: false,
});
sim.strikes.known.push(Known {
site: id,
class: SiteClass::Ramp,
obs: Vec::new(),
est: Some(Estimate {
pos: DVec2::new(0.0, 300.0),
radius: 5.0,
fix: true,
bearing: 0.0,
bearing_err: 0.01,
origin: DVec2::ZERO,
}),
launches: 1,
last: 0,
state: SiteState::Active,
aimed: false,
});
sim.order_test_strike(
id,
DVec3::new(0.0, 64.0, 0.0),
&mut crate::sim::Out::default(),
)
.unwrap();
let mut smoke = Smoke::default();
sim.tick = 1;
smoke.update(&live_scene(&sim));
let from = sim.strikes.flights[0].pos;
sim.tick = 2;
sim.strikes.flights[0].pos += DVec3::Z * 8.0;
smoke.update(&live_scene(&sim));
let segments = smoke.segments(&live_scene(&sim));
assert_eq!(
segments.len(),
1,
"a live strike must emit the cruise trail also seen in replay"
);
assert_eq!(segments[0].az, from.z);
assert_eq!(segments[0].bz, from.z + 8.0);
let expected = drone_look(Class::Cruise, DroneKind::Kalibr.spec().trail_scale());
assert_eq!(segments[0].density, expected.density);
// The same sampled poses now represent a physical cold-ejected round.
sim.strikes.flights[0].carrier = Some(99);
let mut smoke = Smoke::default();
sim.tick = 1;
smoke.update(&live_scene(&sim));
sim.tick = 2;
sim.strikes.flights[0].pos += DVec3::Y;
smoke.update(&live_scene(&sim));
assert!(
smoke.segments(&live_scene(&sim)).is_empty(),
"ejection is not rocket exhaust"
);
sim.tick = crate::sim::strike::EJECT_TICKS;
smoke.update(&live_scene(&sim));
sim.tick += 1;
sim.strikes.flights[0].pos += DVec3::Y * 8.0;
smoke.update(&live_scene(&sim));
let segments = smoke.segments(&live_scene(&sim));
assert_eq!(segments.len(), 1);
assert_eq!(
segments[0].soot, 0.02,
"a physical strike uses the rocket style in both sources"
);
assert!(
segments
.iter()
.all(|s| s.born >= crate::sim::strike::EJECT_TICKS as f64)
);
sim.strikes.flights.clear();
sim.tick = 100;
smoke.update(&live_scene(&sim));
assert!(
smoke.last.is_empty(),
"finished strikes must not leave source bookkeeping behind"
);
}
#[test]
fn recorded_physical_strike_trail_starts_at_ignition_not_at_the_muzzle() {
use crate::sim::record::{Recording, What};
let ignite = 10.0 + crate::sim::strike::EJECT_TICKS as f64;
let mut rec = Recording::blank(120);
rec.straight(1, What::StrikeCarrier(77), 10, 90, DVec3::ZERO, DVec3::Z * 80.0);
assert!(replay_smoke(&rec, 14.0).is_empty());
assert!(replay_smoke(&rec, (ignite - 2.0).max(30.0)).is_empty(), "no trail before the ignition");
let segments = replay_smoke(&rec, ignite + 12.0);
assert_eq!(segments.len(), 2);
assert!((segments[0].az - 20.0).abs() < 1e-6 && (segments[0].bz - 24.0).abs() < 1e-6, "the trail begins at the recorded ignition");
assert!((segments[1].az - 24.0).abs() < 1e-6 && (segments[1].bz - 32.0).abs() < 1e-6);
}
#[test]
fn trails_follow_one_rule() {
assert!(missile_look(MissileKind::P1sun).is_none());
let rocket_look = missile_look(MissileKind::M77n6).unwrap();
let pantsir = missile_look(MissileKind::M57e6).unwrap();
assert!(pantsir.r1 < rocket_look.r1);
let mut s = seg(0, DVec3::ZERO, DVec3::ZERO, 0, 0);
for class in [
Class::Drone,
Class::Jet,
Class::Cruise,
Class::Supersonic,
Class::Ballistic,
] {
style(&mut s, drone_look(class, 1.0));
assert_eq!(s.heat, 0.0);
}
for k in [
MissileKind::Pac3,
MissileKind::M57e6,
MissileKind::M77n6,
MissileKind::Amraam,
] {
style(&mut s, missile_look(k).unwrap());
assert_eq!(s.heat, 0.0);
}
let spec = DroneKind::Shahed.spec();
let shahed = drone_look(Class::Drone, spec.trail_scale());
assert!(shahed.density * 4.0 < rocket_look.density);
}
}