voxel-framework 0.13.1

A reusable voxel engine framework built on Bevy
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
//! Decoupled sound-effect system for the voxel framework.
//!
//! # Design
//!
//! The audio module is deliberately split into two layers:
//!
//! * **Request layer** ([`SfxPlugin`]) — framework systems translate world
//!   events (voxel broken, voxel placed, …) into [`SfxRequest`] messages. The
//!   convenience [`crate::VoxelPlugin`] includes this layer, so it generates
//!   requests but does not play them.
//! * **Playback layer** ([`DefaultAudioPlugin`]) — consumes [`SfxRequest`]
//!   messages, resolves registered paths through [`SfxConfig`], loads the
//!   assets, and spawns Bevy [`AudioPlayer`] entities. Games can replace this
//!   plugin with a custom playback backend.
//!
//! `voxel-framework` enables Bevy's `bevy_audio` and `vorbis` features, so the
//! default playback layer supports Ogg Vorbis assets. The request layer remains
//! separate so games can omit [`DefaultAudioPlugin`] or supply another handler.
//!
//! # Integration
//!
//! 1. Add Bevy's asset and audio plugins, normally through `DefaultPlugins`.
//! 2. Put Ogg Vorbis files in the configured Bevy asset source (normally the
//!    `assets/` directory) and populate [`SfxConfig`] with their asset-relative
//!    paths.
//! 3. Add [`SfxPlugin`] directly, or add [`crate::VoxelPlugin`], to register the
//!    request channel and framework request-producing systems.
//! 4. Add [`DefaultAudioPlugin`] for Bevy audio playback, or add a custom plugin
//!    that consumes [`SfxRequest`] messages. [`crate::VoxelPlugin`] does not add
//!    a playback plugin.
//!
//! # Pitch and low-pass filter
//!
//! * [`PitchedSfxRequest`] is a second request message that also carries a
//!   playback speed. [`SfxRequest`] is unchanged and always plays at normal
//!   speed.
//! * [`SfxFilter`] is a resource that low-pass filters ("muffles") the sound
//!   effects played by [`DefaultAudioPlugin`]. It is off by default.
//!
//! ## Example
//!
//! ```no_run
//! use bevy::prelude::*;
//! use voxel_framework::audio::{DefaultAudioPlugin, SfxConfig, SfxEvent, SfxPlugin};
//!
//! fn main() {
//!     let mut sfx_config = SfxConfig::new();
//!     sfx_config.register(SfxEvent::BlockPlace, vec!["sounds/place1.ogg"]);
//!     sfx_config.register(SfxEvent::MiningComplete, vec!["sounds/break1.ogg"]);
//!
//!     App::new()
//!         .add_plugins(DefaultPlugins)
//!         .insert_resource(sfx_config)
//!         .add_plugins(SfxPlugin)
//!         .add_plugins(DefaultAudioPlugin)
//!         .run();
//! }
//! ```

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;

use bevy::audio::{AddAudioSource, AudioPlugin, Sample as RodioSample, Source as RodioSource};
use bevy::prelude::*;
use bevy::reflect::TypePath;

use crate::world::{VoxelBroken, VoxelPlaced};

// ─── SfxEvent ─────────────────────────────────────────────────────────────────

/// A category of sound effect that the framework can request.
///
/// Each variant corresponds to a distinct gameplay moment.  Framework systems
/// emit these through [`SfxRequest`]; games map them to asset paths via
/// [`SfxConfig`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SfxEvent {
    /// Emitted repeatedly while the player is actively mining a voxel (e.g.
    /// for a continuous digging sound loop or per-hit chip).
    Mining,
    /// Emitted once when a voxel is fully broken and removed from the world.
    /// Triggered by the `VoxelBroken` message.
    MiningComplete,
    /// Emitted when a voxel is successfully placed into the world.
    /// Triggered by the `VoxelPlaced` message.
    BlockPlace,
    /// Emitted when the player picks up an item from the world.
    ItemPickup,
    /// Emitted when the player scrolls the hotbar slot selection.
    HotbarScroll,
    /// Emitted when the pause menu is opened.
    PauseOpen,
    /// Emitted when the pause menu is closed.
    PauseClose,
    /// Emitted on each footstep when the player moves while grounded.
    ///
    /// The inner value is the byte representation of the voxel type underfoot,
    /// allowing games to map different surface types to different sounds.
    Footstep(u8),
    /// Escape hatch for game-specific sounds not covered by the framework
    /// variants.  The inner string is an arbitrary identifier chosen by the
    /// game and must match the key used in [`SfxConfig`].
    Custom(String),
}

impl SfxEvent {
    /// Returns a stable string key for this event used as the `HashMap` key in
    /// [`SfxConfig`].
    pub fn key(&self) -> String {
        match self {
            SfxEvent::Mining => "Mining".to_string(),
            SfxEvent::MiningComplete => "MiningComplete".to_string(),
            SfxEvent::BlockPlace => "BlockPlace".to_string(),
            SfxEvent::ItemPickup => "ItemPickup".to_string(),
            SfxEvent::HotbarScroll => "HotbarScroll".to_string(),
            SfxEvent::PauseOpen => "PauseOpen".to_string(),
            SfxEvent::PauseClose => "PauseClose".to_string(),
            SfxEvent::Footstep(surface) => format!("Footstep:{surface}"),
            SfxEvent::Custom(s) => format!("Custom:{s}"),
        }
    }
}

// ─── SfxRequest ───────────────────────────────────────────────────────────────

/// A request for a sound effect to be played, emitted by framework systems.
///
/// [`SfxPlugin`] adds systems that produce these messages in response to world
/// events.  A playback plugin (e.g. [`DefaultAudioPlugin`] or a custom one)
/// reads them and drives the audio backend.
#[derive(Message, Debug, Clone)]
pub struct SfxRequest {
    /// The sound effect category to play.
    pub event: SfxEvent,
    /// World-space position for spatial (3-D) audio, or `None` for a 2-D / UI
    /// sound that has no position.
    ///
    /// When `Some`, the playback system may attenuate volume and apply panning
    /// based on the listener's position.  When `None`, the sound should be
    /// played at a fixed volume regardless of the camera position.
    pub position: Option<Vec3>,
}

// ─── PitchedSfxRequest ────────────────────────────────────────────────────────

/// A request for a sound effect played at a chosen pitch.
///
/// This is the pitched counterpart of [`SfxRequest`]: the same event and
/// optional position, plus a playback-speed multiplier. It is a separate
/// message so that [`SfxRequest`] keeps its two fields; code that builds or
/// reads [`SfxRequest`] is unaffected. The framework itself never writes this
/// message.
///
/// [`SfxPlugin`] and [`DefaultAudioPlugin`] both register the message.
/// [`DefaultAudioPlugin`] plays it exactly like an [`SfxRequest`] for the same
/// event (same [`SfxConfig`] paths, same round-robin counter, same volume),
/// with the playback speed set to [`PitchedSfxRequest::effective_pitch`]. A
/// custom playback backend that wants pitched sounds must read this message
/// too.
///
/// Pitch is implemented as playback speed: `2.0` plays one octave higher and
/// in half the time, `0.5` one octave lower and twice as long. Pitch cannot be
/// changed without changing the duration.
///
/// The struct is `#[non_exhaustive]`: build it with [`PitchedSfxRequest::new`]
/// and [`PitchedSfxRequest::at`]. The fields can still be read and assigned.
///
/// # Examples
///
/// A sound that rises in pitch on consecutive uses:
///
/// ```no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
///
/// fn rising_sound(mut streak: Local<u32>, mut sfx: MessageWriter<PitchedSfxRequest>) {
///     let pitch = 1.0 + 0.05 * (*streak).min(12) as f32;
///     *streak += 1;
///     sfx.write(PitchedSfxRequest::new(SfxEvent::ItemPickup, pitch));
/// }
/// ```
#[derive(Message, Debug, Clone)]
#[non_exhaustive]
pub struct PitchedSfxRequest {
    /// The sound effect category to play.
    pub event: SfxEvent,
    /// World-space position, or `None` for a sound without a position. Same
    /// meaning as [`SfxRequest::position`].
    pub position: Option<Vec3>,
    /// Playback-speed multiplier; `1.0` is the unmodified sound.
    ///
    /// The stored value is not validated. Playback uses
    /// [`PitchedSfxRequest::effective_pitch`].
    pub pitch: f32,
}

impl PitchedSfxRequest {
    /// Lowest playback speed [`PitchedSfxRequest::effective_pitch`] returns.
    pub const MIN_PITCH: f32 = 0.1;
    /// Highest playback speed [`PitchedSfxRequest::effective_pitch`] returns.
    pub const MAX_PITCH: f32 = 8.0;

    /// Creates a request without a position.
    pub fn new(event: SfxEvent, pitch: f32) -> Self {
        Self {
            event,
            position: None,
            pitch,
        }
    }

    /// Sets the world-space position of the sound.
    pub fn at(mut self, position: Vec3) -> Self {
        self.position = Some(position);
        self
    }

    /// The playback speed a backend should use for this request.
    ///
    /// A pitch that is NaN, infinite, zero or negative yields `1.0`, so an
    /// invalid value plays the sound unmodified instead of silencing or
    /// breaking it. Any other value is clamped to
    /// [`PitchedSfxRequest::MIN_PITCH`]..=[`PitchedSfxRequest::MAX_PITCH`].
    pub fn effective_pitch(&self) -> f32 {
        if self.pitch.is_finite() && self.pitch > 0.0 {
            self.pitch.clamp(Self::MIN_PITCH, Self::MAX_PITCH)
        } else {
            1.0
        }
    }
}

// ─── SfxFilter ────────────────────────────────────────────────────────────────

/// Global low-pass filter ("muffle") for sound effects.
///
/// [`DefaultAudioPlugin`] initializes this resource with the filter off, which
/// leaves playback exactly as it is without the resource. Set
/// [`SfxFilter::low_pass_hz`] to muffle sound effects, for example while a
/// game state is active, and set it back to `None` to return to normal.
///
/// # What is filtered
///
/// * Only sounds played by [`DefaultAudioPlugin`] from [`SfxRequest`] and
///   [`PitchedSfxRequest`] messages. Audio the game spawns itself is not
///   touched, and a custom playback backend has to read this resource itself.
/// * The filter is chosen when a sound starts. A sound that starts while the
///   filter is on follows later changes of the cutoff, including being turned
///   off, while it plays. A sound that starts while the filter is off stays
///   unfiltered until it ends. Sound effects are short, so in practice the
///   change is heard on the next sounds.
/// * The filter needs Bevy's `AudioPlugin` and `AssetPlugin` (both part of
///   `DefaultPlugins`). Without them the resource is ignored and sounds are
///   requested unfiltered.
///
/// The filter is a second-order (12 dB per octave) low-pass applied per
/// channel. It is implemented in this crate on top of Bevy's audio decoding;
/// no other effects (reverb, high-pass, per-sound filters) are provided.
///
/// While the filter is on, a sound's entity carries an `AudioPlayer` of a
/// private filtered asset type instead of `AudioPlayer<AudioSource>`.
/// `PlaybackSettings`, the optional `Transform` and Bevy's `AudioSink` are
/// the same in both cases.
///
/// The struct is `#[non_exhaustive]`: create it with [`SfxFilter::NONE`],
/// [`SfxFilter::low_pass`] or `default()`, then assign fields.
///
/// # Examples
///
/// ```no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
///
/// fn muffle(mut filter: ResMut<SfxFilter>) {
///     filter.low_pass_hz = Some(700.0);
/// }
///
/// fn unmuffle(mut filter: ResMut<SfxFilter>) {
///     *filter = SfxFilter::NONE;
/// }
///
/// fn pitched_sound(mut sfx: MessageWriter<PitchedSfxRequest>) {
///     sfx.write(PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.25));
/// }
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugins(SfxPlugin)
///     .add_plugins(DefaultAudioPlugin)
///     .add_systems(Startup, muffle)
///     .add_systems(Update, (pitched_sound, unmuffle))
///     .run();
/// ```
#[derive(Resource, Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct SfxFilter {
    /// Cutoff frequency of the low-pass filter in hertz, or `None` for no
    /// filter. Lower values sound more muffled.
    ///
    /// The stored value is not validated. Playback uses
    /// [`SfxFilter::effective_low_pass_hz`].
    pub low_pass_hz: Option<f32>,
}

impl SfxFilter {
    /// No filter. Same as `SfxFilter::default()`.
    pub const NONE: Self = Self { low_pass_hz: None };

    /// Lowest cutoff [`SfxFilter::effective_low_pass_hz`] returns, in hertz.
    pub const MIN_LOW_PASS_HZ: f32 = 20.0;
    /// Highest cutoff [`SfxFilter::effective_low_pass_hz`] returns, in hertz.
    pub const MAX_LOW_PASS_HZ: f32 = 20_000.0;

    /// A low-pass filter with the given cutoff frequency in hertz.
    pub const fn low_pass(cutoff_hz: f32) -> Self {
        Self {
            low_pass_hz: Some(cutoff_hz),
        }
    }

    /// The cutoff a backend should apply, or `None` when nothing is filtered.
    ///
    /// A cutoff that is NaN, infinite, zero or negative yields `None`, so an
    /// invalid value never silences sound effects. Any other value is clamped
    /// to [`SfxFilter::MIN_LOW_PASS_HZ`]..=[`SfxFilter::MAX_LOW_PASS_HZ`].
    /// During playback, a cutoff at or above 45 % of a sound's sample rate is
    /// skipped for that sound, because nothing audible would be removed.
    pub fn effective_low_pass_hz(&self) -> Option<f32> {
        let hz = self.low_pass_hz?;
        if hz.is_finite() && hz > 0.0 {
            Some(hz.clamp(Self::MIN_LOW_PASS_HZ, Self::MAX_LOW_PASS_HZ))
        } else {
            None
        }
    }

    /// Whether [`SfxFilter::effective_low_pass_hz`] is `Some`.
    pub fn is_active(&self) -> bool {
        self.effective_low_pass_hz().is_some()
    }
}

// ─── SfxConfig ────────────────────────────────────────────────────────────────

/// Maps [`SfxEvent`] categories to lists of asset paths.
///
/// Each category can hold multiple paths so the game can register variant
/// sounds (e.g. several digging sounds) and play them in round-robin order.
/// A specific path is selected deterministically by `pick_path` using a
/// caller-supplied seed, making the selection reproducible across frames.
///
/// `SfxConfig` is registered as a `Resource` by [`SfxPlugin`]; insert your
/// populated instance before adding the plugin, or mutate the resource after
/// `App::run` via a startup system.
///
/// # Examples
///
/// ```no_run
/// use voxel_framework::audio::{SfxConfig, SfxEvent};
///
/// let mut config = SfxConfig::new();
/// config.register(SfxEvent::BlockPlace, vec!["sounds/place1.ogg", "sounds/place2.ogg"]);
/// assert_eq!(config.pick_path(&SfxEvent::BlockPlace, 0), Some("sounds/place1.ogg"));
/// assert_eq!(config.pick_path(&SfxEvent::BlockPlace, 1), Some("sounds/place2.ogg"));
/// // Seeds wrap around: seed 2 → index 0 again for a two-entry list.
/// assert_eq!(config.pick_path(&SfxEvent::BlockPlace, 2), Some("sounds/place1.ogg"));
/// ```
#[derive(Resource, Debug, Clone)]
pub struct SfxConfig {
    /// Maps the string key of each [`SfxEvent`] to its registered asset paths.
    ///
    /// Keys are produced by [`SfxEvent::key`].  Prefer using
    /// [`SfxConfig::register`] rather than inserting into this map directly.
    pub sounds: HashMap<String, Vec<String>>,
    /// Master playback volume applied to all sounds, in the range `[0.0, 1.0]`.
    ///
    /// `0.0` is silent; `1.0` is full volume.  Default: `1.0`.  Values outside
    /// `[0.0, 1.0]` are not clamped by the framework — the audio backend
    /// determines how they are handled.
    pub volume: f32,
}

impl SfxConfig {
    /// Creates an empty [`SfxConfig`] with master volume `1.0`.
    pub fn new() -> Self {
        Self {
            sounds: HashMap::new(),
            volume: 1.0,
        }
    }

    /// Registers one or more asset paths for the given event category.
    ///
    /// Calling this a second time for the same event **replaces** the
    /// existing path list.
    pub fn register(&mut self, event: SfxEvent, paths: Vec<&str>) {
        self.sounds.insert(
            event.key(),
            paths.into_iter().map(|p| p.to_string()).collect(),
        );
    }

    /// Returns all registered paths for an event, or `None` if unregistered.
    pub fn get_paths(&self, event: &SfxEvent) -> Option<&Vec<String>> {
        self.sounds.get(&event.key())
    }

    /// Deterministically picks one path for `event` using `seed`.
    ///
    /// The selection is `paths[seed % paths.len()]`, so the same seed always
    /// produces the same result. Returns `None` if the event has no paths.
    pub fn pick_path(&self, event: &SfxEvent, seed: u64) -> Option<&str> {
        let paths = self.get_paths(event)?;
        if paths.is_empty() {
            return None;
        }
        let index = (seed % paths.len() as u64) as usize;
        Some(paths[index].as_str())
    }
}

impl Default for SfxConfig {
    fn default() -> Self {
        Self::new()
    }
}

// ─── Systems ──────────────────────────────────────────────────────────────────

/// Translates `VoxelBroken` messages into [`SfxRequest`] messages with event
/// [`SfxEvent::MiningComplete`].
///
/// The request carries the broken voxel's world position so that a spatial
/// audio handler can place the sound in 3-D space.  This system is added by
/// [`SfxPlugin`] and runs in the [`Update`] schedule.
pub fn mining_sfx_system(
    mut broken_reader: MessageReader<VoxelBroken>,
    mut sfx_writer: MessageWriter<SfxRequest>,
) {
    for broken in broken_reader.read() {
        sfx_writer.write(SfxRequest {
            event: SfxEvent::MiningComplete,
            position: Some(broken.world_pos),
        });
    }
}

/// Translates `VoxelPlaced` messages into [`SfxRequest`] messages with event
/// [`SfxEvent::BlockPlace`].
///
/// The request carries the placed voxel's world position so that a spatial
/// audio handler can place the sound in 3-D space.  This system is added by
/// [`SfxPlugin`] and runs in the [`Update`] schedule.
pub fn placement_sfx_system(
    mut placed_reader: MessageReader<VoxelPlaced>,
    mut sfx_writer: MessageWriter<SfxRequest>,
) {
    for placed in placed_reader.read() {
        sfx_writer.write(SfxRequest {
            event: SfxEvent::BlockPlace,
            position: Some(placed.world_pos),
        });
    }
}

// ─── SfxPlugin ────────────────────────────────────────────────────────────────

/// Core plugin for the framework sound-effect system.
///
/// # What it registers
///
/// * [`SfxConfig`] — initialized as a default resource (all categories empty,
///   volume `1.0`).  Insert a pre-populated instance before adding this plugin
///   to override the defaults.
/// * The [`SfxRequest`] message channel so framework systems can emit requests
///   and game systems can read them.
/// * The [`PitchedSfxRequest`] message channel, which only the game writes.
/// * [`mining_sfx_system`] and [`placement_sfx_system`] in the [`Update`]
///   schedule.
///
/// # What it does NOT do
///
/// `SfxPlugin` never loads audio assets, never creates audio entities, and
/// never calls into any audio backend. Actual playback is the responsibility
/// of a separate plugin — either [`DefaultAudioPlugin`], which uses Bevy audio,
/// or a custom plugin that reads [`SfxRequest`] events. [`crate::VoxelPlugin`]
/// includes `SfxPlugin`, but it does not include a playback plugin.
pub struct SfxPlugin;

impl Plugin for SfxPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<SfxConfig>();
        app.add_message::<SfxRequest>();
        app.add_message::<PitchedSfxRequest>();
        app.add_systems(Update, (mining_sfx_system, placement_sfx_system));
    }
}

// ─── DefaultAudioPlugin ───────────────────────────────────────────────────────

/// A round-robin counter per SFX key so successive identical events cycle
/// through registered variant paths rather than always picking the same one.
#[derive(Resource, Default)]
struct SfxCounter(HashMap<String, u64>);

/// Ready-to-use audio plugin that plays [`SfxRequest`] and
/// [`PitchedSfxRequest`] messages via Bevy's built-in `bevy_audio` backend.
///
/// For each incoming request, this plugin:
/// 1. Resolves the event key through [`SfxConfig::pick_path`] (round-robin
///    across registered variants).
/// 2. Loads the asset with `AssetServer::load`.
/// 3. Spawns an `(AudioPlayer, PlaybackSettings::ONCE)` entity that Bevy's
///    audio system plays once. The entity is not despawned when the sound
///    ends. The volume comes from [`SfxConfig::volume`] and, for a
///    [`PitchedSfxRequest`], the speed comes from
///    [`PitchedSfxRequest::effective_pitch`].
///
/// The plugin also initializes [`SfxFilter`] (off by default). While that
/// filter is on, new sounds are played through a low-pass filter; see
/// [`SfxFilter`] for what is and is not filtered.
///
/// # Setup
///
/// Register asset paths with [`SfxConfig`] before adding the plugin, or
/// populate them in a startup system:
///
/// ```no_run
/// use bevy::prelude::*;
/// use voxel_framework::audio::{DefaultAudioPlugin, SfxConfig, SfxEvent, SfxPlugin};
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugins(SfxPlugin)
///     .add_plugins(DefaultAudioPlugin)
///     .add_systems(Startup, |mut cfg: ResMut<SfxConfig>| {
///         cfg.register(SfxEvent::MiningComplete, vec!["sounds/break.ogg"]);
///         cfg.register(SfxEvent::BlockPlace,     vec!["sounds/place.ogg"]);
///     })
///     .run();
/// ```
///
/// # Missing files
///
/// If an asset path is not found on disk, Bevy logs a warning and skips
/// playback — no panic, no crash.
///
/// # Spatial audio
///
/// When the [`SfxRequest::position`] field is `Some`, the plugin attaches a
/// [`SpatialListener`]-compatible [`Transform`] to the audio entity so Bevy
/// can attenuate volume by distance.  Requires a [`SpatialListener`] on the
/// camera/player entity.
pub struct DefaultAudioPlugin;

impl Plugin for DefaultAudioPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<SfxCounter>();
        app.init_resource::<SfxFilter>();
        app.add_message::<PitchedSfxRequest>();
        app.add_systems(Update, play_sfx_system);
    }

    /// Registers the low-pass playback path once every plugin is built, so
    /// the order in which this plugin and Bevy's plugins are added does not
    /// matter. Without Bevy's audio and asset plugins nothing is registered
    /// and [`SfxFilter`] has no effect.
    fn finish(&self, app: &mut App) {
        if app.is_plugin_added::<AudioPlugin>() && app.world().contains_resource::<AssetServer>() {
            app.add_audio_source::<LowPassSfx>();
            install_low_pass_backend(app);
        }
    }
}

/// Adds the resources and systems of the low-pass playback path. The
/// `LowPassSfx` asset type must already be registered.
fn install_low_pass_backend(app: &mut App) {
    app.init_resource::<SfxFilterShared>()
        .init_resource::<LowPassSfxCache>()
        .add_systems(
            Update,
            (
                sync_sfx_filter_system.before(play_sfx_system),
                resolve_low_pass_sfx_system.after(play_sfx_system),
            ),
        );
}

fn play_sfx_system(
    mut sfx_reader: MessageReader<SfxRequest>,
    mut pitched_reader: MessageReader<PitchedSfxRequest>,
    config: Res<SfxConfig>,
    asset_server: Res<AssetServer>,
    mut counter: ResMut<SfxCounter>,
    (filter, low_pass_backend): (Option<Res<SfxFilter>>, Option<Res<SfxFilterShared>>),
    mut commands: Commands,
) {
    let low_pass = low_pass_backend.is_some() && filter.is_some_and(|filter| filter.is_active());

    let plain = sfx_reader
        .read()
        .map(|request| (&request.event, request.position, 1.0_f32));
    let pitched = pitched_reader
        .read()
        .map(|request| (&request.event, request.position, request.effective_pitch()));

    for (event, position, speed) in plain.chain(pitched) {
        let seed = {
            let c = counter.0.entry(event.key()).or_insert(0);
            let s = *c;
            *c = c.wrapping_add(1);
            s
        };
        let Some(path) = config.pick_path(event, seed).map(|p| p.to_owned()) else {
            continue;
        };
        let source: Handle<AudioSource> = asset_server.load(path);
        let mut settings = PlaybackSettings::ONCE;
        settings.volume = bevy::audio::Volume::Linear(config.volume);
        settings.speed = speed;
        let mut entity = if low_pass {
            commands.spawn((PendingLowPassSfx(source), settings))
        } else {
            commands.spawn((AudioPlayer(source), settings))
        };
        if let Some(pos) = position {
            entity.insert(Transform::from_translation(pos));
        }
    }
}

// ─── Low-pass playback path ───────────────────────────────────────────────────

/// The cutoff every playing filtered sound reads: the bits of an `f32` in
/// hertz, where `0.0` means "no filter". Its presence also tells
/// `play_sfx_system` that the low-pass path is installed.
#[derive(Resource, Default)]
struct SfxFilterShared(Arc<AtomicU32>);

/// Filtered asset per source, so repeated sounds reuse one asset. The source
/// handle is kept so the source's id stays valid for as long as the entry.
#[derive(Resource, Default)]
struct LowPassSfxCache(HashMap<AssetId<AudioSource>, (Handle<AudioSource>, Handle<LowPassSfx>)>);

/// A sound waiting for its source to load before it can be played filtered.
#[derive(Component)]
struct PendingLowPassSfx(Handle<AudioSource>);

/// An [`AudioSource`] decoded through `LowPassSource`.
#[derive(Asset, TypePath)]
struct LowPassSfx {
    source: AudioSource,
    cutoff: Arc<AtomicU32>,
}

impl Decodable for LowPassSfx {
    type DecoderItem = f32;
    type Decoder = LowPassSource<<AudioSource as Decodable>::Decoder>;

    fn decoder(&self) -> Self::Decoder {
        LowPassSource::new(self.source.decoder(), self.cutoff.clone())
    }
}

fn sync_sfx_filter_system(filter: Option<Res<SfxFilter>>, shared: Res<SfxFilterShared>) {
    let cutoff_hz = filter
        .and_then(|filter| filter.effective_low_pass_hz())
        .unwrap_or(0.0);
    shared.0.store(cutoff_hz.to_bits(), Ordering::Relaxed);
}

fn resolve_low_pass_sfx_system(
    pending: Query<(Entity, &PendingLowPassSfx)>,
    sources: Res<Assets<AudioSource>>,
    mut filtered: ResMut<Assets<LowPassSfx>>,
    asset_server: Res<AssetServer>,
    shared: Res<SfxFilterShared>,
    mut cache: ResMut<LowPassSfxCache>,
    mut commands: Commands,
) {
    for (entity, pending) in &pending {
        let id = pending.0.id();
        if let Some(source) = sources.get(id) {
            let handle = match cache.0.get(&id) {
                Some((_, handle)) => handle.clone(),
                None => {
                    let handle = filtered.add(LowPassSfx {
                        source: source.clone(),
                        cutoff: shared.0.clone(),
                    });
                    cache.0.insert(id, (pending.0.clone(), handle.clone()));
                    handle
                }
            };
            commands
                .entity(entity)
                .insert(AudioPlayer::<LowPassSfx>(handle))
                .remove::<PendingLowPassSfx>();
        } else if asset_server.load_state(id).is_failed() {
            commands.entity(entity).despawn();
        }
    }
}

/// Normalized biquad coefficients of a second-order Butterworth low-pass.
#[derive(Debug, Clone, Copy, PartialEq)]
struct LowPassCoefficients {
    b0: f32,
    b1: f32,
    b2: f32,
    a1: f32,
    a2: f32,
}

impl LowPassCoefficients {
    /// Returns `None` when nothing should be filtered: an invalid cutoff or
    /// sample rate, or a cutoff at or above 45 % of the sample rate.
    fn new(cutoff_hz: f32, sample_rate: u32) -> Option<Self> {
        if !cutoff_hz.is_finite() || cutoff_hz <= 0.0 || sample_rate == 0 {
            return None;
        }
        let sample_rate = sample_rate as f32;
        if cutoff_hz >= sample_rate * 0.45 {
            return None;
        }
        let w0 = std::f32::consts::TAU * cutoff_hz / sample_rate;
        let (sin, cos) = w0.sin_cos();
        let alpha = sin / (2.0 * std::f32::consts::FRAC_1_SQRT_2);
        let a0 = 1.0 + alpha;
        Some(Self {
            b0: (1.0 - cos) * 0.5 / a0,
            b1: (1.0 - cos) / a0,
            b2: (1.0 - cos) * 0.5 / a0,
            a1: -2.0 * cos / a0,
            a2: (1.0 - alpha) / a0,
        })
    }
}

/// The last two inputs and outputs of one channel.
#[derive(Debug, Clone, Copy, Default)]
struct LowPassHistory {
    x1: f32,
    x2: f32,
    y1: f32,
    y2: f32,
}

impl LowPassHistory {
    /// Filters one sample. Without coefficients the sample is returned as it
    /// came, but the history keeps running so that switching the filter on in
    /// the middle of a sound does not start from silence.
    fn process(&mut self, coefficients: Option<LowPassCoefficients>, input: f32) -> f32 {
        let x = if input.is_finite() { input } else { 0.0 };
        let filtered = coefficients.map(|c| {
            let y = c.b0 * x + c.b1 * self.x1 + c.b2 * self.x2 - c.a1 * self.y1 - c.a2 * self.y2;
            if y.is_finite() { y.clamp(-1.0, 1.0) } else { x }
        });
        let y = filtered.unwrap_or(x);
        self.x2 = self.x1;
        self.x1 = x;
        self.y2 = self.y1;
        self.y1 = y;
        filtered.unwrap_or(input)
    }
}

/// Low-pass filters `inner`, reading the cutoff from a value shared with
/// [`SfxFilter`] so it can change while the sound plays.
struct LowPassSource<S> {
    inner: S,
    cutoff: Arc<AtomicU32>,
    cutoff_bits: u32,
    sample_rate: u32,
    coefficients: Option<LowPassCoefficients>,
    history: Vec<LowPassHistory>,
    channel: usize,
}

impl<S> LowPassSource<S>
where
    S: RodioSource,
    S::Item: RodioSample,
{
    fn new(inner: S, cutoff: Arc<AtomicU32>) -> Self {
        Self {
            inner,
            cutoff,
            cutoff_bits: 0,
            sample_rate: 0,
            coefficients: None,
            history: Vec::new(),
            channel: 0,
        }
    }
}

impl<S> Iterator for LowPassSource<S>
where
    S: RodioSource,
    S::Item: RodioSample,
{
    type Item = f32;

    fn next(&mut self) -> Option<f32> {
        let channels = usize::from(self.inner.channels().max(1));
        let sample_rate = self.inner.sample_rate();
        let sample = RodioSample::to_f32(self.inner.next()?);

        if self.history.len() != channels {
            self.history.clear();
            self.history.resize(channels, LowPassHistory::default());
            self.channel = 0;
        }
        let cutoff_bits = self.cutoff.load(Ordering::Relaxed);
        if cutoff_bits != self.cutoff_bits || sample_rate != self.sample_rate {
            self.cutoff_bits = cutoff_bits;
            self.sample_rate = sample_rate;
            self.coefficients = LowPassCoefficients::new(f32::from_bits(cutoff_bits), sample_rate);
        }

        let channel = self.channel;
        self.channel = (channel + 1) % channels;
        let coefficients = self.coefficients;
        Some(self.history[channel].process(coefficients, sample))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<S> RodioSource for LowPassSource<S>
where
    S: RodioSource,
    S::Item: RodioSample,
{
    fn current_frame_len(&self) -> Option<usize> {
        self.inner.current_frame_len()
    }

    fn channels(&self) -> u16 {
        self.inner.channels()
    }

    fn sample_rate(&self) -> u32 {
        self.inner.sample_rate()
    }

    fn total_duration(&self) -> Option<Duration> {
        self.inner.total_duration()
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn config_with_paths() -> SfxConfig {
        let mut cfg = SfxConfig::new();
        cfg.register(
            SfxEvent::BlockPlace,
            vec![
                "sounds/place1.ogg",
                "sounds/place2.ogg",
                "sounds/place3.ogg",
            ],
        );
        cfg
    }

    #[test]
    fn test_sfx_config_pick_deterministic() {
        let cfg = config_with_paths();
        let first = cfg.pick_path(&SfxEvent::BlockPlace, 0);
        let second = cfg.pick_path(&SfxEvent::BlockPlace, 0);
        assert_eq!(first, second, "same seed must always produce the same path");
    }

    #[test]
    fn test_sfx_config_pick_wraps() {
        let cfg = config_with_paths();
        // 3 paths; seed 5 → 5 % 3 = 2 → "sounds/place3.ogg"
        let path = cfg.pick_path(&SfxEvent::BlockPlace, 5);
        assert!(
            path.is_some(),
            "seed > paths.len() must still return a valid path"
        );
        assert_eq!(path.unwrap(), "sounds/place3.ogg");
    }

    #[test]
    fn test_sfx_config_returns_none_for_unregistered_event() {
        let cfg = SfxConfig::new();
        assert!(cfg.pick_path(&SfxEvent::Mining, 0).is_none());
    }

    #[test]
    fn test_sfx_config_get_paths() {
        let cfg = config_with_paths();
        let paths = cfg.get_paths(&SfxEvent::BlockPlace).unwrap();
        assert_eq!(paths.len(), 3);
    }

    #[test]
    fn test_sfx_event_key_custom() {
        let event = SfxEvent::Custom("footstep".to_string());
        assert_eq!(event.key(), "Custom:footstep");
    }

    // ── Pitch and filter values ──────────────────────────────────────────────

    #[test]
    fn pitched_request_builder_sets_fields() {
        let request = PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.5);
        assert_eq!(request.event, SfxEvent::ItemPickup);
        assert_eq!(request.position, None);
        assert_eq!(request.effective_pitch(), 1.5);

        let positioned = request.at(Vec3::new(1.0, 2.0, 3.0));
        assert_eq!(positioned.position, Some(Vec3::new(1.0, 2.0, 3.0)));
    }

    #[test]
    fn invalid_pitch_plays_at_normal_speed() {
        for pitch in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0, -0.0, -2.0] {
            let request = PitchedSfxRequest::new(SfxEvent::ItemPickup, pitch);
            assert_eq!(request.effective_pitch(), 1.0, "pitch {pitch}");
        }
    }

    #[test]
    fn extreme_pitch_is_clamped() {
        let low = PitchedSfxRequest::new(SfxEvent::ItemPickup, 0.0001);
        let high = PitchedSfxRequest::new(SfxEvent::ItemPickup, 1000.0);
        assert_eq!(low.effective_pitch(), PitchedSfxRequest::MIN_PITCH);
        assert_eq!(high.effective_pitch(), PitchedSfxRequest::MAX_PITCH);
    }

    #[test]
    fn filter_is_off_by_default() {
        assert_eq!(SfxFilter::default(), SfxFilter::NONE);
        assert_eq!(SfxFilter::default().effective_low_pass_hz(), None);
        assert!(!SfxFilter::default().is_active());
    }

    #[test]
    fn invalid_cutoff_disables_the_filter() {
        for hz in [
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
            0.0,
            -0.0,
            -500.0,
        ] {
            let filter = SfxFilter::low_pass(hz);
            assert_eq!(filter.effective_low_pass_hz(), None, "cutoff {hz}");
            assert!(!filter.is_active(), "cutoff {hz}");
        }
    }

    #[test]
    fn valid_cutoff_is_kept_and_clamped() {
        assert_eq!(
            SfxFilter::low_pass(800.0).effective_low_pass_hz(),
            Some(800.0)
        );
        assert_eq!(
            SfxFilter::low_pass(1.0).effective_low_pass_hz(),
            Some(SfxFilter::MIN_LOW_PASS_HZ)
        );
        assert_eq!(
            SfxFilter::low_pass(1.0e9).effective_low_pass_hz(),
            Some(SfxFilter::MAX_LOW_PASS_HZ)
        );
    }

    // ── Playback entities ────────────────────────────────────────────────────

    /// An app that can run the playback systems without an audio device:
    /// Bevy's `AudioPlugin` is not added, so nothing is ever decoded or played.
    fn headless_app() -> App {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default()));
        app.init_asset::<AudioSource>();
        app.add_message::<SfxRequest>();
        let mut config = SfxConfig::new();
        config.register(SfxEvent::ItemPickup, vec!["sounds/pickup.ogg"]);
        config.volume = 0.5;
        app.insert_resource(config);
        app.add_plugins(DefaultAudioPlugin);
        app
    }

    /// Installs what `DefaultAudioPlugin::finish` installs next to Bevy's
    /// `AudioPlugin`, minus Bevy's own playback systems.
    fn headless_app_with_low_pass() -> App {
        let mut app = headless_app();
        app.init_asset::<LowPassSfx>();
        install_low_pass_backend(&mut app);
        app
    }

    struct Spawned {
        settings: PlaybackSettings,
        plain: bool,
        pending: bool,
        filtered: bool,
        translation: Option<Vec3>,
    }

    fn spawned_sounds(app: &mut App) -> Vec<Spawned> {
        let world = app.world_mut();
        let mut query = world.query::<(
            &PlaybackSettings,
            Has<AudioPlayer<AudioSource>>,
            Has<PendingLowPassSfx>,
            Has<AudioPlayer<LowPassSfx>>,
            Option<&Transform>,
        )>();
        query
            .iter(world)
            .map(|(settings, plain, pending, filtered, transform)| Spawned {
                settings: *settings,
                plain,
                pending,
                filtered,
                translation: transform.map(|transform| transform.translation),
            })
            .collect()
    }

    fn shared_cutoff(app: &App) -> f32 {
        f32::from_bits(
            app.world()
                .resource::<SfxFilterShared>()
                .0
                .load(Ordering::Relaxed),
        )
    }

    #[test]
    fn sfx_plugin_registers_pitched_requests() {
        let mut app = App::new();
        app.add_message::<VoxelBroken>();
        app.add_message::<VoxelPlaced>();
        app.add_plugins(SfxPlugin);
        assert!(
            app.world()
                .contains_resource::<bevy::ecs::message::Messages<PitchedSfxRequest>>()
        );
    }

    #[test]
    fn plain_request_plays_with_unchanged_settings() {
        let mut app = headless_app_with_low_pass();
        assert_eq!(*app.world().resource::<SfxFilter>(), SfxFilter::NONE);

        app.world_mut().write_message(SfxRequest {
            event: SfxEvent::ItemPickup,
            position: Some(Vec3::new(4.0, 5.0, 6.0)),
        });
        app.update();

        let sounds = spawned_sounds(&mut app);
        assert_eq!(sounds.len(), 1);
        let sound = &sounds[0];
        assert!(sound.plain && !sound.pending && !sound.filtered);
        assert_eq!(sound.settings.speed, 1.0);
        assert_eq!(sound.settings.volume, bevy::audio::Volume::Linear(0.5));
        assert!(matches!(
            sound.settings.mode,
            bevy::audio::PlaybackMode::Once
        ));
        assert!(!sound.settings.spatial);
        assert_eq!(sound.translation, Some(Vec3::new(4.0, 5.0, 6.0)));
    }

    #[test]
    fn pitched_request_sets_playback_speed() {
        let mut app = headless_app();
        app.world_mut()
            .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.5));
        app.world_mut()
            .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, f32::NAN).at(Vec3::X));
        app.update();

        let sounds = spawned_sounds(&mut app);
        assert_eq!(sounds.len(), 2);
        let pitched = sounds
            .iter()
            .find(|sound| sound.translation.is_none())
            .expect("the request without a position");
        let invalid = sounds
            .iter()
            .find(|sound| sound.translation == Some(Vec3::X))
            .expect("the request with a position");
        assert!(pitched.plain);
        assert_eq!(pitched.settings.speed, 1.5);
        assert_eq!(pitched.settings.volume, bevy::audio::Volume::Linear(0.5));
        assert!(invalid.plain);
        assert_eq!(invalid.settings.speed, 1.0);
    }

    #[test]
    fn pitched_request_for_unregistered_event_plays_nothing() {
        let mut app = headless_app();
        app.world_mut()
            .write_message(PitchedSfxRequest::new(SfxEvent::Mining, 1.5));
        app.update();
        assert!(spawned_sounds(&mut app).is_empty());
    }

    #[test]
    fn active_filter_holds_the_sound_for_the_low_pass_path() {
        let mut app = headless_app_with_low_pass();
        app.insert_resource(SfxFilter::low_pass(800.0));
        app.world_mut()
            .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 2.0).at(Vec3::Y));
        app.update();

        // The path does not exist, so the source never loads and the sound
        // must not fall back to unfiltered playback.
        let sounds = spawned_sounds(&mut app);
        assert_eq!(sounds.len(), 1);
        let sound = &sounds[0];
        assert!(!sound.plain && !sound.filtered);
        assert!(sound.pending);
        assert_eq!(sound.settings.speed, 2.0);
        assert_eq!(sound.translation, Some(Vec3::Y));
        assert_eq!(shared_cutoff(&app), 800.0);
    }

    #[test]
    fn filtered_sound_whose_source_fails_to_load_is_despawned() {
        let mut app = headless_app_with_low_pass();
        app.insert_resource(SfxFilter::low_pass(800.0));
        app.world_mut()
            .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.0));
        app.update();
        assert_eq!(spawned_sounds(&mut app).len(), 1);

        // The load fails on a background task; give it a bounded time.
        for _ in 0..500 {
            if spawned_sounds(&mut app).is_empty() {
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
            app.update();
        }
        assert!(
            spawned_sounds(&mut app).is_empty(),
            "a sound that can never be decoded must not wait forever"
        );
    }

    #[test]
    fn loaded_source_is_played_through_the_filtered_asset() {
        let mut app = headless_app_with_low_pass();
        let bytes: Arc<[u8]> = Arc::from(vec![1_u8, 2, 3]);
        let source = app
            .world_mut()
            .resource_mut::<Assets<AudioSource>>()
            .add(AudioSource {
                bytes: bytes.clone(),
            });
        let settings = PlaybackSettings::ONCE.with_speed(1.5);
        let first = app
            .world_mut()
            .spawn((PendingLowPassSfx(source.clone()), settings))
            .id();
        let second = app
            .world_mut()
            .spawn((PendingLowPassSfx(source.clone()), settings))
            .id();
        app.update();

        let sounds = spawned_sounds(&mut app);
        assert_eq!(sounds.len(), 2);
        for sound in &sounds {
            assert!(sound.filtered && !sound.pending && !sound.plain);
            assert_eq!(sound.settings.speed, 1.5);
        }

        let first_handle = app
            .world()
            .get::<AudioPlayer<LowPassSfx>>(first)
            .expect("filtered player")
            .0
            .clone();
        let second_handle = app
            .world()
            .get::<AudioPlayer<LowPassSfx>>(second)
            .expect("filtered player")
            .0
            .clone();
        assert_eq!(first_handle, second_handle, "one filtered asset per source");

        let shared = app.world().resource::<SfxFilterShared>().0.clone();
        let filtered = app
            .world()
            .resource::<Assets<LowPassSfx>>()
            .get(&first_handle)
            .expect("filtered asset");
        assert!(Arc::ptr_eq(&filtered.source.bytes, &bytes));
        assert!(Arc::ptr_eq(&filtered.cutoff, &shared));
    }

    #[test]
    fn invalid_cutoff_plays_unfiltered() {
        for hz in [f32::NAN, -100.0, 0.0] {
            let mut app = headless_app_with_low_pass();
            app.insert_resource(SfxFilter::low_pass(hz));
            app.world_mut().write_message(SfxRequest {
                event: SfxEvent::ItemPickup,
                position: None,
            });
            app.update();

            let sounds = spawned_sounds(&mut app);
            assert_eq!(sounds.len(), 1, "cutoff {hz}");
            assert!(sounds[0].plain && !sounds[0].pending, "cutoff {hz}");
            assert_eq!(shared_cutoff(&app), 0.0, "cutoff {hz}");
        }
    }

    #[test]
    fn missing_filter_resource_plays_unfiltered() {
        let mut app = headless_app_with_low_pass();
        app.insert_resource(SfxFilter::low_pass(800.0));
        app.update();
        assert_eq!(shared_cutoff(&app), 800.0);

        app.world_mut().remove_resource::<SfxFilter>();
        app.world_mut().write_message(SfxRequest {
            event: SfxEvent::ItemPickup,
            position: None,
        });
        app.update();

        let sounds = spawned_sounds(&mut app);
        assert_eq!(sounds.len(), 1);
        assert!(sounds[0].plain && !sounds[0].pending);
        assert_eq!(shared_cutoff(&app), 0.0);
    }

    #[test]
    fn filter_without_audio_backend_plays_unfiltered() {
        let mut app = headless_app();
        app.insert_resource(SfxFilter::low_pass(800.0));
        // `finish` must not register the low-pass path without `AudioPlugin`.
        app.finish();
        app.cleanup();
        assert!(!app.world().contains_resource::<SfxFilterShared>());

        app.world_mut().write_message(SfxRequest {
            event: SfxEvent::ItemPickup,
            position: None,
        });
        app.update();

        let sounds = spawned_sounds(&mut app);
        assert_eq!(sounds.len(), 1);
        assert!(sounds[0].plain && !sounds[0].pending);
    }

    // ── Low-pass signal processing ───────────────────────────────────────────

    struct TestSignal {
        samples: std::vec::IntoIter<f32>,
        channels: u16,
        sample_rate: u32,
    }

    impl Iterator for TestSignal {
        type Item = f32;

        fn next(&mut self) -> Option<f32> {
            self.samples.next()
        }
    }

    impl RodioSource for TestSignal {
        fn current_frame_len(&self) -> Option<usize> {
            None
        }

        fn channels(&self) -> u16 {
            self.channels
        }

        fn sample_rate(&self) -> u32 {
            self.sample_rate
        }

        fn total_duration(&self) -> Option<Duration> {
            None
        }
    }

    const TEST_RATE: u32 = 44_100;

    fn sine(frequency_hz: f32, samples: usize) -> Vec<f32> {
        (0..samples)
            .map(|i| (std::f32::consts::TAU * frequency_hz * i as f32 / TEST_RATE as f32).sin())
            .collect()
    }

    fn cutoff_cell(cutoff_hz: f32) -> Arc<AtomicU32> {
        Arc::new(AtomicU32::new(cutoff_hz.to_bits()))
    }

    fn filter_mono(samples: Vec<f32>, cutoff: Arc<AtomicU32>) -> Vec<f32> {
        let signal = TestSignal {
            samples: samples.into_iter(),
            channels: 1,
            sample_rate: TEST_RATE,
        };
        LowPassSource::new(signal, cutoff).collect()
    }

    /// Root mean square of the second half, after the filter has settled.
    fn settled_rms(samples: &[f32]) -> f32 {
        let tail = &samples[samples.len() / 2..];
        (tail.iter().map(|sample| sample * sample).sum::<f32>() / tail.len() as f32).sqrt()
    }

    #[test]
    fn low_pass_attenuates_high_frequencies_and_keeps_low_ones() {
        let high = sine(8_000.0, 8_820);
        let low = sine(100.0, 8_820);
        let high_out = filter_mono(high.clone(), cutoff_cell(500.0));
        let low_out = filter_mono(low.clone(), cutoff_cell(500.0));

        assert_eq!(high_out.len(), high.len());
        assert!(
            settled_rms(&high_out) < 0.05 * settled_rms(&high),
            "8 kHz must be strongly attenuated by a 500 Hz low-pass"
        );
        let low_ratio = settled_rms(&low_out) / settled_rms(&low);
        assert!(
            (0.9..=1.05).contains(&low_ratio),
            "100 Hz must pass a 500 Hz low-pass, got ratio {low_ratio}"
        );
    }

    #[test]
    fn low_pass_without_cutoff_is_the_identity() {
        let input = sine(8_000.0, 512);
        assert_eq!(filter_mono(input.clone(), cutoff_cell(0.0)), input);
        // A cutoff the sample rate cannot represent is skipped as well.
        assert_eq!(filter_mono(input.clone(), cutoff_cell(20_000.0)), input);
        // The cell is trusted to hold a sanitized value, but must not break.
        assert_eq!(filter_mono(input.clone(), cutoff_cell(f32::NAN)), input);
    }

    #[test]
    fn low_pass_follows_cutoff_changes_while_playing() {
        let input = sine(8_000.0, 8_820);
        let cutoff = cutoff_cell(0.0);
        let signal = TestSignal {
            samples: input.clone().into_iter(),
            channels: 1,
            sample_rate: TEST_RATE,
        };
        let mut source = LowPassSource::new(signal, cutoff.clone());

        let unfiltered: Vec<f32> = source.by_ref().take(2_940).collect();
        assert_eq!(unfiltered, input[..2_940]);

        cutoff.store(500.0_f32.to_bits(), Ordering::Relaxed);
        let filtered: Vec<f32> = source.by_ref().take(2_940).collect();
        assert!(settled_rms(&filtered) < 0.05 * settled_rms(&input));

        cutoff.store(0.0_f32.to_bits(), Ordering::Relaxed);
        let restored: Vec<f32> = source.collect();
        assert_eq!(restored, input[5_880..]);
    }

    #[test]
    fn low_pass_filters_each_channel_separately() {
        // Left: a constant level. Right: the fastest possible alternation.
        let frames = 4_410;
        let samples: Vec<f32> = (0..frames)
            .flat_map(|frame| [0.5, if frame % 2 == 0 { 1.0 } else { -1.0 }])
            .collect();
        let signal = TestSignal {
            samples: samples.into_iter(),
            channels: 2,
            sample_rate: TEST_RATE,
        };
        let output: Vec<f32> = LowPassSource::new(signal, cutoff_cell(500.0)).collect();

        assert_eq!(output.len(), frames * 2);
        let left = output[output.len() - 2];
        let right = output[output.len() - 1];
        assert!(
            (left - 0.5).abs() < 0.01,
            "constant level must pass, got {left}"
        );
        assert!(
            right.abs() < 0.01,
            "alternation must be removed, got {right}"
        );
    }

    #[test]
    fn low_pass_output_stays_finite_for_bad_input() {
        let mut input = sine(100.0, 256);
        input[10] = f32::NAN;
        input[20] = f32::INFINITY;
        let output = filter_mono(input, cutoff_cell(500.0));
        assert!(output.iter().all(|sample| sample.is_finite()));
        assert!(output.iter().all(|sample| (-1.0..=1.0).contains(sample)));
    }

    #[test]
    fn low_pass_reports_the_inner_format() {
        let signal = TestSignal {
            samples: vec![0.0; 4].into_iter(),
            channels: 2,
            sample_rate: 22_050,
        };
        let source = LowPassSource::new(signal, cutoff_cell(500.0));
        assert_eq!(source.channels(), 2);
        assert_eq!(source.sample_rate(), 22_050);
        assert_eq!(source.current_frame_len(), None);
        assert_eq!(source.total_duration(), None);
    }

    #[test]
    fn coefficients_reject_values_that_cannot_filter() {
        assert!(LowPassCoefficients::new(500.0, TEST_RATE).is_some());
        assert_eq!(LowPassCoefficients::new(500.0, 0), None);
        assert_eq!(LowPassCoefficients::new(0.0, TEST_RATE), None);
        assert_eq!(LowPassCoefficients::new(-1.0, TEST_RATE), None);
        assert_eq!(LowPassCoefficients::new(f32::NAN, TEST_RATE), None);
        assert_eq!(LowPassCoefficients::new(f32::INFINITY, TEST_RATE), None);
        assert_eq!(LowPassCoefficients::new(22_050.0, TEST_RATE), None);
    }
}