Play every sound through the vanilla SoundEngine model

Audio now keeps vanilla SoundEngine bookkeeping over a mixer that stands in
for OpenAL sources (gain, pitch, linear distance attenuation, looping,
relative, source states, the 247/8 channel pools), ticks once per client
tick with pauseAllExcept/resume and stops everything when the world closes.
MusicManager holds a forMusic instance and checks isActive as vanilla does;
the ambient handlers play LoopSoundInstance, UnderLiquid* and mood instances,
the enter/exit sounds seeded from the level random; jukebox songs use
forJukeboxSong instead of a hand-made volume ramp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 21:44:58 +02:00
parent d68efbabfc
commit ccdf49d3e5
8 changed files with 892 additions and 867 deletions
+176 -254
View File
@@ -1,7 +1,9 @@
//! The player's ambient sound handlers: `BiomeAmbientSoundsHandler` (biome
//! loops with 40-tick cross-fades, random additions, cave mood) driven by the
//! `minecraft:audio/ambient_sounds` attribute, `UnderwaterAmbientSoundHandler`
//! and the underwater loop (`UnderLiquidAmbientSoundInstance`).
//! and `LocalPlayer.updateIsUnderwater` (enter/exit sounds and the
//! `UnderLiquidAmbientSoundInstance` loop), played through the sound engine.
use crate::sound_engine::{AMBIENT, InstanceId, SoundEngine, SoundInstance, Sounds};
use horizon_core::random::{LegacyRandom, RandomSource};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
@@ -80,87 +82,35 @@ impl AmbientTables {
.unwrap_or_default()
}
}
/// The sound engine side of the handlers.
pub trait AmbientOutput {
/// A relative tickable instance; None when it could not start.
fn play_tracked(&mut self, event: &str, volume: f32, looping: bool) -> Option<u64>;
fn set_volume(&mut self, id: u64, volume: f32);
fn stop(&mut self, id: u64);
fn is_active(&self, id: u64) -> bool;
/// A positional one-shot (`SimpleSoundInstance`, linear attenuation).
fn play_at(&mut self, event: &str, at: [f64; 3]);
}
impl AmbientOutput for crate::audio::Audio {
fn play_tracked(&mut self, event: &str, volume: f32, looping: bool) -> Option<u64> {
crate::audio::Audio::play_tracked(self, event, volume, looping)
}
fn set_volume(&mut self, id: u64, volume: f32) {
self.set_tracked_volume(id, volume);
}
fn stop(&mut self, id: u64) {
self.stop_tracked(id);
}
fn is_active(&self, id: u64) -> bool {
self.tracked_active(id)
}
fn play_at(&mut self, event: &str, at: [f64; 3]) {
self.play(event, Some(at), 1.0, 1.0);
}
}
/// `BiomeAmbientSoundsHandler.LoopSoundInstance`.
struct LoopSound {
id: Option<u64>,
fade: i32,
direction: i32,
stopped: bool,
}
impl LoopSound {
fn tick(&mut self) -> f32 {
if self.fade < 0 {
self.stopped = true;
}
self.fade += self.direction;
(self.fade as f32 / 40.0).clamp(0.0, 1.0)
}
fn fade_out(&mut self) {
self.fade = self.fade.min(40);
self.direction = -1;
}
fn fade_in(&mut self) {
self.fade = self.fade.max(0);
self.direction = 1;
}
}
/// What the handlers read about the player and level each tick.
pub struct AmbientContext<'a> {
/// `AMBIENT_SOUNDS` at the player's position.
pub sounds: &'a AmbientSounds,
/// Feet and eye position.
/// The player's position (feet) and eye height.
pub position: [f64; 3],
pub eye_y: f64,
/// `isEyeInFluid(WATER)` this tick (`Entity.updateIsUnderwater`).
pub underwater: bool,
/// Raw (sky, block) light at a block.
pub spectator: bool,
/// `Level.getBrightness` (sky, block) at a block.
pub light: &'a dyn Fn([i32; 3]) -> (u8, u8),
}
/// The local player's ambient sound handlers.
pub struct Ambience {
/// The client level's random.
random: LegacyRandom,
loops: Vec<(String, LoopSound)>,
pub random: LegacyRandom,
/// `BiomeAmbientSoundsHandler.loopSounds` (insertion order).
loops: Vec<(String, InstanceId)>,
previous_loop: Option<String>,
pub moodiness: f32,
/// `UnderwaterAmbientSoundHandler.tickDelay`.
underwater_delay: i32,
/// The underwater loop instance and its fade.
underwater_loop: Option<(u64, i32)>,
/// UnderLiquidSubSound instances (stop when the player leaves the water).
sub_sounds: Vec<u64>,
/// `LocalPlayer.wasUnderwater`.
was_underwater: bool,
}
impl Default for Ambience {
fn default() -> Self {
let seed = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos() as i64);
Self::new(seed)
Self::new(crate::sound_engine::unique_seed())
}
}
impl Ambience {
@@ -171,53 +121,54 @@ impl Ambience {
previous_loop: None,
moodiness: 0.0,
underwater_delay: 0,
underwater_loop: None,
sub_sounds: Vec::new(),
was_underwater: false,
}
}
/// Stop everything (leaving the world).
pub fn clear(&mut self, out: &mut impl AmbientOutput) {
for (_, l) in self.loops.drain(..) {
if let Some(id) = l.id {
out.stop(id);
}
}
if let Some((id, _)) = self.underwater_loop.take() {
out.stop(id);
}
for id in self.sub_sounds.drain(..) {
out.stop(id);
/// `LocalPlayer.isUnderWater`.
pub fn was_underwater(&self) -> bool {
self.was_underwater
}
/// A new player (leaving or changing worlds): fresh handlers.
pub fn clear(&mut self, sounds: &mut impl Sounds) {
for (_, id) in self.loops.drain(..) {
sounds.release(id);
}
self.previous_loop = None;
self.moodiness = 0.0;
self.underwater_delay = 0;
self.was_underwater = false;
}
/// `LocalPlayer.updateIsUnderwater` enter/exit sounds and loop, then
/// `UnderwaterAmbientSoundHandler`, `BubbleColumn` (absent) and
/// `BiomeAmbientSoundsHandler` ticks, then the tickable instances.
pub fn tick(&mut self, ctx: &AmbientContext, out: &mut impl AmbientOutput) {
let feet = ctx.position;
if !self.was_underwater && ctx.underwater {
out.play_at("minecraft:ambient.underwater.enter", feet);
if let Some((id, _)) = self.underwater_loop.take() {
out.stop(id);
}
self.underwater_loop = out
.play_tracked("minecraft:ambient.underwater.loop", 0.0, true)
.map(|id| (id, 0));
}
if self.was_underwater && !ctx.underwater {
out.play_at("minecraft:ambient.underwater.exit", feet);
}
self.was_underwater = ctx.underwater;
self.tick_underwater(ctx, out);
self.tick_biome(ctx, out);
self.tick_instances(ctx, out);
/// `ClientLevel.playLocalSound(x, y, z, sound, AMBIENT, 1, 1, false)`.
fn play_local(&mut self, event: &str, at: [f64; 3], sounds: &mut impl Sounds) {
let seed = self.random.next_long();
let instance = SoundInstance::at(event, AMBIENT, 1.0, 1.0, LegacyRandom::new(seed), at);
sounds.play_instance(instance, false);
}
fn tick_underwater(&mut self, ctx: &AmbientContext, out: &mut impl AmbientOutput) {
/// `LocalPlayer.updateIsUnderwater`, then the `ambientSoundHandlers`
/// (underwater, bubble column, biome) as `LocalPlayer.tick` runs them.
pub fn tick(&mut self, ctx: &AmbientContext, sounds: &mut impl Sounds) {
let old = self.was_underwater;
self.was_underwater = ctx.underwater;
if !ctx.spectator {
if !old && ctx.underwater {
self.play_local("minecraft:ambient.underwater.enter", ctx.position, sounds);
let instance = SoundInstance::under_liquid_loop(
"minecraft:ambient.underwater.loop",
SoundEngine::unseeded(),
);
sounds.play_instance(instance, false);
}
if old && !ctx.underwater {
self.play_local("minecraft:ambient.underwater.exit", ctx.position, sounds);
}
}
self.tick_underwater(sounds);
self.tick_biome(ctx, sounds);
}
/// `UnderwaterAmbientSoundHandler.tick`.
fn tick_underwater(&mut self, sounds: &mut impl Sounds) {
self.underwater_delay -= 1;
if self.underwater_delay <= 0 && ctx.underwater {
if self.underwater_delay <= 0 && self.was_underwater {
let rand = self.random.next_float();
let sound = if rand < 1.0E-4 {
Some("minecraft:ambient.underwater.loop.additions.ultra_rare")
@@ -230,147 +181,121 @@ impl Ambience {
};
if let Some(sound) = sound {
self.underwater_delay = 0;
if let Some(id) = out.play_tracked(sound, 1.0, false) {
self.sub_sounds.push(id);
}
let instance = SoundInstance::under_liquid_sub(sound, SoundEngine::unseeded());
sounds.play_instance(instance, false);
}
}
}
fn tick_biome(&mut self, ctx: &AmbientContext, out: &mut impl AmbientOutput) {
self.loops.retain(|(_, l)| !l.stopped);
let sounds = ctx.sounds;
if sounds.r#loop != self.previous_loop {
self.previous_loop = sounds.r#loop.clone();
for (_, l) in &mut self.loops {
l.fade_out();
/// `BiomeAmbientSoundsHandler.tick`.
fn tick_biome(&mut self, ctx: &AmbientContext, sounds: &mut impl Sounds) {
let mut kept = Vec::new();
for (event, id) in std::mem::take(&mut self.loops) {
if sounds.engine().instance(id).is_some_and(|i| i.stopped) {
sounds.release(id);
} else {
kept.push((event, id));
}
if let Some(event) = &sounds.r#loop {
if !self.loops.iter().any(|(e, _)| e == event) {
let id = out.play_tracked(event, 0.0, true);
self.loops.push((
event.clone(),
LoopSound {
id,
fade: 0,
direction: 0,
stopped: false,
},
));
}
self.loops = kept;
let current = ctx
.sounds
.r#loop
.as_deref()
.map(crate::sound_events::normalize);
if current != self.previous_loop {
self.previous_loop = current.clone();
for (_, id) in &self.loops {
if let Some(i) = sounds.engine().instance_mut(*id) {
i.fade_out();
}
if let Some((_, l)) = self.loops.iter_mut().find(|(e, _)| e == event) {
l.fade_in();
}
if let Some(event) = current {
let id = match self.loops.iter().find(|(e, _)| *e == event) {
Some((_, id)) => *id,
None => {
let instance = SoundInstance::biome_loop(&event, SoundEngine::unseeded());
let id = sounds.engine().add(instance, true);
sounds.play_id(id);
self.loops.push((event, id));
id
}
};
if let Some(i) = sounds.engine().instance_mut(id) {
i.fade_in();
}
}
}
for (sound, chance) in &sounds.additions {
if self.random.next_double() < *chance
&& let Some(id) = out.play_tracked(sound, 1.0, false)
{
// forAmbientAddition: a one-shot nobody ticks.
let _ = id;
for (sound, chance) in &ctx.sounds.additions {
if self.random.next_double() < *chance {
let event = crate::sound_events::normalize(sound);
let instance = SoundInstance::for_ambient_addition(&event, SoundEngine::unseeded());
sounds.play_instance(instance, false);
}
}
let Some(mood) = &sounds.mood else { return };
let Some(mood) = &ctx.sounds.mood else { return };
let extent = mood.block_search_extent;
let span = extent * 2 + 1;
let mut offset = || self.random.next_int_bound(span).unwrap_or(0) - extent;
let (dx, dy, dz) = (offset(), offset(), offset());
let sample = [
(ctx.position[0] + f64::from(dx)).floor() as i32,
(ctx.eye_y + f64::from(dy)).floor() as i32,
(ctx.position[2] + f64::from(dz)).floor() as i32,
];
let x = ctx.position[0] + f64::from(self.random.next_int_bound(span).unwrap_or(0))
- f64::from(extent);
let y = ctx.eye_y + f64::from(self.random.next_int_bound(span).unwrap_or(0))
- f64::from(extent);
let z = ctx.position[2] + f64::from(self.random.next_int_bound(span).unwrap_or(0))
- f64::from(extent);
let sample = [x.floor() as i32, y.floor() as i32, z.floor() as i32];
let (sky, block) = (ctx.light)(sample);
if sky > 0 {
self.moodiness -= f32::from(sky) / 15.0 * 0.001;
} else {
self.moodiness -= (f32::from(block) - 1.0) / mood.tick_delay as f32;
self.moodiness -= (i32::from(block) - 1) as f32 / mood.tick_delay as f32;
}
if self.moodiness >= 1.0 {
let d = [
f64::from(sample[0]) + 0.5 - ctx.position[0],
f64::from(sample[1]) + 0.5 - ctx.eye_y,
f64::from(sample[2]) + 0.5 - ctx.position[2],
];
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
let sample_x = f64::from(sample[0]) + 0.5;
let sample_y = f64::from(sample[1]) + 0.5;
let sample_z = f64::from(sample[2]) + 0.5;
let dx = sample_x - ctx.position[0];
let dy = sample_y - ctx.eye_y;
let dz = sample_z - ctx.position[2];
let distance = (dx * dx + dy * dy + dz * dz).sqrt();
let source = distance + mood.offset;
out.play_at(
&mood.sound,
[
ctx.position[0] + d[0] / distance * source,
ctx.eye_y + d[1] / distance * source,
ctx.position[2] + d[2] / distance * source,
],
);
let at = [
ctx.position[0] + dx / distance * source,
ctx.eye_y + dy / distance * source,
ctx.position[2] + dz / distance * source,
];
// The mood sound draws from the level random itself.
let event = crate::sound_events::normalize(&mood.sound);
let instance = SoundInstance::for_ambient_mood(&event, self.random.clone(), at);
let id = sounds.engine().add(instance, true);
sounds.play_id(id);
if let Some(i) = sounds.engine().instance(id) {
self.random = i.random.clone();
}
sounds.release(id);
self.moodiness = 0.0;
} else {
self.moodiness = self.moodiness.max(0.0);
}
}
/// The tickable instances' own ticks (SoundEngine.tickInGameSound).
fn tick_instances(&mut self, ctx: &AmbientContext, out: &mut impl AmbientOutput) {
for (_, l) in &mut self.loops {
let volume = l.tick();
if let Some(id) = l.id {
if l.stopped {
out.stop(id);
} else {
out.set_volume(id, volume);
}
}
}
// UnderLiquidAmbientSoundInstance: +1 per tick under water, -2 out of it.
if let Some((id, fade)) = self.underwater_loop.as_mut() {
if *fade >= 0 {
*fade += if ctx.underwater { 1 } else { -2 };
*fade = (*fade).min(40);
out.set_volume(*id, (*fade as f32 / 40.0).clamp(0.0, 1.0));
} else {
out.stop(*id);
self.underwater_loop = None;
}
}
// UnderLiquidSubSound: stops when the player leaves the water.
self.sub_sounds.retain(|&id| {
let keep = ctx.underwater && out.is_active(id);
if !keep {
out.stop(id);
}
keep
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sound_engine::{Bound, TickContext, test_backend::Null};
use crate::sound_events::SoundRegistry;
#[derive(Default)]
struct Fake {
next: u64,
live: HashMap<u64, (String, f32)>,
at: Vec<String>,
}
impl AmbientOutput for Fake {
fn play_tracked(&mut self, event: &str, volume: f32, _looping: bool) -> Option<u64> {
self.next += 1;
self.live.insert(self.next, (event.to_owned(), volume));
Some(self.next)
}
fn set_volume(&mut self, id: u64, volume: f32) {
if let Some(v) = self.live.get_mut(&id) {
v.1 = volume;
}
}
fn stop(&mut self, id: u64) {
self.live.remove(&id);
}
fn is_active(&self, id: u64) -> bool {
self.live.contains_key(&id)
}
fn play_at(&mut self, event: &str, _at: [f64; 3]) {
self.at.push(event.to_owned());
}
fn engine() -> SoundEngine {
let mut registry = SoundRegistry::default();
registry.add_file(
"minecraft",
br#"{"crimson": {"sounds": ["c"]}, "warped": {"sounds": ["w"]},
"ambient.cave": {"sounds": ["a", "b"]},
"ambient.underwater.loop": {"sounds": ["u"]},
"ambient.underwater.enter": {"sounds": ["e"]},
"ambient.underwater.exit": {"sounds": ["x"]}}"#,
&|_, _| true,
);
SoundEngine::new(registry)
}
fn ctx<'a>(
sounds: &'a AmbientSounds,
@@ -382,49 +307,58 @@ mod tests {
position: [0.5, 10.0, 0.5],
eye_y: 11.62,
underwater,
spectator: false,
light,
}
}
#[test]
fn loops_cross_fade_over_forty_ticks() {
let (mut engine, mut backend) = (engine(), Null::default());
let mut a = Ambience::new(1);
let mut out = Fake::default();
let dark = |_: [i32; 3]| (15u8, 0u8);
let lit = |_: [i32; 3]| (15u8, 0u8);
let crimson = AmbientSounds {
r#loop: Some("crimson".into()),
r#loop: Some("minecraft:crimson".into()),
..Default::default()
};
for _ in 0..40 {
a.tick(&ctx(&crimson, false, &dark), &mut out);
}
assert_eq!(out.live.values().map(|v| v.1).collect::<Vec<_>>(), [1.0]);
let warped = AmbientSounds {
r#loop: Some("warped".into()),
r#loop: Some("minecraft:warped".into()),
..Default::default()
};
let tick =
|a: &mut Ambience, s: &AmbientSounds, engine: &mut SoundEngine, backend: &mut Null| {
a.tick(
&ctx(s, false, &lit),
&mut Bound {
engine: &mut *engine,
backend: &mut *backend,
},
);
engine.tick(false, &TickContext::default(), backend);
};
for _ in 0..40 {
tick(&mut a, &crimson, &mut engine, &mut backend);
}
for _ in 0..20 {
a.tick(&ctx(&warped, false, &dark), &mut out);
tick(&mut a, &warped, &mut engine, &mut backend);
}
let mut volumes: Vec<_> = out.live.values().map(|v| (v.0.clone(), v.1)).collect();
volumes.sort_by(|x, y| x.0.cmp(&y.0));
assert_eq!(
volumes,
[("crimson".to_owned(), 0.5), ("warped".to_owned(), 0.5)]
);
let volumes: Vec<f32> = a
.loops
.iter()
.map(|(_, id)| engine.instance(*id).unwrap().volume)
.collect();
assert_eq!(volumes, [0.5, 0.5]);
for _ in 0..30 {
a.tick(&ctx(&warped, false, &dark), &mut out);
tick(&mut a, &warped, &mut engine, &mut backend);
}
assert_eq!(
out.live.values().map(|v| v.0.as_str()).collect::<Vec<_>>(),
["warped"]
);
assert_eq!(a.loops.len(), 1);
}
#[test]
fn mood_builds_in_the_dark_and_plays_a_cave_sound() {
let (mut engine, mut backend) = (engine(), Null::default());
engine.listening = true;
let mut a = Ambience::new(2);
let mut out = Fake::default();
let cave = |_: [i32; 3]| (0u8, 0u8);
let sounds = AmbientSounds {
mood: Some(Mood {
@@ -435,31 +369,19 @@ mod tests {
}),
..Default::default()
};
// Block light 0: +1/6000 per tick (float), so the sound plays around tick 6000.
let mut ticks = 0;
while out.at.is_empty() && ticks < 7000 {
a.tick(&ctx(&sounds, false, &cave), &mut out);
while engine.notifications.is_empty() && ticks < 7000 {
a.tick(
&ctx(&sounds, false, &cave),
&mut Bound {
engine: &mut engine,
backend: &mut backend,
},
);
ticks += 1;
}
assert!((5990..=6010).contains(&ticks), "{ticks}");
assert_eq!(out.at, ["minecraft:ambient.cave"]);
assert_eq!(engine.notifications[0].identifier, "minecraft:ambient.cave");
assert_eq!(a.moodiness, 0.0);
}
#[test]
fn entering_water_plays_enter_and_fades_the_loop_in() {
let mut a = Ambience::new(3);
let mut out = Fake::default();
let lit = |_: [i32; 3]| (15u8, 0u8);
let none = AmbientSounds::default();
a.tick(&ctx(&none, true, &lit), &mut out);
assert_eq!(out.at, ["minecraft:ambient.underwater.enter"]);
let id = a.underwater_loop.unwrap().0;
assert_eq!(out.live[&id].1, 1.0 / 40.0);
a.tick(&ctx(&none, false, &lit), &mut out);
assert_eq!(out.at.last().unwrap(), "minecraft:ambient.underwater.exit");
// Fade 1 -> -1 stops on the next tick.
a.tick(&ctx(&none, false, &lit), &mut out);
assert!(!out.live.contains_key(&id));
}
}
+407 -440
View File
@@ -1,9 +1,16 @@
//! Sound playback: `sounds.json` events with weighted variants, Ogg/Vorbis
//! decoding, and a small mixer with vanilla's linear distance attenuation
//! (`SoundInstance.Attenuation.LINEAR`, default range 16 blocks) and stereo panning.
//! Sound playback: vanilla's `SoundEngine` bookkeeping (`sound_engine`) over a
//! small mixer standing in for OpenAL: one channel per source with its gain,
//! pitch, linear distance attenuation (`AL_LINEAR_DISTANCE`, reference 0,
//! rolloff 1), looping, relative flag and source state, Ogg/Vorbis decoding
//! (streams on a worker thread) and stereo panning.
use crate::Result;
use crate::sound_engine::{
Attenuation, Backend, Bound, ChannelId, InstanceId, PlayResult, SoundEngine, SoundInstance,
Sounds, TickContext,
};
use crate::sound_events::{Sound, SoundRegistry};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use serde_json::Value;
use horizon_core::random::{LegacyRandom, RandomSource};
use std::{
collections::HashMap,
fs,
@@ -11,46 +18,32 @@ use std::{
sync::{Arc, Mutex},
};
#[derive(Clone, Debug)]
struct Variant {
name: String,
volume: f32,
pitch: f32,
weight: u32,
attenuation: f32,
is_event: bool,
/// An OpenAL source's state.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum State {
Initial,
Playing,
Paused,
Stopped,
}
struct Voice {
samples: Arc<Vec<f32>>,
/// An OpenAL source.
struct Channel {
samples: Option<(Arc<Vec<f32>>, u32)>,
position: f64,
step: f64,
left: f32,
right: f32,
/// The sound event and `SoundSource` index (what `/stopsound` matches).
event: Arc<str>,
source: usize,
state: State,
gain: f32,
pitch: f32,
/// `AL_LINEAR_DISTANCE` max distance, or no attenuation.
linear: Option<f32>,
looping: bool,
at: [f32; 3],
relative: bool,
}
#[derive(Default)]
struct Mixer {
voices: Vec<Voice>,
/// The streaming music track (`SoundSource.MUSIC`), kept apart from the
/// voice cap and scaled by `music_gain` (MusicManager's fade).
music: Option<Voice>,
music_gain: f32,
/// Tickable sound instances the game keeps a handle to (ambient loops).
tracked: Vec<Tracked>,
}
struct Tracked {
id: u64,
voice: Voice,
looping: bool,
volume: f32,
}
/// The current music track: decoding on a worker until the voice exists.
struct MusicTrack {
event: String,
/// Set by the decoder thread once the voice is in the mixer (or failed).
ready: Arc<std::sync::atomic::AtomicBool>,
channels: HashMap<ChannelId, Channel>,
listener: [f64; 3],
listener_yaw: f32,
}
/// A sound the player could have heard (`SoundEventListener.onPlaySound`):
/// what the subtitle overlay needs.
@@ -58,30 +51,31 @@ struct MusicTrack {
pub struct Heard {
/// The `subtitle` translation key of the sound event.
pub subtitle: String,
/// Where it played (None = relative to the listener, e.g. UI sounds).
/// The instance's position (relative sounds report their raw coordinates).
pub at: Option<[f64; 3]>,
/// `SoundEngine.getRange`: infinite for relative and non-attenuated sounds.
pub range: f32,
pub looping: bool,
}
/// The mixer side of the engine (`Backend`).
pub struct MixerBackend {
mixer: Arc<Mutex<Mixer>>,
root: PathBuf,
cache: HashMap<String, Option<(Arc<Vec<f32>>, u32)>>,
next: ChannelId,
live: bool,
}
pub struct Audio {
_stream: Option<cpal::Stream>,
/// `subtitle` keys of `sounds.json` events.
subtitles: HashMap<String, String>,
pub engine: SoundEngine,
backend: MixerBackend,
/// Record `Heard` sounds (the subtitle overlay is listening).
pub record_heard: bool,
heard: Vec<Heard>,
mixer: Arc<Mutex<Mixer>>,
rate: u32,
root: PathBuf,
events: HashMap<String, Vec<Variant>>,
cache: HashMap<String, Option<(Arc<Vec<f32>>, u32)>>,
seed: u64,
pub listener: [f64; 3],
pub listener_yaw: f32,
pub master: f32,
music: Option<MusicTrack>,
next_tracked: u64,
/// Seeds of positional plays (the client level random's `nextLong`).
random: LegacyRandom,
/// A `SoundSource` index the next sound plays on (`/playsound`).
source_override: Option<usize>,
/// Positional sounds played since the last drain, kept while the world
@@ -130,75 +124,242 @@ fn decode(path: &Path) -> Option<(Vec<f32>, u32)> {
}
Some((mono, rate))
}
impl Audio {
pub fn new(root: &Path) -> Self {
let mut events = HashMap::new();
let mut subtitles = HashMap::new();
if let Ok(text) = fs::read(root.join("assets/minecraft/sounds.json"))
&& let Ok(Value::Object(map)) = serde_json::from_slice::<Value>(&text)
impl MixerBackend {
fn with(&self, channel: ChannelId, f: impl FnOnce(&mut Channel)) {
if let Ok(mut m) = self.mixer.lock()
&& let Some(c) = m.channels.get_mut(&channel)
{
for (name, def) in map {
let variants = def["sounds"]
.as_array()
.into_iter()
.flatten()
.map(|s| match s {
Value::String(n) => Variant {
name: n.clone(),
volume: 1.0,
pitch: 1.0,
weight: 1,
attenuation: 16.0,
is_event: false,
},
_ => Variant {
name: s["name"].as_str().unwrap_or("").to_owned(),
volume: s["volume"].as_f64().unwrap_or(1.0) as f32,
pitch: s["pitch"].as_f64().unwrap_or(1.0) as f32,
weight: s["weight"].as_u64().unwrap_or(1) as u32,
attenuation: s["attenuation_distance"].as_f64().unwrap_or(16.0) as f32,
is_event: s["type"].as_str() == Some("event"),
},
})
.collect::<Vec<_>>();
if let Some(key) = def["subtitle"].as_str() {
subtitles.insert(format!("minecraft:{name}"), key.to_owned());
}
events.insert(format!("minecraft:{name}"), variants);
}
f(c);
}
let mixer = Arc::new(Mutex::new(Mixer {
music_gain: 1.0,
..Mixer::default()
}));
let (stream, rate) = match Self::open(mixer.clone()) {
Ok(v) => (Some(v.0), v.1),
Err(e) => {
eprintln!("Horizon: audio unavailable: {e}");
(None, 48_000)
}
}
impl Backend for MixerBackend {
fn create(&mut self, _streaming: bool) -> Option<ChannelId> {
self.next += 1;
let id = self.next;
self.mixer.lock().ok()?.channels.insert(
id,
Channel {
samples: None,
position: 0.0,
state: State::Initial,
gain: 1.0,
pitch: 1.0,
linear: None,
looping: false,
at: [0.0; 3],
relative: false,
},
);
Some(id)
}
fn destroy(&mut self, channel: ChannelId) {
if let Ok(mut m) = self.mixer.lock() {
m.channels.remove(&channel);
}
}
fn set_pitch(&mut self, channel: ChannelId, pitch: f32) {
self.with(channel, |c| c.pitch = pitch);
}
fn set_volume(&mut self, channel: ChannelId, volume: f32) {
self.with(channel, |c| c.gain = volume);
}
fn set_attenuation(&mut self, channel: ChannelId, linear: Option<f32>) {
self.with(channel, |c| c.linear = linear);
}
fn set_looping(&mut self, channel: ChannelId, looping: bool) {
self.with(channel, |c| c.looping = looping);
}
fn set_position(&mut self, channel: ChannelId, p: [f64; 3]) {
self.with(channel, |c| c.at = [p[0] as f32, p[1] as f32, p[2] as f32]);
}
fn set_relative(&mut self, channel: ChannelId, relative: bool) {
self.with(channel, |c| c.relative = relative);
}
/// `getCompleteBuffer` (decoded now, cached) or `getStream` (decoded on a
/// worker), then attach and `alSourcePlay`. A sound that cannot load
/// leaves its source initial, as a failed buffer future does in vanilla.
fn start(&mut self, channel: ChannelId, sound: &Sound, looping: bool) {
if !self.live {
return;
}
let (namespace, path) = sound.path();
let file = self.root.join("assets").join(namespace).join(&path);
let attach = move |mixer: &Mutex<Mixer>, samples: Option<(Arc<Vec<f32>>, u32)>| {
if let Some(samples) = samples
&& let Ok(mut m) = mixer.lock()
&& let Some(c) = m.channels.get_mut(&channel)
{
c.samples = Some(samples);
c.position = 0.0;
c.state = State::Playing;
}
};
if sound.stream {
// A streamed sound loops by restarting its stream.
let mixer = self.mixer.clone();
std::thread::spawn(move || {
let samples = decode(&file).map(|(s, r)| (Arc::new(s), r));
if looping
&& let Ok(mut m) = mixer.lock()
&& let Some(c) = m.channels.get_mut(&channel)
{
c.looping = true;
}
attach(&mixer, samples);
});
} else {
let samples = self
.cache
.entry(format!("{namespace}:{path}"))
.or_insert_with(|| decode(&file).map(|(s, r)| (Arc::new(s), r)))
.clone();
attach(&self.mixer, samples);
}
}
fn stop(&mut self, channel: ChannelId) {
self.with(channel, |c| {
if c.state != State::Initial {
c.state = State::Stopped;
}
});
}
fn pause(&mut self, channel: ChannelId) {
self.with(channel, |c| {
if c.state == State::Playing {
c.state = State::Paused;
}
});
}
fn unpause(&mut self, channel: ChannelId) {
self.with(channel, |c| {
if c.state == State::Paused {
c.state = State::Playing;
}
});
}
fn stopped(&mut self, channel: ChannelId) -> bool {
self.mixer
.lock()
.map(|m| {
m.channels
.get(&channel)
.is_none_or(|c| c.state == State::Stopped)
})
.unwrap_or(true)
}
}
/// The gain OpenAL applies for distance (`AL_LINEAR_DISTANCE` with reference
/// distance 0 and rolloff 1: the distance clamps to the max distance).
fn distance_gain(linear: Option<f32>, distance: f32) -> f32 {
match linear {
None => 1.0,
Some(max) if max > 0.0 => (1.0 - distance.min(max) / max).clamp(0.0, 1.0),
Some(_) => 0.0,
}
}
fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
data.fill(0.0);
let listener = mixer.listener;
let yaw = mixer.listener_yaw.to_radians();
// Gains and pans per source for this buffer.
let mut voices: Vec<(ChannelId, f32, f32, f64)> = Vec::new();
for (id, c) in &mixer.channels {
let Some((_, source_rate)) = &c.samples else {
continue;
};
if c.state != State::Playing {
continue;
}
let d = if c.relative {
[f64::from(c.at[0]), f64::from(c.at[1]), f64::from(c.at[2])]
} else {
[
f64::from(c.at[0]) - listener[0],
f64::from(c.at[1]) - listener[1],
f64::from(c.at[2]) - listener[2],
]
};
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32;
let gain = c.gain.clamp(0.0, 1.0) * distance_gain(c.linear, distance);
// The listener's right vector for a Minecraft yaw.
let side = if c.relative {
(d[0] as f32) / distance.max(0.001)
} else {
(-(yaw.cos()) as f64 * d[0] - (yaw.sin()) as f64 * d[2]) as f32 / distance.max(0.001)
};
let pan = side.clamp(-1.0, 1.0);
let left = gain * (1.0 - pan.max(0.0) * 0.6);
let right = gain * (1.0 + pan.min(0.0) * 0.6);
let step = f64::from(*source_rate) / f64::from(rate) * f64::from(c.pitch.max(0.0));
voices.push((*id, left, right, step));
}
for (id, left, right, step) in voices {
let Some(c) = mixer.channels.get_mut(&id) else {
continue;
};
let Some((samples, _)) = c.samples.clone() else {
continue;
};
for frame in data.chunks_mut(channels) {
let mut i = c.position as usize;
if i + 1 >= samples.len() {
if c.looping && samples.len() > 1 {
c.position = 0.0;
i = 0;
} else {
c.state = State::Stopped;
break;
}
}
let t = (c.position - i as f64) as f32;
let s = samples[i] * (1.0 - t) + samples[i + 1] * t;
if channels >= 2 {
frame[0] += s * left;
frame[1] += s * right;
} else {
frame[0] += s * (left + right) / 2.0;
}
c.position += step;
}
}
for s in data.iter_mut() {
*s = s.clamp(-1.0, 1.0);
}
}
impl Audio {
pub fn new(root: &Path) -> Self {
let registry = SoundRegistry::load(root);
let mixer = Arc::new(Mutex::new(Mixer::default()));
let (stream, live) = match Self::open(mixer.clone()) {
Ok(v) => (Some(v), true),
Err(e) => {
eprintln!("Horizon: audio unavailable: {e}");
(None, false)
}
};
let mut engine = SoundEngine::new(registry);
engine.loaded = live;
Self {
_stream: stream,
subtitles,
engine,
backend: MixerBackend {
mixer,
root: root.to_owned(),
cache: HashMap::new(),
next: 0,
live,
},
record_heard: false,
heard: Vec::new(),
mixer,
rate,
root: root.to_owned(),
events,
cache: HashMap::new(),
seed: 0x5DEE_CE66,
listener: [0.0; 3],
listener_yaw: 0.0,
master: 1.0,
music: None,
next_tracked: 0,
random: LegacyRandom::new(crate::sound_engine::unique_seed()),
source_override: None,
capture: None,
}
}
fn open(mixer: Arc<Mutex<Mixer>>) -> Result<(cpal::Stream, u32)> {
fn open(mixer: Arc<Mutex<Mixer>>) -> Result<cpal::Stream> {
let host = cpal::default_host();
let device = host
.default_output_device()
@@ -209,269 +370,110 @@ impl Audio {
let stream = device.build_output_stream(
&config.into(),
move |data: &mut [f32], _| {
data.fill(0.0);
let Ok(mut mixer) = mixer.lock() else { return };
for frame in data.chunks_mut(channels) {
let (mut l, mut r) = (0.0f32, 0.0f32);
for v in mixer.voices.iter_mut() {
let i = v.position as usize;
if i + 1 >= v.samples.len() {
continue;
}
let t = (v.position - i as f64) as f32;
let s = v.samples[i] * (1.0 - t) + v.samples[i + 1] * t;
l += s * v.left;
r += s * v.right;
v.position += v.step;
}
for t in mixer.tracked.iter_mut() {
let v = &mut t.voice;
let mut i = v.position as usize;
if t.looping && i + 1 >= v.samples.len() {
v.position = 0.0;
i = 0;
}
if i + 1 < v.samples.len() {
let f = (v.position - i as f64) as f32;
let s = (v.samples[i] * (1.0 - f) + v.samples[i + 1] * f) * t.volume;
l += s * v.left;
r += s * v.right;
v.position += v.step;
}
}
let gain = mixer.music_gain;
if let Some(v) = mixer.music.as_mut() {
let i = v.position as usize;
if i + 1 < v.samples.len() {
let t = (v.position - i as f64) as f32;
let s = (v.samples[i] * (1.0 - t) + v.samples[i + 1] * t) * gain;
l += s * v.left;
r += s * v.right;
v.position += v.step;
}
}
if channels >= 2 {
frame[0] = l.clamp(-1.0, 1.0);
frame[1] = r.clamp(-1.0, 1.0);
} else {
frame[0] = ((l + r) / 2.0).clamp(-1.0, 1.0);
}
}
mixer
.voices
.retain(|v| (v.position as usize) + 1 < v.samples.len());
mixer.tracked.retain(|t| {
t.looping || (t.voice.position as usize) + 1 < t.voice.samples.len()
});
if mixer
.music
.as_ref()
.is_some_and(|v| (v.position as usize) + 1 >= v.samples.len())
{
mixer.music = None;
if let Ok(mut m) = mixer.lock() {
mix(&mut m, data, channels, rate);
} else {
data.fill(0.0);
}
},
|e| eprintln!("Horizon: audio stream error: {e}"),
None,
)?;
stream.play()?;
Ok((stream, rate))
Ok(stream)
}
fn random(&mut self) -> u64 {
self.seed ^= self.seed << 13;
self.seed ^= self.seed >> 7;
self.seed ^= self.seed << 17;
self.seed
}
fn resolve(&mut self, event: &str, depth: u32) -> Option<Variant> {
let variants = self.events.get(event)?.clone();
let total: u32 = variants.iter().map(|v| v.weight).sum();
if total == 0 {
return None;
fn bound(&mut self) -> Bound<'_, MixerBackend> {
Bound {
engine: &mut self.engine,
backend: &mut self.backend,
}
let mut pick = (self.random() % u64::from(total)) as u32;
let chosen = variants.into_iter().find(|v| {
if pick < v.weight {
true
} else {
pick -= v.weight;
false
}
/// `SoundManager.updateSource`: the camera position and yaw.
pub fn set_listener(&mut self, position: [f64; 3], yaw: f32) {
self.listener = position;
self.listener_yaw = yaw;
if let Ok(mut m) = self.backend.mixer.lock() {
m.listener = position;
m.listener_yaw = yaw;
}
}
/// Sync the volume options, refreshing the categories that changed
/// (the option sliders' `refreshCategoryVolume`).
fn sync_volumes(&mut self) {
let mut volumes = [self.master; 11];
for (i, v) in volumes.iter_mut().enumerate().skip(1) {
*v = crate::settings::source_volume(i);
}
for source in 0..11 {
if self.engine.source_volumes[source] != volumes[source] {
self.engine.source_volumes[source] = volumes[source];
self.engine
.refresh_category_volume(source, &mut self.backend);
}
})?;
if chosen.is_event && depth < 4 {
let name = if chosen.name.contains(':') {
chosen.name.clone()
} else {
format!("minecraft:{}", chosen.name)
};
let mut inner = self.resolve(&name, depth + 1)?;
inner.volume *= chosen.volume;
inner.pitch *= chosen.pitch;
return Some(inner);
}
Some(chosen)
self.engine.listening = self.record_heard;
}
/// Play a sound event at a world position (None = non-positional UI sound).
/// `SoundManager.tick(paused)`, once per client tick.
pub fn tick(&mut self, paused: bool, ctx: &TickContext) {
self.sync_volumes();
self.engine.tick(paused, ctx, &mut self.backend);
}
/// `SoundManager.pauseAllExcept(MUSIC, UI)`.
pub fn pause(&mut self) {
self.engine.pause_all_except(
&[crate::sound_engine::MUSIC, crate::sound_engine::UI],
&mut self.backend,
);
}
/// `SoundManager.resume`.
pub fn resume(&mut self) {
self.engine.resume(&mut self.backend);
}
/// `SoundManager.stop()`: every sound.
pub fn stop_all(&mut self) {
self.engine.stop_all(&mut self.backend);
}
/// Play a sound event at a world position, as `ClientLevel.playLocalSound`
/// (a `SimpleSoundInstance` seeded from the level random), or relative to
/// the listener without attenuation (`None`).
pub fn play(&mut self, event: &str, at: Option<[f64; 3]>, volume: f32, pitch: f32) {
let seed = self.random.next_long();
self.play_seeded(event, at, volume, pitch, seed);
}
/// `play` with the seed a sound packet carries.
pub fn play_seeded(
&mut self,
event: &str,
at: Option<[f64; 3]>,
volume: f32,
pitch: f32,
seed: i64,
) {
if let (Some(capture), Some(at)) = (self.capture.as_mut(), at) {
capture.push((event.to_owned(), at, volume, pitch));
}
let Some(variant) = self.resolve(event, 0) else {
return;
};
if self.record_heard
&& let Some(key) = self.subtitles.get(event)
{
let range = if at.is_some() {
variant.attenuation * volume.max(1.0)
} else {
f32::INFINITY
};
self.heard.push(Heard {
subtitle: key.clone(),
at,
range,
looping: false,
});
}
if self._stream.is_none() {
return;
}
let file = variant.name.trim_start_matches("minecraft:").to_owned();
let entry = self.cache.entry(file.clone()).or_insert_with(|| {
decode(
&self
.root
.join(format!("assets/minecraft/sounds/{file}.ogg")),
)
.map(|(s, r)| (Arc::new(s), r))
});
let Some((samples, rate)) = entry.clone() else {
return;
};
self.sync_volumes();
let event = crate::sound_events::normalize(event);
let source = self
.source_override
.unwrap_or_else(|| crate::settings::sound_source(event));
let volume = (volume * variant.volume).clamp(0.0, 1.0)
* self.master
* crate::settings::source_volume(source);
let pitch = (pitch * variant.pitch).clamp(0.5, 2.0);
let (mut left, mut right) = (volume, volume);
if let Some(p) = at {
let d = [
p[0] - self.listener[0],
p[1] - self.listener[1],
p[2] - self.listener[2],
];
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32;
let range = variant.attenuation * volume.max(1.0);
let gain = (1.0 - distance / range).clamp(0.0, 1.0);
if gain <= 0.0 {
return;
}
let yaw = self.listener_yaw.to_radians();
// Right vector of a Minecraft yaw.
let side = (-(yaw.cos()) as f64 * d[0] - (yaw.sin()) as f64 * d[2]) as f32
/ distance.max(0.001);
let pan = side.clamp(-1.0, 1.0);
left = volume * gain * (1.0 - pan.max(0.0) * 0.6);
right = volume * gain * (1.0 + pan.min(0.0) * 0.6);
}
let step = f64::from(rate) / f64::from(self.rate) * f64::from(pitch);
if let Ok(mut m) = self.mixer.lock() {
if m.voices.len() > 64 {
m.voices.remove(0);
}
m.voices.push(Voice {
samples,
position: 0.0,
step,
left,
right,
event: event.into(),
.unwrap_or_else(|| crate::settings::sound_source(&event));
let random = LegacyRandom::new(seed);
let instance = match at {
Some(at) => SoundInstance::at(&event, source, volume, pitch, random, at),
None => SoundInstance::new(
&event,
source,
});
}
}
/// `SoundManager.play` of a music instance (`SimpleSoundInstance.forMusic`:
/// non-positional, streamed). Decoding runs on a worker thread; the track
/// counts as active from now on. Returns false when nothing can play.
pub fn play_music(&mut self, event: &str) -> bool {
self.stop_music();
if self._stream.is_none() {
return false;
}
let Some(variant) = self.resolve(event, 0) else {
return false;
volume,
pitch,
random,
false,
0,
Attenuation::None,
[0.0; 3],
true,
),
};
let path = self.root.join(format!(
"assets/minecraft/sounds/{}.ogg",
variant.name.trim_start_matches("minecraft:")
));
let volume =
variant.volume.clamp(0.0, 1.0) * self.master * crate::settings::event_volume(event);
let step_scale = f64::from(variant.pitch.clamp(0.5, 2.0)) / f64::from(self.rate);
let ready = Arc::new(std::sync::atomic::AtomicBool::new(false));
let (mixer, done) = (self.mixer.clone(), ready.clone());
let music_event = event.to_owned();
std::thread::spawn(move || {
if let Some((samples, rate)) = decode(&path)
&& let Ok(mut m) = mixer.lock()
&& !done.load(std::sync::atomic::Ordering::Acquire)
{
m.music = Some(Voice {
samples: Arc::new(samples),
position: 0.0,
step: f64::from(rate) * step_scale,
left: volume,
right: volume,
event: music_event.as_str().into(),
source: 1,
});
}
done.store(true, std::sync::atomic::Ordering::Release);
});
self.music = Some(MusicTrack {
event: event.to_owned(),
ready,
});
true
}
/// `SoundManager.stop` of the music instance.
pub fn stop_music(&mut self) {
if let Some(track) = self.music.take() {
// A decoder still running sees the flag and drops its result.
track
.ready
.store(true, std::sync::atomic::Ordering::Release);
}
if let Ok(mut m) = self.mixer.lock() {
m.music = None;
}
}
/// `SoundManager.isActive`: decoding or still sounding.
pub fn music_active(&mut self) -> bool {
let Some(track) = &self.music else {
return false;
};
if !track.ready.load(std::sync::atomic::Ordering::Acquire) {
return true;
}
let playing = self.mixer.lock().is_ok_and(|m| m.music.is_some());
if !playing {
self.music = None;
}
playing
}
/// The event of the current music track.
pub fn music_event(&self) -> Option<&str> {
self.music.as_ref().map(|t| t.event.as_str())
}
/// Every sound event id (for command completion).
pub fn event_names(&self) -> Vec<String> {
let mut v: Vec<String> = self.events.keys().cloned().collect();
v.sort();
v
self.play_instance(instance, false);
}
/// Play a sound on a given `SoundSource` index (`/playsound`).
pub fn play_on(
@@ -486,102 +488,67 @@ impl Audio {
self.play(event, at, volume, pitch);
self.source_override = None;
}
/// `SimpleSoundInstance.forJukeboxSong` at a jukebox; the handle stays
/// until `release`.
pub fn play_jukebox_song(&mut self, event: &str, pos: [i32; 3]) -> InstanceId {
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
];
let event = crate::sound_events::normalize(event);
let instance = SoundInstance::for_jukebox_song(&event, at, SoundEngine::unseeded());
self.play_instance(instance, true).0
}
/// Stop and drop a held instance.
pub fn stop_and_release(&mut self, id: InstanceId) {
self.stop_instance(id);
self.release(id);
}
/// Every sound event id (for command completion).
pub fn event_names(&self) -> Vec<String> {
let mut v: Vec<String> = self.engine.registry.names().cloned().collect();
v.sort();
v
}
/// `ClientboundStopSoundPacket`: stop the playing sounds of an event
/// and/or a source.
pub fn stop_sounds(&mut self, event: Option<&str>, source: Option<usize>) {
let matches = |v: &Voice| {
event.is_none_or(|e| &*v.event == e) && source.is_none_or(|s| v.source == s)
};
if let Ok(mut m) = self.mixer.lock() {
m.voices.retain(|v| !matches(v));
m.tracked.retain(|t| !matches(&t.voice));
if m.music.as_ref().is_some_and(matches) {
m.music = None;
}
}
if self
.music
.as_ref()
.is_some_and(|t| event.is_none_or(|e| t.event == e) && source.is_none_or(|s| s == 1))
{
self.music = None;
}
let event = event.map(crate::sound_events::normalize);
self.engine
.stop_matching(event.as_deref(), source, &mut self.backend);
}
/// The sounds played since the last call, for the subtitle overlay.
pub fn take_heard(&mut self) -> Vec<Heard> {
std::mem::take(&mut self.heard)
}
/// `SoundManager.updateCategoryVolume(MUSIC, gain)`.
pub fn set_music_gain(&mut self, gain: f32) {
if let Ok(mut m) = self.mixer.lock() {
m.music_gain = gain;
}
}
/// Play a relative (non-positional) tickable sound instance the caller
/// keeps a handle to: ambient loops (`looping`) and sub-sounds.
pub fn play_tracked(&mut self, event: &str, volume: f32, looping: bool) -> Option<u64> {
let variant = self.resolve(event, 0)?;
if self.record_heard
&& let Some(key) = self.subtitles.get(event)
{
self.heard.push(Heard {
subtitle: key.clone(),
at: None,
range: f32::INFINITY,
looping,
});
}
self._stream.as_ref()?;
let file = variant.name.trim_start_matches("minecraft:").to_owned();
let root = &self.root;
let (samples, rate) = self
.cache
.entry(file.clone())
.or_insert_with(|| {
decode(&root.join(format!("assets/minecraft/sounds/{file}.ogg")))
.map(|(s, r)| (Arc::new(s), r))
std::mem::take(&mut self.engine.notifications)
.into_iter()
.filter_map(|n| {
Some(Heard {
subtitle: n.subtitle?,
at: Some(n.position),
range: n.range,
looping: n.looping,
})
})
.clone()?;
let gain =
variant.volume.clamp(0.0, 1.0) * self.master * crate::settings::event_volume(event);
let step =
f64::from(rate) / f64::from(self.rate) * f64::from(variant.pitch.clamp(0.5, 2.0));
self.next_tracked += 1;
let id = self.next_tracked;
let mut m = self.mixer.lock().ok()?;
m.tracked.push(Tracked {
id,
voice: Voice {
samples,
position: 0.0,
step,
left: gain,
right: gain,
event: event.into(),
source: crate::settings::sound_source(event),
},
looping,
volume: volume.clamp(0.0, 1.0),
});
Some(id)
}
/// A tracked instance's volume (`AbstractTickableSoundInstance.volume`).
pub fn set_tracked_volume(&mut self, id: u64, volume: f32) {
if let Ok(mut m) = self.mixer.lock()
&& let Some(t) = m.tracked.iter_mut().find(|t| t.id == id)
{
t.volume = volume.clamp(0.0, 1.0);
}
}
pub fn stop_tracked(&mut self, id: u64) {
if let Ok(mut m) = self.mixer.lock() {
m.tracked.retain(|t| t.id != id);
}
}
/// Still sounding (a finished one-shot is gone).
pub fn tracked_active(&self, id: u64) -> bool {
self.mixer
.lock()
.is_ok_and(|m| m.tracked.iter().any(|t| t.id == id))
.collect()
}
}
impl Sounds for Audio {
fn engine(&mut self) -> &mut SoundEngine {
&mut self.engine
}
fn play_instance(&mut self, instance: SoundInstance, retain: bool) -> (InstanceId, PlayResult) {
self.sync_volumes();
self.bound().play_instance(instance, retain)
}
fn play_id(&mut self, id: InstanceId) -> PlayResult {
self.sync_volumes();
self.bound().play_id(id)
}
fn stop_instance(&mut self, id: InstanceId) {
self.bound().stop_instance(id);
}
fn update_category_volume(&mut self, source: usize, gain: f32) {
self.bound().update_category_volume(source, gain);
}
}
+10 -2
View File
@@ -594,6 +594,8 @@ struct Game<'a> {
audio: Audio,
music: horizon_client::music::MusicManager,
ambience: horizon_client::ambience::Ambience,
/// The sound engine was told the game paused (pauseAllExcept).
sound_paused: bool,
dropped: Vec<ItemEntity>,
next_entity: u32,
particles: horizon_client::particles::ParticleEngine,
@@ -5706,6 +5708,10 @@ impl Game<'_> {
}
fn close_world(&mut self) -> Result<()> {
self.ambience.clear(&mut self.audio);
// updateLevelInEngines(null): every sound stops; the music manager
// lets go of its track.
self.music.stop_playing(None, &mut self.audio);
self.audio.stop_all();
if self.remote.is_some() {
return self.leave_server(None);
}
@@ -7409,8 +7415,8 @@ impl Game<'_> {
self.pitch,
),
};
self.audio.listener = [camera.x, camera.y, camera.z];
self.audio.listener_yaw = view_yaw;
self.audio
.set_listener([camera.x, camera.y, camera.z], view_yaw);
let block = [
camera.x.floor() as i32,
camera.y.floor() as i32,
@@ -8209,6 +8215,7 @@ impl ApplicationHandler for Game<'_> {
self.tick_fov();
}
self.tick_music();
self.tick_sound_engine();
self.clock.record(started.elapsed());
if let Some(report) = self.clock.take_sprint_report() {
self.sprint_report(&report);
@@ -8507,6 +8514,7 @@ pub fn run() -> Result<()> {
audio,
music: Default::default(),
ambience: Default::default(),
sound_paused: false,
dropped: Vec::new(),
next_entity: 0,
particles,
+1 -1
View File
@@ -509,7 +509,7 @@ impl Game<'_> {
"frames": self.frames,
"ticks": self.ticks,
"day_time": self.world.day_time,
"music": self.music.current(),
"music": self.music.current(&self.audio.engine),
"fishing": self.hook_status(),
"tridents": self.tridents.len(),
"rockets": self.rockets.len(),
+7 -20
View File
@@ -12,9 +12,6 @@ use horizon_client::{
use horizon_core::{position::BlockPos, random::RandomSource};
use horizon_world::level::flags as level_flags;
/// Linear attenuation range of a song (`SimpleSoundInstance.forJukeboxSong`: volume 4).
const RANGE: f64 = 64.0;
impl Game<'_> {
fn jukebox(&self, pos: [i32; 3]) -> Option<&Jukebox> {
match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) {
@@ -101,9 +98,9 @@ impl Game<'_> {
let Some(s) = self.res.items.songs.get(song).cloned() else {
return;
};
if let Some(id) = self.audio.play_tracked(&s.sound, 0.0, false) {
self.jukebox_sounds.insert((pos[0], pos[1], pos[2]), id);
}
// LevelRenderer.playJukeboxSong: SimpleSoundInstance.forJukeboxSong.
let id = self.audio.play_jukebox_song(&s.sound, pos);
self.jukebox_sounds.insert((pos[0], pos[1], pos[2]), id);
let description =
horizon_client::component::to_text(&s.description, &mut |k| Text::literal(k));
self.titles
@@ -113,7 +110,7 @@ impl Game<'_> {
}
fn stop_song(&mut self, pos: [i32; 3]) {
if let Some(id) = self.jukebox_sounds.remove(&(pos[0], pos[1], pos[2])) {
self.audio.stop_tracked(id);
self.audio.stop_and_release(id);
}
}
/// `popOutTheItem`: the disc above the jukebox, and the song stops.
@@ -202,30 +199,20 @@ impl Game<'_> {
}
self.update_song_volumes();
}
/// Linear distance attenuation of each song at the listener.
/// Let go of songs that ended or whose jukebox stopped.
fn update_song_volumes(&mut self) {
let Some(eye) = self.eye_position() else {
return;
};
let sounds: Vec<_> = self
.jukebox_sounds
.iter()
.map(|(k, id)| (*k, *id))
.collect();
for (k, id) in sounds {
if !self.audio.tracked_active(id)
if !self.audio.engine.is_active(id)
|| !matches!(self.world.block_entities.get(&k), Some(BlockEntity::Jukebox(j)) if j.playing)
{
self.audio.stop_tracked(id);
self.audio.stop_and_release(id);
self.jukebox_sounds.remove(&k);
continue;
}
let d = ((f64::from(k.0) + 0.5 - eye[0]).powi(2)
+ (f64::from(k.1) + 0.5 - eye[1]).powi(2)
+ (f64::from(k.2) + 0.5 - eye[2]).powi(2))
.sqrt();
self.audio
.set_tracked_volume(id, (1.0 - d / RANGE).clamp(0.0, 1.0) as f32);
}
}
}
+63 -41
View File
@@ -1,6 +1,11 @@
//! `Minecraft.getSituationalMusic` and `getMusicVolume` for the music manager.
//! `Minecraft.getSituationalMusic` and `getMusicVolume` for the music manager,
//! the local player's ambient sound handlers and the sound engine tick.
use super::Game;
use horizon_client::{blocks::Fluid, music::Music};
use horizon_client::{
blocks::Fluid,
music::Music,
sound_engine::TickContext,
};
impl Game<'_> {
/// `Minecraft.tick` -> `MusicManager.tick`, once per client tick.
@@ -11,6 +16,25 @@ impl Game<'_> {
self.music
.tick(music.as_ref(), volume, loading, &mut self.audio);
}
/// `Minecraft.tick` -> `SoundManager.tick(pause)`, after the music, with
/// `pauseAllExcept(MUSIC, UI)` when the game pauses and `resume` when it
/// carries on.
pub(super) fn tick_sound_engine(&mut self) {
if self.pause != self.sound_paused {
if self.pause {
self.audio.pause();
} else {
self.audio.resume();
}
self.sound_paused = self.pause;
}
let ctx = TickContext {
player_underwater: self.ambience.was_underwater(),
player_removed: self.player.is_none(),
};
self.audio.tick(self.pause, &ctx);
}
/// `getSituationalMusic` and `getMusicVolume`.
fn situational_music(&self) -> (Option<Music>, f32) {
// Title screen: no player, Musics.MENU at full volume.
if self.title.is_some() {
@@ -19,33 +43,44 @@ impl Game<'_> {
let Some(eye) = self.eye_position() else {
return (Some(Music::menu()), 1.0);
};
let (x, y, z) = (
eye[0].floor() as i32,
eye[1].floor() as i32,
eye[2].floor() as i32,
);
let biome = self
.world
let biome = self.biome_at(eye);
let dimension = self.dim.id();
let tables = &self.res.music;
let volume = tables.volume(dimension, biome);
// Minecraft.getSituationalMusic: the boss overlay's music in the End.
if self.dim == super::Dim::End && self.boss_music() {
return (Some(Music::end_boss()), volume);
}
let music = tables
.background(dimension, biome)
.select(self.creative, self.ambience.was_underwater())
.cloned();
(music, volume)
}
/// `BiomeManager.getNoiseBiomeAtPosition`: the quart cell holding a position.
fn biome_at(&self, p: [f64; 3]) -> &str {
let (x, y, z) = (p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32);
self.world
.chunks
.get(&(x >> 4, z >> 4))
.map_or("minecraft:plains", |c| {
self.res.biomes.list[c.biome(x, y, z) as usize]
.name
.as_str()
});
// Minecraft.getSituationalMusic: the boss bar's music in the End.
if self.boss_music() {
return (Some(Music::end_boss()), 1.0);
self.res.biomes.list[c.biome(x, y, z) as usize].name.as_str()
})
}
/// `isEyeInFluid(WATER)`: the eye inside the water of its block column.
fn eye_in_water(&self, x: f64, eye_y: f64, z: f64) -> bool {
let (bx, by, bz) = (x.floor() as i32, eye_y.floor() as i32, z.floor() as i32);
let f = self.res.facts.get(self.world.block(bx, by, bz));
if f.fluid != Fluid::Water {
return false;
}
let dimension = self.dim.id();
let tables = &self.res.music;
// Player.isUnderWater: eyes in water.
let underwater = self.res.facts.get(self.world.block(x, y, z)).fluid == Fluid::Water;
let music = tables
.background(dimension, biome)
.select(self.creative, underwater)
.cloned();
(music, tables.volume(dimension, biome))
let above = self.res.facts.get(self.world.block(bx, by + 1, bz));
let height = if above.fluid == Fluid::Water {
1.0
} else {
f64::from(f.fluid_level) / 9.0
};
eye_y <= f64::from(by) + height
}
}
@@ -57,23 +92,9 @@ impl Game<'_> {
};
let feet = [p.position.x, p.position.y, p.position.z];
let eye_y = feet[1] + f64::from(p.dimensions.eye_height);
let (x, z) = (feet[0].floor() as i32, feet[2].floor() as i32);
let sounds = self.res.ambient.get(self.dim.id(), self.biome_at(feet));
let underwater = self.eye_in_water(feet[0], eye_y, feet[2]);
let world = &self.world;
let biome = world
.chunks
.get(&(x >> 4, z >> 4))
.map_or("minecraft:plains", |c| {
self.res.biomes.list[c.biome(x, feet[1].floor() as i32, z) as usize]
.name
.as_str()
});
let sounds = self.res.ambient.get(self.dim.id(), biome);
let underwater = self
.res
.facts
.get(world.block(x, eye_y.floor() as i32, z))
.fluid
== Fluid::Water;
let light = |b: [i32; 3]| {
let l = world.light(b[0], b[1], b[2]);
(l >> 4, l & 15)
@@ -83,6 +104,7 @@ impl Game<'_> {
position: feet,
eye_y,
underwater,
spectator: self.spectator(),
light: &light,
};
self.ambience.tick(&ctx, &mut self.audio);
+145 -109
View File
@@ -2,6 +2,7 @@
//! `Minecraft.getSituationalMusic`, with the `minecraft:audio/background_music`
//! and `minecraft:audio/music_volume` environment attributes of dimension
//! types and biomes (a biome value overrides its dimension's).
use crate::sound_engine::{InstanceId, MUSIC, PlayResult, SoundEngine, SoundInstance, Sounds};
use horizon_core::random::{LegacyRandom, RandomSource};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
@@ -15,7 +16,7 @@ pub struct Music {
pub replace_current_music: bool,
}
impl Music {
fn new(sound: &str, min_delay: i32, max_delay: i32, replace_current_music: bool) -> Self {
pub fn new(sound: &str, min_delay: i32, max_delay: i32, replace_current_music: bool) -> Self {
Self {
sound: sound.to_owned(),
min_delay,
@@ -177,45 +178,23 @@ fn next_int(random: &mut LegacyRandom, min: i32, max: i32) -> i32 {
random.next_int_bound(max - min + 1).unwrap_or(0) + min
}
}
/// What the music manager drives (the sound engine's music channel).
pub trait MusicOutput {
/// Start a track; false when nothing can play.
fn play(&mut self, event: &str) -> bool;
fn stop(&mut self);
fn is_active(&mut self) -> bool;
/// `SoundManager.updateCategoryVolume(MUSIC, gain)`.
fn set_gain(&mut self, gain: f32);
}
impl MusicOutput for crate::audio::Audio {
fn play(&mut self, event: &str) -> bool {
self.play_music(event)
}
fn stop(&mut self) {
self.stop_music();
}
fn is_active(&mut self) -> bool {
self.music_active()
}
fn set_gain(&mut self, gain: f32) {
self.set_music_gain(gain);
}
}
/// `MusicManager`.
pub struct MusicManager {
random: LegacyRandom,
/// The sound event of the current track.
current: Option<String>,
/// `currentMusic`: the instance the manager holds.
current: Option<InstanceId>,
current_gain: f32,
next_song_delay: i32,
toast_shown: bool,
pub frequency: MusicFrequency,
/// `ToastManager.showNowPlayingToast` (true) / `hideNowPlayingToast`
/// (false) calls since the last drain.
pub toast_requests: Vec<bool>,
}
impl Default for MusicManager {
fn default() -> Self {
// RandomSource.create(): seeded from the clock, not the world.
let seed = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos() as i64);
Self::new(seed)
Self::new(crate::sound_engine::unique_seed())
}
}
impl MusicManager {
@@ -225,35 +204,68 @@ impl MusicManager {
current: None,
current_gain: 1.0,
next_song_delay: 100,
toast_shown: false,
frequency: MusicFrequency::Default,
toast_requests: Vec::new(),
}
}
pub fn current(&self) -> Option<&str> {
self.current.as_deref()
/// The sound event of the current track.
pub fn current<'a>(&self, sounds: &'a SoundEngine) -> Option<&'a str> {
self.current
.and_then(|id| sounds.instance(id))
.map(|i| i.identifier.as_str())
}
/// `MusicManager.tick` with the situational music and music volume;
/// `loading` holds back a new track (`LevelLoadingScreen`).
pub fn current_instance(&self) -> Option<InstanceId> {
self.current
}
pub fn next_song_delay(&self) -> i32 {
self.next_song_delay
}
pub fn current_gain(&self) -> f32 {
self.current_gain
}
pub fn toast_shown(&self) -> bool {
self.toast_shown
}
fn set_current(&mut self, id: Option<InstanceId>, sounds: &mut impl Sounds) {
if let Some(old) = self.current
&& Some(old) != id
{
sounds.release(old);
}
self.current = id;
}
/// `MusicManager.tick` with `Minecraft.getMusicVolume` and
/// `getSituationalMusic`; `loading` is a `LevelLoadingScreen`.
pub fn tick(
&mut self,
music: Option<&Music>,
volume: f32,
loading: bool,
out: &mut impl MusicOutput,
sounds: &mut impl Sounds,
) {
if self.current.is_some() && self.current_gain != volume && !self.fade(volume, music, out) {
if self.current.is_some()
&& self.current_gain != volume
&& !self.fade(volume, music, sounds)
{
return;
}
let Some(music) = music else {
self.next_song_delay = self.next_song_delay.max(100);
return;
};
if let Some(current) = &self.current {
if music.replace_current_music && music.sound != *current {
out.stop();
if let Some(current) = self.current {
// canReplace
let playing = sounds
.engine()
.instance(current)
.map(|i| i.identifier.clone());
if music.replace_current_music && playing.as_deref() != Some(music.sound.as_str()) {
sounds.stop_instance(current);
self.next_song_delay = next_int(&mut self.random, 0, music.min_delay / 2);
}
if !out.is_active() {
self.current = None;
if !sounds.is_active(current) {
self.set_current(None, sounds);
let delay = self
.frequency
.next_song_delay(Some(music), &mut self.random);
@@ -264,35 +276,68 @@ impl MusicManager {
if self.current.is_none() && !loading {
self.next_song_delay -= 1;
if self.next_song_delay <= 0 {
self.start(music, out);
self.start_playing(music, sounds);
}
}
}
/// `MusicManager.startPlaying`.
fn start(&mut self, music: &Music, out: &mut impl MusicOutput) {
// The instance is current even if it could not start; the next tick
// finds it inactive and schedules another.
out.play(&music.sound);
self.current = Some(music.sound.clone());
pub fn start_playing(&mut self, music: &Music, sounds: &mut impl Sounds) {
let instance = SoundInstance::for_music(&music.sound, SoundEngine::unseeded());
let (id, result) = sounds.play_instance(instance, true);
self.set_current(Some(id), sounds);
match result {
PlayResult::Started => {
self.toast_requests.push(true);
self.toast_shown = true;
}
PlayResult::StartedSilently => self.toast_shown = false,
PlayResult::NotStarted => {}
}
self.next_song_delay = i32::MAX;
}
/// `MusicManager.stopPlaying`.
pub fn stop(&mut self, situational: Option<&Music>, out: &mut impl MusicOutput) {
if self.current.take().is_some() {
out.stop();
/// `MusicManager.showNowPlayingToastIfNeeded`.
pub fn show_now_playing_toast_if_needed(&mut self) {
if !self.toast_shown {
self.toast_requests.push(true);
self.toast_shown = true;
}
}
/// `MusicManager.stopPlaying(Music)`.
pub fn stop_playing_music(
&mut self,
music: &Music,
situational: Option<&Music>,
sounds: &mut impl Sounds,
) {
if self.is_playing_music(music, sounds.engine()) {
self.stop_playing(situational, sounds);
}
}
/// `MusicManager.stopPlaying()`.
pub fn stop_playing(&mut self, situational: Option<&Music>, sounds: &mut impl Sounds) {
if let Some(current) = self.current {
sounds.stop_instance(current);
self.set_current(None, sounds);
self.toast_requests.push(false);
}
self.next_song_delay = self
.frequency
.next_song_delay(situational, &mut self.random)
+ 100;
}
/// `MusicManager.isPlayingMusic`.
pub fn is_playing_music(&self, music: &Music, sounds: &SoundEngine) -> bool {
self.current(sounds) == Some(music.sound.as_str())
}
/// `MusicManager.setMinutesBetweenSongs`.
pub fn set_frequency(&mut self, frequency: MusicFrequency, situational: Option<&Music>) {
self.frequency = frequency;
self.next_song_delay = self
.frequency
.next_song_delay(situational, &mut self.random);
}
/// `MusicManager.fadePlaying`: false once the track faded out and stopped.
fn fade(
&mut self,
volume: f32,
situational: Option<&Music>,
out: &mut impl MusicOutput,
) -> bool {
fn fade(&mut self, volume: f32, situational: Option<&Music>, sounds: &mut impl Sounds) -> bool {
if self.current.is_none() {
return false;
}
@@ -312,10 +357,10 @@ impl MusicManager {
}
self.current_gain = self.current_gain.clamp(0.0, 1.0);
if self.current_gain <= 1.0E-4 {
self.stop(situational, out);
self.stop_playing(situational, sounds);
false
} else {
out.set_gain(self.current_gain);
sounds.update_category_volume(MUSIC, self.current_gain);
true
}
}
@@ -324,79 +369,70 @@ impl MusicManager {
#[cfg(test)]
mod tests {
use super::*;
use crate::sound_engine::{Bound, test_backend::Null};
use crate::sound_events::SoundRegistry;
#[derive(Default)]
struct Fake {
playing: Option<String>,
started: Vec<String>,
gain: f32,
}
impl MusicOutput for Fake {
fn play(&mut self, event: &str) -> bool {
self.playing = Some(event.to_owned());
self.started.push(event.to_owned());
true
}
fn stop(&mut self) {
self.playing = None;
}
fn is_active(&mut self) -> bool {
self.playing.is_some()
}
fn set_gain(&mut self, gain: f32) {
self.gain = gain;
}
fn engine() -> SoundEngine {
let mut registry = SoundRegistry::default();
registry.add_file(
"minecraft",
br#"{"music.menu": {"sounds": [{"name": "m", "stream": true}]},
"music.game": {"sounds": [{"name": "g", "stream": true}]},
"music.end": {"sounds": [{"name": "e", "stream": true}]}}"#,
&|_, _| true,
);
SoundEngine::new(registry)
}
#[test]
fn menu_music_starts_within_its_delay_and_game_music_replaces_nothing() {
let (mut engine, mut backend) = (engine(), Null::default());
let mut m = MusicManager::new(1);
let mut out = Fake::default();
let menu = Music::menu();
let tick =
|m: &mut MusicManager, music: &Music, engine: &mut SoundEngine, backend: &mut Null| {
m.tick(Some(music), 1.0, false, &mut Bound { engine, backend });
};
// nextSongDelay starts at 100, capped to MENU's max delay 600: starts on tick 100.
for _ in 0..99 {
m.tick(Some(&menu), 1.0, false, &mut out);
tick(&mut m, &menu, &mut engine, &mut backend);
}
assert!(out.started.is_empty());
m.tick(Some(&menu), 1.0, false, &mut out);
assert_eq!(out.started, ["minecraft:music.menu"]);
assert!(m.current(&engine).is_none());
tick(&mut m, &menu, &mut engine, &mut backend);
assert_eq!(m.current(&engine), Some("minecraft:music.menu"));
// Game music does not replace the current track.
let game = Music::new("minecraft:music.game", 12000, 24000, false);
m.tick(Some(&game), 1.0, false, &mut out);
assert_eq!(m.current(), Some("minecraft:music.menu"));
// When the menu track ends, the next delay comes from the game music range.
out.playing = None;
m.tick(Some(&game), 1.0, false, &mut out);
assert!(m.current().is_none());
assert!((12000..=24000).contains(&m.next_song_delay));
}
#[test]
fn replacing_music_stops_the_current_track() {
let mut m = MusicManager::new(2);
let mut out = Fake::default();
m.start(&Music::menu(), &mut out);
let end = Music::new("minecraft:music.end", 6000, 24000, true);
m.tick(Some(&end), 1.0, false, &mut out);
assert!(out.playing.is_none());
assert!(m.current().is_none());
assert!(m.next_song_delay <= 3000);
tick(&mut m, &game, &mut engine, &mut backend);
assert_eq!(m.current(&engine), Some("minecraft:music.menu"));
}
#[test]
fn zero_music_volume_fades_out_and_stops() {
let (mut engine, mut backend) = (engine(), Null::default());
let mut m = MusicManager::new(3);
let mut out = Fake::default();
let game = Music::new("minecraft:music.game", 12000, 24000, false);
m.start(&game, &mut out);
m.start_playing(
&game,
&mut Bound {
engine: &mut engine,
backend: &mut backend,
},
);
let mut ticks = 0;
while m.current().is_some() && ticks < 1000 {
m.tick(Some(&game), 0.0, false, &mut out);
while m.current_instance().is_some() && ticks < 1000 {
m.tick(
Some(&game),
0.0,
false,
&mut Bound {
engine: &mut engine,
backend: &mut backend,
},
);
ticks += 1;
}
// 0.97^n < 1e-4 after ~303 ticks.
assert!((290..=310).contains(&ticks), "{ticks}");
assert!(out.playing.is_none());
}
#[test]
+83
View File
@@ -934,3 +934,86 @@ pub fn unique_seed() -> i64 {
.map_or(0, |d| d.as_nanos() as i64);
next ^ nanos
}
/// The `SoundManager` calls game code makes.
pub trait Sounds {
fn engine(&mut self) -> &mut SoundEngine;
/// `SoundManager.play` of a new instance (`retain`: the caller keeps it).
fn play_instance(&mut self, instance: SoundInstance, retain: bool) -> (InstanceId, PlayResult);
/// `SoundManager.play` of an instance the caller holds.
fn play_id(&mut self, id: InstanceId) -> PlayResult;
/// `SoundManager.stop(SoundInstance)`.
fn stop_instance(&mut self, id: InstanceId);
/// `SoundManager.isActive`.
fn is_active(&mut self, id: InstanceId) -> bool {
self.engine().is_active(id)
}
/// `SoundManager.updateCategoryVolume`.
fn update_category_volume(&mut self, source: usize, gain: f32);
/// The caller drops its instance.
fn release(&mut self, id: InstanceId) {
self.engine().release(id);
}
}
/// An engine with its backend.
pub struct Bound<'a, B: Backend> {
pub engine: &'a mut SoundEngine,
pub backend: &'a mut B,
}
impl<B: Backend> Sounds for Bound<'_, B> {
fn engine(&mut self) -> &mut SoundEngine {
self.engine
}
fn play_instance(&mut self, instance: SoundInstance, retain: bool) -> (InstanceId, PlayResult) {
self.engine.play_new(instance, retain, self.backend)
}
fn play_id(&mut self, id: InstanceId) -> PlayResult {
self.engine.play(id, self.backend)
}
fn stop_instance(&mut self, id: InstanceId) {
self.engine.stop(id, self.backend);
}
fn update_category_volume(&mut self, source: usize, gain: f32) {
self.engine
.update_category_volume(source, gain, self.backend);
}
}
#[cfg(test)]
pub mod test_backend {
use super::{Backend, ChannelId};
use crate::sound_events::Sound;
use std::collections::HashMap;
/// Channels that play until stopped.
#[derive(Default)]
pub struct Null {
next: ChannelId,
pub stopped: HashMap<ChannelId, bool>,
pub volume: HashMap<ChannelId, f32>,
}
impl Backend for Null {
fn create(&mut self, _streaming: bool) -> Option<ChannelId> {
self.next += 1;
self.stopped.insert(self.next, false);
Some(self.next)
}
fn destroy(&mut self, c: ChannelId) {
self.stopped.remove(&c);
}
fn set_pitch(&mut self, _: ChannelId, _: f32) {}
fn set_volume(&mut self, c: ChannelId, v: f32) {
self.volume.insert(c, v);
}
fn set_attenuation(&mut self, _: ChannelId, _: Option<f32>) {}
fn set_looping(&mut self, _: ChannelId, _: bool) {}
fn set_position(&mut self, _: ChannelId, _: [f64; 3]) {}
fn set_relative(&mut self, _: ChannelId, _: bool) {}
fn start(&mut self, _: ChannelId, _: &Sound, _: bool) {}
fn stop(&mut self, c: ChannelId) {
self.stopped.insert(c, true);
}
fn pause(&mut self, _: ChannelId) {}
fn unpause(&mut self, _: ChannelId) {}
fn stopped(&mut self, c: ChannelId) -> bool {
self.stopped.get(&c).copied().unwrap_or(true)
}
}
}