rayengine 0.0.3

A small Linux-first Rust game SDK over raylib
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! Opt-in streamed music and one-shot mixing. See [`crate::guides::audio`].
//!
//! The runtime owns all native resources and advances this mixer once per frame,
//! including while minimized. State-stack policies never implicitly stop audio.

use crate::{
    Error,
    assets::{Assets, SoundId, asset_path, path_string},
};
use rayengine_core::audio::validate_gain;
pub use rayengine_core::audio::{
    AudioBuses, AudioError, AudioSettings, BusId, BusSettings, GainFade,
};
use raylib::prelude::{Music, RaylibAudio, Sound, Wave};
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    time::Duration,
};

impl From<AudioError> for Error {
    fn from(error: AudioError) -> Self {
        Self::Asset(error.to_string())
    }
}

/// Cached, run-local music stream handle, separate from a short [`SoundId`].
/// Unloading permanently invalidates it; handles must not be shared between runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MusicId(usize);

/// Controls for one one-shot instance. Independent instances can overlap.
#[derive(Clone, Copy, Debug)]
pub struct SoundOptions {
    /// Destination bus; defaults to sfx.
    pub bus: BusId,
    /// Finite per-instance volume in 0..=1.
    pub volume: f32,
    /// Playback-rate multiplier in 0.25..=4.0 (also changes duration).
    pub pitch: f32,
    /// Stereo pan: -1 left, 0 center, 1 right.
    pub pan: f32,
}
impl Default for SoundOptions {
    fn default() -> Self {
        Self {
            bus: BusId::SFX,
            volume: 1.0,
            pitch: 1.0,
            pan: 0.0,
        }
    }
}
impl SoundOptions {
    fn validate(&self, buses: &AudioBuses) -> Result<(), Error> {
        validate_gain(self.volume)?;
        buses.gain(self.bus)?;
        if !self.pitch.is_finite() || !(0.25..=4.0).contains(&self.pitch) {
            return Err(Error::Asset("pitch must be finite and in 0.25..=4".into()));
        }
        if !self.pan.is_finite() || !(-1.0..=1.0).contains(&self.pan) {
            return Err(Error::Asset("pan must be finite and in -1..=1".into()));
        }
        Ok(())
    }
    fn apply(&self, sound: &impl SoundControls, buses: &AudioBuses) {
        sound.set_volume(self.volume * buses.gain(self.bus).expect("validated bus"));
        sound.set_pitch(self.pitch);
        sound.set_pan(self.pan);
    }
}

// Keep the native bridge mechanical; tests exercise the same dispatch of all
// three controls, including the volume product, through an observing adapter.
trait SoundControls {
    fn set_volume(&self, value: f32);
    fn set_pitch(&self, value: f32);
    fn set_pan(&self, value: f32);
}
impl SoundControls for Sound<'_> {
    fn set_volume(&self, value: f32) {
        Sound::set_volume(self, value);
    }
    fn set_pitch(&self, value: f32) {
        Sound::set_pitch(self, value);
    }
    fn set_pan(&self, value: f32) {
        Sound::set_pan(self, value);
    }
}

/// Stream playback controls. Each cached handle represents one playback cursor.
#[derive(Clone, Copy, Debug)]
pub struct MusicOptions {
    /// Destination bus; defaults to music.
    pub bus: BusId,
    /// Finite per-track volume in 0..=1.
    pub volume: f32,
    /// Whether the stream repeats at end of file. Changing this on an active
    /// stream restarts its cursor while retaining its current fade gain.
    pub looping: bool,
    /// Initial fade duration when starting a stopped stream.
    pub fade_in: Duration,
}
impl Default for MusicOptions {
    fn default() -> Self {
        Self {
            bus: BusId::MUSIC,
            volume: 1.0,
            looping: true,
            fade_in: Duration::ZERO,
        }
    }
}
impl MusicOptions {
    fn validate(&self, buses: &AudioBuses) -> Result<(), Error> {
        validate_gain(self.volume)?;
        buses.gain(self.bus)?;
        Ok(())
    }
}

/// Snapshot of a live stream's playback cursor and fade (before bus gain).
#[derive(Clone, Copy, Debug)]
pub struct MusicStatus {
    /// Whether playback is active, including explicitly paused streams.
    pub active: bool,
    /// Whether explicitly paused. Paused fades continue on the frame clock.
    pub paused: bool,
    /// Current linear envelope gain in 0..=1, before track/bus volume.
    pub gain: f32,
    /// Playback cursor in seconds reported by raylib.
    pub seconds: f32,
}
struct Track<'audio> {
    stream: Music<'audio>,
    options: MusicOptions,
    fade: GainFade,
    active: bool,
    paused: bool,
    stop_after_fade: bool,
}
impl Track<'_> {
    fn sync_volume(&self, buses: &AudioBuses) {
        self.stream.set_volume(
            self.options.volume * self.fade.gain() * buses.gain(self.options.bus).unwrap_or(0.0),
        );
    }
    fn stop(&mut self) {
        // raylib's buffer stop ignores paused buffers. Resume first so stopping
        // also resets the native cursor/counters, including after a paused fade.
        if self.paused {
            self.stream.resume_stream();
        }
        self.stream.stop_stream();
        self.active = false;
        self.paused = false;
        self.stop_after_fade = false;
        self.fade = GainFade::new(0.0, 0.0, Duration::ZERO).expect("zero gain");
    }
    fn start(&mut self, options: MusicOptions, duration: Duration, buses: &AudioBuses) {
        let start = if self.active { self.fade.gain() } else { 0.0 };
        // raylib accumulates decoded frames while looping. Disabling looping
        // without resetting that counter can underflow its remaining-frame
        // calculation and loop forever. Restart on mode changes for every
        // supported format (some formats cannot seek), preserving the envelope.
        if self.active && self.options.looping != options.looping {
            self.stop();
        }
        self.options = options;
        self.stream.set_looping(options.looping);
        self.fade = GainFade::new(start, 1.0, duration).expect("unit gains");
        self.stop_after_fade = false;
        self.sync_volume(buses);
        if !self.active {
            self.stream.play_stream();
        } else if self.paused {
            self.stream.resume_stream();
        }
        self.paused = false;
        self.active = true;
    }
}
struct Voice<'audio> {
    sound: Sound<'audio>,
    options: SoundOptions,
}
pub(crate) struct SoundPool<'audio> {
    wave: Wave<'audio>,
    voices: Vec<Voice<'audio>>,
    limit: Option<usize>,
}
impl<'audio> SoundPool<'audio> {
    pub(crate) fn new(wave: Wave<'audio>) -> Self {
        Self {
            wave,
            voices: Vec::new(),
            limit: None,
        }
    }
}

/// Run-owned audio controls, accessible through [`Assets::audio`].
/// Bus edits apply to already playing voices on the next frame. New playback
/// uses current bus values immediately. All methods run on the owning thread.
pub struct AudioMixer<'audio> {
    buses: AudioBuses,
    tracks: Vec<Option<Track<'audio>>>,
    music_paths: HashMap<PathBuf, MusicId>,
    pub(crate) sounds: Vec<Option<SoundPool<'audio>>>,
    device: Option<&'audio RaylibAudio>,
}
impl<'audio> AudioMixer<'audio> {
    pub(crate) fn new(device: Option<&'audio RaylibAudio>) -> Self {
        Self {
            buses: AudioBuses::default(),
            tracks: Vec::new(),
            music_paths: HashMap::new(),
            sounds: Vec::new(),
            device,
        }
    }
    /// Reads named buses and persistent settings.
    pub fn buses(&self) -> &AudioBuses {
        &self.buses
    }
    /// Changes named bus volumes/mutes, transient ducking, or saved settings.
    pub fn buses_mut(&mut self) -> &mut AudioBuses {
        &mut self.buses
    }
    pub(crate) fn load_music(&mut self, path: &Path) -> Result<MusicId, Error> {
        let device = self
            .device
            .ok_or_else(|| Error::Asset("enable Config::audio before loading music".into()))?;
        let path = asset_path(path)?;
        if let Some(&id) = self.music_paths.get(&path) {
            return Ok(id);
        }
        let stream = device
            .new_music(path_string(&path)?)
            .map_err(|error| Error::Asset(format!("{}: {error}", path.display())))?;
        let id = MusicId(self.tracks.len());
        self.tracks.push(Some(Track {
            stream,
            options: MusicOptions::default(),
            fade: GainFade::new(0.0, 0.0, Duration::ZERO)?,
            active: false,
            paused: false,
            stop_after_fade: false,
        }));
        self.music_paths.insert(path, id);
        Ok(id)
    }
    fn track_mut(&mut self, id: MusicId) -> Result<&mut Track<'audio>, Error> {
        self.tracks
            .get_mut(id.0)
            .and_then(Option::as_mut)
            .ok_or_else(|| Error::Asset("music handle is unloaded".into()))
    }
    /// Starts/fades in a stream. An active handle retains its current gain,
    /// retargeting toward full gain; an explicitly paused handle resumes. Its
    /// cursor is retained unless `options.looping` changes, which restarts it.
    pub fn play_music(&mut self, id: MusicId, options: MusicOptions) -> Result<(), Error> {
        options.validate(&self.buses)?;
        let buses = &self.buses;
        let track = self
            .tracks
            .get_mut(id.0)
            .and_then(Option::as_mut)
            .ok_or_else(|| Error::Asset("music handle is unloaded".into()))?;
        track.start(options, options.fade_in, buses);
        Ok(())
    }
    /// Fades all other active streams out and this stream in over `duration`.
    /// An active target retains its cursor unless its looping mode changes.
    /// Interrupted fades begin at current gains; zero duration switches immediately.
    /// Validates the target/options before changing any outgoing stream.
    /// `options.fade_in` is replaced by `duration` for this operation.
    pub fn crossfade(
        &mut self,
        id: MusicId,
        options: MusicOptions,
        duration: Duration,
    ) -> Result<(), Error> {
        options.validate(&self.buses)?;
        self.track_mut(id)?;
        for (index, track) in self.tracks.iter_mut().enumerate() {
            let Some(track) = track else {
                continue;
            };
            if index == id.0 {
                track.start(options, duration, &self.buses);
            } else if track.active {
                track.fade.retarget(0.0, duration)?;
                track.stop_after_fade = true;
                if duration.is_zero() {
                    track.stop();
                }
            }
        }
        Ok(())
    }
    /// Fades a stream to silence and stops/rewinds it at completion.
    pub fn fade_out(&mut self, id: MusicId, duration: Duration) -> Result<(), Error> {
        let track = self.track_mut(id)?;
        if track.active {
            track.fade.retarget(0.0, duration)?;
            track.stop_after_fade = true;
            if duration.is_zero() {
                track.stop();
            }
        }
        Ok(())
    }
    /// Immediately stops and rewinds a stream.
    pub fn stop_music(&mut self, id: MusicId) -> Result<(), Error> {
        self.track_mut(id)?.stop();
        Ok(())
    }
    /// Pauses the playback cursor. Frame-clock fades continue while paused.
    pub fn pause_music(&mut self, id: MusicId) -> Result<(), Error> {
        let track = self.track_mut(id)?;
        if track.active && !track.paused {
            track.stream.pause_stream();
            track.paused = true;
        }
        Ok(())
    }
    /// Resumes an explicitly paused stream at its current fade gain.
    pub fn resume_music(&mut self, id: MusicId) -> Result<(), Error> {
        let track = self.track_mut(id)?;
        if track.active && track.paused {
            track.stream.resume_stream();
            track.paused = false;
        }
        Ok(())
    }
    /// Returns None for an unloaded handle.
    pub fn music_status(&self, id: MusicId) -> Option<MusicStatus> {
        let track = self.tracks.get(id.0)?.as_ref()?;
        Some(MusicStatus {
            active: track.active,
            paused: track.paused,
            gain: track.fade.gain(),
            seconds: track.stream.get_time_played(),
        })
    }
    /// Stops and releases the stream immediately; future reloads get a new ID.
    pub fn unload_music(&mut self, id: MusicId) -> bool {
        let removed = self.tracks.get_mut(id.0).and_then(Option::take).is_some();
        self.music_paths.retain(|_, handle| *handle != id);
        removed
    }
    /// Sets a per-sound concurrency cap. None permits unlimited instances.
    /// Zero rejects all new playback; reducing a cap does not stop existing voices.
    /// Completed native voice buffers are reused until the sound unloads.
    pub fn set_sound_limit(&mut self, id: SoundId, limit: Option<usize>) -> Result<(), Error> {
        self.sounds
            .get_mut(id.0)
            .and_then(Option::as_mut)
            .ok_or_else(|| Error::Asset("sound handle is unloaded".into()))?
            .limit = limit;
        Ok(())
    }
    pub(crate) fn play_legacy(&self, id: SoundId, source: &Sound<'audio>) -> bool {
        let Some(pool) = self.sounds.get(id.0).and_then(Option::as_ref) else {
            return false;
        };
        let playing = usize::from(source.is_playing())
            + pool
                .voices
                .iter()
                .filter(|voice| voice.sound.is_playing())
                .count();
        if pool.limit == Some(0)
            || (pool.limit.is_some_and(|limit| playing >= limit) && !source.is_playing())
        {
            return false;
        }
        // The original voice is the pre-mixer raw API. Preserve all its controls;
        // managed playback uses separate buffers so the frame mixer cannot reset it.
        source.play();
        true
    }
    pub(crate) fn play_sound(
        &mut self,
        id: SoundId,
        source: &Sound<'audio>,
        options: SoundOptions,
    ) -> Result<bool, Error> {
        options.validate(&self.buses)?;
        let pool = self
            .sounds
            .get_mut(id.0)
            .and_then(Option::as_mut)
            .ok_or_else(|| Error::Asset("sound handle is unloaded".into()))?;
        let playing = usize::from(source.is_playing())
            + pool
                .voices
                .iter()
                .filter(|voice| voice.sound.is_playing())
                .count();
        if pool.limit.is_some_and(|limit| playing >= limit) {
            return Ok(false);
        }
        let slot = pool
            .voices
            .iter()
            .position(|voice| !voice.sound.is_playing());
        let voice = if let Some(slot) = slot {
            &mut pool.voices[slot]
        } else {
            let sound = self
                .device
                .expect("loaded sound requires audio")
                .new_sound_from_wave(&pool.wave)
                .map_err(|error| Error::Asset(error.to_string()))?;
            pool.voices.push(Voice { sound, options });
            pool.voices.last_mut().expect("pushed voice")
        };
        voice.options = options;
        options.apply(&voice.sound, &self.buses);
        voice.sound.play();
        Ok(true)
    }
    pub(crate) fn update(&mut self, delta: Duration) {
        self.buses.advance(delta);
        for track in self.tracks.iter_mut().flatten() {
            if !track.active {
                continue;
            }
            track.fade.advance(delta);
            if track.stop_after_fade && track.fade.finished() {
                track.stop();
                continue;
            }
            track.sync_volume(&self.buses);
            if !track.paused {
                track.stream.update_stream();
                if !track.stream.is_stream_playing() {
                    track.stop();
                }
            }
        }
        for pool in self.sounds.iter().flatten() {
            for voice in &pool.voices {
                voice.sound.set_volume(
                    voice.options.volume * self.buses.gain(voice.options.bus).unwrap_or(0.0),
                );
            }
        }
    }
    pub(crate) fn resource_counts(&self) -> (u64, u64) {
        (
            self.tracks.iter().flatten().count() as u64,
            self.sounds
                .iter()
                .flatten()
                .map(|pool| pool.voices.len() as u64)
                .sum(),
        )
    }
}

impl<'audio> Assets<'audio> {
    /// Audio controls available during init, fixed updates, and draw callbacks.
    /// Keep this guard short-lived: calling another audio asset operation while
    /// holding it would borrow the same mixer twice.
    pub fn audio(&self) -> std::cell::RefMut<'_, AudioMixer<'audio>> {
        self.mixer.borrow_mut()
    }
    /// Plays an independent one-shot with volume/pitch/pan and bus routing.
    /// Returns Ok(false) for stale handles or when the configured limit is reached.
    /// Each new simultaneous managed voice allocates a buffer from cached PCM;
    /// later plays reuse completed buffers. No files are read during playback.
    pub fn play_sound(&self, id: SoundId, options: SoundOptions) -> Result<bool, Error> {
        let Some(source) = self.sound(id) else {
            return Ok(false);
        };
        self.mixer.borrow_mut().play_sound(id, source, options)
    }
    /// Unloads a streamed track. It remains invalid for the rest of this run.
    pub fn unload_music(&mut self, id: MusicId) -> bool {
        self.mixer.get_mut().unload_music(id)
    }
    pub(crate) fn load_music(&mut self, path: &Path) -> Result<MusicId, Error> {
        self.mixer.get_mut().load_music(path)
    }
    pub(crate) fn update_audio(&mut self, delta: Duration) {
        self.mixer.get_mut().update(delta);
    }
}

#[cfg(test)]
mod tests;