audionimbus 0.13.0

A safe wrapper around Steam Audio that provides spatial audio capabilities with realistic occlusion, reverb, and HRTF effects, accounting for physical attributes and scene geometry.
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Sound probe generation and storage.

use crate::baking::BakedDataIdentifier;
use crate::context::Context;
use crate::energy_field::EnergyField;
use crate::error::{to_option_error, SteamAudioError};
use crate::geometry::{Matrix, Scene, Sphere};
use crate::serialized_object::SerializedObject;
use std::sync::{Arc, Mutex};

/// An array of sound probes.
///
/// Each probe has a position and a radius of influence.
#[derive(Debug)]
pub struct ProbeArray(audionimbus_sys::IPLProbeArray);

impl ProbeArray {
    /// Creates a new probe array.
    ///
    /// # Errors
    ///
    /// Returns [`SteamAudioError`] if creation fails.
    pub fn try_new(context: &Context) -> Result<Self, SteamAudioError> {
        let mut probe_array = Self(std::ptr::null_mut());

        let status = unsafe {
            audionimbus_sys::iplProbeArrayCreate(context.raw_ptr(), probe_array.raw_ptr_mut())
        };

        if let Some(error) = to_option_error(status) {
            return Err(error);
        }

        Ok(probe_array)
    }

    /// Generates probes and adds them to the probe array.
    pub fn generate_probes(&mut self, scene: &Scene, probe_params: &ProbeGenerationParams) {
        unsafe {
            audionimbus_sys::iplProbeArrayGenerateProbes(
                self.raw_ptr(),
                scene.raw_ptr(),
                &mut audionimbus_sys::IPLProbeGenerationParams::from(*probe_params),
            );
        }
    }

    /// Returns the number of probes in the probe array.
    pub fn num_probes(&self) -> usize {
        unsafe { audionimbus_sys::iplProbeArrayGetNumProbes(self.raw_ptr()) as usize }
    }

    /// Returns the probe at a given index in the probe array.
    ///
    /// # Errors
    ///
    /// Returns [`ProbeArrayError::ProbeIndexOutOfBounds`] if `index` is out of bounds.
    pub fn probe(&self, index: usize) -> Result<Sphere, ProbeArrayError> {
        let num_probes = self.num_probes();
        if index >= num_probes {
            return Err(ProbeArrayError::ProbeIndexOutOfBounds {
                probe_index: index,
                num_probes,
            });
        }

        let ipl_sphere =
            unsafe { audionimbus_sys::iplProbeArrayGetProbe(self.raw_ptr(), index as i32) };

        Ok(Sphere::from(ipl_sphere))
    }

    /// Returns the raw FFI pointer to the underlying probe array.
    ///
    /// This is intended for internal use and advanced scenarios.
    pub const fn raw_ptr(&self) -> audionimbus_sys::IPLProbeArray {
        self.0
    }

    /// Returns a mutable reference to the raw FFI pointer.
    ///
    /// This is intended for internal use and advanced scenarios.
    pub const fn raw_ptr_mut(&mut self) -> &mut audionimbus_sys::IPLProbeArray {
        &mut self.0
    }
}

impl Drop for ProbeArray {
    fn drop(&mut self) {
        unsafe { audionimbus_sys::iplProbeArrayRelease(&raw mut self.0) }
    }
}

unsafe impl Send for ProbeArray {}
unsafe impl Sync for ProbeArray {}

impl Clone for ProbeArray {
    /// Retains an additional reference to the probe array.
    ///
    /// The returned [`ProbeArray`] shares the same underlying Steam Audio object.
    fn clone(&self) -> Self {
        // SAFETY: The probe array will not be destroyed until all references are released.
        Self(unsafe { audionimbus_sys::iplProbeArrayRetain(self.0) })
    }
}

/// [`ProbeArray`] errors.
#[derive(Debug, PartialEq, Eq)]
pub enum ProbeArrayError {
    /// Probe index is out of bounds.
    ProbeIndexOutOfBounds {
        probe_index: usize,
        num_probes: usize,
    },
}

impl std::error::Error for ProbeArrayError {}

impl std::fmt::Display for ProbeArrayError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::ProbeIndexOutOfBounds {
                probe_index,
                num_probes,
            } => write!(
                f,
                "probe index {probe_index} out of bounds (num_probes: {num_probes})"
            ),
        }
    }
}

/// Settings used to generate probes.
#[derive(Copy, Clone, Debug)]
pub enum ProbeGenerationParams {
    /// Generates a single probe at the center of the specified box.
    Centroid {
        /// A transformation matrix that transforms an axis-aligned unit cube, with minimum and maximum vertices at (0.0, 0.0, 0.0) and (1.0, 1.0, 1.0), into a parallelopiped volume.
        /// Probes will be generated within this volume.
        transform: Matrix<f32, 4, 4>,
    },

    /// Generates probes that are uniformly-spaced, at a fixed height above solid geometry.
    /// A probe will never be generated above another probe unless there is a solid object between them.
    /// The goal is to model floors or terrain, and generate probes that are a fixed height above the floor or terrain, and uniformly-spaced along the horizontal plane.
    /// This algorithm is not suitable for scenarios where the listener may fly into a region with no probes; if this happens, the listener will not be influenced by any of the baked data.
    UniformFloor {
        /// Spacing (in meters) between two neighboring probes.
        spacing: f32,

        /// Height (in meters) above the floor at which probes will be generated.
        height: f32,

        /// A transformation matrix that transforms an axis-aligned unit cube, with minimum and maximum vertices at (0.0, 0.0, 0.0) and (1.0, 1.0, 1.0), into a parallelopiped volume.
        /// Probes will be generated within this volume.
        transform: Matrix<f32, 4, 4>,
    },
}

impl From<ProbeGenerationParams> for audionimbus_sys::IPLProbeGenerationParams {
    fn from(probe_generation_params: ProbeGenerationParams) -> Self {
        let (type_, spacing, height, transform) = match probe_generation_params {
            ProbeGenerationParams::Centroid { transform } => (
                audionimbus_sys::IPLProbeGenerationType::IPL_PROBEGENERATIONTYPE_CENTROID,
                f32::default(),
                f32::default(),
                transform,
            ),
            ProbeGenerationParams::UniformFloor {
                spacing,
                height,
                transform,
            } => (
                audionimbus_sys::IPLProbeGenerationType::IPL_PROBEGENERATIONTYPE_UNIFORMFLOOR,
                spacing,
                height,
                transform,
            ),
        };

        Self {
            type_,
            spacing,
            height,
            transform: transform.into(),
        }
    }
}

/// A batch of sound probes, along with associated data.
///
/// The associated data may include reverb, reflections from a static source position, pathing, and more.
/// This data is loaded and unloaded as a unit, either from disk or over the network.
#[derive(Debug)]
pub struct ProbeBatch {
    inner: audionimbus_sys::IPLProbeBatch,
    shared: Arc<Mutex<ProbeBatchShared>>,
}

/// Shared ownership of [`ProbeBatch`] data across clones.
#[derive(Default, Debug)]
struct ProbeBatchShared {
    /// Number of probes after the last commit.
    committed_num_probes: usize,

    /// Pending probe count to be committed.
    pending_num_probes: i32,
}

impl ProbeBatch {
    /// Creates a new probe batch.
    ///
    /// # Errors
    ///
    /// Returns [`SteamAudioError`] if creation fails.
    pub fn try_new(context: &Context) -> Result<Self, SteamAudioError> {
        let mut probe_batch = Self {
            inner: std::ptr::null_mut(),
            shared: Arc::new(Mutex::new(ProbeBatchShared::default())),
        };

        let status = unsafe {
            audionimbus_sys::iplProbeBatchCreate(context.raw_ptr(), probe_batch.raw_ptr_mut())
        };

        if let Some(error) = to_option_error(status) {
            return Err(error);
        }

        Ok(probe_batch)
    }

    /// Returns the number of probes in the probe batch.
    pub fn num_probes(&self) -> usize {
        unsafe { audionimbus_sys::iplProbeBatchGetNumProbes(self.raw_ptr()) as usize }
    }

    /// Returns the number of committed probes in the probe batch.
    pub fn committed_num_probes(&self) -> usize {
        self.shared.lock().unwrap().committed_num_probes
    }

    /// Returns the size (in bytes) of a specific baked data layer in the probe batch.
    pub fn data_size(&self, identifier: BakedDataIdentifier) -> usize {
        let mut ffi_identifier: audionimbus_sys::IPLBakedDataIdentifier = identifier.into();

        unsafe {
            audionimbus_sys::iplProbeBatchGetDataSize(self.raw_ptr(), &raw mut ffi_identifier)
                as usize
        }
    }

    pub fn remove_data(&mut self, identifier: BakedDataIdentifier) {
        let mut ffi_identifier: audionimbus_sys::IPLBakedDataIdentifier = identifier.into();

        unsafe {
            audionimbus_sys::iplProbeBatchRemoveData(self.raw_ptr(), &raw mut ffi_identifier);
        }
    }

    /// Adds a probe to a batch.
    /// The new probe will be added as the last probe in the batch.
    pub fn add_probe(&mut self, probe: Sphere) {
        unsafe {
            audionimbus_sys::iplProbeBatchAddProbe(
                self.raw_ptr(),
                audionimbus_sys::IPLSphere::from(probe),
            );
        }

        self.shared.lock().unwrap().pending_num_probes += 1;
    }

    /// Removes a probe from the batch.
    ///
    /// # Errors
    ///
    /// Returns [`ProbeBatchError::ProbeIndexOutOfBounds`] if `probe_index` is out of bounds.
    pub fn remove_probe(&mut self, probe_index: usize) -> Result<(), ProbeBatchError> {
        let num_probes = self.num_probes();
        if probe_index >= num_probes {
            return Err(ProbeBatchError::ProbeIndexOutOfBounds {
                probe_index,
                num_probes,
            });
        }

        unsafe {
            audionimbus_sys::iplProbeBatchRemoveProbe(self.raw_ptr(), probe_index as i32);
        }

        self.shared.lock().unwrap().pending_num_probes -= 1;

        Ok(())
    }

    /// Adds every probe in an array to a batch.
    /// The new probes will be added, in order, at the end of the batch.
    pub fn add_probe_array(&mut self, probe_array: &ProbeArray) {
        unsafe {
            audionimbus_sys::iplProbeBatchAddProbeArray(self.raw_ptr(), probe_array.raw_ptr());
        }

        self.shared.lock().unwrap().pending_num_probes += probe_array.num_probes() as i32;
    }

    /// Retrieves a single array of parametric reverb times in a specific baked data layer of a specific probe in the probe batch.
    ///
    /// # Errors
    ///
    /// Returns [`ProbeBatchError::ProbeIndexOutOfBounds`] if `probe_index` is out of bounds.
    pub fn reverb(
        &self,
        identifier: BakedDataIdentifier,
        probe_index: usize,
    ) -> Result<[f32; 3], ProbeBatchError> {
        let num_probes = self.num_probes();
        if probe_index >= num_probes {
            return Err(ProbeBatchError::ProbeIndexOutOfBounds {
                probe_index,
                num_probes,
            });
        }

        let mut ffi_identifier: audionimbus_sys::IPLBakedDataIdentifier = identifier.into();
        let mut reverb_times: [f32; 3] = [0.0; 3];

        unsafe {
            audionimbus_sys::iplProbeBatchGetReverb(
                self.raw_ptr(),
                &raw mut ffi_identifier,
                probe_index as i32,
                reverb_times.as_mut_ptr(),
            );
        }

        Ok(reverb_times)
    }

    /// Retrieves a single energy field in a specific baked data layer of a specific probe in the probe batch.
    ///
    /// # Errors
    ///
    /// Returns [`ProbeBatchError::ProbeIndexOutOfBounds`] if `probe_index` is out of bounds.
    pub fn energy_field(
        &self,
        identifier: BakedDataIdentifier,
        probe_index: usize,
    ) -> Result<EnergyField, ProbeBatchError> {
        let num_probes = self.num_probes();
        if probe_index >= num_probes {
            return Err(ProbeBatchError::ProbeIndexOutOfBounds {
                probe_index,
                num_probes,
            });
        }

        let mut ffi_identifier: audionimbus_sys::IPLBakedDataIdentifier = identifier.into();
        let energy_field = EnergyField(std::ptr::null_mut());

        unsafe {
            audionimbus_sys::iplProbeBatchGetEnergyField(
                self.raw_ptr(),
                &raw mut ffi_identifier,
                probe_index as i32,
                energy_field.raw_ptr(),
            );
        }

        Ok(energy_field)
    }

    /// Commits all changes made to a probe batch since this function was last called (or since the probe batch was first created, if this function was never called).
    ///
    /// This function must be called after adding, removing, or updating any probes in the batch, for the changes to take effect.
    pub fn commit(&mut self) {
        unsafe { audionimbus_sys::iplProbeBatchCommit(self.raw_ptr()) }

        let mut shared = self.shared.lock().unwrap();

        shared.committed_num_probes = shared
            .committed_num_probes
            .saturating_add_signed(shared.pending_num_probes as isize);
        shared.pending_num_probes = 0;
    }

    /// Saves a probe batch to a serialized object.
    ///
    /// Typically, the serialized object will then be saved to disk.
    pub fn save(&self, serialized_object: &mut SerializedObject) {
        unsafe {
            audionimbus_sys::iplProbeBatchSave(self.raw_ptr(), serialized_object.raw_ptr());
        }
    }

    /// Loads a probe batch from a serialized object.
    ///
    /// Typically, the serialized object will be created from a byte array loaded from disk or over the network.
    ///
    /// # Errors
    ///
    /// Returns [`SteamAudioError`] if loading fails.
    pub fn load(
        context: &Context,
        serialized_object: &mut SerializedObject,
    ) -> Result<Self, SteamAudioError> {
        let shared = Arc::new(Mutex::new(ProbeBatchShared::default()));

        let mut probe_batch = Self {
            inner: std::ptr::null_mut(),
            shared: shared.clone(),
        };

        let status = unsafe {
            audionimbus_sys::iplProbeBatchLoad(
                context.raw_ptr(),
                serialized_object.raw_ptr(),
                probe_batch.raw_ptr_mut(),
            )
        };

        if let Some(error) = to_option_error(status) {
            return Err(error);
        }

        shared.lock().unwrap().committed_num_probes = probe_batch.num_probes();

        Ok(probe_batch)
    }

    /// Returns the raw FFI pointer to the underlying probe batch.
    ///
    /// This is intended for internal use and advanced scenarios.
    pub const fn raw_ptr(&self) -> audionimbus_sys::IPLProbeBatch {
        self.inner
    }

    /// Returns a mutable reference to the raw FFI pointer.
    ///
    /// This is intended for internal use and advanced scenarios.
    pub const fn raw_ptr_mut(&mut self) -> &mut audionimbus_sys::IPLProbeBatch {
        &mut self.inner
    }
}

impl Drop for ProbeBatch {
    fn drop(&mut self) {
        unsafe { audionimbus_sys::iplProbeBatchRelease(&raw mut self.inner) }
    }
}

unsafe impl Send for ProbeBatch {}
unsafe impl Sync for ProbeBatch {}

impl Clone for ProbeBatch {
    /// Retains an additional reference to the probe batch.
    ///
    /// The returned [`ProbeBatch`] shares the same underlying Steam Audio object.
    fn clone(&self) -> Self {
        // SAFETY: The probe batch will not be destroyed until all references are released.
        Self {
            inner: unsafe { audionimbus_sys::iplProbeBatchRetain(self.inner) },
            shared: Arc::clone(&self.shared),
        }
    }
}

/// [`ProbeBatch`] errors.
#[derive(Debug, PartialEq, Eq)]
pub enum ProbeBatchError {
    /// Probe index is out of bounds.
    ProbeIndexOutOfBounds {
        probe_index: usize,
        num_probes: usize,
    },
}

impl std::error::Error for ProbeBatchError {}

impl std::fmt::Display for ProbeBatchError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::ProbeIndexOutOfBounds {
                probe_index,
                num_probes,
            } => write!(
                f,
                "probe index {probe_index} out of bounds (num_probes: {num_probes})"
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Material, Point, StaticMesh, StaticMeshSettings, Triangle};

    mod probe_array {
        use super::*;

        #[test]
        fn test_try_new() {
            let context = Context::default();
            let probe_array = ProbeArray::try_new(&context);
            assert!(probe_array.is_ok());
        }

        #[test]
        fn test_generation_centroid() {
            let context = Context::default();
            let scene = Scene::try_new(&context).expect("failed to create scene");
            let mut probe_array = ProbeArray::try_new(&context).unwrap();

            let transform = Matrix::new([
                [10.0, 0.0, 0.0, 0.0],
                [0.0, 10.0, 0.0, 0.0],
                [0.0, 0.0, 10.0, 0.0],
                [0.0, 0.0, 0.0, 1.0],
            ]);

            let params = ProbeGenerationParams::Centroid { transform };
            probe_array.generate_probes(&scene, &params);

            assert_eq!(probe_array.num_probes(), 1);
        }

        #[test]
        fn test_generation_uniform_floor() {
            let context = Context::default();
            let mut scene = Scene::try_new(&context).expect("failed to create scene");

            // Add a floor mesh.
            let vertices = vec![
                Point::new(-50.0, 0.0, -50.0),
                Point::new(50.0, 0.0, -50.0),
                Point::new(50.0, 0.0, 50.0),
                Point::new(-50.0, 0.0, 50.0),
            ];
            let triangles = vec![Triangle::new(0, 1, 2), Triangle::new(0, 2, 3)];
            let material_indices = vec![0, 0];
            let materials = vec![Material::default()];

            let static_mesh_settings = StaticMeshSettings {
                vertices: &vertices,
                triangles: &triangles,
                material_indices: &material_indices,
                materials: &materials,
            };
            let static_mesh = StaticMesh::try_new(&scene, &static_mesh_settings).unwrap();
            scene.add_static_mesh(static_mesh);
            scene.commit();

            let mut probe_array = ProbeArray::try_new(&context).unwrap();
            let transform = Matrix::new([
                [100.0, 0.0, 0.0, 0.0],
                [0.0, 100.0, 0.0, 0.0],
                [0.0, 0.0, 100.0, 0.0],
                [0.0, 0.0, 0.0, 1.0],
            ]);

            let params = ProbeGenerationParams::UniformFloor {
                spacing: 10.0,
                height: 1.5,
                transform,
            };

            probe_array.generate_probes(&scene, &params);
            assert_eq!(probe_array.num_probes(), 121);
        }

        #[test]
        fn test_clone() {
            let context = Context::default();
            let probe_array = ProbeArray::try_new(&context).unwrap();
            let clone = probe_array.clone();
            assert_eq!(probe_array.raw_ptr(), clone.raw_ptr());
            drop(probe_array);
            assert!(!clone.raw_ptr().is_null());
        }
    }

    mod probe_batch {
        use super::*;

        #[test]
        fn test_try_new() {
            let context = Context::default();
            let probe_batch = ProbeBatch::try_new(&context);
            assert!(probe_batch.is_ok());
        }

        #[test]
        fn test_add_remove() {
            let context = Context::default();
            let mut probe_batch = ProbeBatch::try_new(&context).unwrap();

            let probe = Sphere {
                center: Point::new(0.0, 0.0, 0.0),
                radius: 1.0,
            };

            probe_batch.add_probe(probe);
            probe_batch.commit();
            assert_eq!(probe_batch.num_probes(), 1);

            probe_batch.remove_probe(0).unwrap();
            probe_batch.commit();
            assert_eq!(probe_batch.num_probes(), 0);
        }

        #[test]
        fn test_add_array() {
            let context = Context::default();
            let scene = Scene::try_new(&context).expect("failed to create scene");

            let mut probe_array = ProbeArray::try_new(&context).unwrap();
            let transform = Matrix::new([
                [10.0, 0.0, 0.0, 0.0],
                [0.0, 10.0, 0.0, 0.0],
                [0.0, 0.0, 10.0, 0.0],
                [0.0, 0.0, 0.0, 1.0],
            ]);
            let params = ProbeGenerationParams::Centroid { transform };
            probe_array.generate_probes(&scene, &params);

            let mut probe_batch = ProbeBatch::try_new(&context).unwrap();
            probe_batch.add_probe_array(&probe_array);
            probe_batch.commit();

            assert_eq!(probe_batch.num_probes(), probe_array.num_probes());
        }

        #[test]
        fn test_remove_out_of_bounds() {
            let context = Context::default();
            let mut probe_batch = ProbeBatch::try_new(&context).unwrap();
            assert_eq!(
                probe_batch.remove_probe(2),
                Err(ProbeBatchError::ProbeIndexOutOfBounds {
                    probe_index: 2,
                    num_probes: 0,
                })
            );
        }

        #[test]
        fn test_clone() {
            let context = Context::default();
            let probe_batch = ProbeBatch::try_new(&context).unwrap();
            let clone = probe_batch.clone();
            assert_eq!(probe_batch.raw_ptr(), clone.raw_ptr());
            drop(probe_batch);
            assert!(!clone.raw_ptr().is_null());
        }
    }
}