Files
airdef/airdef-mod/src/engines.rs
T
2026-11-02 23:59:11 +03:00

333 lines
12 KiB
Rust

//! Engines as persistent sound sources (#95): a drone's or a missile's engine is one source that
//! follows the entity, instead of a one-shot repeated every second or two.
//!
//! The simulation (live) and the replay (from a recording's tracks and the replay's time) each
//! *declare* the engines sounding this tick; [`Engines::step`] turns that into the changes of
//! `render.sound-sources`: a start with an attack when an engine appears (ignition), an update
//! every tick, a stop with a release when it is gone (burnout, the entity removed), and a fall
//! of pitch and gain over a second when it is damaged (a drone shot down). A declaration missing
//! for a tick or two (a step the simulation skipped) does not stop the sound; a *cut* (a replay
//! seek, a new shot) stops every engine and starts them again under new ids, so nothing glides
//! across the jump.
use glam::DVec3;
use std::collections::{BTreeMap, BTreeSet};
/// Ticks an engine may go undeclared before it is stopped.
const GRACE: u32 = 3;
/// Ticks a damaged engine takes to die: its pitch falls and it fades.
const DYING: u32 = 20;
/// The most engines that sound at once (the nearest ones; the game's budget picks the audible).
const MAX: usize = 128;
/// Doppler applied to engines. The kinds already differ in pitch, and the fight's speed must not
/// change what is heard, so it stays off; the game bounds it to 12% anyway.
pub const DOPPLER: f32 = 0.0;
pub use crate::sim::EngineDecl as Decl;
/// What a source is asked to be.
#[derive(Clone, Debug, PartialEq)]
pub struct Voice {
pub event: &'static str,
pub at: DVec3,
pub vel: DVec3,
pub gain: f32,
pub pitch: f32,
pub attack: f32,
pub release: f32,
pub loop_from: f32,
pub loop_to: f32,
}
/// One change of `render.sound-sources`.
#[derive(Clone, Debug, PartialEq)]
pub enum Op {
Start(u32, Voice),
Update(u32, Voice),
Stop(u32),
}
/// The steady part of each engine sound, seconds into the file: the sounds fade in at their start
/// and die away at their end (synthesis, reverb tail, fade: tools/gen_sounds.py), so looping a
/// whole file leaves a gap; these were found as `audio::tests::a_loop_of_the_steady_part_of_the_
/// engine_sounds_has_no_hole` finds them (after the fade-in, before the sound begins to die).
pub fn steady_part(event: &str) -> (f32, f32) {
match event {
"airdef:drone.shahed" => (0.2, 2.2),
"airdef:drone.geran3" => (0.2, 2.0),
"airdef:drone.lancet" => (0.2, 1.4),
"airdef:drone.cruise" => (0.2, 2.6),
"airdef:drone.rocket" => (0.2, 2.6),
"airdef:missile.flight" => (0.2, 2.2),
_ => (0.0, 0.0),
}
}
struct Live {
id: u32,
event: &'static str,
missed: u32,
dying: u32,
}
#[derive(Default)]
pub struct Engines {
live: BTreeMap<u32, Live>,
/// Engines that died and are still declared (a wreck falling): not started again.
dead: BTreeSet<u32>,
next_id: u32,
}
impl Engines {
pub fn is_empty(&self) -> bool {
self.live.is_empty()
}
/// An explicitly unpowered entity releases its source without waiting for the missing-frame grace.
pub fn stop(&mut self, key: u32) -> Option<Op> {
self.dead.remove(&key);
self.live.remove(&key).map(|live| Op::Stop(live.id))
}
/// The game released every source: forget them (nothing to stop).
pub fn reset(&mut self) {
self.live.clear();
self.dead.clear();
}
fn voice(d: &Decl, dying: u32) -> Voice {
let u = (dying as f32 / DYING as f32).min(1.0);
let (loop_from, loop_to) = steady_part(d.event);
Voice {
event: d.event,
at: d.at,
vel: d.vel,
// A shot-down engine coughs: the pitch falls by almost half, the sound fades.
gain: d.gain * (1.0 - u),
pitch: d.pitch * (1.0 - 0.45 * u),
attack: 0.3,
release: 0.25,
loop_from,
loop_to,
}
}
/// One tick: what is declared now, and whether the picture cut (a seek or a new shot).
pub fn step(&mut self, mut decls: Vec<Decl>, cut: bool, listener: DVec3) -> Vec<Op> {
let mut ops = Vec::new();
if cut {
for (_, l) in std::mem::take(&mut self.live) {
ops.push(Op::Stop(l.id));
}
self.dead.clear();
}
if decls.len() > MAX {
decls.sort_by(|a, b| {
a.at.distance_squared(listener)
.total_cmp(&b.at.distance_squared(listener))
.then(a.key.cmp(&b.key))
});
decls.truncate(MAX);
}
decls.sort_by_key(|d| d.key);
for l in self.live.values_mut() {
l.missed += 1;
}
let declared: BTreeSet<u32> = decls.iter().map(|d| d.key).collect();
self.dead.retain(|k| declared.contains(k));
for d in &decls {
if self.dead.contains(&d.key) {
continue;
}
match self.live.get_mut(&d.key) {
Some(l) if l.event == d.event => {
l.missed = 0;
if d.damaged {
l.dying += 1;
}
if l.dying >= DYING {
ops.push(Op::Stop(l.id));
self.live.remove(&d.key);
self.dead.insert(d.key);
} else {
ops.push(Op::Update(l.id, Self::voice(d, l.dying)));
}
}
other => {
// A new engine, or the same entity with another sound: the old one releases.
if let Some(l) = other {
ops.push(Op::Stop(l.id));
}
self.next_id = self.next_id.wrapping_add(1).max(1);
let dying = u32::from(d.damaged);
ops.push(Op::Start(self.next_id, Self::voice(d, dying)));
self.live.insert(
d.key,
Live {
id: self.next_id,
event: d.event,
missed: 0,
dying,
},
);
}
}
}
// Gone for good: the entity was removed (burnout, a hit, a crash).
let gone: Vec<u32> = self
.live
.iter()
.filter(|(_, l)| l.missed > GRACE)
.map(|(k, _)| *k)
.collect();
for k in gone {
if let Some(l) = self.live.remove(&k) {
ops.push(Op::Stop(l.id));
}
}
ops
}
}
#[cfg(test)]
mod tests {
use super::*;
fn d(key: u32, x: f64) -> Decl {
Decl {
key,
event: "airdef:drone.shahed",
at: DVec3::new(x, 50.0, 0.0),
vel: DVec3::new(30.0, 0.0, 0.0),
gain: 0.8,
pitch: 1.0,
damaged: false,
}
}
#[test]
fn explicit_burnout_releases_the_source_immediately() {
let mut engines = Engines::default();
let ops = engines.step(vec![d(42, 0.0)], false, DVec3::ZERO);
assert!(matches!(ops.as_slice(), [Op::Start(_, _)]));
assert!(matches!(engines.stop(42), Some(Op::Stop(_))));
assert!(engines.is_empty());
assert!(engines.stop(42).is_none());
}
fn starts(ops: &[Op]) -> usize {
ops.iter().filter(|o| matches!(o, Op::Start(..))).count()
}
fn stops(ops: &[Op]) -> usize {
ops.iter().filter(|o| matches!(o, Op::Stop(_))).count()
}
#[test]
fn an_engine_ignites_follows_and_stops_when_its_entity_goes() {
let mut e = Engines::default();
let ops = e.step(vec![d(1, 0.0)], false, DVec3::ZERO);
assert_eq!(starts(&ops), 1);
let Op::Start(id, v) = &ops[0] else { panic!() };
assert_eq!((v.attack, v.loop_from, v.loop_to), (0.3, 0.2, 2.2));
for i in 1..10 {
let ops = e.step(vec![d(1, f64::from(i))], false, DVec3::ZERO);
assert!(matches!(&ops[..], [Op::Update(u, v)] if u == id && v.at.x == f64::from(i)));
}
// Undeclared for a moment: still sounding; then gone.
for _ in 0..GRACE {
assert!(e.step(vec![], false, DVec3::ZERO).is_empty());
}
let ops = e.step(vec![], false, DVec3::ZERO);
assert_eq!(ops, vec![Op::Stop(*id)]);
assert!(e.is_empty());
}
#[test]
fn a_shot_down_engine_coughs_and_dies_and_stays_dead_while_it_falls() {
let mut e = Engines::default();
e.step(vec![d(1, 0.0)], false, DVec3::ZERO);
let mut last = 1.0;
let mut stopped_at = None;
for t in 1..60 {
let mut f = d(1, 0.0);
f.damaged = true;
let ops = e.step(vec![f], false, DVec3::ZERO);
match ops.as_slice() {
[Op::Update(_, v)] => {
assert!(v.pitch < last, "the pitch falls");
last = v.pitch;
}
[Op::Stop(_)] => stopped_at = stopped_at.or(Some(t)),
[] => {}
o => panic!("{o:?}"),
}
}
assert_eq!(stopped_at, Some(DYING));
assert!(last < 0.6);
// The wreck is gone, a new drone with the same key sounds again.
e.step(vec![], false, DVec3::ZERO);
assert_eq!(starts(&e.step(vec![d(1, 0.0)], false, DVec3::ZERO)), 1);
}
#[test]
fn a_cut_stops_every_engine_and_starts_them_under_new_ids() {
let mut e = Engines::default();
let a = e.step(vec![d(1, 0.0), d(2, 5.0)], false, DVec3::ZERO);
let ops = e.step(vec![d(1, 100.0), d(2, 105.0)], true, DVec3::ZERO);
assert_eq!((stops(&ops), starts(&ops)), (2, 2));
let old: Vec<u32> = a.iter().filter_map(|o| if let Op::Start(i, _) = o { Some(*i) } else { None }).collect();
for o in &ops {
if let Op::Start(i, _) = o {
assert!(!old.contains(i), "a new id, so nothing glides across the jump");
}
}
}
#[test]
fn another_sound_for_the_same_entity_restarts_it() {
let mut e = Engines::default();
e.step(vec![d(1, 0.0)], false, DVec3::ZERO);
let mut other = d(1, 0.0);
other.event = "airdef:drone.rocket";
let ops = e.step(vec![other], false, DVec3::ZERO);
assert_eq!((stops(&ops), starts(&ops)), (1, 1));
}
#[test]
fn only_the_nearest_are_kept_and_the_same_input_gives_the_same_ops() {
let run = || {
let mut e = Engines::default();
let all: Vec<Decl> = (0..300).map(|i| d(i, f64::from(i) * 3.0)).collect();
e.step(all, false, DVec3::ZERO)
};
let ops = run();
assert_eq!(starts(&ops), MAX);
assert_eq!(ops, run());
let far = ops.iter().filter_map(|o| if let Op::Start(_, v) = o { Some(v.at.x) } else { None }).fold(0.0, f64::max);
assert!(far <= (MAX as f64) * 3.0);
}
#[test]
fn a_hundred_seek_cycles_leave_no_engine_behind() {
let mut e = Engines::default();
let mut open = std::collections::BTreeSet::new();
for round in 0..100 {
let ops = e.step(vec![d(1, round as f64), d(2, 0.0)], round % 3 == 0, DVec3::ZERO);
for o in ops {
match o {
Op::Start(i, _) => {
open.insert(i);
}
Op::Stop(i) => {
assert!(open.remove(&i), "a stop for a source that was never started");
}
Op::Update(i, _) => assert!(open.contains(&i)),
}
}
}
for o in e.step(vec![], true, DVec3::ZERO) {
if let Op::Stop(i) = o {
open.remove(&i);
}
}
assert!(open.is_empty(), "every start was stopped");
}
}