use glam::{DVec3, IVec3};
use roxlap_scene::Scene;
mod backend;
mod cavity;
pub mod synth;
#[cfg(feature = "kira")]
mod kira_out;
pub use backend::{AudioOut, SoundKey, SourceId, SourcePool};
pub use cavity::{probe_cavity, CavityConfig, CavityEstimator, CavityProbe, ListenerAcoustics};
pub use synth::SoundBuffer;
#[cfg(feature = "kira")]
pub use kira_out::KiraAudio;
#[derive(Debug, Clone, PartialEq)]
pub struct AcousticsConfig {
pub rays: u32,
pub jitter_radius: f64,
pub absorption_per_voxel: f64,
pub open_cutoff_hz: f32,
pub occluded_cutoff_hz: f32,
pub max_occlusion_db: f32,
pub send_occlusion_frac: f32,
pub max_distance: f64,
}
impl Default for AcousticsConfig {
fn default() -> Self {
Self {
rays: 9,
jitter_radius: 1.5,
absorption_per_voxel: 0.25,
open_cutoff_hz: 20_000.0,
occluded_cutoff_hz: 800.0,
max_occlusion_db: -24.0,
send_occlusion_frac: 0.5,
max_distance: 128.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SourceAcoustics {
pub transmission: f32,
pub gain_db: f32,
pub lowpass_cutoff_hz: f32,
pub reverb_send_db: f32,
}
impl SourceAcoustics {
#[must_use]
pub fn clear(cfg: &AcousticsConfig) -> Self {
Self {
transmission: 1.0,
gain_db: 0.0,
lowpass_cutoff_hz: cfg.open_cutoff_hz,
reverb_send_db: 0.0,
}
}
}
#[must_use]
pub fn path_thickness(scene: &Scene, a: DVec3, b: DVec3) -> f64 {
let mut total = 0.0;
for (_, grid) in scene.grids() {
let inv = grid.transform.rotation.inverse();
let la = inv * (a - grid.transform.origin);
let lb = inv * (b - grid.transform.origin);
total += grid_thickness(grid, la, lb);
}
total
}
fn grid_thickness(grid: &roxlap_scene::Grid, a: DVec3, b: DVec3) -> f64 {
let seg = b - a;
let len = seg.length();
if len < 1e-9 {
return 0.0;
}
let dir = seg / len;
#[allow(clippy::cast_possible_truncation)]
let mut cell = IVec3::new(a.x.floor() as i32, a.y.floor() as i32, a.z.floor() as i32);
let mut t_max = [f64::INFINITY; 3];
let mut t_delta = [f64::INFINITY; 3];
let mut step = [0i32; 3];
for ax in 0..3 {
let d = dir[ax];
if d.abs() < 1e-12 {
continue;
}
step[ax] = if d > 0.0 { 1 } else { -1 };
t_delta[ax] = 1.0 / d.abs();
let cell_f = f64::from(cell[ax]);
let next_boundary = if d > 0.0 { cell_f + 1.0 } else { cell_f };
t_max[ax] = (next_boundary - a[ax]) / d;
}
let mut thickness = 0.0;
let mut t_prev = 0.0;
let mut cached_idx = IVec3::MAX;
let mut cached_chunk = None;
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let max_steps = (len * 3.0) as u32 + 8;
for _ in 0..max_steps {
let ax = min_axis(&t_max);
let t_next = t_max[ax].min(len);
let (chunk_idx, in_chunk) = roxlap_scene::voxel_split(cell);
if chunk_idx != cached_idx {
cached_idx = chunk_idx;
cached_chunk = grid.chunk(chunk_idx);
}
let solid =
cached_chunk.is_some_and(|vxl| roxlap_scene::Grid::chunk_voxel_solid(vxl, in_chunk));
if solid {
thickness += t_next - t_prev;
}
if t_max[ax] >= len {
break;
}
t_prev = t_next;
cell[ax] += step[ax];
t_max[ax] += t_delta[ax];
}
thickness
}
fn min_axis(t: &[f64; 3]) -> usize {
if t[0] <= t[1] && t[0] <= t[2] {
0
} else if t[1] <= t[2] {
1
} else {
2
}
}
#[must_use]
pub fn source_acoustics(
scene: &Scene,
source: DVec3,
listener: DVec3,
cfg: &AcousticsConfig,
) -> SourceAcoustics {
let seg = listener - source;
let dist = seg.length();
if dist > cfg.max_distance || dist < 1e-9 {
return SourceAcoustics::clear(cfg);
}
let dir = seg / dist;
let helper = if dir.x.abs() < 0.9 {
DVec3::X
} else {
DVec3::Y
};
let u = dir.cross(helper).normalize();
let v = dir.cross(u);
let rays = cfg.rays.max(1);
let mut energy = 0.0f64;
for i in 0..rays {
let origin = if i == 0 {
source
} else {
let ang = std::f64::consts::TAU * f64::from(i - 1) / f64::from(rays - 1);
source + (u * ang.cos() + v * ang.sin()) * cfg.jitter_radius
};
let t = path_thickness(scene, origin, listener);
energy += (-cfg.absorption_per_voxel * t).exp();
}
#[allow(clippy::cast_possible_truncation)]
let transmission = (energy / f64::from(rays)).clamp(0.0, 1.0) as f32;
let ratio = cfg.open_cutoff_hz / cfg.occluded_cutoff_hz;
let lowpass_cutoff_hz = cfg.occluded_cutoff_hz * ratio.powf(transmission);
let gain_db = cfg.max_occlusion_db * (1.0 - transmission);
SourceAcoustics {
transmission,
gain_db,
lowpass_cutoff_hz,
reverb_send_db: gain_db * cfg.send_occlusion_frac,
}
}
#[cfg(test)]
mod tests {
use super::*;
use roxlap_scene::{GridTransform, VoxColor};
const STONE: VoxColor = VoxColor(0x80_66_77_88);
fn scene_with(build: impl FnOnce(&mut roxlap_scene::Grid)) -> Scene {
let mut scene = Scene::new();
let id = scene.add_grid(GridTransform::identity());
build(scene.grid_mut(id).expect("grid just added"));
scene
}
fn wall(grid: &mut roxlap_scene::Grid, x0: i32, thick: i32) {
grid.set_rect(
IVec3::new(x0, 0, 100),
IVec3::new(x0 + thick - 1, 127, 180),
Some(STONE),
);
}
#[test]
fn open_air_is_clear() {
let scene = scene_with(|_| {});
let cfg = AcousticsConfig::default();
let a = source_acoustics(
&scene,
DVec3::new(10.0, 40.0, 140.0),
DVec3::new(60.0, 40.0, 140.0),
&cfg,
);
assert_eq!(a, SourceAcoustics::clear(&cfg));
}
#[test]
fn thickness_is_exact_for_perpendicular_and_diagonal_crossings() {
let scene = scene_with(|g| wall(g, 30, 3));
let t = path_thickness(
&scene,
DVec3::new(10.0, 40.5, 140.5),
DVec3::new(60.0, 40.5, 140.5),
);
assert!((t - 3.0).abs() < 1e-6, "perpendicular thickness: {t}");
let t = path_thickness(
&scene,
DVec3::new(10.0, 20.5, 140.5),
DVec3::new(60.0, 70.5, 140.5),
);
assert!((t - 3.0 * 2.0f64.sqrt()).abs() < 1e-6, "diagonal: {t}");
}
#[test]
fn thicker_walls_muffle_monotonically() {
let cfg = AcousticsConfig::default();
let src = DVec3::new(10.0, 64.0, 140.5);
let dst = DVec3::new(60.0, 64.0, 140.5);
let mut prev = 1.0f32;
for thick in [1, 2, 5] {
let scene = scene_with(|g| wall(g, 30, thick));
let a = source_acoustics(&scene, src, dst, &cfg);
assert!(
a.transmission < prev,
"{thick}-voxel wall must transmit less than the previous ({} vs {prev})",
a.transmission
);
assert!(a.gain_db < 0.0 && a.gain_db >= cfg.max_occlusion_db);
assert!(a.lowpass_cutoff_hz < cfg.open_cutoff_hz);
assert!(a.lowpass_cutoff_hz > cfg.occluded_cutoff_hz);
prev = a.transmission;
}
}
#[test]
fn doorway_leaks_more_than_sealed_wall() {
let src = DVec3::new(10.0, 64.0, 140.5);
let dst = DVec3::new(60.0, 64.0, 140.5);
let cfg = AcousticsConfig::default();
let sealed = scene_with(|g| wall(g, 30, 2));
let sealed_a = source_acoustics(&sealed, src, dst, &cfg);
let doorway = scene_with(|g| {
wall(g, 30, 2);
g.set_rect(IVec3::new(30, 63, 139), IVec3::new(31, 63, 141), None);
});
let door_a = source_acoustics(&doorway, src, dst, &cfg);
assert!(
door_a.transmission > sealed_a.transmission,
"doorway must leak: {} vs sealed {}",
door_a.transmission,
sealed_a.transmission
);
assert!(
door_a.transmission < 1.0,
"off-axis doorway is not fully clear"
);
}
#[test]
fn cross_chunk_wall_counts_once() {
let scene = scene_with(|g| {
g.set_rect(
IVec3::new(126, 0, 100),
IVec3::new(129, 255, 180),
Some(STONE),
);
});
let t = path_thickness(
&scene,
DVec3::new(100.0, 64.5, 140.5),
DVec3::new(160.0, 64.5, 140.5),
);
assert!((t - 4.0).abs() < 1e-6, "seam-straddling wall: {t}");
}
#[test]
fn cross_grid_thickness_sums() {
let mut scene = Scene::new();
let id_a = scene.add_grid(GridTransform::identity());
wall(scene.grid_mut(id_a).expect("grid a"), 20, 2);
let id_b = scene.add_grid(GridTransform::at(DVec3::new(20.0, 0.0, 0.0)));
wall(scene.grid_mut(id_b).expect("grid b"), 20, 2); let t = path_thickness(
&scene,
DVec3::new(10.0, 64.5, 140.5),
DVec3::new(60.0, 64.5, 140.5),
);
assert!((t - 4.0).abs() < 1e-6, "two 2-voxel walls: {t}");
}
#[test]
fn beyond_max_distance_reports_clear_not_buried() {
let scene = scene_with(|g| wall(g, 30, 5));
let cfg = AcousticsConfig::default();
let a = source_acoustics(
&scene,
DVec3::new(10.0, 64.0, 140.5),
DVec3::new(10.0 + cfg.max_distance + 10.0, 64.0, 140.5),
&cfg,
);
assert_eq!(a, SourceAcoustics::clear(&cfg));
}
#[test]
fn rotated_grid_thickness_is_world_true() {
use glam::{DQuat, DVec3};
let mut scene = Scene::new();
let rot = DQuat::from_rotation_z(std::f64::consts::FRAC_PI_2);
let id = scene.add_grid(GridTransform {
origin: DVec3::new(0.0, 0.0, 0.0),
rotation: rot,
voxel_world_size: 1.0,
});
wall(scene.grid_mut(id).expect("rotated grid"), 30, 3);
let t = path_thickness(
&scene,
DVec3::new(-40.5, 10.0, 140.5),
DVec3::new(-40.5, 60.0, 140.5),
);
assert!(
(t - 3.0).abs() < 1e-6,
"rotated-grid wall must stay 3 world voxels thick: {t}"
);
let control = scene_with(|g| wall(g, 30, 3));
let t = path_thickness(
&control,
DVec3::new(-40.5, 10.0, 140.5),
DVec3::new(-40.5, 60.0, 140.5),
);
assert!(t.abs() < 1e-9, "identity control must miss: {t}");
}
#[test]
fn bedrock_plane_counts_as_solid_documented() {
let scene = scene_with(|g| {
g.ensure_chunk(IVec3::ZERO);
});
let t = path_thickness(
&scene,
DVec3::new(10.0, 64.0, 255.5),
DVec3::new(20.0, 64.0, 255.5),
);
assert!(t > 9.0, "bedrock plane accumulates thickness: {t}");
}
#[test]
fn deterministic() {
let scene = scene_with(|g| wall(g, 30, 2));
let cfg = AcousticsConfig::default();
let src = DVec3::new(10.0, 64.0, 140.5);
let dst = DVec3::new(60.0, 64.0, 140.5);
let a = source_acoustics(&scene, src, dst, &cfg);
let b = source_acoustics(&scene, src, dst, &cfg);
assert_eq!(a, b);
}
}