Skip to main content

unbanished_audio/
scene.rs

1//! The sound scene: the layer above the [`Device`](crate::Device) that plays sound effects.
2//!
3//! - **256 effects.** Each one walks its effect's timeline and starts every sound whose start time
4//!   falls in the frame, with a random variant and a random pitch, at the volume
5//!   `variant × effect × kind`. When all its sounds have ended, the effect frees itself (and the 3D
6//!   effect that started it).
7//! - **4,096 effects in the world.** Each has a position or a list of emitters. Every update takes
8//!   the loudest emitter (the volume falls in a straight line from the inner radius to the radius,
9//!   plus the listener's reach), starts the effect when it can be heard, stops it when it cannot,
10//!   and passes the volume on.
11//! - **Kinds of sound:** 1 interface, 2 music, 3 ambient, 4 effects (kind 0 never plays). Each
12//!   kind has a volume (by default 100, 50, 100 and 100) and can be paused.
13//!
14//! Handles are encoded as in the original: an effect is `index·2 | counter<<9`, an effect in the
15//! world `index·2 | 1 | counter<<13`. A stale handle does nothing. See
16//! [Audio](https://tanepiper.github.io/unbanished/topics/audio).
17//!
18//! Original: `Audio::Scene` in the Runtime.
19mod effects;
20mod emitters;
21pub use effects::{Effect, EffectCache, Prepared};
22
23// The effects are at Scene +0x10 (0x70 bytes each), the 3D effects at +0x20 (0x40 bytes), the
24// paused kinds at +0x30. See docs/AUDIO.md.
25
26use std::collections::HashMap;
27use std::rc::Rc;
28use std::time::Duration;
29
30use glam::Vec3;
31use unbanished_formats::audio::SoundEffect;
32
33use crate::device::{Channel, PlayParams, Sound};
34
35/// `0x100` and `0x1000` slots (`FindFreeEffect`, `FindFree3DEffect`).
36const EFFECTS: usize = 0x100;
37const EFFECTS_3D: usize = 0x1000;
38/// Sounds per effect (`+0x20`, eight channel pointers; `+0x60`, eight flag bytes).
39const SOUNDS: usize = 8;
40/// `DAT_1801647cc`: 2^-32.
41const UNIT: f32 = 2.328_306_4e-10;
42/// `DAT_180164870`: a 3D effect is not restarted within `max_length / 20` of itself.
43const RETRIGGER_DIVISOR: f32 = 20.0;
44
45/// The kinds of sound. Each kind has its own volume in the options. Kind 0 never plays.
46///
47/// Original: `Audio::Scene::SoundType`.
48pub mod sound_type {
49    /// Interface sounds.
50    pub const UI: u32 = 1;
51    /// Music.
52    pub const MUSIC: u32 = 2;
53    /// Ambient sounds: weather, rivers, forests.
54    pub const AMBIENT: u32 = 3;
55    /// Sound effects in the world.
56    pub const EFFECT: u32 = 4;
57}
58
59/// What the scene needs from the channel pool (implemented by [`crate::Device`]).
60pub trait Mixer {
61    /// Start a sound on a free channel, or return `None` when no channel is free.
62    fn play(&mut self, sound: &Sound, params: PlayParams) -> Option<Channel>;
63    /// Stop a channel.
64    fn stop(&mut self, channel: Channel);
65    /// Change a channel's volume.
66    fn set_volume(&mut self, channel: Channel, volume: f32);
67}
68
69impl Mixer for crate::Device {
70    fn play(&mut self, sound: &Sound, params: PlayParams) -> Option<Channel> {
71        crate::Device::play(self, sound, params).ok().flatten()
72    }
73    fn stop(&mut self, channel: Channel) {
74        crate::Device::stop(self, channel)
75    }
76    fn set_volume(&mut self, channel: Channel, volume: f32) {
77        crate::Device::set_volume(self, channel, volume)
78    }
79}
80
81/// The volume of each kind of sound, from 0 to 100, as in the Audio options.
82///
83/// Original: `Audio::Configuration`; its constructor `Configuration::Configuration`, Runtime
84/// `0x1800e0700`.
85#[derive(Debug, Clone, Copy, PartialEq)]
86pub struct Volumes {
87    /// Interface sounds.
88    pub ui: i32,
89    /// Music.
90    pub music: i32,
91    /// Ambient sounds.
92    pub ambient: i32,
93    /// Sound effects.
94    pub effect: i32,
95}
96
97impl Default for Volumes {
98    fn default() -> Self {
99        Volumes {
100            ui: 100,
101            music: 50,
102            ambient: 100,
103            effect: 100,
104        }
105    }
106}
107
108impl Volumes {
109    /// `Scene::Update`'s per-type table: type 0 is silent.
110    fn table(&self) -> [f32; 5] {
111        [
112            0.0,
113            self.ui as f32 / 100.0,
114            self.music as f32 / 100.0,
115            self.ambient as f32 / 100.0,
116            self.effect as f32 / 100.0,
117        ]
118    }
119}
120
121/// One playing effect (`0x70` bytes).
122struct Effect2D {
123    effect: Rc<Effect>,
124    kind: u32,
125    /// `+0x10`: time into the effect (µs).
126    elapsed: i64,
127    /// `+0x18`: volume set by the 3D effect that drives it (1 otherwise).
128    volume: f32,
129    /// `+0x1c`: volume of the last variant started.
130    variant_volume: f32,
131    channels: [Option<Channel>; SOUNDS],
132    /// Bit 0 started, bit 1 ended.
133    flags: [u8; SOUNDS],
134    handle: u32,
135    /// `+0x6c`: cleared on start and unpause; the first update's window then begins at 0.
136    started: bool,
137}
138
139/// One positional effect (`0x40` bytes).
140struct Effect3D {
141    position: Vec3,
142    kind: u32,
143    effect: Rc<Effect>,
144    /// `+0x18`: µs.
145    elapsed: i64,
146    /// `+0x20`: the 2D effect playing it, or 0.
147    playing: u32,
148    handle: u32,
149    /// `+0x28`.
150    volume: f32,
151    /// `+0x30`: positions and volumes; empty means `position` at volume 1.
152    emitters: Vec<(Vec3, f32)>,
153}
154
155/// The sound scene: up to 256 playing effects and 4,096 effects in the world, their emitters,
156/// and the volumes of the kinds of sound. [`Scene::update`] mixes them every frame.
157///
158/// Original: `Audio::Scene`.
159pub struct Scene {
160    /// `+0x00`: the frame's simulation time step (µs), the minimum retrigger window.
161    step: i64,
162    /// `+0x08`: handle counter, starting at 1.
163    counter: u32,
164    effects: Vec<Option<Effect2D>>,
165    effects3d: Vec<Option<Effect3D>>,
166    /// `+0x30`: paused sound types.
167    paused: [bool; 5],
168    /// The volume of each kind of sound.
169    pub volumes: Volumes,
170}
171
172impl Default for Scene {
173    fn default() -> Self {
174        Scene {
175            step: 0,
176            counter: 1,
177            effects: (0..EFFECTS).map(|_| None).collect(),
178            effects3d: (0..EFFECTS_3D).map(|_| None).collect(),
179            paused: [false; 5],
180            volumes: Volumes::default(),
181        }
182    }
183}
184
185fn index2d(handle: u32) -> usize {
186    (handle >> 1 & 0xff) as usize
187}
188
189fn index3d(handle: u32) -> usize {
190    (handle >> 1 & 0xfff) as usize
191}
192
193/// `GetVolumeForPosition` (`0x1800e2720`).
194fn volume_for_position(at: Vec3, radius: f32, inner: f32, listener: Vec3) -> f32 {
195    // The terms in the original's order: y, then x, then z.
196    let v = at - listener;
197    let d = (v.y * v.y + v.x * v.x + v.z * v.z).sqrt();
198    if radius < d {
199        0.0
200    } else if inner <= d {
201        1.0 - (d - inner) / (radius - inner)
202    } else {
203        1.0
204    }
205}
206
207fn micros(seconds: f32) -> i64 {
208    (seconds as f64 * 1e6) as i64
209}
210
211impl Scene {
212    fn effect_mut(&mut self, handle: u32) -> Option<&mut Effect2D> {
213        self.effects
214            .get_mut(index2d(handle))?
215            .as_mut()
216            .filter(|e| (e.handle ^ handle) & 0xffff_fe00 == 0)
217    }
218
219    /// `PlayEffect`: the first free slot, starting `start` µs into the effect. Returns 0 when all
220    /// 256 are busy.
221    ///
222    /// Original: Runtime `0x1800e17b0`.
223    pub fn play_effect(&mut self, effect: &Rc<Effect>, kind: u32, start: i64) -> u32 {
224        let Some(i) = self.effects.iter().position(Option::is_none) else {
225            return 0;
226        };
227        self.counter = self.counter.wrapping_add(1);
228        let handle = ((i as u32) * 2) | (self.counter << 9);
229        self.effects[i] = Some(Effect2D {
230            effect: effect.clone(),
231            kind,
232            elapsed: start,
233            volume: 1.0,
234            variant_volume: 1.0,
235            channels: [None; SOUNDS],
236            flags: [0; SOUNDS],
237            handle,
238            started: false,
239        });
240        handle
241    }
242
243    /// `IsEffectPlaying`.
244    pub fn is_effect_playing(&self, handle: u32) -> bool {
245        self.effects
246            .get(index2d(handle))
247            .and_then(Option::as_ref)
248            .is_some_and(|e| (e.handle ^ handle) & 0xffff_fe00 == 0)
249    }
250
251    /// `StopEffect`: stop its channels and free it.
252    pub fn stop_effect(&mut self, mixer: &mut dyn Mixer, handle: u32) {
253        if let Some(e) = self.effect_mut(handle) {
254            for c in e.channels.iter().flatten() {
255                mixer.stop(*c);
256            }
257            self.effects[index2d(handle)] = None;
258        }
259    }
260
261    /// `StopAll`: every 2D effect (3D effects stay and restart when audible).
262    pub fn stop_all(&mut self, mixer: &mut dyn Mixer) {
263        for slot in &mut self.effects {
264            if let Some(e) = slot.take() {
265                for c in e.channels.iter().flatten() {
266                    mixer.stop(*c);
267                }
268            }
269        }
270    }
271
272    /// `PauseEffect`: stop the channels; started sounds are not restarted.
273    fn pause_effect(e: &mut Effect2D, mixer: &mut dyn Mixer) {
274        for (c, f) in e.channels.iter_mut().zip(&mut e.flags) {
275            if let Some(ch) = c.take() {
276                mixer.stop(ch);
277                *f &= !2;
278            }
279        }
280    }
281
282    /// `Pause(type, paused)`.
283    pub fn pause(&mut self, mixer: &mut dyn Mixer, kind: u32, paused: bool) {
284        let k = kind as usize;
285        if k >= self.paused.len() || self.paused[k] == paused {
286            return;
287        }
288        for e in self.effects.iter_mut().flatten().filter(|e| e.kind == kind) {
289            if paused {
290                Self::pause_effect(e, mixer);
291            } else {
292                e.started = false;
293            }
294        }
295        self.paused[k] = paused;
296    }
297
298    /// `IsPaused(type)`.
299    pub fn is_paused(&self, kind: u32) -> bool {
300        self.paused.get(kind as usize).copied().unwrap_or(false)
301    }
302
303    /// The device's end callback (`OnSoundEnded`): mark the sound ended.
304    pub fn on_ended(&mut self, channel: Channel) {
305        for e in self.effects.iter_mut().flatten() {
306            for (c, f) in e.channels.iter_mut().zip(&mut e.flags) {
307                if *c == Some(channel) {
308                    *c = None;
309                    *f |= 2;
310                }
311            }
312        }
313    }
314
315    /// `Update(dt, step, random, listener, reach)`. `dt` advances the effects; `step` is the
316    /// simulation step of the frame; `reach` extends every 3D effect's radius (the camera's
317    /// distance from its pivot).
318    ///
319    /// Original: Runtime `0x1800e1f10`.
320    pub fn update(
321        &mut self,
322        mixer: &mut dyn Mixer,
323        dt: i64,
324        step: i64,
325        rand: &mut dyn FnMut() -> u32,
326        listener: Vec3,
327        reach: f32,
328    ) {
329        self.step = step;
330        // 3D effects.
331        for i in 0..EFFECTS_3D {
332            let Some(e) = &self.effects3d[i] else {
333                continue;
334            };
335            if self.paused[e.kind as usize % 5] {
336                continue;
337            }
338            let volume = self.attenuated_volume(e, listener, reach);
339            let (handle, kind, effect, playing, elapsed) =
340                (e.handle, e.kind, e.effect.clone(), e.playing, e.elapsed);
341            let mut playing = playing;
342            if volume == 0.0 && playing != 0 {
343                self.stop_effect(mixer, playing);
344                playing = 0;
345            } else if volume > 0.0 && playing == 0 {
346                playing = self.play_effect(&effect, kind, elapsed);
347            }
348            if let Some(p) = self.effect_mut(playing) {
349                p.volume = volume;
350            }
351            let e = self.effects3d[i].as_mut().unwrap();
352            e.playing = playing;
353            if playing == 0 && effect.max_length() != 0 && effect.max_length() <= e.elapsed {
354                self.stop_effect_3d(mixer, handle);
355            } else {
356                e.elapsed += dt;
357            }
358        }
359        // 2D effects.
360        let volumes = self.volumes.table();
361        for i in 0..EFFECTS {
362            let Some(e) = self.effects[i].as_mut() else {
363                continue;
364            };
365            if self.paused[e.kind as usize % 5] {
366                continue;
367            }
368            let from = if e.started { e.elapsed } else { 0 };
369            e.started = true;
370            let to = e.elapsed + dt;
371            let mut done = false;
372            if e.kind != 0 {
373                let type_volume = volumes[e.kind as usize % 5];
374                let mut ended = 0;
375                for (s, sound) in e.effect.desc.sounds.iter().enumerate().take(SOUNDS) {
376                    let at = micros(sound.start);
377                    if at < from || to <= at {
378                        // Playing sounds follow the effect's volume.
379                        if e.flags[s] & 1 != 0 && e.flags[s] & 2 == 0 {
380                            if let Some(c) = e.channels[s] {
381                                mixer.set_volume(c, e.variant_volume * e.volume * type_volume);
382                            }
383                        }
384                    } else {
385                        // In the window: start it (`GetSoundBuffer`: a random variant and a
386                        // random pitch). The original does not check whether the sound already
387                        // started; after an unpause the window reopens at 0, so paused sounds
388                        // restart at the effect's elapsed time, which resumes them.
389                        let n = sound.variants.len() as u32;
390                        let v = if n == 0 { 0 } else { (rand() % n) as usize };
391                        let r = rand();
392                        let Some(variant) = sound.variants.get(v) else {
393                            e.flags[s] |= 3;
394                            ended += 1;
395                            continue;
396                        };
397                        let pitch = (variant.pitch_max - variant.pitch_min) * r as f32 * UNIT
398                            + variant.pitch_min;
399                        e.variant_volume = variant.volume;
400                        let channel = e.effect.buffers[s][v].as_ref().and_then(|buffer| {
401                            mixer.play(
402                                buffer,
403                                PlayParams {
404                                    offset: Duration::from_micros(e.elapsed.max(0) as u64),
405                                    volume: variant.volume * e.volume * type_volume,
406                                    pitch,
407                                    looping: None,
408                                },
409                            )
410                        });
411                        e.channels[s] = channel;
412                        e.flags[s] |= 1;
413                        if channel.is_none() {
414                            // No buffer or no free channel: the sound is over at once.
415                            e.flags[s] |= 2;
416                        }
417                    }
418                    if e.flags[s] & 2 != 0 {
419                        ended += 1;
420                    }
421                }
422                done = ended == e.effect.desc.sounds.len().min(SOUNDS);
423            }
424            e.elapsed = to;
425            if done {
426                let handle = e.handle;
427                self.effects[i] = None;
428                for slot in &mut self.effects3d {
429                    if slot.as_ref().is_some_and(|f| f.playing == handle) {
430                        *slot = None;
431                    }
432                }
433            }
434        }
435    }
436
437    /// `GetAttenuatedVolume` (`0x1800e2630`).
438    fn attenuated_volume(&self, e: &Effect3D, listener: Vec3, reach: f32) -> f32 {
439        let radius = reach + e.effect.desc.radius;
440        let inner = e.effect.desc.inner_radius;
441        let v = if e.emitters.is_empty() {
442            volume_for_position(e.position, radius, inner, listener)
443        } else {
444            e.emitters.iter().fold(0.0f32, |best, (p, w)| {
445                best.max(volume_for_position(*p, radius, inner, listener) * w)
446            })
447        };
448        v * e.volume
449    }
450
451    /// Effects currently held (tests, debugging).
452    pub fn active(&self) -> (usize, usize) {
453        (
454            self.effects.iter().flatten().count(),
455            self.effects3d.iter().flatten().count(),
456        )
457    }
458}
459
460#[cfg(test)]
461mod tests;