Files
horizon-airdef/crates/horizon-client/src/mod_sources.rs
T

617 lines
22 KiB
Rust

//! Persistent sound sources for mods (AirDef fork, mod API level 20): sounds that go on, follow a
//! pose and have a lifetime, over the same mixer channels the rest of the game plays on.
//!
//! A source is a mixer channel with a smoothed voice (`Backend::voice_*`): gain, pan and pitch
//! ramp across each buffer, it fades in over its attack and out over its release, a loop can lay
//! its end over its start, and the position is carried along the velocity between two poses.
//! This module only decides *which* sources hold a channel: a budget of [`VOICES`], the loudest
//! near ones first (priority times what the listener would hear); the others stay virtual, alive
//! and silent, and get a voice when they rank again. A stop always works: it frees a channel or a
//! virtual entry at once, whatever the budget did.
use crate::sound_engine::{Backend, ChannelId, SoundEngine};
use crate::sound_events::{Sentinel, Sound};
use horizon_core::random::LegacyRandom;
use std::collections::BTreeMap;
/// Channels at most this many sources sound on at once.
pub const VOICES: usize = 24;
/// Faded-out channels kept until silent; past this a release is cut short (a stop is still done).
pub const RELEASING: usize = 24;
/// Below this loudness a source gets no voice.
const AUDIBLE: f32 = 0.002;
/// A source that holds a voice is kept against one that ranks this much higher.
const STICKY: f32 = 1.25;
/// A source's owner (the mod's run) and its id.
pub type Key = (u64, u32);
/// What a mod asked of a source.
#[derive(Clone, Debug, PartialEq)]
pub struct Params {
pub event: String,
pub at: [f64; 3],
pub velocity: [f32; 3],
pub gain: f32,
pub pitch: f32,
pub looping: bool,
pub priority: f32,
pub attack: f32,
pub release: f32,
pub doppler: f32,
pub loop_from: f32,
pub loop_to: f32,
}
/// One change, as the mod runtime's books give them.
#[derive(Clone, Debug, PartialEq)]
pub enum Change {
Start(Key, Params),
Update(Key, Params),
Stop(Key),
}
struct Source {
p: Params,
sound: Sound,
/// The sound's own volume and pitch factors, drawn once.
sound_volume: f32,
sound_pitch: f32,
channel: Option<ChannelId>,
}
/// The mod sources of a game.
#[derive(Default)]
pub struct ModSources {
sources: BTreeMap<Key, Source>,
releasing: Vec<ChannelId>,
/// Moves on whenever every source was released (the mods read it as the generation).
pub epoch: u32,
paused: bool,
/// Sources dropped for good: one-shots that found no voice (a count for `status`).
pub dropped: u32,
}
fn seed(key: Key, event: &str) -> i64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ key.0 ^ (u64::from(key.1) << 32);
for b in event.bytes() {
h = (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3);
}
h as i64
}
impl ModSources {
/// How many sources live, how many sound, how many fade out.
pub fn counts(&self) -> [usize; 3] {
let voiced = self.sources.values().filter(|s| s.channel.is_some()).count();
[self.sources.len(), voiced, self.releasing.len()]
}
/// The channels in use (voices and fading ones).
pub fn channels(&self) -> usize {
self.counts()[1] + self.releasing.len()
}
pub fn apply(
&mut self,
changes: Vec<Change>,
listener: [f64; 3],
engine: &SoundEngine,
backend: &mut impl Backend,
) {
// Stops first: nothing a budget does later can leave one undone.
let (stops, rest): (Vec<_>, Vec<_>) = changes
.into_iter()
.partition(|c| matches!(c, Change::Stop(_)));
for c in stops {
if let Change::Stop(key) = c {
self.stop(key, backend);
}
}
for c in rest {
match c {
Change::Start(key, p) => self.start(key, p, engine, backend),
Change::Update(key, p) => self.update(key, p, engine, backend),
Change::Stop(_) => {}
}
}
self.rebalance(listener, engine, backend);
}
fn start(&mut self, key: Key, p: Params, engine: &SoundEngine, backend: &mut impl Backend) {
// A restart: the old one releases first.
self.stop(key, backend);
if !engine.loaded {
return;
}
let event = crate::sound_events::normalize(&p.event);
let mut random = LegacyRandom::new(seed(key, &event));
let Some(sound) = engine.registry.sound(&event, &mut random) else {
return;
};
if sound.sentinel != Sentinel::None {
return;
}
let sound_volume = sound.volume.sample(&mut random);
let sound_pitch = sound.pitch.sample(&mut random);
self.sources.insert(
key,
Source {
p,
sound,
sound_volume,
sound_pitch,
channel: None,
},
);
}
fn update(&mut self, key: Key, mut p: Params, engine: &SoundEngine, backend: &mut impl Backend) {
let Some(s) = self.sources.get_mut(&key) else {
return;
};
p.event = std::mem::take(&mut s.p.event);
s.p = p;
if let Some(c) = s.channel {
Self::push(s, c, engine, backend);
}
}
/// Releases one source: a voice fades out over its release, a virtual one just goes.
pub fn stop(&mut self, key: Key, backend: &mut impl Backend) {
if let Some(s) = self.sources.remove(&key)
&& let Some(c) = s.channel
{
self.release(c, s.p.release, backend);
}
}
fn release(&mut self, channel: ChannelId, seconds: f32, backend: &mut impl Backend) {
if self.releasing.len() >= RELEASING {
// Cut short: the oldest fading channel goes at once, the stop still happens.
let old = self.releasing.remove(0);
backend.destroy(old);
}
backend.voice_release(channel, seconds);
self.releasing.push(channel);
}
/// Releases the sources of any run not in `runs` (a mod stopped or was reloaded).
pub fn retain_runs(&mut self, runs: &[u64], backend: &mut impl Backend) {
let gone: Vec<Key> = self
.sources
.keys()
.filter(|k| !runs.contains(&k.0))
.copied()
.collect();
for k in gone {
self.stop(k, backend);
}
}
/// Everything stops now (the world closed, a film began or ended, the sounds reloaded):
/// no fade, the channels are destroyed, and the generation moves on.
pub fn release_all(&mut self, backend: &mut impl Backend) {
for (_, s) in std::mem::take(&mut self.sources) {
if let Some(c) = s.channel {
backend.destroy(c);
}
}
for c in self.releasing.drain(..) {
backend.destroy(c);
}
self.epoch = self.epoch.wrapping_add(1);
}
pub fn pause(&mut self, backend: &mut impl Backend) {
self.paused = true;
for c in self.sources.values().filter_map(|s| s.channel) {
backend.pause(c);
}
for &c in &self.releasing {
backend.pause(c);
}
}
pub fn resume(&mut self, backend: &mut impl Backend) {
self.paused = false;
for c in self.sources.values().filter_map(|s| s.channel) {
backend.unpause(c);
}
for &c in &self.releasing {
backend.unpause(c);
}
}
fn volume(s: &Source, engine: &SoundEngine) -> f32 {
let category = crate::settings::sound_source(&s.p.event);
engine.calculate_volume(s.p.gain * s.sound_volume, category)
}
fn range(s: &Source) -> f32 {
s.sound.attenuation_distance(s.p.gain * s.sound_volume)
}
/// Sets everything a pose changes on the source's channel.
fn push(s: &Source, channel: ChannelId, engine: &SoundEngine, backend: &mut impl Backend) {
backend.set_pitch(
channel,
SoundEngine::calculate_pitch(s.p.pitch * s.sound_pitch),
);
backend.set_volume(channel, Self::volume(s, engine));
backend.set_attenuation(channel, Some(Self::range(s)));
backend.set_looping(channel, s.p.looping);
backend.set_position(channel, s.p.at);
backend.voice_pose(channel, s.p.velocity, s.p.doppler);
}
/// What the listener would hear of the source now, 0 to 1.
fn loudness(s: &Source, listener: [f64; 3], engine: &SoundEngine) -> f32 {
let d = [
s.p.at[0] - listener[0],
s.p.at[1] - listener[1],
s.p.at[2] - listener[2],
];
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32;
let range = Self::range(s);
if range <= 0.0 {
return 0.0;
}
Self::volume(s, engine) * (1.0 - distance.min(range) / range)
}
/// Once per tick: channels of finished or faded sources are given back, volumes follow the
/// sliders, and the budget is settled.
pub fn tick(&mut self, listener: [f64; 3], engine: &SoundEngine, backend: &mut impl Backend) {
let mut i = 0;
while i < self.releasing.len() {
if backend.stopped(self.releasing[i]) {
backend.destroy(self.releasing.remove(i));
} else {
i += 1;
}
}
// A source that is not looping ends by itself.
let ended: Vec<Key> = self
.sources
.iter()
.filter(|(_, s)| !s.p.looping && s.channel.is_some_and(|c| backend.stopped(c)))
.map(|(k, _)| *k)
.collect();
for k in ended {
if let Some(s) = self.sources.remove(&k)
&& let Some(c) = s.channel
{
backend.destroy(c);
}
}
for s in self.sources.values() {
if let Some(c) = s.channel {
backend.set_volume(c, Self::volume(s, engine));
}
}
self.rebalance(listener, engine, backend);
}
/// Gives the loudest sources the voices and takes them from the rest.
fn rebalance(&mut self, listener: [f64; 3], engine: &SoundEngine, backend: &mut impl Backend) {
let mut ranked: Vec<(f32, Key)> = self
.sources
.iter()
.filter_map(|(k, s)| {
let loud = Self::loudness(s, listener, engine);
(loud > AUDIBLE).then(|| {
let sticky = if s.channel.is_some() { STICKY } else { 1.0 };
(loud * s.p.priority * sticky, *k)
})
})
.collect();
// Loudest first; the key breaks ties, so the same input ranks the same way.
ranked.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
let winners: Vec<Key> = ranked.iter().take(VOICES).map(|(_, k)| *k).collect();
// Take voices from those that lost them: a virtual loop keeps living, a one-shot is gone.
let losers: Vec<Key> = self
.sources
.iter()
.filter(|(k, s)| s.channel.is_some() && !winners.contains(k))
.map(|(k, _)| *k)
.collect();
for k in losers {
let Some(s) = self.sources.get_mut(&k) else {
continue;
};
let (channel, release, looping) = (s.channel.take(), s.p.release.min(0.1), s.p.looping);
if let Some(c) = channel {
self.release(c, release, backend);
}
if !looping {
self.sources.remove(&k);
self.dropped += 1;
}
}
// And voices to the winners.
for k in winners {
let Some(s) = self.sources.get_mut(&k) else {
continue;
};
if s.channel.is_some() {
continue;
}
// A channel in the engine's pool is not needed; one more is made.
if self.releasing.len() + self.sources.values().filter(|s| s.channel.is_some()).count()
>= VOICES + RELEASING
{
break;
}
let Some(s) = self.sources.get_mut(&k) else {
continue;
};
let Some(channel) = backend.create(s.sound.stream) else {
continue;
};
Self::push(s, channel, engine, backend);
backend.set_relative(channel, false);
backend.voice_begin(channel, s.p.attack, s.p.loop_from, s.p.loop_to);
backend.voice_pose(channel, s.p.velocity, s.p.doppler);
backend.start(channel, &s.sound, s.p.looping);
if self.paused {
backend.pause(channel);
}
s.channel = Some(channel);
}
// One-shots that found no voice are never heard: forget them.
let mute: Vec<Key> = self
.sources
.iter()
.filter(|(_, s)| s.channel.is_none() && !s.p.looping)
.map(|(k, _)| *k)
.collect();
for k in mute {
self.sources.remove(&k);
self.dropped += 1;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sound_events::SoundRegistry;
use std::collections::HashMap;
/// A backend that records what the sources do to their channels.
#[derive(Default)]
struct Rec {
next: ChannelId,
live: HashMap<ChannelId, Chan>,
destroyed: u32,
}
#[derive(Default, Clone)]
struct Chan {
at: [f64; 3],
volume: f32,
looping: bool,
started: bool,
stopped: bool,
releasing: Option<f32>,
attack: f32,
}
impl Backend for Rec {
fn create(&mut self, _: bool) -> Option<ChannelId> {
self.next += 1;
self.live.insert(self.next, Chan::default());
Some(self.next)
}
fn destroy(&mut self, c: ChannelId) {
self.live.remove(&c);
self.destroyed += 1;
}
fn set_pitch(&mut self, _: ChannelId, _: f32) {}
fn set_volume(&mut self, c: ChannelId, v: f32) {
if let Some(c) = self.live.get_mut(&c) {
c.volume = v;
}
}
fn set_attenuation(&mut self, _: ChannelId, _: Option<f32>) {}
fn set_looping(&mut self, c: ChannelId, l: bool) {
if let Some(c) = self.live.get_mut(&c) {
c.looping = l;
}
}
fn set_position(&mut self, c: ChannelId, p: [f64; 3]) {
if let Some(c) = self.live.get_mut(&c) {
c.at = p;
}
}
fn set_relative(&mut self, _: ChannelId, _: bool) {}
fn start(&mut self, c: ChannelId, _: &Sound, _: bool) {
if let Some(c) = self.live.get_mut(&c) {
c.started = true;
}
}
fn stop(&mut self, c: ChannelId) {
if let Some(c) = self.live.get_mut(&c) {
c.stopped = true;
}
}
fn pause(&mut self, _: ChannelId) {}
fn unpause(&mut self, _: ChannelId) {}
fn stopped(&mut self, c: ChannelId) -> bool {
self.live.get(&c).is_none_or(|c| c.stopped)
}
fn voice_begin(&mut self, c: ChannelId, attack: f32, _: f32, _: f32) {
if let Some(c) = self.live.get_mut(&c) {
c.attack = attack;
}
}
fn voice_release(&mut self, c: ChannelId, release: f32) {
if let Some(c) = self.live.get_mut(&c) {
c.releasing = Some(release);
}
}
}
fn engine() -> SoundEngine {
let mut registry = SoundRegistry::default();
let json = br#"{"hum":{"sounds":[{"name":"t:hum","attenuation_distance":100}]},
"bang":{"sounds":[{"name":"t:bang","attenuation_distance":100}]}}"#;
registry.add_file("t", json, &|_, _| true);
SoundEngine::new(registry)
}
fn p(event: &str, x: f64, looping: bool) -> Params {
Params {
event: event.into(),
at: [x, 0.0, 0.0],
velocity: [0.0; 3],
gain: 1.0,
pitch: 1.0,
looping,
priority: 1.0,
attack: 0.1,
release: 0.2,
doppler: 0.0,
loop_from: 0.0,
loop_to: 0.0,
}
}
const ZERO: [f64; 3] = [0.0; 3];
#[test]
fn start_update_stop_follow_the_lifecycle() {
let (e, mut b, mut m) = (engine(), Rec::default(), ModSources::default());
m.apply(vec![Change::Start((1, 5), p("t:hum", 10.0, true))], ZERO, &e, &mut b);
assert_eq!(m.counts(), [1, 1, 0]);
let c = *b.live.keys().next().unwrap();
assert!(b.live[&c].started && b.live[&c].looping);
assert_eq!(b.live[&c].attack, 0.1);
m.apply(vec![Change::Update((1, 5), p("", 20.0, true))], ZERO, &e, &mut b);
assert_eq!(b.live[&c].at[0], 20.0);
// An update for an id that does not run (or another run's) changes nothing.
m.apply(vec![Change::Update((2, 5), p("", 99.0, true))], ZERO, &e, &mut b);
assert_eq!(b.live[&c].at[0], 20.0);
m.apply(vec![Change::Stop((1, 5))], ZERO, &e, &mut b);
assert_eq!(m.counts(), [0, 0, 1]);
assert_eq!(b.live[&c].releasing, Some(0.2));
// The faded channel is given back once silent.
b.stop(c);
m.tick(ZERO, &e, &mut b);
assert_eq!(m.counts(), [0, 0, 0]);
assert!(b.live.is_empty());
}
#[test]
fn a_stop_of_another_run_or_generation_touches_nothing() {
let (e, mut b, mut m) = (engine(), Rec::default(), ModSources::default());
m.apply(vec![Change::Start((1, 5), p("t:hum", 10.0, true))], ZERO, &e, &mut b);
m.apply(vec![Change::Stop((2, 5)), Change::Stop((1, 6))], ZERO, &e, &mut b);
assert_eq!(m.counts(), [1, 1, 0]);
}
#[test]
fn the_budget_keeps_the_loud_near_ones_and_virtualises_the_rest_without_losing_a_stop() {
let (e, mut b, mut m) = (engine(), Rec::default(), ModSources::default());
// 100 loops from 1 to 100 blocks: the budget gives voices to the nearest.
let starts = (0..100u32)
.map(|i| Change::Start((1, i), p("t:hum", f64::from(i) + 1.0, true)))
.collect();
m.apply(starts, ZERO, &e, &mut b);
let [all, voiced, _] = m.counts();
assert_eq!((all, voiced), (100, VOICES));
assert!(b.live.values().all(|c| c.at[0] <= VOICES as f64 + 0.5));
assert!(b.live.len() <= VOICES + RELEASING);
// The listener walks: the far ones win the voices, the near ones go virtual and live on.
m.tick([90.0, 0.0, 0.0], &e, &mut b);
assert_eq!(m.counts()[0], 100);
assert!(m.counts()[1] <= VOICES);
assert!(m.sources.iter().filter(|(_, s)| s.channel.is_some()).all(|(k, _)| k.1 > 60));
// Stopping all of them leaves nothing, voiced or virtual.
let stops = (0..100u32).map(|i| Change::Stop((1, i))).collect();
m.apply(stops, [90.0, 0.0, 0.0], &e, &mut b);
assert_eq!(m.counts()[0], 0);
for c in b.live.keys().copied().collect::<Vec<_>>() {
b.stop(c);
}
m.tick(ZERO, &e, &mut b);
assert!(b.live.is_empty(), "no voice outlives its source");
}
#[test]
fn a_one_shot_without_a_voice_is_forgotten_and_a_finished_one_gives_its_channel_back() {
let (e, mut b, mut m) = (engine(), Rec::default(), ModSources::default());
// Far beyond its range: never heard, so not kept.
m.apply(vec![Change::Start((1, 1), p("t:bang", 500.0, false))], ZERO, &e, &mut b);
assert_eq!(m.counts(), [0, 0, 0]);
m.apply(vec![Change::Start((1, 2), p("t:bang", 5.0, false))], ZERO, &e, &mut b);
assert_eq!(m.counts()[1], 1);
let c = *b.live.keys().next().unwrap();
b.stop(c);
m.tick(ZERO, &e, &mut b);
assert_eq!(m.counts(), [0, 0, 0]);
assert!(b.live.is_empty());
}
#[test]
fn release_all_frees_every_channel_and_moves_the_generation() {
let (e, mut b, mut m) = (engine(), Rec::default(), ModSources::default());
let starts = (0..30u32)
.map(|i| Change::Start((1, i), p("t:hum", 5.0, true)))
.collect();
m.apply(starts, ZERO, &e, &mut b);
m.apply(vec![Change::Stop((1, 0))], ZERO, &e, &mut b);
let epoch = m.epoch;
m.release_all(&mut b);
assert!(b.live.is_empty());
assert_eq!(m.counts(), [0, 0, 0]);
assert_eq!(m.epoch, epoch + 1);
}
#[test]
fn a_run_that_is_gone_loses_its_sources() {
let (e, mut b, mut m) = (engine(), Rec::default(), ModSources::default());
m.apply(
vec![
Change::Start((1, 1), p("t:hum", 5.0, true)),
Change::Start((2, 1), p("t:hum", 6.0, true)),
],
ZERO,
&e,
&mut b,
);
m.retain_runs(&[2], &mut b);
assert_eq!(m.counts()[0], 1);
assert!(m.sources.contains_key(&(2, 1)));
}
#[test]
fn a_hundred_start_seek_stop_cycles_accumulate_no_voices() {
let (e, mut b, mut m) = (engine(), Rec::default(), ModSources::default());
for round in 0..100u32 {
let starts = (0..8u32)
.map(|i| Change::Start((1, round * 8 + i), p("t:hum", f64::from(i) + 2.0, true)))
.collect();
m.apply(starts, ZERO, &e, &mut b);
// A seek: everything restarts under new ids, the old ones stop.
if round % 2 == 0 {
let stops = (0..8u32).map(|i| Change::Stop((1, round * 8 + i))).collect();
m.apply(stops, ZERO, &e, &mut b);
} else {
m.release_all(&mut b);
}
for c in b.live.keys().copied().collect::<Vec<_>>() {
if b.live[&c].releasing.is_some() {
b.stop(c);
}
}
m.tick(ZERO, &e, &mut b);
assert!(b.live.len() <= VOICES + RELEASING);
}
assert_eq!(m.counts(), [0, 0, 0]);
assert!(b.live.is_empty());
}
#[test]
fn a_restart_releases_the_old_voice_and_attacks_a_new_one() {
let (e, mut b, mut m) = (engine(), Rec::default(), ModSources::default());
m.apply(vec![Change::Start((1, 1), p("t:hum", 5.0, true))], ZERO, &e, &mut b);
m.apply(vec![Change::Start((1, 1), p("t:hum", 6.0, true))], ZERO, &e, &mut b);
assert_eq!(m.counts(), [1, 1, 1]);
}
}