Skip to main content

euv_core/game/audio/
impl.rs

1use super::*;
2
3/// Default unmuted audio bus at `0.85` master volume.
4impl Default for AudioBus {
5    /// Creates a default `AudioBus`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Ready audio bus.
10    fn default() -> Self {
11        Self {
12            master_volume: 0.85,
13            muted: false,
14            queue: Vec::new(),
15            total_played: 0,
16        }
17    }
18}
19
20/// Sound cue scheduling and frame draining for `AudioBus`.
21impl AudioBus {
22    /// Queues a sound cue with normalized volume, pan, and pitch.
23    ///
24    /// # Arguments
25    ///
26    /// - `&Self` - Mutable audio bus.
27    /// - `SoundCue` - Sound cue to play.
28    /// - `f32` - Linear volume `[0.0, 1.0]`.
29    /// - `f32` - Stereo pan `[-1.0, 1.0]`.
30    /// - `f32` - Pitch multiplier `[0.25, 4.0]`.
31    pub fn play(&mut self, cue: SoundCue, volume: f32, pan: f32, pitch: f32) {
32        if self.get_muted() {
33            return;
34        }
35        let eff_vol: f32 = (volume.clamp(0.0, 1.0) * self.get_master_volume()).clamp(0.0, 1.0);
36        if eff_vol <= 0.001 {
37            return;
38        }
39        self.get_mut_queue().push(AudioCommand::new(
40            cue,
41            eff_vol,
42            pan.clamp(-1.0, 1.0),
43            pitch.clamp(0.25, 4.0),
44        ));
45        let next_total: u64 = self.get_total_played().saturating_add(1);
46        self.set_total_played(next_total);
47    }
48
49    /// Drains all queued audio commands for platform audio playback.
50    ///
51    /// # Arguments
52    ///
53    /// - `&Self` - Mutable audio bus.
54    ///
55    /// # Returns
56    ///
57    /// - `Vec<AudioCommand>` - Ordered commands emitted since the previous drain.
58    pub fn drain(&mut self) -> Vec<AudioCommand> {
59        take(self.get_mut_queue())
60    }
61
62    /// Spatializes a 3D sound emitter relative to `listener` with inverse-distance attenuation, stereo ear panning, and Doppler shift.
63    ///
64    /// # Arguments
65    ///
66    /// - `&Self` - Mutable audio bus.
67    /// - `&AudioListener3D` - Active 3D listener pose.
68    /// - `&SpatialAudioSource3D` - World-space sound source parameters.
69    pub fn play_spatial_3d(&mut self, listener: &AudioListener3D, source: &SpatialAudioSource3D) {
70        let delta: Vec3 = source.get_position().sub(listener.get_position());
71        let dist: f32 = delta.length();
72        let max_d: f32 = source.get_max_distance().max(1.0);
73        if dist >= max_d {
74            return;
75        }
76        let min_d: f32 = source.get_min_distance().clamp(0.25, max_d);
77        let atten: f32 = if dist <= min_d {
78            1.0
79        } else {
80            let norm: f32 = ((dist - min_d) / (max_d - min_d).max(0.01)).clamp(0.0, 1.0);
81            (1.0 - norm) * (1.0 - norm)
82        };
83        let to_src: Vec3 = if dist > 1e-4 {
84            delta.scale(1.0 / dist)
85        } else {
86            Vec3::zero()
87        };
88        let pan: f32 = to_src.dot(listener.get_right()).clamp(-1.0, 1.0);
89        let rel_vel: f32 = source
90            .get_velocity()
91            .sub(listener.get_velocity())
92            .dot(to_src);
93        let speed_of_sound: f32 = 343.0;
94        let doppler: f32 =
95            (speed_of_sound / (speed_of_sound + rel_vel).clamp(120.0, 680.0)).clamp(0.5, 2.0);
96        self.play(
97            source.get_cue(),
98            source.get_volume() * atten,
99            pan,
100            source.get_pitch() * doppler,
101        );
102    }
103}
104
105/// Camera-based listener builder for `AudioListener3D`.
106impl AudioListener3D {
107    /// Builds an `AudioListener3D` from a `Camera3D` and optional linear velocity.
108    ///
109    /// # Arguments
110    ///
111    /// - `&Camera3D` - Active 3D perspective camera.
112    /// - `Vec3` - Listener linear velocity in meters/sec.
113    ///
114    /// # Returns
115    ///
116    /// - `Self` - Positioned and oriented 3D audio listener.
117    #[must_use]
118    pub fn from_camera(camera: &Camera3D, velocity: Vec3) -> Self {
119        Self::new(camera.get_position(), velocity, camera.right())
120    }
121}
122
123/// Fluent constructor for `SpatialAudioSource3D`.
124impl SpatialAudioSource3D {
125    /// Creates a `SpatialAudioSource3D` at `position` with default `[2.0m, 80.0m]` attenuation radius.
126    ///
127    /// # Arguments
128    ///
129    /// - `SoundCue` - Sound cue identifier.
130    /// - `Vec3` - World-space position in meters.
131    ///
132    /// # Returns
133    ///
134    /// - `Self` - Ready 3D spatial audio emitter.
135    #[must_use]
136    pub fn new(cue: SoundCue, position: Vec3) -> Self {
137        Self {
138            cue,
139            position,
140            velocity: Vec3::zero(),
141            volume: 1.0,
142            pitch: 1.0,
143            min_distance: 2.0,
144            max_distance: 80.0,
145        }
146    }
147
148    /// Sets linear velocity for Doppler pitch calculation.
149    ///
150    /// # Arguments
151    ///
152    /// - `Self` - Source emitter.
153    /// - `Vec3` - Velocity in meters/sec.
154    ///
155    /// # Returns
156    ///
157    /// - `Self` - Updated spatial audio source.
158    #[must_use]
159    pub fn with_velocity(mut self, velocity: Vec3) -> Self {
160        self.set_velocity(velocity);
161        self
162    }
163
164    /// Sets nominal volume and audible `[min_distance, max_distance]` range.
165    ///
166    /// # Arguments
167    ///
168    /// - `Self` - Source emitter.
169    /// - `f32` - Nominal volume `[0.0, 1.0]`.
170    /// - `f32` - Reference full-volume distance in meters.
171    /// - `f32` - Maximum audible radius in meters.
172    ///
173    /// # Returns
174    ///
175    /// - `Self` - Updated spatial audio source.
176    #[must_use]
177    pub fn with_range(mut self, volume: f32, min_distance: f32, max_distance: f32) -> Self {
178        self.set_volume(volume.clamp(0.0, 1.0));
179        self.set_min_distance(min_distance.max(0.25));
180        self.set_max_distance(max_distance.max(min_distance + 0.5));
181        self
182    }
183}