1use std::collections::HashMap;
61use std::sync::Arc;
62use std::sync::atomic::{AtomicU32, Ordering};
63use std::time::Duration;
64
65use bevy::audio::{AddAudioSource, AudioPlugin, Sample as RodioSample, Source as RodioSource};
66use bevy::prelude::*;
67use bevy::reflect::TypePath;
68
69use crate::world::{VoxelBroken, VoxelPlaced};
70
71#[derive(Debug, Clone, PartialEq, Eq, Hash)]
79pub enum SfxEvent {
80 Mining,
83 MiningComplete,
86 BlockPlace,
89 ItemPickup,
91 HotbarScroll,
93 PauseOpen,
95 PauseClose,
97 Footstep(u8),
102 Custom(String),
106}
107
108impl SfxEvent {
109 pub fn key(&self) -> String {
112 match self {
113 SfxEvent::Mining => "Mining".to_string(),
114 SfxEvent::MiningComplete => "MiningComplete".to_string(),
115 SfxEvent::BlockPlace => "BlockPlace".to_string(),
116 SfxEvent::ItemPickup => "ItemPickup".to_string(),
117 SfxEvent::HotbarScroll => "HotbarScroll".to_string(),
118 SfxEvent::PauseOpen => "PauseOpen".to_string(),
119 SfxEvent::PauseClose => "PauseClose".to_string(),
120 SfxEvent::Footstep(surface) => format!("Footstep:{surface}"),
121 SfxEvent::Custom(s) => format!("Custom:{s}"),
122 }
123 }
124}
125
126#[derive(Message, Debug, Clone)]
134pub struct SfxRequest {
135 pub event: SfxEvent,
137 pub position: Option<Vec3>,
144}
145
146#[derive(Message, Debug, Clone)]
185#[non_exhaustive]
186pub struct PitchedSfxRequest {
187 pub event: SfxEvent,
189 pub position: Option<Vec3>,
192 pub pitch: f32,
197}
198
199impl PitchedSfxRequest {
200 pub const MIN_PITCH: f32 = 0.1;
202 pub const MAX_PITCH: f32 = 8.0;
204
205 pub fn new(event: SfxEvent, pitch: f32) -> Self {
207 Self {
208 event,
209 position: None,
210 pitch,
211 }
212 }
213
214 pub fn at(mut self, position: Vec3) -> Self {
216 self.position = Some(position);
217 self
218 }
219
220 pub fn effective_pitch(&self) -> f32 {
227 if self.pitch.is_finite() && self.pitch > 0.0 {
228 self.pitch.clamp(Self::MIN_PITCH, Self::MAX_PITCH)
229 } else {
230 1.0
231 }
232 }
233}
234
235#[derive(Resource, Debug, Clone, Copy, PartialEq, Default)]
297#[non_exhaustive]
298pub struct SfxFilter {
299 pub low_pass_hz: Option<f32>,
305}
306
307impl SfxFilter {
308 pub const NONE: Self = Self { low_pass_hz: None };
310
311 pub const MIN_LOW_PASS_HZ: f32 = 20.0;
313 pub const MAX_LOW_PASS_HZ: f32 = 20_000.0;
315
316 pub const fn low_pass(cutoff_hz: f32) -> Self {
318 Self {
319 low_pass_hz: Some(cutoff_hz),
320 }
321 }
322
323 pub fn effective_low_pass_hz(&self) -> Option<f32> {
331 let hz = self.low_pass_hz?;
332 if hz.is_finite() && hz > 0.0 {
333 Some(hz.clamp(Self::MIN_LOW_PASS_HZ, Self::MAX_LOW_PASS_HZ))
334 } else {
335 None
336 }
337 }
338
339 pub fn is_active(&self) -> bool {
341 self.effective_low_pass_hz().is_some()
342 }
343}
344
345#[derive(Resource, Debug, Clone)]
371pub struct SfxConfig {
372 pub sounds: HashMap<String, Vec<String>>,
377 pub volume: f32,
383}
384
385impl SfxConfig {
386 pub fn new() -> Self {
388 Self {
389 sounds: HashMap::new(),
390 volume: 1.0,
391 }
392 }
393
394 pub fn register(&mut self, event: SfxEvent, paths: Vec<&str>) {
399 self.sounds.insert(
400 event.key(),
401 paths.into_iter().map(|p| p.to_string()).collect(),
402 );
403 }
404
405 pub fn get_paths(&self, event: &SfxEvent) -> Option<&Vec<String>> {
407 self.sounds.get(&event.key())
408 }
409
410 pub fn pick_path(&self, event: &SfxEvent, seed: u64) -> Option<&str> {
415 let paths = self.get_paths(event)?;
416 if paths.is_empty() {
417 return None;
418 }
419 let index = (seed % paths.len() as u64) as usize;
420 Some(paths[index].as_str())
421 }
422}
423
424impl Default for SfxConfig {
425 fn default() -> Self {
426 Self::new()
427 }
428}
429
430pub fn mining_sfx_system(
439 mut broken_reader: MessageReader<VoxelBroken>,
440 mut sfx_writer: MessageWriter<SfxRequest>,
441) {
442 for broken in broken_reader.read() {
443 sfx_writer.write(SfxRequest {
444 event: SfxEvent::MiningComplete,
445 position: Some(broken.world_pos),
446 });
447 }
448}
449
450pub fn placement_sfx_system(
457 mut placed_reader: MessageReader<VoxelPlaced>,
458 mut sfx_writer: MessageWriter<SfxRequest>,
459) {
460 for placed in placed_reader.read() {
461 sfx_writer.write(SfxRequest {
462 event: SfxEvent::BlockPlace,
463 position: Some(placed.world_pos),
464 });
465 }
466}
467
468pub struct SfxPlugin;
493
494impl Plugin for SfxPlugin {
495 fn build(&self, app: &mut App) {
496 app.init_resource::<SfxConfig>();
497 app.add_message::<SfxRequest>();
498 app.add_message::<PitchedSfxRequest>();
499 app.add_message::<VoxelBroken>();
502 app.add_message::<VoxelPlaced>();
503 app.add_systems(Update, (mining_sfx_system, placement_sfx_system));
504 }
505}
506
507#[derive(Resource, Default)]
512struct SfxCounter(HashMap<String, u64>);
513
514pub struct DefaultAudioPlugin;
563
564impl Plugin for DefaultAudioPlugin {
565 fn build(&self, app: &mut App) {
566 app.init_resource::<SfxCounter>();
567 app.init_resource::<SfxFilter>();
568 app.add_message::<PitchedSfxRequest>();
569 app.add_systems(Update, play_sfx_system);
570 }
571
572 fn finish(&self, app: &mut App) {
577 if app.is_plugin_added::<AudioPlugin>() && app.world().contains_resource::<AssetServer>() {
578 app.add_audio_source::<LowPassSfx>();
579 install_low_pass_backend(app);
580 }
581 }
582}
583
584fn install_low_pass_backend(app: &mut App) {
587 app.init_resource::<SfxFilterShared>()
588 .init_resource::<LowPassSfxCache>()
589 .add_systems(
590 Update,
591 (
592 sync_sfx_filter_system.before(play_sfx_system),
593 resolve_low_pass_sfx_system.after(play_sfx_system),
594 ),
595 );
596}
597
598fn play_sfx_system(
599 mut sfx_reader: MessageReader<SfxRequest>,
600 mut pitched_reader: MessageReader<PitchedSfxRequest>,
601 config: Res<SfxConfig>,
602 asset_server: Res<AssetServer>,
603 mut counter: ResMut<SfxCounter>,
604 (filter, low_pass_backend): (Option<Res<SfxFilter>>, Option<Res<SfxFilterShared>>),
605 mut commands: Commands,
606) {
607 let low_pass = low_pass_backend.is_some() && filter.is_some_and(|filter| filter.is_active());
608
609 let plain = sfx_reader
610 .read()
611 .map(|request| (&request.event, request.position, 1.0_f32));
612 let pitched = pitched_reader
613 .read()
614 .map(|request| (&request.event, request.position, request.effective_pitch()));
615
616 for (event, position, speed) in plain.chain(pitched) {
617 let seed = {
618 let c = counter.0.entry(event.key()).or_insert(0);
619 let s = *c;
620 *c = c.wrapping_add(1);
621 s
622 };
623 let Some(path) = config.pick_path(event, seed).map(|p| p.to_owned()) else {
624 continue;
625 };
626 let source: Handle<AudioSource> = asset_server.load(path);
627 let mut settings = PlaybackSettings::ONCE;
628 settings.volume = bevy::audio::Volume::Linear(config.volume);
629 settings.speed = speed;
630 let mut entity = if low_pass {
631 commands.spawn((PendingLowPassSfx(source), settings))
632 } else {
633 commands.spawn((AudioPlayer(source), settings))
634 };
635 if let Some(pos) = position {
636 entity.insert(Transform::from_translation(pos));
637 }
638 }
639}
640
641#[derive(Resource, Default)]
647struct SfxFilterShared(Arc<AtomicU32>);
648
649#[derive(Resource, Default)]
652struct LowPassSfxCache(HashMap<AssetId<AudioSource>, (Handle<AudioSource>, Handle<LowPassSfx>)>);
653
654#[derive(Component)]
656struct PendingLowPassSfx(Handle<AudioSource>);
657
658#[derive(Asset, TypePath)]
660struct LowPassSfx {
661 source: AudioSource,
662 cutoff: Arc<AtomicU32>,
663}
664
665impl Decodable for LowPassSfx {
666 type DecoderItem = f32;
667 type Decoder = LowPassSource<<AudioSource as Decodable>::Decoder>;
668
669 fn decoder(&self) -> Self::Decoder {
670 LowPassSource::new(self.source.decoder(), self.cutoff.clone())
671 }
672}
673
674fn sync_sfx_filter_system(filter: Option<Res<SfxFilter>>, shared: Res<SfxFilterShared>) {
675 let cutoff_hz = filter
676 .and_then(|filter| filter.effective_low_pass_hz())
677 .unwrap_or(0.0);
678 shared.0.store(cutoff_hz.to_bits(), Ordering::Relaxed);
679}
680
681fn resolve_low_pass_sfx_system(
682 pending: Query<(Entity, &PendingLowPassSfx)>,
683 sources: Res<Assets<AudioSource>>,
684 mut filtered: ResMut<Assets<LowPassSfx>>,
685 asset_server: Res<AssetServer>,
686 shared: Res<SfxFilterShared>,
687 mut cache: ResMut<LowPassSfxCache>,
688 mut commands: Commands,
689) {
690 for (entity, pending) in &pending {
691 let id = pending.0.id();
692 if let Some(source) = sources.get(id) {
693 let handle = match cache.0.get(&id) {
694 Some((_, handle)) => handle.clone(),
695 None => {
696 let handle = filtered.add(LowPassSfx {
697 source: source.clone(),
698 cutoff: shared.0.clone(),
699 });
700 cache.0.insert(id, (pending.0.clone(), handle.clone()));
701 handle
702 }
703 };
704 commands
705 .entity(entity)
706 .insert(AudioPlayer::<LowPassSfx>(handle))
707 .remove::<PendingLowPassSfx>();
708 } else if asset_server.load_state(id).is_failed() {
709 commands.entity(entity).despawn();
710 }
711 }
712}
713
714#[derive(Debug, Clone, Copy, PartialEq)]
716struct LowPassCoefficients {
717 b0: f32,
718 b1: f32,
719 b2: f32,
720 a1: f32,
721 a2: f32,
722}
723
724impl LowPassCoefficients {
725 fn new(cutoff_hz: f32, sample_rate: u32) -> Option<Self> {
728 if !cutoff_hz.is_finite() || cutoff_hz <= 0.0 || sample_rate == 0 {
729 return None;
730 }
731 let sample_rate = sample_rate as f32;
732 if cutoff_hz >= sample_rate * 0.45 {
733 return None;
734 }
735 let w0 = std::f32::consts::TAU * cutoff_hz / sample_rate;
736 let (sin, cos) = w0.sin_cos();
737 let alpha = sin / (2.0 * std::f32::consts::FRAC_1_SQRT_2);
738 let a0 = 1.0 + alpha;
739 Some(Self {
740 b0: (1.0 - cos) * 0.5 / a0,
741 b1: (1.0 - cos) / a0,
742 b2: (1.0 - cos) * 0.5 / a0,
743 a1: -2.0 * cos / a0,
744 a2: (1.0 - alpha) / a0,
745 })
746 }
747}
748
749#[derive(Debug, Clone, Copy, Default)]
751struct LowPassHistory {
752 x1: f32,
753 x2: f32,
754 y1: f32,
755 y2: f32,
756}
757
758impl LowPassHistory {
759 fn process(&mut self, coefficients: Option<LowPassCoefficients>, input: f32) -> f32 {
763 let x = if input.is_finite() { input } else { 0.0 };
764 let filtered = coefficients.map(|c| {
765 let y = c.b0 * x + c.b1 * self.x1 + c.b2 * self.x2 - c.a1 * self.y1 - c.a2 * self.y2;
766 if y.is_finite() { y.clamp(-1.0, 1.0) } else { x }
767 });
768 let y = filtered.unwrap_or(x);
769 self.x2 = self.x1;
770 self.x1 = x;
771 self.y2 = self.y1;
772 self.y1 = y;
773 filtered.unwrap_or(input)
774 }
775}
776
777struct LowPassSource<S> {
780 inner: S,
781 cutoff: Arc<AtomicU32>,
782 cutoff_bits: u32,
783 sample_rate: u32,
784 coefficients: Option<LowPassCoefficients>,
785 history: Vec<LowPassHistory>,
786 channel: usize,
787}
788
789impl<S> LowPassSource<S>
790where
791 S: RodioSource,
792 S::Item: RodioSample,
793{
794 fn new(inner: S, cutoff: Arc<AtomicU32>) -> Self {
795 Self {
796 inner,
797 cutoff,
798 cutoff_bits: 0,
799 sample_rate: 0,
800 coefficients: None,
801 history: Vec::new(),
802 channel: 0,
803 }
804 }
805}
806
807impl<S> Iterator for LowPassSource<S>
808where
809 S: RodioSource,
810 S::Item: RodioSample,
811{
812 type Item = f32;
813
814 fn next(&mut self) -> Option<f32> {
815 let channels = usize::from(self.inner.channels().max(1));
816 let sample_rate = self.inner.sample_rate();
817 let sample = RodioSample::to_f32(self.inner.next()?);
818
819 if self.history.len() != channels {
820 self.history.clear();
821 self.history.resize(channels, LowPassHistory::default());
822 self.channel = 0;
823 }
824 let cutoff_bits = self.cutoff.load(Ordering::Relaxed);
825 if cutoff_bits != self.cutoff_bits || sample_rate != self.sample_rate {
826 self.cutoff_bits = cutoff_bits;
827 self.sample_rate = sample_rate;
828 self.coefficients = LowPassCoefficients::new(f32::from_bits(cutoff_bits), sample_rate);
829 }
830
831 let channel = self.channel;
832 self.channel = (channel + 1) % channels;
833 let coefficients = self.coefficients;
834 Some(self.history[channel].process(coefficients, sample))
835 }
836
837 fn size_hint(&self) -> (usize, Option<usize>) {
838 self.inner.size_hint()
839 }
840}
841
842impl<S> RodioSource for LowPassSource<S>
843where
844 S: RodioSource,
845 S::Item: RodioSample,
846{
847 fn current_frame_len(&self) -> Option<usize> {
848 self.inner.current_frame_len()
849 }
850
851 fn channels(&self) -> u16 {
852 self.inner.channels()
853 }
854
855 fn sample_rate(&self) -> u32 {
856 self.inner.sample_rate()
857 }
858
859 fn total_duration(&self) -> Option<Duration> {
860 self.inner.total_duration()
861 }
862}
863
864#[cfg(test)]
867mod tests {
868 use super::*;
869
870 fn config_with_paths() -> SfxConfig {
871 let mut cfg = SfxConfig::new();
872 cfg.register(
873 SfxEvent::BlockPlace,
874 vec![
875 "sounds/place1.ogg",
876 "sounds/place2.ogg",
877 "sounds/place3.ogg",
878 ],
879 );
880 cfg
881 }
882
883 #[test]
884 fn test_sfx_config_pick_deterministic() {
885 let cfg = config_with_paths();
886 let first = cfg.pick_path(&SfxEvent::BlockPlace, 0);
887 let second = cfg.pick_path(&SfxEvent::BlockPlace, 0);
888 assert_eq!(first, second, "same seed must always produce the same path");
889 }
890
891 #[test]
892 fn sfx_plugin_runs_without_the_mining_and_placement_plugins() {
893 let mut app = App::new();
894 app.add_plugins(MinimalPlugins).add_plugins(SfxPlugin);
895
896 app.update();
899 }
900
901 #[test]
902 fn sfx_plugin_turns_world_messages_into_requests_on_its_own() {
903 let mut app = App::new();
904 app.add_plugins(MinimalPlugins).add_plugins(SfxPlugin);
905
906 app.world_mut().write_message(VoxelPlaced {
907 chunk_coord: IVec3::ZERO,
908 local: (0, 0, 0),
909 world_pos: Vec3::new(1.0, 2.0, 3.0),
910 face_normal: IVec3::Y,
911 });
912 app.update();
913
914 let requests = app.world().resource::<Messages<SfxRequest>>();
915 let mut cursor = requests.get_cursor();
916 let read: Vec<_> = cursor.read(requests).collect();
917 assert_eq!(read.len(), 1);
918 assert_eq!(read[0].event, SfxEvent::BlockPlace);
919 assert_eq!(read[0].position, Some(Vec3::new(1.0, 2.0, 3.0)));
920 }
921
922 #[test]
923 fn test_sfx_config_pick_wraps() {
924 let cfg = config_with_paths();
925 let path = cfg.pick_path(&SfxEvent::BlockPlace, 5);
927 assert!(
928 path.is_some(),
929 "seed > paths.len() must still return a valid path"
930 );
931 assert_eq!(path.unwrap(), "sounds/place3.ogg");
932 }
933
934 #[test]
935 fn test_sfx_config_returns_none_for_unregistered_event() {
936 let cfg = SfxConfig::new();
937 assert!(cfg.pick_path(&SfxEvent::Mining, 0).is_none());
938 }
939
940 #[test]
941 fn test_sfx_config_get_paths() {
942 let cfg = config_with_paths();
943 let paths = cfg.get_paths(&SfxEvent::BlockPlace).unwrap();
944 assert_eq!(paths.len(), 3);
945 }
946
947 #[test]
948 fn test_sfx_event_key_custom() {
949 let event = SfxEvent::Custom("footstep".to_string());
950 assert_eq!(event.key(), "Custom:footstep");
951 }
952
953 #[test]
956 fn pitched_request_builder_sets_fields() {
957 let request = PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.5);
958 assert_eq!(request.event, SfxEvent::ItemPickup);
959 assert_eq!(request.position, None);
960 assert_eq!(request.effective_pitch(), 1.5);
961
962 let positioned = request.at(Vec3::new(1.0, 2.0, 3.0));
963 assert_eq!(positioned.position, Some(Vec3::new(1.0, 2.0, 3.0)));
964 }
965
966 #[test]
967 fn invalid_pitch_plays_at_normal_speed() {
968 for pitch in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0, -0.0, -2.0] {
969 let request = PitchedSfxRequest::new(SfxEvent::ItemPickup, pitch);
970 assert_eq!(request.effective_pitch(), 1.0, "pitch {pitch}");
971 }
972 }
973
974 #[test]
975 fn extreme_pitch_is_clamped() {
976 let low = PitchedSfxRequest::new(SfxEvent::ItemPickup, 0.0001);
977 let high = PitchedSfxRequest::new(SfxEvent::ItemPickup, 1000.0);
978 assert_eq!(low.effective_pitch(), PitchedSfxRequest::MIN_PITCH);
979 assert_eq!(high.effective_pitch(), PitchedSfxRequest::MAX_PITCH);
980 }
981
982 #[test]
983 fn filter_is_off_by_default() {
984 assert_eq!(SfxFilter::default(), SfxFilter::NONE);
985 assert_eq!(SfxFilter::default().effective_low_pass_hz(), None);
986 assert!(!SfxFilter::default().is_active());
987 }
988
989 #[test]
990 fn invalid_cutoff_disables_the_filter() {
991 for hz in [
992 f32::NAN,
993 f32::INFINITY,
994 f32::NEG_INFINITY,
995 0.0,
996 -0.0,
997 -500.0,
998 ] {
999 let filter = SfxFilter::low_pass(hz);
1000 assert_eq!(filter.effective_low_pass_hz(), None, "cutoff {hz}");
1001 assert!(!filter.is_active(), "cutoff {hz}");
1002 }
1003 }
1004
1005 #[test]
1006 fn valid_cutoff_is_kept_and_clamped() {
1007 assert_eq!(
1008 SfxFilter::low_pass(800.0).effective_low_pass_hz(),
1009 Some(800.0)
1010 );
1011 assert_eq!(
1012 SfxFilter::low_pass(1.0).effective_low_pass_hz(),
1013 Some(SfxFilter::MIN_LOW_PASS_HZ)
1014 );
1015 assert_eq!(
1016 SfxFilter::low_pass(1.0e9).effective_low_pass_hz(),
1017 Some(SfxFilter::MAX_LOW_PASS_HZ)
1018 );
1019 }
1020
1021 fn headless_app() -> App {
1026 let mut app = App::new();
1027 app.add_plugins((MinimalPlugins, AssetPlugin::default()));
1028 app.init_asset::<AudioSource>();
1029 app.add_message::<SfxRequest>();
1030 let mut config = SfxConfig::new();
1031 config.register(SfxEvent::ItemPickup, vec!["sounds/pickup.ogg"]);
1032 config.volume = 0.5;
1033 app.insert_resource(config);
1034 app.add_plugins(DefaultAudioPlugin);
1035 app
1036 }
1037
1038 fn headless_app_with_low_pass() -> App {
1041 let mut app = headless_app();
1042 app.init_asset::<LowPassSfx>();
1043 install_low_pass_backend(&mut app);
1044 app
1045 }
1046
1047 struct Spawned {
1048 settings: PlaybackSettings,
1049 plain: bool,
1050 pending: bool,
1051 filtered: bool,
1052 translation: Option<Vec3>,
1053 }
1054
1055 fn spawned_sounds(app: &mut App) -> Vec<Spawned> {
1056 let world = app.world_mut();
1057 let mut query = world.query::<(
1058 &PlaybackSettings,
1059 Has<AudioPlayer<AudioSource>>,
1060 Has<PendingLowPassSfx>,
1061 Has<AudioPlayer<LowPassSfx>>,
1062 Option<&Transform>,
1063 )>();
1064 query
1065 .iter(world)
1066 .map(|(settings, plain, pending, filtered, transform)| Spawned {
1067 settings: *settings,
1068 plain,
1069 pending,
1070 filtered,
1071 translation: transform.map(|transform| transform.translation),
1072 })
1073 .collect()
1074 }
1075
1076 fn shared_cutoff(app: &App) -> f32 {
1077 f32::from_bits(
1078 app.world()
1079 .resource::<SfxFilterShared>()
1080 .0
1081 .load(Ordering::Relaxed),
1082 )
1083 }
1084
1085 #[test]
1086 fn sfx_plugin_registers_pitched_requests() {
1087 let mut app = App::new();
1088 app.add_message::<VoxelBroken>();
1089 app.add_message::<VoxelPlaced>();
1090 app.add_plugins(SfxPlugin);
1091 assert!(
1092 app.world()
1093 .contains_resource::<bevy::ecs::message::Messages<PitchedSfxRequest>>()
1094 );
1095 }
1096
1097 #[test]
1098 fn plain_request_plays_with_unchanged_settings() {
1099 let mut app = headless_app_with_low_pass();
1100 assert_eq!(*app.world().resource::<SfxFilter>(), SfxFilter::NONE);
1101
1102 app.world_mut().write_message(SfxRequest {
1103 event: SfxEvent::ItemPickup,
1104 position: Some(Vec3::new(4.0, 5.0, 6.0)),
1105 });
1106 app.update();
1107
1108 let sounds = spawned_sounds(&mut app);
1109 assert_eq!(sounds.len(), 1);
1110 let sound = &sounds[0];
1111 assert!(sound.plain && !sound.pending && !sound.filtered);
1112 assert_eq!(sound.settings.speed, 1.0);
1113 assert_eq!(sound.settings.volume, bevy::audio::Volume::Linear(0.5));
1114 assert!(matches!(
1115 sound.settings.mode,
1116 bevy::audio::PlaybackMode::Once
1117 ));
1118 assert!(!sound.settings.spatial);
1119 assert_eq!(sound.translation, Some(Vec3::new(4.0, 5.0, 6.0)));
1120 }
1121
1122 #[test]
1123 fn pitched_request_sets_playback_speed() {
1124 let mut app = headless_app();
1125 app.world_mut()
1126 .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.5));
1127 app.world_mut()
1128 .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, f32::NAN).at(Vec3::X));
1129 app.update();
1130
1131 let sounds = spawned_sounds(&mut app);
1132 assert_eq!(sounds.len(), 2);
1133 let pitched = sounds
1134 .iter()
1135 .find(|sound| sound.translation.is_none())
1136 .expect("the request without a position");
1137 let invalid = sounds
1138 .iter()
1139 .find(|sound| sound.translation == Some(Vec3::X))
1140 .expect("the request with a position");
1141 assert!(pitched.plain);
1142 assert_eq!(pitched.settings.speed, 1.5);
1143 assert_eq!(pitched.settings.volume, bevy::audio::Volume::Linear(0.5));
1144 assert!(invalid.plain);
1145 assert_eq!(invalid.settings.speed, 1.0);
1146 }
1147
1148 #[test]
1149 fn pitched_request_for_unregistered_event_plays_nothing() {
1150 let mut app = headless_app();
1151 app.world_mut()
1152 .write_message(PitchedSfxRequest::new(SfxEvent::Mining, 1.5));
1153 app.update();
1154 assert!(spawned_sounds(&mut app).is_empty());
1155 }
1156
1157 #[test]
1158 fn active_filter_holds_the_sound_for_the_low_pass_path() {
1159 let mut app = headless_app_with_low_pass();
1160 app.insert_resource(SfxFilter::low_pass(800.0));
1161 app.world_mut()
1162 .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 2.0).at(Vec3::Y));
1163 app.update();
1164
1165 let sounds = spawned_sounds(&mut app);
1168 assert_eq!(sounds.len(), 1);
1169 let sound = &sounds[0];
1170 assert!(!sound.plain && !sound.filtered);
1171 assert!(sound.pending);
1172 assert_eq!(sound.settings.speed, 2.0);
1173 assert_eq!(sound.translation, Some(Vec3::Y));
1174 assert_eq!(shared_cutoff(&app), 800.0);
1175 }
1176
1177 #[test]
1178 fn filtered_sound_whose_source_fails_to_load_is_despawned() {
1179 let mut app = headless_app_with_low_pass();
1180 app.insert_resource(SfxFilter::low_pass(800.0));
1181 app.world_mut()
1182 .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.0));
1183 app.update();
1184 assert_eq!(spawned_sounds(&mut app).len(), 1);
1185
1186 for _ in 0..500 {
1188 if spawned_sounds(&mut app).is_empty() {
1189 break;
1190 }
1191 std::thread::sleep(Duration::from_millis(10));
1192 app.update();
1193 }
1194 assert!(
1195 spawned_sounds(&mut app).is_empty(),
1196 "a sound that can never be decoded must not wait forever"
1197 );
1198 }
1199
1200 #[test]
1201 fn loaded_source_is_played_through_the_filtered_asset() {
1202 let mut app = headless_app_with_low_pass();
1203 let bytes: Arc<[u8]> = Arc::from(vec![1_u8, 2, 3]);
1204 let source = app
1205 .world_mut()
1206 .resource_mut::<Assets<AudioSource>>()
1207 .add(AudioSource {
1208 bytes: bytes.clone(),
1209 });
1210 let settings = PlaybackSettings::ONCE.with_speed(1.5);
1211 let first = app
1212 .world_mut()
1213 .spawn((PendingLowPassSfx(source.clone()), settings))
1214 .id();
1215 let second = app
1216 .world_mut()
1217 .spawn((PendingLowPassSfx(source.clone()), settings))
1218 .id();
1219 app.update();
1220
1221 let sounds = spawned_sounds(&mut app);
1222 assert_eq!(sounds.len(), 2);
1223 for sound in &sounds {
1224 assert!(sound.filtered && !sound.pending && !sound.plain);
1225 assert_eq!(sound.settings.speed, 1.5);
1226 }
1227
1228 let first_handle = app
1229 .world()
1230 .get::<AudioPlayer<LowPassSfx>>(first)
1231 .expect("filtered player")
1232 .0
1233 .clone();
1234 let second_handle = app
1235 .world()
1236 .get::<AudioPlayer<LowPassSfx>>(second)
1237 .expect("filtered player")
1238 .0
1239 .clone();
1240 assert_eq!(first_handle, second_handle, "one filtered asset per source");
1241
1242 let shared = app.world().resource::<SfxFilterShared>().0.clone();
1243 let filtered = app
1244 .world()
1245 .resource::<Assets<LowPassSfx>>()
1246 .get(&first_handle)
1247 .expect("filtered asset");
1248 assert!(Arc::ptr_eq(&filtered.source.bytes, &bytes));
1249 assert!(Arc::ptr_eq(&filtered.cutoff, &shared));
1250 }
1251
1252 #[test]
1253 fn invalid_cutoff_plays_unfiltered() {
1254 for hz in [f32::NAN, -100.0, 0.0] {
1255 let mut app = headless_app_with_low_pass();
1256 app.insert_resource(SfxFilter::low_pass(hz));
1257 app.world_mut().write_message(SfxRequest {
1258 event: SfxEvent::ItemPickup,
1259 position: None,
1260 });
1261 app.update();
1262
1263 let sounds = spawned_sounds(&mut app);
1264 assert_eq!(sounds.len(), 1, "cutoff {hz}");
1265 assert!(sounds[0].plain && !sounds[0].pending, "cutoff {hz}");
1266 assert_eq!(shared_cutoff(&app), 0.0, "cutoff {hz}");
1267 }
1268 }
1269
1270 #[test]
1271 fn missing_filter_resource_plays_unfiltered() {
1272 let mut app = headless_app_with_low_pass();
1273 app.insert_resource(SfxFilter::low_pass(800.0));
1274 app.update();
1275 assert_eq!(shared_cutoff(&app), 800.0);
1276
1277 app.world_mut().remove_resource::<SfxFilter>();
1278 app.world_mut().write_message(SfxRequest {
1279 event: SfxEvent::ItemPickup,
1280 position: None,
1281 });
1282 app.update();
1283
1284 let sounds = spawned_sounds(&mut app);
1285 assert_eq!(sounds.len(), 1);
1286 assert!(sounds[0].plain && !sounds[0].pending);
1287 assert_eq!(shared_cutoff(&app), 0.0);
1288 }
1289
1290 #[test]
1291 fn filter_without_audio_backend_plays_unfiltered() {
1292 let mut app = headless_app();
1293 app.insert_resource(SfxFilter::low_pass(800.0));
1294 app.finish();
1296 app.cleanup();
1297 assert!(!app.world().contains_resource::<SfxFilterShared>());
1298
1299 app.world_mut().write_message(SfxRequest {
1300 event: SfxEvent::ItemPickup,
1301 position: None,
1302 });
1303 app.update();
1304
1305 let sounds = spawned_sounds(&mut app);
1306 assert_eq!(sounds.len(), 1);
1307 assert!(sounds[0].plain && !sounds[0].pending);
1308 }
1309
1310 struct TestSignal {
1313 samples: std::vec::IntoIter<f32>,
1314 channels: u16,
1315 sample_rate: u32,
1316 }
1317
1318 impl Iterator for TestSignal {
1319 type Item = f32;
1320
1321 fn next(&mut self) -> Option<f32> {
1322 self.samples.next()
1323 }
1324 }
1325
1326 impl RodioSource for TestSignal {
1327 fn current_frame_len(&self) -> Option<usize> {
1328 None
1329 }
1330
1331 fn channels(&self) -> u16 {
1332 self.channels
1333 }
1334
1335 fn sample_rate(&self) -> u32 {
1336 self.sample_rate
1337 }
1338
1339 fn total_duration(&self) -> Option<Duration> {
1340 None
1341 }
1342 }
1343
1344 const TEST_RATE: u32 = 44_100;
1345
1346 fn sine(frequency_hz: f32, samples: usize) -> Vec<f32> {
1347 (0..samples)
1348 .map(|i| (std::f32::consts::TAU * frequency_hz * i as f32 / TEST_RATE as f32).sin())
1349 .collect()
1350 }
1351
1352 fn cutoff_cell(cutoff_hz: f32) -> Arc<AtomicU32> {
1353 Arc::new(AtomicU32::new(cutoff_hz.to_bits()))
1354 }
1355
1356 fn filter_mono(samples: Vec<f32>, cutoff: Arc<AtomicU32>) -> Vec<f32> {
1357 let signal = TestSignal {
1358 samples: samples.into_iter(),
1359 channels: 1,
1360 sample_rate: TEST_RATE,
1361 };
1362 LowPassSource::new(signal, cutoff).collect()
1363 }
1364
1365 fn settled_rms(samples: &[f32]) -> f32 {
1367 let tail = &samples[samples.len() / 2..];
1368 (tail.iter().map(|sample| sample * sample).sum::<f32>() / tail.len() as f32).sqrt()
1369 }
1370
1371 #[test]
1372 fn low_pass_attenuates_high_frequencies_and_keeps_low_ones() {
1373 let high = sine(8_000.0, 8_820);
1374 let low = sine(100.0, 8_820);
1375 let high_out = filter_mono(high.clone(), cutoff_cell(500.0));
1376 let low_out = filter_mono(low.clone(), cutoff_cell(500.0));
1377
1378 assert_eq!(high_out.len(), high.len());
1379 assert!(
1380 settled_rms(&high_out) < 0.05 * settled_rms(&high),
1381 "8 kHz must be strongly attenuated by a 500 Hz low-pass"
1382 );
1383 let low_ratio = settled_rms(&low_out) / settled_rms(&low);
1384 assert!(
1385 (0.9..=1.05).contains(&low_ratio),
1386 "100 Hz must pass a 500 Hz low-pass, got ratio {low_ratio}"
1387 );
1388 }
1389
1390 #[test]
1391 fn low_pass_without_cutoff_is_the_identity() {
1392 let input = sine(8_000.0, 512);
1393 assert_eq!(filter_mono(input.clone(), cutoff_cell(0.0)), input);
1394 assert_eq!(filter_mono(input.clone(), cutoff_cell(20_000.0)), input);
1396 assert_eq!(filter_mono(input.clone(), cutoff_cell(f32::NAN)), input);
1398 }
1399
1400 #[test]
1401 fn low_pass_follows_cutoff_changes_while_playing() {
1402 let input = sine(8_000.0, 8_820);
1403 let cutoff = cutoff_cell(0.0);
1404 let signal = TestSignal {
1405 samples: input.clone().into_iter(),
1406 channels: 1,
1407 sample_rate: TEST_RATE,
1408 };
1409 let mut source = LowPassSource::new(signal, cutoff.clone());
1410
1411 let unfiltered: Vec<f32> = source.by_ref().take(2_940).collect();
1412 assert_eq!(unfiltered, input[..2_940]);
1413
1414 cutoff.store(500.0_f32.to_bits(), Ordering::Relaxed);
1415 let filtered: Vec<f32> = source.by_ref().take(2_940).collect();
1416 assert!(settled_rms(&filtered) < 0.05 * settled_rms(&input));
1417
1418 cutoff.store(0.0_f32.to_bits(), Ordering::Relaxed);
1419 let restored: Vec<f32> = source.collect();
1420 assert_eq!(restored, input[5_880..]);
1421 }
1422
1423 #[test]
1424 fn low_pass_filters_each_channel_separately() {
1425 let frames = 4_410;
1427 let samples: Vec<f32> = (0..frames)
1428 .flat_map(|frame| [0.5, if frame % 2 == 0 { 1.0 } else { -1.0 }])
1429 .collect();
1430 let signal = TestSignal {
1431 samples: samples.into_iter(),
1432 channels: 2,
1433 sample_rate: TEST_RATE,
1434 };
1435 let output: Vec<f32> = LowPassSource::new(signal, cutoff_cell(500.0)).collect();
1436
1437 assert_eq!(output.len(), frames * 2);
1438 let left = output[output.len() - 2];
1439 let right = output[output.len() - 1];
1440 assert!(
1441 (left - 0.5).abs() < 0.01,
1442 "constant level must pass, got {left}"
1443 );
1444 assert!(
1445 right.abs() < 0.01,
1446 "alternation must be removed, got {right}"
1447 );
1448 }
1449
1450 #[test]
1451 fn low_pass_output_stays_finite_for_bad_input() {
1452 let mut input = sine(100.0, 256);
1453 input[10] = f32::NAN;
1454 input[20] = f32::INFINITY;
1455 let output = filter_mono(input, cutoff_cell(500.0));
1456 assert!(output.iter().all(|sample| sample.is_finite()));
1457 assert!(output.iter().all(|sample| (-1.0..=1.0).contains(sample)));
1458 }
1459
1460 #[test]
1461 fn low_pass_reports_the_inner_format() {
1462 let signal = TestSignal {
1463 samples: vec![0.0; 4].into_iter(),
1464 channels: 2,
1465 sample_rate: 22_050,
1466 };
1467 let source = LowPassSource::new(signal, cutoff_cell(500.0));
1468 assert_eq!(source.channels(), 2);
1469 assert_eq!(source.sample_rate(), 22_050);
1470 assert_eq!(source.current_frame_len(), None);
1471 assert_eq!(source.total_duration(), None);
1472 }
1473
1474 #[test]
1475 fn coefficients_reject_values_that_cannot_filter() {
1476 assert!(LowPassCoefficients::new(500.0, TEST_RATE).is_some());
1477 assert_eq!(LowPassCoefficients::new(500.0, 0), None);
1478 assert_eq!(LowPassCoefficients::new(0.0, TEST_RATE), None);
1479 assert_eq!(LowPassCoefficients::new(-1.0, TEST_RATE), None);
1480 assert_eq!(LowPassCoefficients::new(f32::NAN, TEST_RATE), None);
1481 assert_eq!(LowPassCoefficients::new(f32::INFINITY, TEST_RATE), None);
1482 assert_eq!(LowPassCoefficients::new(22_050.0, TEST_RATE), None);
1483 }
1484}