codecraft 0.1.1

A minimalist 3D game engine built on parts of Bevy (ECS, color) with wgpu and winit: OpenPBR materials, clustered lighting, an immediate-mode UI, audio and gamepad haptics
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
//! Sound: recorded clips, synthesised effects, and loops that run until told
//! to stop.
//!
//! Clips are decoded once when they are loaded and kept as samples, so
//! playing one is a copy rather than an ogg decode in the middle of a frame.
//!
//! Sounds are grouped into named sets, and playing a set picks one of its
//! clips — footsteps that repeat the same recording read as a glitch, which
//! is why the pick avoids whatever was heard last.
//!
//! [`Effect`]s have no recording behind them: they are made from arithmetic
//! (see [`synth`]) when the audio opens, a few takes of each, and from then
//! on are played the way a set is. A [`Voice`] is the same idea run without
//! end — an engine — and the [`LoopHandle`] it returns is how a game turns it
//! with the throttle.
//!
//! A PlayStation pad on USB is an output of its own, with a speaker and a
//! pair of actuators that take audio — see [`pads`] — and the same effects
//! and voices can be played on a particular pad, so that a player's own gun
//! comes out of the thing in their hands.
use std::collections::HashMap;
use std::f32::consts::TAU;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::time::Duration;

use rodio::Source;
use rodio::buffer::SamplesBuffer;

pub mod pads;
mod synth;

pub use pads::{PadKey, PadSpeaker};

/// A decoded clip, ready to be handed to the mixer.
struct Clip {
    channels: rodio::ChannelCount,
    sample_rate: rodio::SampleRate,
    samples: Vec<f32>,
}

/// The clips of one set, and which was heard last.
#[derive(Default)]
struct Set {
    clips: Vec<Clip>,
    last: Option<usize>,
}

/// A sound made from arithmetic rather than played from a file.
///
/// Each is a pure function of the device rate and a seed — see [`synth`] —
/// so a game gets a gun without shipping a recording of one. A few takes of
/// each are rendered when the audio opens and played the way a recorded set
/// is: whichever comes up, but not the one just heard.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Effect {
    /// The main gun firing.
    Gunshot,
    /// A tank going up.
    Explosion,
    /// A shell hitting the ground.
    Impact,
    /// A shell on armour, or a part coming off.
    Clank,
    /// A shield going up: a whoomp.
    Shield,
}

impl Effect {
    /// Every effect, in the order the bank is filed in: an effect's place in
    /// [`Audio::effects`] is its discriminant.
    const ALL: [Self; 5] = [
        Self::Gunshot,
        Self::Explosion,
        Self::Impact,
        Self::Clank,
        Self::Shield,
    ];

    fn render(self, rate: u32, seed: u32) -> Vec<f32> {
        match self {
            Self::Gunshot => synth::gunshot(rate, seed),
            Self::Explosion => synth::explosion(rate, seed),
            Self::Impact => synth::impact(rate, seed),
            Self::Clank => synth::clank(rate, seed),
            Self::Shield => synth::shield(rate, seed),
        }
    }

    /// How loud the effect is played, as a fraction of full scale.
    ///
    /// The mixer adds sources without limiting the sum, so the ceilings here
    /// and [`ENGINE_CEILING`] are all that stands between a fight and
    /// clipping. The budget is one engine under the loudest one-shot: 0.35
    /// and 0.6 come to a little under full scale. Two engines under a gun go
    /// over it, by nearly a third at the crack's loudest sample, and are let
    /// to — a handful of clipped samples inside a gunshot is not something
    /// the ear picks out. The shield sits under the gun: it is a push, and
    /// most of it is meant to be felt rather than heard.
    fn gain(self) -> f32 {
        match self {
            Self::Gunshot => 0.6,
            Self::Explosion => 0.6,
            Self::Impact => 0.4,
            Self::Clank => 0.5,
            Self::Shield => 0.55,
        }
    }
}

/// How many takes of each effect are rendered.
///
/// Four is enough that a volley is not the same shot over and over, and few
/// enough that the whole bank is a megabyte and a half and a few dozen
/// milliseconds of a debug build's startup.
const EFFECT_TAKES: usize = 4;

/// Renders every effect's takes at the device's rate, seeded from `seed`.
fn render_effects(sample_rate: rodio::SampleRate, seed: &mut u32) -> [Set; Effect::ALL.len()] {
    Effect::ALL.map(|effect| Set {
        clips: (0..EFFECT_TAKES)
            .map(|_| Clip {
                channels: rodio::ChannelCount::MIN,
                sample_rate,
                samples: effect.render(sample_rate.get(), synth::xorshift(seed)),
            })
            .collect(),
        last: None,
    })
}

/// A sound that runs until it is stopped, driven from a [`LoopHandle`].
///
/// Each variant is one generator in [`Loop::next`]; a new kind of loop is a
/// new variant and a new arm there.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Voice {
    /// A diesel at idle, which the handle's pitch revs and its gain brings
    /// up under load.
    Engine,
}

/// The engine's fundamental with the pitch at one, in hertz. A big diesel
/// idles well under a hundred.
const ENGINE_BASE_HZ: f32 = 40.0;

/// The most an engine loop ever puts out — see [`Effect::gain`] for why the
/// mixer needs headroom left for it.
const ENGINE_CEILING: f32 = 0.35;

/// How long pitch and gain take to follow the handle, roughly.
///
/// A control written once a frame is a staircase, and a staircase in gain is
/// zipper noise; a one-pole filter this slow turns it into a slope the ear
/// takes for a smooth change. Still quick enough that a throttle feels
/// immediate.
const SMOOTHING_SECONDS: f32 = 0.04;

/// Below this the smoothed gain of a stopped loop counts as silent and the
/// source ends: -60 dB, gone under anything else that is playing. From full
/// gain that is seven smoothing times away, a little over a quarter of a
/// second.
const SILENCE: f32 = 1e-3;

/// What a [`LoopHandle`] and its running [`Loop`] share.
///
/// Atomics rather than a lock: the audio thread reads these once per sample
/// and must never wait on the game thread writing them.
struct Controls {
    /// f32 bits: a factor on the voice's base pitch.
    pitch: AtomicU32,
    /// f32 bits: 0..1 of the voice's ceiling.
    gain: AtomicU32,
    alive: AtomicBool,
}

impl Controls {
    fn pitch(&self) -> f32 {
        f32::from_bits(self.pitch.load(Ordering::Relaxed))
    }

    fn gain(&self) -> f32 {
        f32::from_bits(self.gain.load(Ordering::Relaxed))
    }
}

/// The game's end of a running loop: turn it, or stop it.
///
/// Cheap to clone and to keep on a component; every clone drives the same
/// sound. The loop ends when it is told to, or when the last handle is
/// dropped — an engine nothing can turn any more has no business running,
/// and this is what lets a despawned tank take its engine with it without a
/// word. It also means a handle that is not kept is a loop that fades out
/// before it is heard.
#[must_use = "a loop stops when its last handle is dropped"]
#[derive(Clone)]
pub struct LoopHandle(Arc<Controls>);

impl std::fmt::Debug for LoopHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LoopHandle")
            .field("pitch", &self.0.pitch())
            .field("gain", &self.0.gain())
            .field("alive", &self.0.alive.load(Ordering::Relaxed))
            .finish()
    }
}

impl LoopHandle {
    fn new() -> Self {
        Self(Arc::new(Controls {
            pitch: AtomicU32::new(1.0f32.to_bits()),
            gain: AtomicU32::new(1.0f32.to_bits()),
            alive: AtomicBool::new(true),
        }))
    }

    /// Sets the pitch as a factor on the voice's own — two is an octave up —
    /// and the gain as a fraction of the voice's ceiling.
    ///
    /// Both are clamped: a gain over one would spend the headroom the
    /// ceiling exists to keep, and a pitch of nought is a loop that never
    /// moves. Neither takes effect at once; see [`SMOOTHING_SECONDS`].
    pub fn set(&self, pitch: f32, gain: f32) {
        let pitch = if pitch.is_finite() {
            pitch.clamp(0.25, 4.0)
        } else {
            1.0
        };
        let gain = if gain.is_finite() {
            gain.clamp(0.0, 1.0)
        } else {
            0.0
        };
        self.0.pitch.store(pitch.to_bits(), Ordering::Relaxed);
        self.0.gain.store(gain.to_bits(), Ordering::Relaxed);
    }

    /// Ends the loop. It fades rather than cuts — a quarter of a second or
    /// so down to [`SILENCE`] — and then the mixer drops it.
    pub fn stop(&self) {
        self.0.alive.store(false, Ordering::Relaxed);
    }
}

/// A value that follows its target along an exponential rather than jumping.
struct Smoothed {
    value: f32,
    coefficient: f32,
}

impl Smoothed {
    fn new(value: f32, rate: f32, seconds: f32) -> Self {
        Self {
            value,
            coefficient: 1.0 - (-1.0 / (rate * seconds)).exp(),
        }
    }

    fn step(&mut self, target: f32) -> f32 {
        self.value += (target - self.value) * self.coefficient;
        self.value
    }
}

/// A running [`Voice`]: the [`Source`] the mixer pulls from.
///
/// Pitch is applied inside the generator, as a step on a phase accumulator,
/// rather than by wrapping the source in rodio's `Speed`. The mixer resamples
/// each source once for its whole span, and a source that never ends is one
/// span, so a rate change reported by `Speed` after the first sample is
/// never read. A phase step is read every sample.
struct Loop {
    voice: Voice,
    controls: Arc<Controls>,
    /// The audio's master gain, so a mute reaches a loop already running.
    master: Arc<AtomicU32>,
    sample_rate: rodio::SampleRate,
    /// 0..1 of one cycle of the fundamental.
    phase: f32,
    /// Which stroke of two the engine is on: a four-stroke fires every other
    /// turn, and the lope that gives it is most of what says *diesel*.
    stroke: bool,
    pitch: Smoothed,
    gain: Smoothed,
    /// Takes the edge off the saw.
    tone: synth::OnePole,
    /// Turns white noise into the shake under the note.
    rumble: synth::OnePole,
    noise: synth::Noise,
}

impl Loop {
    fn new(
        voice: Voice,
        controls: Arc<Controls>,
        master: Arc<AtomicU32>,
        sample_rate: rodio::SampleRate,
        seed: u32,
    ) -> Self {
        let rate = sample_rate.get() as f32;
        Self {
            voice,
            controls,
            master,
            sample_rate,
            phase: 0.0,
            stroke: false,
            pitch: Smoothed::new(1.0, rate, SMOOTHING_SECONDS),
            // Starting silent and rising is what keeps the first sample from
            // being a click.
            gain: Smoothed::new(0.0, rate, SMOOTHING_SECONDS),
            tone: synth::OnePole::new(rate, 600.0),
            rumble: synth::OnePole::new(rate, 200.0),
            noise: synth::Noise::new(seed),
        }
    }

    /// One sample of the engine at the given phase, before gain.
    ///
    /// Bounded by one: the weights sum to one and each part stays within
    /// one, so the ceiling applied afterwards is a real ceiling.
    fn engine(&mut self) -> f32 {
        let saw = 2.0 * self.phase - 1.0;
        let second = (2.0 * TAU * self.phase).sin();
        let rumble = self.rumble.step(self.noise.sample());
        let stroke = if self.stroke { 1.0 } else { 0.7 };
        self.tone
            .step((0.45 * saw + 0.35 * second) * stroke + 0.2 * rumble)
    }
}

impl Iterator for Loop {
    type Item = f32;

    fn next(&mut self) -> Option<f32> {
        // Once every handle is gone nothing can say stop, so the last one
        // going is taken as having said it: the only count left is this
        // source's own, and no clone can bring it back up.
        let held = Arc::strong_count(&self.controls) > 1;
        let alive = held && self.controls.alive.load(Ordering::Relaxed);
        let master = f32::from_bits(self.master.load(Ordering::Relaxed));
        let target = if alive {
            self.controls.gain() * master
        } else {
            0.0
        };
        let gain = self.gain.step(target);
        if !alive && gain < SILENCE {
            return None;
        }

        let pitch = self.pitch.step(self.controls.pitch());
        let base = match self.voice {
            Voice::Engine => ENGINE_BASE_HZ,
        };
        self.phase += base * pitch / self.sample_rate.get() as f32;
        if self.phase >= 1.0 {
            self.phase -= 1.0;
            self.stroke = !self.stroke;
        }

        let sample = match self.voice {
            Voice::Engine => self.engine() * ENGINE_CEILING,
        };
        Some(sample * gain)
    }
}

impl Source for Loop {
    /// One span without end, which is why pitch cannot come from outside —
    /// see [`Loop`].
    fn current_span_len(&self) -> Option<usize> {
        None
    }

    fn channels(&self) -> rodio::ChannelCount {
        rodio::ChannelCount::MIN
    }

    fn sample_rate(&self) -> rodio::SampleRate {
        self.sample_rate
    }

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

/// Plays sound effects, if the machine has anywhere to play them.
pub struct Audio {
    /// Dropping this stops the sound, so it is kept even though the mixer is
    /// what gets used.
    _device: rodio::MixerDeviceSink,
    mixer: rodio::mixer::Mixer,
    /// What the output runs at. Synthesised sound is made at this rate so
    /// it goes to the device untouched.
    sample_rate: rodio::SampleRate,
    sets: HashMap<String, Set>,
    /// The synthesised takes, one set per [`Effect`], filed by discriminant.
    effects: [Set; Effect::ALL.len()],
    muted: bool,
    volume: f32,
    /// f32 bits of the volume, or zero while muted, shared with every
    /// running loop so a mute reaches sounds that started before it.
    master: Arc<AtomicU32>,
    /// Enough randomness to vary a footstep; nothing here needs more.
    seed: u32,
    /// Every pad sound card that would open, for playing a player's own
    /// sounds on their own pad. Empty on a machine without one, and nothing
    /// else changes.
    pads: Vec<PadSpeaker>,
}

impl Audio {
    /// Opens the default output. `None` when there is no sound device — a
    /// game should still run on a machine with no audio.
    pub fn new() -> Option<Self> {
        let mut device = match rodio::DeviceSinkBuilder::open_default_sink() {
            Ok(device) => device,
            Err(error) => {
                log::warn!("no audio output ({error}); the game will be silent");
                return None;
            }
        };
        // Quitting stops the sound on purpose; rodio need not warn about it.
        device.log_on_drop(false);
        let mixer = device.mixer().clone();
        let sample_rate = device.config().sample_rate();

        // The clock is only being used to start the sequence somewhere.
        let mut seed = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|since| since.subsec_nanos())
            .unwrap_or(0x2545_F491)
            | 1;
        let effects = render_effects(sample_rate, &mut seed);
        let pads = pads::open_pad_speakers();

        Some(Self {
            _device: device,
            mixer,
            sample_rate,
            sets: HashMap::new(),
            effects,
            muted: false,
            volume: 1.0,
            master: Arc::new(AtomicU32::new(1.0f32.to_bits())),
            seed,
            pads,
        })
    }

    /// The key of every pad sound card that opened, in the host's order. A
    /// game matches these against [`PadKey::of_hid_path`] on the pads it is
    /// reading input from.
    pub fn pad_keys(&self) -> Vec<PadKey> {
        self.pads.iter().map(|pad| pad.key).collect()
    }

    fn pad(&self, key: &PadKey) -> Option<&PadSpeaker> {
        self.pads.iter().find(|pad| pad.key == *key)
    }

    /// Decodes clips and files them under `name`. Anything that will not
    /// decode is reported and skipped, rather than taking the game down.
    pub fn load_set(&mut self, name: impl Into<String>, clips: &[&'static [u8]]) {
        let name = name.into();
        let mut set = Set::default();
        for bytes in clips {
            match decode(bytes) {
                Ok(clip) => set.clips.push(clip),
                Err(error) => log::error!("could not decode a {name} clip: {error}"),
            }
        }
        log::debug!("loaded {} {name} clips", set.clips.len());
        self.sets.insert(name, set);
    }

    /// Plays one clip from a set. Silent if muted, if the set is empty, or if
    /// there is no such set.
    pub fn play(&mut self, name: &str) {
        if self.silent() {
            return;
        }
        let roll = self.roll();
        let volume = self.volume;

        let Some(set) = self.sets.get_mut(name) else {
            log::warn!("no sound set called {name:?}");
            return;
        };
        play_from(&self.mixer, set, roll, volume);
    }

    /// Plays one take of a synthesised effect. Silent if muted.
    pub fn play_effect(&mut self, effect: Effect) {
        if self.silent() {
            return;
        }
        let roll = self.roll();
        let gain = self.volume * effect.gain();
        play_from(&self.mixer, &mut self.effects[effect as usize], roll, gain);
    }

    /// Plays one take of an effect out of a particular pad: `speaker` and
    /// `haptic` scale the effect's own gain for the pad's speaker and its
    /// actuators. The take is chosen as [`Self::play_effect`] chooses, from
    /// the same bank with the same memory of what was heard last, so a gun
    /// on the pad and the same gun on the main output never share a take
    /// back to back. Silent if muted, and nothing for a key no pad has.
    pub fn play_effect_on(&mut self, key: &PadKey, effect: Effect, speaker: f32, haptic: f32) {
        if self.silent() {
            return;
        }
        let roll = self.roll();
        let gain = self.volume * effect.gain();
        let Some(pad) = self.pads.iter().find(|pad| pad.key == *key) else {
            log::debug!("no pad speaker for {key:?}");
            return;
        };
        if let Some(clip) = take(&mut self.effects[effect as usize], roll) {
            pad.play(clip, speaker * gain, haptic * gain);
        }
    }

    /// Starts a voice on a particular pad, spread over its lanes the way
    /// [`Self::play_effect_on`] spreads a take. The handle drives it as any
    /// loop's does, and it reads the master gain, so mute reaches it. `None`
    /// for a key no pad has: there is nothing to run it on.
    #[must_use = "a loop stops when its last handle is dropped"]
    pub fn start_loop_on(
        &mut self,
        key: &PadKey,
        voice: Voice,
        speaker: f32,
        haptic: f32,
    ) -> Option<LoopHandle> {
        let seed = self.roll() as u32;
        let pad = self.pad(key)?;
        let handle = LoopHandle::new();
        // Made at the pad's own rate, as the main output's loops are made at
        // its, so it goes to the device without resampling.
        let source = Loop::new(
            voice,
            Arc::clone(&handle.0),
            Arc::clone(&self.master),
            pad.sample_rate(),
            seed,
        );
        pad.add(source, speaker, haptic);
        Some(handle)
    }

    /// Starts a voice running and returns the handle that drives it, for as
    /// long as the handle is held.
    ///
    /// Not silenced by mute the way a one-shot is: the loop starts either
    /// way and reads the master gain as it goes, so unmuting later brings an
    /// engine back that was started while muted.
    #[must_use = "a loop stops when its last handle is dropped"]
    pub fn start_loop(&mut self, voice: Voice) -> LoopHandle {
        let handle = LoopHandle::new();
        let seed = self.roll() as u32;
        self.mixer.add(Loop::new(
            voice,
            Arc::clone(&handle.0),
            Arc::clone(&self.master),
            self.sample_rate,
            seed,
        ));
        handle
    }

    pub fn set_muted(&mut self, muted: bool) {
        self.muted = muted;
        self.share_master();
    }

    pub fn is_muted(&self) -> bool {
        self.muted
    }

    /// How loud effects are, 1.0 being as recorded.
    pub fn set_volume(&mut self, volume: f32) {
        self.volume = volume.clamp(0.0, 1.0);
        self.share_master();
    }

    /// Whether a one-shot started now would be heard at all.
    fn silent(&self) -> bool {
        self.muted || self.volume <= 0.0
    }

    /// Writes the gain the running loops read.
    fn share_master(&self) {
        let gain = if self.muted { 0.0 } else { self.volume };
        self.master.store(gain.to_bits(), Ordering::Relaxed);
    }

    /// A xorshift step: varied enough to shuffle footsteps.
    fn roll(&mut self) -> usize {
        synth::xorshift(&mut self.seed) as usize
    }
}

/// Hands one clip of a set to the mixer at `gain`: `roll` chooses, but never
/// the one just heard. Nothing happens for an empty set.
fn play_from(mixer: &rodio::mixer::Mixer, set: &mut Set, roll: usize, gain: f32) {
    if let Some(source) = take(set, roll) {
        mixer.add(source.amplify(gain));
    }
}

/// One clip of a set as a source, chosen by `roll` but never the one just
/// heard, and noted as heard. `None` for an empty set.
fn take(set: &mut Set, roll: usize) -> Option<SamplesBuffer> {
    let index = pick(set.clips.len(), set.last, roll)?;
    set.last = Some(index);
    let clip = &set.clips[index];
    Some(SamplesBuffer::new(
        clip.channels,
        clip.sample_rate,
        clip.samples.clone(),
    ))
}

/// Which clip to play: `roll` chooses, but never the one just heard.
///
/// `None` when the set is empty. A set with a single clip has to repeat it,
/// since there is nothing else to play.
fn pick(count: usize, last: Option<usize>, roll: usize) -> Option<usize> {
    match count {
        0 => None,
        1 => Some(0),
        _ => {
            let Some(last) = last.filter(|last| *last < count) else {
                return Some(roll % count);
            };
            // Choose among the others, then map back around the one played
            // last, so every other clip stays equally likely.
            let choice = roll % (count - 1);
            Some(if choice >= last { choice + 1 } else { choice })
        }
    }
}

/// Decodes a clip into samples.
fn decode(bytes: &'static [u8]) -> Result<Clip, rodio::decoder::DecoderError> {
    let decoder = rodio::Decoder::new(std::io::Cursor::new(bytes))?;
    let channels = decoder.channels();
    let sample_rate = decoder.sample_rate();
    Ok(Clip {
        channels,
        sample_rate,
        samples: decoder.collect(),
    })
}

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

    const RATE: u32 = 48000;

    /// A loop with nothing behind it but a handle and a master gain, which
    /// is all the source itself ever touches.
    fn engine() -> (Loop, LoopHandle, Arc<AtomicU32>) {
        let handle = LoopHandle::new();
        let master = Arc::new(AtomicU32::new(1.0f32.to_bits()));
        let source = Loop::new(
            Voice::Engine,
            Arc::clone(&handle.0),
            Arc::clone(&master),
            rodio::SampleRate::new(RATE).unwrap(),
            9,
        );
        (source, handle, master)
    }

    fn peak(samples: impl Iterator<Item = f32>) -> f32 {
        samples.fold(0.0f32, |peak, s| peak.max(s.abs()))
    }

    #[test]
    fn an_empty_set_plays_nothing() {
        assert_eq!(pick(0, None, 7), None);
        assert_eq!(pick(0, Some(0), 7), None);
    }

    #[test]
    fn a_single_clip_is_all_there_is_to_play() {
        assert_eq!(pick(1, None, 3), Some(0));
        assert_eq!(pick(1, Some(0), 3), Some(0), "it has to repeat");
    }

    #[test]
    fn the_clip_just_heard_is_never_played_again_at_once() {
        for last in 0..3 {
            for roll in 0..30 {
                let picked = pick(3, Some(last), roll).unwrap();
                assert_ne!(picked, last, "roll {roll} repeated clip {last}");
                assert!(picked < 3, "picked outside the set: {picked}");
            }
        }
    }

    #[test]
    fn every_other_clip_can_still_come_up() {
        // With one clip excluded, the rest must all be reachable — a pick
        // that always lands on the same alternative is no better than repeating.
        let mut seen = std::collections::HashSet::new();
        for roll in 0..30 {
            seen.insert(pick(3, Some(1), roll).unwrap());
        }
        assert_eq!(seen, [0, 2].into_iter().collect());
    }

    #[test]
    fn a_first_play_may_be_any_clip() {
        let mut seen = std::collections::HashSet::new();
        for roll in 0..30 {
            seen.insert(pick(3, None, roll).unwrap());
        }
        assert_eq!(seen, [0, 1, 2].into_iter().collect());
    }

    #[test]
    fn a_stale_last_index_does_not_break_the_pick() {
        // A set can be reloaded with fewer clips than were there before.
        let picked = pick(2, Some(9), 5).unwrap();
        assert!(picked < 2);
    }

    #[test]
    fn an_engine_under_the_loudest_one_shot_fits_under_full_scale() {
        let loudest = Effect::ALL
            .into_iter()
            .map(Effect::gain)
            .fold(0.0, f32::max);
        assert!(
            ENGINE_CEILING + loudest <= 1.0,
            "{ENGINE_CEILING} + {loudest} clips"
        );
    }

    #[test]
    fn the_bank_is_filed_by_discriminant() {
        for (index, effect) in Effect::ALL.into_iter().enumerate() {
            assert_eq!(effect as usize, index, "{effect:?} is out of order");
        }
    }

    #[test]
    fn every_effect_has_its_takes_and_no_two_are_alike() {
        let mut seed = 1;
        let bank = render_effects(rodio::SampleRate::new(RATE).unwrap(), &mut seed);
        for effect in Effect::ALL {
            let takes = &bank[effect as usize].clips;
            assert_eq!(takes.len(), EFFECT_TAKES, "{effect:?}");
            for (i, take) in takes.iter().enumerate() {
                assert_eq!(take.sample_rate.get(), RATE);
                for other in &takes[i + 1..] {
                    assert_ne!(take.samples, other.samples, "{effect:?} repeats a take");
                }
            }
        }
    }

    #[test]
    fn stopping_a_loop_ends_its_source() {
        let (mut source, handle, _) = engine();
        assert_eq!(
            source.by_ref().take(RATE as usize).count(),
            RATE as usize,
            "it runs while alive",
        );
        assert!(source.next().is_some());

        handle.stop();
        // It fades rather than cuts, but well inside half a second it has
        // to be gone or the mixer keeps it forever.
        let fade: Vec<f32> = source.by_ref().take(RATE as usize).collect();
        assert!(fade.len() < RATE as usize / 2, "the source never ended");
        assert!(source.next().is_none(), "and stays ended");
        let last_tenth = &fade[fade.len() * 9 / 10..];
        assert!(peak(last_tenth.iter().copied()) < 0.01, "it went out loud");
    }

    #[test]
    fn dropping_the_last_handle_stops_the_loop() {
        let (mut source, handle, _) = engine();
        source.by_ref().take(RATE as usize / 4).count();
        drop(handle);
        assert!(
            source.by_ref().take(RATE as usize).count() < RATE as usize,
            "nothing could ever stop it now"
        );
    }

    #[test]
    fn a_clone_keeps_the_loop_going_when_the_original_is_dropped() {
        let (mut source, handle, _) = engine();
        let kept = handle.clone();
        drop(handle);
        assert_eq!(
            source.by_ref().take(RATE as usize).count(),
            RATE as usize,
            "the clone still holds it"
        );
        drop(kept);
        assert!(source.by_ref().take(RATE as usize).count() < RATE as usize);
    }

    #[test]
    fn a_loop_stopped_before_it_sounds_ends_at_once() {
        let (mut source, handle, _) = engine();
        handle.stop();
        assert_eq!(source.next(), None);
    }

    #[test]
    fn a_loop_fades_in_rather_than_starting_with_a_click() {
        let (mut source, _handle, _) = engine();
        let first = source.next().unwrap();
        assert!(first.abs() < 1e-3, "opened at {first}");
    }

    #[test]
    fn the_engine_never_exceeds_its_ceiling() {
        // One of them and a gun have to fit under full scale together.
        let (mut source, handle, _) = engine();
        handle.set(4.0, 1.0);
        let loudest = peak(source.by_ref().take(RATE as usize * 2));
        assert!(loudest <= ENGINE_CEILING + 1e-6, "{loudest}");
        assert!(
            loudest > ENGINE_CEILING * 0.3,
            "or it is barely there: {loudest}"
        );
    }

    #[test]
    fn muting_the_master_silences_a_loop_already_running() {
        let (mut source, _handle, master) = engine();
        source.by_ref().take(RATE as usize / 2).count();
        master.store(0.0f32.to_bits(), Ordering::Relaxed);
        // Half a second on: a dozen smoothing times past the mute, and
        // still running.
        let after: Vec<f32> = source.by_ref().take(RATE as usize / 2).collect();
        assert_eq!(after.len(), RATE as usize / 2, "muting must not end it");
        assert!(peak(after[after.len() * 9 / 10..].iter().copied()) < 1e-4);

        master.store(1.0f32.to_bits(), Ordering::Relaxed);
        source.by_ref().take(RATE as usize / 2).count();
        assert!(
            peak(source.by_ref().take(RATE as usize / 4)) > 0.05,
            "and unmuting brings it back"
        );
    }

    #[test]
    fn pitch_smoothing_moves_monotonically_toward_the_target() {
        let mut pitch = Smoothed::new(1.0, RATE as f32, SMOOTHING_SECONDS);
        let mut previous = 1.0;
        for _ in 0..RATE {
            let now = pitch.step(2.0);
            assert!(now >= previous && now <= 2.0, "{previous} -> {now}");
            previous = now;
        }
        assert!((previous - 2.0).abs() < 1e-3, "never got there: {previous}");

        // And back down again, the same way.
        let mut previous = pitch.step(0.5);
        for _ in 0..RATE {
            let now = pitch.step(0.5);
            assert!(now <= previous && now >= 0.5, "{previous} -> {now}");
            previous = now;
        }
    }

    #[test]
    fn smoothing_takes_about_as_long_as_it_says() {
        // One time constant on: 63% of the way, give or take the rounding
        // of a sample.
        let mut gain = Smoothed::new(0.0, RATE as f32, SMOOTHING_SECONDS);
        let steps = (RATE as f32 * SMOOTHING_SECONDS) as usize;
        let mut value = 0.0;
        for _ in 0..steps {
            value = gain.step(1.0);
        }
        assert!((value - 0.632).abs() < 0.01, "{value}");
    }

    #[test]
    fn the_handle_keeps_pitch_and_gain_where_the_ceiling_still_holds() {
        let handle = LoopHandle::new();
        handle.set(100.0, 7.0);
        assert_eq!((handle.0.pitch(), handle.0.gain()), (4.0, 1.0));
        handle.set(f32::NAN, f32::INFINITY);
        assert_eq!((handle.0.pitch(), handle.0.gain()), (1.0, 0.0));
        handle.set(0.0, -1.0);
        assert_eq!((handle.0.pitch(), handle.0.gain()), (0.25, 0.0));
    }

    #[test]
    fn a_clone_of_the_handle_drives_the_same_loop() {
        let (mut source, handle, _) = engine();
        handle.clone().stop();
        assert_eq!(source.next(), None);
    }
}