mirage-engine 0.2.0

Mirage, an immediate-mode 3D engine for simple games on desktop and the browser
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
//! A session, not a game — the same kind as `stress-preview.rs`, over
//! every public sound knob. A small room holds three sources a drag moves
//! and a listener a walk moves, its marked ears and facing marker matching
//! what the engine computes for pan. A source's cube is glowing while its
//! cue sustains, dim while it does not. The left holds the master volume,
//! sustained cues, and each source's own controls; the bottom holds
//! one-shot playback.
//!
//! `cargo run --example sound-lab`. `WASD` or a stick walks the listener;
//! hold the left mouse button over a source's cube and move it.

use core::f32::consts::TAU;
use core::time::Duration;
use std::collections::HashMap;

use mirage_engine::prelude::*;
use mirage_engine::{MAX_VOICES, ray};

const ROOM_HALF: f32 = 6.0;
const WALL_THICKNESS: f32 = 0.3;
const WALL_HEIGHT: f32 = 2.4;
/// Where a source or the listener may be placed, clear of the walls.
const PLAY_BOUND: f32 = ROOM_HALF - WALL_THICKNESS - 0.4;

const EYE_HEIGHT: f32 = 1.6;
const WALK_SPEED: f32 = 4.0;
const CHASE_BACK: f32 = 6.0;
const CHASE_UP: f32 = 5.0;

const SOURCE_HEIGHT: f32 = 0.4;
const SOURCE_HALF: f32 = 0.22;
/// Distance a source holds its full level within until a slider moves it: a
/// meter and a half, so a source across the room is still heard.
const SOURCE_REFERENCE: f32 = 1.5;
/// A source's cube counts as hit within this many meters of a click's ray.
const SOURCE_PICK_RADIUS: f32 = 0.5;

/// The listener's footprint, from the ground up to [`EYE_HEIGHT`].
const LISTENER_WIDTH: f32 = 0.4;
const LISTENER_DEPTH: f32 = 0.3;
/// Ear size, and their offset from the listener along its right.
const EAR_SIZE: f32 = 0.14;
const EAR_OFFSET: f32 = 0.24;
/// The facing marker's size, set with its point at the listener.
const FACING_MARKER_SIZE: f32 = 0.22;

const FLOOR_COLOR: Color = Color::rgb(0.14, 0.14, 0.17);
const WALL_COLOR: Color = Color::rgb(0.22, 0.24, 0.30);
const SUN_COLOR: Color = Color::rgb(0.85, 0.85, 0.90);
const LISTENER_COLOR: Color = Color::rgb(0.85, 0.85, 0.75);
/// Red on the right, white on the left: the pair the engine's own pan
/// reads, set on the ears so the sides are distinct.
const RIGHT_EAR_COLOR: Color = Color::rgb(0.85, 0.2, 0.2);
const LEFT_EAR_COLOR: Color = Color::rgb(0.92, 0.92, 0.88);
const SOURCE_COLORS: [Color; 3] = [
    Color::rgb(0.85, 0.35, 0.35),
    Color::rgb(0.35, 0.75, 0.85),
    Color::rgb(0.85, 0.75, 0.30),
];
const RANGE_COLOR: Color = Color::rgba(1.0, 1.0, 1.0, 0.35);
/// The inner ring drawn around a source, where its level stops being full.
const REFERENCE_COLOR: Color = Color::rgba(1.0, 0.85, 0.35, 0.5);

const SKY_ZENITH: Color = Color::rgb(0.10, 0.11, 0.16);
const SKY_HORIZON: Color = Color::rgb(0.20, 0.20, 0.24);
const SKY_NADIR: Color = Color::rgb(0.06, 0.06, 0.08);
/// The fraction of its own light the sky lands and reflects: dim, so the
/// cubes' own glow and the room's light still read.
const SKY_LIGHT: f32 = 0.2;

/// Two fixed positions holding the same clip at the default instance,
/// read only while [`SoundCheck::merge_demo`] is set.
const MERGE_POS_A: Vec3 = Vec3::new(-4.0, SOURCE_HEIGHT, 4.5);
const MERGE_POS_B: Vec3 = Vec3::new(4.0, SOURCE_HEIGHT, 4.5);
const MERGE_GAIN: f32 = 0.5;
const MERGE_COLOR_A: Color = Color::rgb(0.95, 0.55, 0.15);
const MERGE_COLOR_B: Color = Color::rgb(0.55, 0.4, 0.85);

/// Where [`Sound::Theme`] and [`Sound::ThemeDecoded`] loop from once
/// declared: a few seconds short of the end, so a wrap seeks across most of
/// the clip.
const THEME_LOOP_FROM: Duration = Duration::from_secs(130);

/// Count of sustains the ring declares at once: more than the engine plays,
/// so the least loud of them hold no voice.
const RING_COUNT: u32 = MAX_VOICES as u32 + 8;
/// Radius of the ring they stand on.
const RING_RADIUS: f32 = 4.6;
/// Distance the ring's sustains hold their full level within: over half the
/// radius, so the whole ring is heard from the middle of the room.
const RING_REFERENCE: f32 = 2.5;
/// Gain the loudest of them takes; each one after it is less loud, so the cut
/// falls inside the ring.
const RING_GAIN: f32 = 0.35;
/// Color of the ring's cubes, taken less bright the less loud the sustain a
/// cube stands for.
const RING_COLOR: Color = Color::rgb(0.35, 0.75, 0.95);

/// Every source this example loads, next to `index.html` on the web and
/// under the working directory on the desktop.
const ASSET_FILES: [&str; 9] = [
    "examples/assets/bounce.ogg",
    "examples/assets/break.ogg",
    "examples/assets/serve.ogg",
    "examples/assets/gameover.ogg",
    "examples/assets/lost.ogg",
    "examples/assets/win.ogg",
    "examples/assets/click.ogg",
    "examples/assets/music.ogg",
    "examples/assets/menu_music.ogg",
];

fn main() {
    run(
        Config::new("Mirage: sound lab")
            .with_size(1280, 720)
            .with_assets(ASSET_FILES),
        SoundCheck::init,
    );
}

/// The one sky this room draws, a gradient set each frame.
#[derive(Catalog, Clone, Copy, Debug, Eq, Hash, PartialEq)]
enum Sky {
    Room,
}

impl Skyboxes for Sky {
    fn build(&self, _assets: &Assets) -> SkyboxData {
        match self {
            Self::Room => {
                SkyboxData::gradient(SKY_ZENITH, SKY_HORIZON, SKY_NADIR).lit_by(SKY_LIGHT)
            }
        }
    }
}

/// A source's reference or its range: a flat ring on the ground,
/// unit-sized, drawn that many meters across by its scale.
#[derive(Catalog, Clone, PartialEq, Eq, Hash)]
struct Ring;

impl Mesh for Ring {
    fn build(&self, _: &Assets) -> MeshData {
        ring_outline()
    }
}

/// The listener's facing marker: a point through `-Z`, unit-sized.
#[derive(Catalog, Clone, PartialEq, Eq, Hash)]
struct Facing;

impl Mesh for Facing {
    fn build(&self, _: &Assets) -> MeshData {
        facing_marker()
    }
}

// Everything else this game draws is a built-in primitive, given its
// color and placed per draw: the room's floor and walls, a cube drawn for
// a source or the listener, and the listener's ears.
meshes! { enum Shape { Plane, Cube, Ring, Sphere, Facing } }

fn ring_outline() -> MeshData {
    const SEGMENTS: u32 = 48;
    const OUTER: f32 = 1.0;
    const INNER: f32 = 0.94;

    let mut vertices = Vec::with_capacity(SEGMENTS as usize * 4);
    let mut indices = Vec::with_capacity(SEGMENTS as usize * 6);
    for segment in 0..SEGMENTS {
        let a0 = segment as f32 / SEGMENTS as f32 * TAU;
        let a1 = (segment + 1) as f32 / SEGMENTS as f32 * TAU;
        let (u0, v0) = (a0.cos(), a0.sin());
        let (u1, v1) = (a1.cos(), a1.sin());
        let base = vertices.len() as u32;
        vertices.extend([
            Vertex::new(Vec3::new(INNER * u0, 0.0, -INNER * v0), Vec3::Y, Vec2::ZERO),
            Vertex::new(Vec3::new(OUTER * u0, 0.0, -OUTER * v0), Vec3::Y, Vec2::ZERO),
            Vertex::new(Vec3::new(OUTER * u1, 0.0, -OUTER * v1), Vec3::Y, Vec2::ZERO),
            Vertex::new(Vec3::new(INNER * u1, 0.0, -INNER * v1), Vec3::Y, Vec2::ZERO),
        ]);
        indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]);
    }
    MeshData::new(vertices, indices)
}

fn facing_marker() -> MeshData {
    const TIP: Vec3 = Vec3::new(0.0, 0.0, -0.5);
    const BACK: [Vec3; 4] = [
        Vec3::new(-0.5, -0.5, 0.5),
        Vec3::new(0.5, -0.5, 0.5),
        Vec3::new(0.5, 0.5, 0.5),
        Vec3::new(-0.5, 0.5, 0.5),
    ];

    let mut vertices = Vec::with_capacity(BACK.len() * 3);
    for (corner, next) in BACK.iter().zip(BACK.iter().cycle().skip(1)) {
        let normal = (next - corner).cross(TIP - corner).normalize();
        vertices.extend([
            Vertex::new(*corner, normal, Vec2::new(0.0, 1.0)),
            Vertex::new(*next, normal, Vec2::new(1.0, 1.0)),
            Vertex::new(TIP, normal, Vec2::new(0.5, 0.0)),
        ]);
    }
    let indices = (0..vertices.len() as u32).collect();
    MeshData::new(vertices, indices)
}

/// Every sound this game plays. [`Sound::Break`] and [`Sound::Pulse`] read the
/// same source under two names, so sustaining one and playing the other
/// once never share a voice; [`Sound::Theme`] and [`Sound::ThemeDecoded`] do
/// the same for the streamed side against the decoded one, since a clip
/// decodes one way or the other for good, once built.
#[derive(Catalog, Clone, Copy, PartialEq, Eq, Hash)]
enum Sound {
    Bounce,
    Break,
    Serve,
    GameOver,
    Lost,
    Win,
    Click,
    Theme,
    ThemeDecoded,
    MenuTheme,
    Pulse,
}

impl Sound {
    /// The alternatives a one-shot play offers.
    const ONE_SHOTS: [Sound; 7] = [
        Sound::Bounce,
        Sound::Break,
        Sound::Serve,
        Sound::GameOver,
        Sound::Lost,
        Sound::Win,
        Sound::Click,
    ];

    /// The alternatives one source's sustain offers.
    const SOURCE_CHOICES: [Sound; 9] = [
        Sound::Bounce,
        Sound::Break,
        Sound::Serve,
        Sound::GameOver,
        Sound::Lost,
        Sound::Win,
        Sound::Click,
        Sound::Theme,
        Sound::ThemeDecoded,
    ];

    fn label(self) -> &'static str {
        match self {
            Sound::Bounce => "bounce",
            Sound::Break => "break",
            Sound::Serve => "serve",
            Sound::GameOver => "game over",
            Sound::Lost => "lost",
            Sound::Win => "win",
            Sound::Click => "click",
            Sound::Theme => "theme (streamed)",
            Sound::ThemeDecoded => "theme (decoded)",
            Sound::MenuTheme => "menu theme",
            Sound::Pulse => "pulse",
        }
    }
}

impl Sounds for Sound {
    fn build(&self, assets: &Assets) -> SoundData {
        match self {
            Sound::Bounce => assets.sound("bounce"),
            Sound::Break => assets.sound("break"),
            Sound::Serve => assets.sound("serve"),
            Sound::GameOver => assets.sound("gameover"),
            Sound::Lost => assets.sound("lost"),
            Sound::Win => assets.sound("win"),
            Sound::Click => assets.sound("click"),
            Sound::Theme => assets.sound("music").streamed(),
            Sound::ThemeDecoded => assets.sound("music"),
            Sound::MenuTheme => assets.sound("menu_music").streamed(),
            Sound::Pulse => assets.sound("break"),
        }
    }
}

/// The one button this game reads: it holds a source down and moves it.
#[derive(InputButtonAction, Clone, Copy, PartialEq)]
enum Button {
    Select,
}

impl InputButtonAction for Button {
    fn bindings(&self) -> Vec<ButtonBinding> {
        match self {
            Button::Select => vec![MouseButton::Left.into()],
        }
    }
}

/// The listener's walk, in the ground plane.
#[derive(InputAxis2Action, Clone, Copy, PartialEq)]
enum Move {
    Walk,
}

impl InputAxis2Action for Move {
    fn bindings(&self) -> Vec<Axis2Binding> {
        match self {
            Move::Walk => vec![
                Axis2Binding::from(ButtonAxis2 {
                    left: Key::A,
                    right: Key::D,
                    down: Key::S,
                    up: Key::W,
                }),
                Axis2Binding::stick(Stick::Left),
            ],
        }
    }
}

struct Controls;

impl InputActions for Controls {
    type Button = Button;
    type Axis = NoInputAxes;
    type Axis2 = Move;
}

/// One source a drag moves: a cube on the ground, playing a sustained clip
/// with its own gain, reference, range, and pitch.
struct Source {
    position: Vec3,
    sound: Sound,
    gain: f32,
    reference: f32,
    range: f32,
    pitch: f32,
    /// Whether this source sustains at all; off keeps startup silent.
    enabled: bool,
}

impl Source {
    fn new(x: f32, z: f32, sound: Sound, range: f32, enabled: bool) -> Self {
        Self {
            position: Vec3::new(x, SOURCE_HEIGHT, z),
            sound,
            gain: 0.5,
            reference: SOURCE_REFERENCE,
            range,
            pitch: 1.0,
            enabled,
        }
    }

    /// This source's sustained cue, with the loop point that seeks far
    /// where its choice needs one.
    fn cue(&self) -> SoundCue<Sound> {
        let cue = self
            .sound
            .at(self.position)
            .gain(self.gain)
            .reference(self.reference)
            .range(self.range)
            .pitch(self.pitch);
        match self.sound {
            Sound::Theme | Sound::ThemeDecoded => cue.loop_from(THEME_LOOP_FROM),
            _ => cue,
        }
    }
}

struct SoundCheck {
    master_volume: f32,

    picked: Sound,
    one_shot_gain: f32,
    one_shot_pitch: f32,
    one_shot_fade: f32,
    trim_start: f32,
    trim_end: f32,
    one_shot_loop_from: f32,

    theme_on: bool,
    menu_on: bool,
    pulse_on: bool,
    cue_fade: f32,

    /// Sustains [`Sound::Click`] at [`MERGE_POS_A`] and [`MERGE_POS_B`]
    /// both at the default instance: shows the merge each source's own
    /// instance above keeps clear of.
    merge_demo: bool,

    /// Declares [`RING_COUNT`] sustains at once, more than the engine
    /// plays, so that the cap is heard as it allocates by level.
    ring_demo: bool,

    player: Vec2,
    player_prev: Vec2,
    sources: [Source; 3],
    dragging: Option<usize>,

    /// Every catalog value's length, read once at startup.
    durations: HashMap<Sound, Duration>,
}

impl SoundCheck {
    fn init(ctx: &mut InitContext<'_, SoundCheck>) -> Result<Self, Error> {
        let durations = ctx.durations();

        let picked = Sound::Bounce;
        let trim_end = durations.get(&picked).copied().unwrap_or_default();

        Ok(Self {
            master_volume: 1.0,

            picked,
            one_shot_gain: 1.0,
            one_shot_pitch: 1.0,
            one_shot_fade: SoundCue::<Sound>::DEFAULT_FADE.as_secs_f32(),
            trim_start: 0.0,
            trim_end: trim_end.as_secs_f32(),
            one_shot_loop_from: 0.0,

            theme_on: false,
            menu_on: false,
            pulse_on: false,
            cue_fade: 1.0,

            merge_demo: false,
            ring_demo: false,

            player: Vec2::ZERO,
            player_prev: Vec2::ZERO,
            sources: [
                Source::new(-2.5, -2.0, Sound::Bounce, 4.0, false),
                Source::new(2.5, -2.0, Sound::Serve, 4.0, false),
                Source::new(0.0, 2.8, Sound::Theme, 7.0, true),
            ],
            dragging: None,

            durations,
        })
    }

    fn camera(player: Vec2) -> Camera {
        let ground = Vec3::new(player.x, 0.0, player.y);
        Camera::new(
            View::look_at(
                ground + Vec3::new(0.0, CHASE_UP, CHASE_BACK),
                ground + Vec3::Y * 0.5,
            ),
            Projection::perspective(55.0),
        )
    }

    fn handle_walk(&mut self, ctx: &mut TickContext<'_, SoundCheck>) {
        self.player_prev = self.player;
        if ctx.ui_wants_keyboard() {
            return;
        }
        let walk = ctx.axis2(Move::Walk);
        let world = Vec2::new(walk.x, -walk.y);
        self.player = (self.player + world * WALK_SPEED * ctx.dt().as_secs_f32())
            .clamp(Vec2::splat(-PLAY_BOUND), Vec2::splat(PLAY_BOUND));
    }

    /// Takes hold of the source a click's ray intersects, moves it across
    /// the floor while the button stays down, and frees it on release.
    fn handle_drag(&mut self, ctx: &mut TickContext<'_, SoundCheck>) {
        // Read before the check below for the UI's own claim on the
        // pointer, so a release over it still frees a source a drag moved
        // there.
        if ctx.released(Button::Select) {
            self.dragging = None;
        }
        if ctx.ui_wants_pointer() {
            return;
        }
        let ray = ctx
            .last_camera()
            .ray_through(ctx.pointer(), ctx.window_size());

        if ctx.pressed(Button::Select) {
            self.dragging = self.sources.iter().position(|source| {
                ray.hit_sphere(source.position, SOURCE_PICK_RADIUS)
                    .is_some()
            });
        }

        let Some(index) = self.dragging else {
            return;
        };
        let Some(distance) = ray.hit_plane(ray::Plane {
            point: Vec3::ZERO,
            normal: Vec3::Y,
        }) else {
            return;
        };
        let hit = ray.at(distance);
        let dropped =
            Vec2::new(hit.x, hit.z).clamp(Vec2::splat(-PLAY_BOUND), Vec2::splat(PLAY_BOUND));
        self.sources[index].position = Vec3::new(dropped.x, SOURCE_HEIGHT, dropped.y);
    }

    fn draw_room(&self, ctx: &mut FrameContext<'_, SoundCheck>) {
        ctx.draw(
            Plane
                .at(Transform::from_scale(Vec3::new(
                    ROOM_HALF * 2.0,
                    1.0,
                    ROOM_HALF * 2.0,
                )))
                .material(Material::lit(FLOOR_COLOR)),
        );

        let side_half = Vec3::new(WALL_THICKNESS * 0.5, WALL_HEIGHT * 0.5, ROOM_HALF);
        for side in [-1.0, 1.0] {
            let x = side * (ROOM_HALF - WALL_THICKNESS * 0.5);
            ctx.draw(
                Cube.at(Transform::from_scale_rotation_translation(
                    side_half * 2.0,
                    Quat::IDENTITY,
                    Vec3::new(x, side_half.y, 0.0),
                ))
                .material(Material::lit(WALL_COLOR)),
            );
        }
        let end_half = Vec3::new(ROOM_HALF, WALL_HEIGHT * 0.5, WALL_THICKNESS * 0.5);
        for side in [-1.0, 1.0] {
            let z = side * (ROOM_HALF - WALL_THICKNESS * 0.5);
            ctx.draw(
                Cube.at(Transform::from_scale_rotation_translation(
                    end_half * 2.0,
                    Quat::IDENTITY,
                    Vec3::new(0.0, end_half.y, z),
                ))
                .material(Material::lit(WALL_COLOR)),
            );
        }
    }

    fn draw_sources(&self, ctx: &mut FrameContext<'_, SoundCheck>) {
        for (index, source) in self.sources.iter().enumerate() {
            let color = SOURCE_COLORS[index];
            let picked_up = self.dragging == Some(index);
            let scale = if picked_up { 1.3 } else { 1.0 };
            let emissive = if source.enabled {
                Color::rgb(color.red * 3.0, color.green * 3.0, color.blue * 3.0)
            } else {
                color.dimmed(0.15)
            };

            for (radius, ring_color) in [
                (source.range, RANGE_COLOR),
                (source.reference, REFERENCE_COLOR),
            ] {
                ctx.draw(
                    Ring.at(Transform::from_scale_rotation_translation(
                        Vec3::new(radius, 1.0, radius),
                        Quat::IDENTITY,
                        Vec3::new(source.position.x, 0.01, source.position.z),
                    ))
                    .material(Material::color(ring_color)),
                );
            }
            ctx.draw(
                Cube.at(Transform::from_scale_rotation_translation(
                    Vec3::splat(SOURCE_HALF * 2.0 * scale),
                    Quat::IDENTITY,
                    source.position,
                ))
                .material(Material::shaded(color, 0.6).emissive(emissive)),
            );
        }
    }

    /// The listener: a cube drawn from the ground up to [`EYE_HEIGHT`],
    /// an ear pair set on ± `view`'s right, and a marker at the front that
    /// shows its fixed `-Z` facing.
    fn draw_listener(&self, ctx: &mut FrameContext<'_, SoundCheck>, view: View) {
        let head = view.eye();
        let ground = Vec3::new(head.x, 0.0, head.z);

        ctx.draw(
            Cube.at(Transform::from_scale_rotation_translation(
                Vec3::new(LISTENER_WIDTH, head.y, LISTENER_DEPTH),
                Quat::IDENTITY,
                ground + Vec3::Y * head.y * 0.5,
            ))
            .material(Material::lit(LISTENER_COLOR)),
        );

        let right = listener_right(view) * EAR_OFFSET;
        for (offset, color) in [(right, RIGHT_EAR_COLOR), (-right, LEFT_EAR_COLOR)] {
            ctx.draw(
                Sphere { subdivisions: 1 }
                    .at(Transform::from_scale_rotation_translation(
                        Vec3::splat(EAR_SIZE),
                        Quat::IDENTITY,
                        head + offset,
                    ))
                    .material(Material::lit(color)),
            );
        }

        ctx.draw(
            Facing
                .at(Transform::from_scale_rotation_translation(
                    Vec3::splat(FACING_MARKER_SIZE),
                    Quat::IDENTITY,
                    head + Vec3::NEG_Z * (FACING_MARKER_SIZE * 0.5),
                ))
                .material(Material::lit(LISTENER_COLOR)),
        );
    }

    fn draw_merge_markers(&self, ctx: &mut FrameContext<'_, SoundCheck>) {
        if !self.merge_demo {
            return;
        }
        for (position, color) in [(MERGE_POS_A, MERGE_COLOR_A), (MERGE_POS_B, MERGE_COLOR_B)] {
            ctx.draw(
                Cube.at(Transform::from_scale_rotation_translation(
                    Vec3::splat(SOURCE_HALF * 2.0),
                    Quat::IDENTITY,
                    position,
                ))
                .material(Material::lit(color)),
            );
        }
    }

    /// Draws the ring, each cube as dim as the gain its sustain is declared
    /// at.
    fn draw_ring(&self, ctx: &mut FrameContext<'_, SoundCheck>) {
        if !self.ring_demo {
            return;
        }
        for nth in 0..RING_COUNT {
            let over = 1.0 - nth as f32 / RING_COUNT as f32;
            ctx.draw(
                Cube.at(Transform::from_scale_rotation_translation(
                    Vec3::splat(SOURCE_HALF),
                    Quat::IDENTITY,
                    ring_place(nth),
                ))
                .material(Material::lit(RING_COLOR.dimmed(over))),
            );
        }
    }

    /// The controls held at the left: master volume, sustained cues, and
    /// each source's own knobs.
    fn side_panel(&mut self, ctx: &mut FrameContext<'_, SoundCheck>) {
        #[cfg(target_arch = "wasm32")]
        let unlocked = ctx.sound_unlocked();

        let master_volume = &mut self.master_volume;
        let theme_on = &mut self.theme_on;
        let menu_on = &mut self.menu_on;
        let pulse_on = &mut self.pulse_on;
        let cue_fade = &mut self.cue_fade;
        let merge_demo = &mut self.merge_demo;
        let ring_demo = &mut self.ring_demo;
        let ring_label = format!("cap demo: sustain {RING_COUNT} sounds at once");
        let ring_note = format!(
            "each one is quieter than the one before it, so the engine plays the loudest {MAX_VOICES} and the rest go silent without stopping"
        );
        let sources = &mut self.sources;

        ctx.ui(|ui| {
            egui::Panel::left("controls").show(ui, |ui| {
                egui::ScrollArea::vertical()
                    .auto_shrink([false, false])
                    .show(ui, |ui| {
                        ui.heading("master");
                        ui.add(egui::Slider::new(master_volume, 0.0..=1.5).text("volume"));
                        #[cfg(target_arch = "wasm32")]
                        if !unlocked {
                            ui.label("audio unlocks on the first click or key in the browser");
                        }

                        ui.separator();
                        ui.heading("cue lab");
                        ui.label("a checked box is the sustain declaration");
                        ui.label("unchecking fades it out and parks it");
                        ui.checkbox(theme_on, Sound::Theme.label());
                        ui.checkbox(menu_on, Sound::MenuTheme.label());
                        ui.checkbox(pulse_on, Sound::Pulse.label());
                        ui.add(egui::Slider::new(cue_fade, 0.0..=3.0).text("fade (seconds)"));

                        ui.separator();
                        ui.heading("spatial lab");
                        ui.label("drag a source's marker on the floor to move it");
                        ui.label(
                            "a source is at full level inside its gold ring and falls to nothing at the white one",
                        );
                        ui.label("red is the right ear (RCA convention), white is the left");
                        ui.label("the point on the listener always faces -Z");
                        for (index, source) in sources.iter_mut().enumerate() {
                            ui.push_id(index, |ui| {
                                ui.separator();
                                ui.label(format!("source {}", index + 1));
                                ui.checkbox(&mut source.enabled, "enabled");
                                egui::ComboBox::from_label("clip")
                                    .selected_text(source.sound.label())
                                    .show_ui(ui, |ui| {
                                        for choice in Sound::SOURCE_CHOICES {
                                            ui.selectable_value(
                                                &mut source.sound,
                                                choice,
                                                choice.label(),
                                            );
                                        }
                                    });
                                ui.add(egui::Slider::new(&mut source.gain, 0.0..=2.0).text("gain"));
                                ui.add(
                                    egui::Slider::new(&mut source.range, 1.0..=12.0).text("range"),
                                );
                                let range = source.range;
                                ui.add(
                                    egui::Slider::new(&mut source.reference, 0.25..=range)
                                        .text("reference"),
                                );
                                ui.add(
                                    egui::Slider::new(&mut source.pitch, 0.5..=2.0).text("pitch"),
                                );
                            });
                        }
                        ui.separator();
                        ui.label(
                            "each enabled source above sustains at its own instance (0, 1, 2 by position), so the same clip can play at every one without merging into one voice",
                        );
                        ui.checkbox(merge_demo, "merge demo: same clip, both at instance 0");
                        ui.label(
                            "both declarations below target the same clip at the default instance",
                        );
                        ui.label(
                            "only the one declared last is heard, proof of what the sources above avoid",
                        );
                        ui.separator();
                        ui.checkbox(ring_demo, &ring_label);
                        ui.label(&ring_note);
                        ui.label(
                            "walk into the ring, or turn a source up, and what is played changes with what is loudest",
                        );
                    });
            });
        });
    }

    /// Reads what the one-shot controls hold, returning whether `play` and
    /// `play x32` were pressed this frame — read inside the closure, applied
    /// after it, since the closure cannot borrow `ctx`.
    fn one_shot_panel(&mut self, ctx: &mut FrameContext<'_, SoundCheck>) -> (bool, bool) {
        let mut play_once = false;
        let mut play_many = false;
        let durations = &self.durations;
        let picked = &mut self.picked;
        let gain = &mut self.one_shot_gain;
        let pitch = &mut self.one_shot_pitch;
        let fade = &mut self.one_shot_fade;
        let trim_start = &mut self.trim_start;
        let trim_end = &mut self.trim_end;
        let loop_from = &mut self.one_shot_loop_from;
        let duration = durations
            .get(picked)
            .copied()
            .unwrap_or_default()
            .as_secs_f32()
            .max(0.001);

        ctx.ui(|ui| {
            egui::Panel::bottom("one-shot").show(ui, |ui| {
                ui.heading("one-shot lab");
                egui::ComboBox::from_label("clip")
                    .selected_text(picked.label())
                    .show_ui(ui, |ui| {
                        for choice in Sound::ONE_SHOTS {
                            if ui
                                .selectable_label(*picked == choice, choice.label())
                                .clicked()
                                && *picked != choice
                            {
                                *picked = choice;
                                *trim_start = 0.0;
                                *trim_end = durations
                                    .get(&choice)
                                    .copied()
                                    .unwrap_or_default()
                                    .as_secs_f32();
                                *loop_from = 0.0;
                            }
                        }
                    });

                ui.add(egui::Slider::new(gain, 0.0..=2.0).text("gain"));
                ui.add(egui::Slider::new(pitch, 0.5..=2.0).text("pitch"));
                ui.add(egui::Slider::new(fade, 0.0..=2.0).text("fade (seconds)"));

                duration_bar(ui, duration, trim_start, trim_end, loop_from);
                ui.label(
                    "the marker sets loop_from, which a one-shot ignores: only sustain reads it",
                );

                ui.horizontal(|ui| {
                    play_once = ui.button("play").clicked();
                    play_many = ui.button("play ×32 (overruns the voice cap)").clicked();
                });
            });
        });

        (play_once, play_many)
    }

    fn one_shot_cue(&self) -> SoundCue<Sound> {
        self.picked
            .gain(self.one_shot_gain)
            .pitch(self.one_shot_pitch)
            .fade(Duration::from_secs_f32(self.one_shot_fade))
            .trim_to(
                Duration::from_secs_f32(self.trim_start),
                Duration::from_secs_f32(self.trim_end),
            )
            .loop_from(Duration::from_secs_f32(self.one_shot_loop_from))
    }

    /// Declares [`RING_COUNT`] sustains on a ring, each less loud than the
    /// one before it, so the engine's cap plays the loudest of them and the
    /// rest hold no voice while their playback goes on.
    fn sustain_ring(&self, ctx: &mut FrameContext<'_, SoundCheck>) {
        if !self.ring_demo {
            return;
        }
        for nth in 0..RING_COUNT {
            let gain = RING_GAIN * (1.0 - nth as f32 / RING_COUNT as f32);
            ctx.sustain(
                Sound::Pulse
                    .at(ring_place(nth))
                    .gain(gain)
                    .reference(RING_REFERENCE)
                    .range(RING_RADIUS * 3.0)
                    .instance(nth + 1),
            );
        }
    }

    fn sustain_cues(&self, ctx: &mut FrameContext<'_, SoundCheck>) {
        let fade = Duration::from_secs_f32(self.cue_fade);
        if self.theme_on {
            ctx.sustain(Sound::Theme.gain(0.5).fade(fade));
        }
        if self.menu_on {
            ctx.sustain(Sound::MenuTheme.gain(0.5).fade(fade));
        }
        if self.pulse_on {
            ctx.sustain(Sound::Pulse.gain(0.3).fade(fade));
        }
    }
}

/// Where the `nth` sustain of the ring stands: around the room, starting
/// behind the listener's back.
fn ring_place(nth: u32) -> Vec3 {
    let turn = TAU * nth as f32 / RING_COUNT as f32;

    Vec3::new(
        turn.sin() * RING_RADIUS,
        SOURCE_HEIGHT,
        turn.cos() * RING_RADIUS,
    )
}

/// The direction the ear pair is offset along — the same side the
/// engine's own pan reads.
fn listener_right(view: View) -> Vec3 {
    (view.target() - view.eye())
        .normalize_or_zero()
        .cross(view.up())
}

/// The clip's duration, with two trim handles and a loop marker, each moved
/// by the pointer's own place rather than by a moving total.
fn duration_bar(
    ui: &mut egui::Ui,
    duration: f32,
    trim_start: &mut f32,
    trim_end: &mut f32,
    loop_from: &mut f32,
) {
    let size = egui::vec2(ui.available_width().min(420.0), 28.0);
    let (rect, _response) = ui.allocate_exact_size(size, egui::Sense::hover());
    let painter = ui.painter();
    painter.rect_filled(rect, 3.0, egui::Color32::from_gray(35));

    let x_of = |seconds: f32| rect.left() + (seconds / duration).clamp(0.0, 1.0) * rect.width();
    let seconds_of = |x: f32| ((x - rect.left()) / rect.width()).clamp(0.0, 1.0) * duration;

    let span = egui::Rect::from_min_max(
        egui::pos2(x_of(*trim_start), rect.top()),
        egui::pos2(x_of(*trim_end), rect.bottom()),
    );
    painter.rect_filled(span, 3.0, egui::Color32::from_rgb(70, 120, 95));

    let start_x = x_of(*trim_start);
    if let Some(x) = drag_handle(
        ui,
        rect,
        "trim-start",
        start_x,
        egui::Color32::from_rgb(230, 200, 80),
    ) {
        *trim_start = seconds_of(x).min(*trim_end);
    }
    let end_x = x_of(*trim_end);
    if let Some(x) = drag_handle(
        ui,
        rect,
        "trim-end",
        end_x,
        egui::Color32::from_rgb(230, 200, 80),
    ) {
        *trim_end = seconds_of(x).max(*trim_start);
    }
    let loop_x = x_of(*loop_from);
    if let Some(x) = drag_handle(
        ui,
        rect,
        "loop-from",
        loop_x,
        egui::Color32::from_rgb(90, 170, 230),
    ) {
        *loop_from = seconds_of(x).clamp(*trim_start, *trim_end);
    }
}

/// One round handle at `x`. Returns the pointer's `x` while a drag holds
/// it.
fn drag_handle(
    ui: &mut egui::Ui,
    bar: egui::Rect,
    salt: &str,
    x: f32,
    color: egui::Color32,
) -> Option<f32> {
    let radius = 6.0;
    let center = egui::pos2(x, bar.center().y);
    let sense_rect = egui::Rect::from_center_size(center, egui::Vec2::splat(radius * 2.5));
    let id = ui.id().with(salt);
    let response = ui.interact(sense_rect, id, egui::Sense::drag());
    ui.painter().circle_filled(center, radius, color);

    response
        .dragged()
        .then(|| response.interact_pointer_pos())
        .flatten()
        .map(|pos| pos.x)
}

impl Game for SoundCheck {
    type Meshes = Shape;
    type Sounds = Sound;
    type InputActions = Controls;
    type Skyboxes = Sky;
    type SurfaceStyles = NoSurfaceStyles;
    type PostEffects = NoPostEffects;

    fn tick(&mut self, ctx: &mut TickContext<'_, SoundCheck>) {
        self.handle_walk(ctx);
        self.handle_drag(ctx);
    }

    fn frame(&mut self, ctx: &mut FrameContext<'_, SoundCheck>) {
        ctx.set_volume(self.master_volume);

        let player = self.player_prev.lerp(self.player, ctx.alpha());
        let ear = Vec3::new(player.x, EYE_HEIGHT, player.y);
        let listener = View::look_at(ear, ear + Vec3::NEG_Z);
        ctx.set_listener(listener);

        ctx.set_camera(Self::camera(player));
        ctx.set_skybox(Sky::Room);
        ctx.set_bloom(0.2);
        ctx.light(Light::directional(Vec3::new(-0.4, -1.0, -0.5), SUN_COLOR).shadow());

        self.draw_room(ctx);
        self.draw_sources(ctx);
        self.draw_listener(ctx, listener);
        self.draw_merge_markers(ctx);
        self.draw_ring(ctx);

        self.sustain_cues(ctx);
        for (index, source) in self.sources.iter().enumerate() {
            if source.enabled {
                ctx.sustain(source.cue().instance(index as u32));
            }
        }
        if self.merge_demo {
            ctx.sustain(Sound::Click.at(MERGE_POS_A).gain(MERGE_GAIN));
            ctx.sustain(Sound::Click.at(MERGE_POS_B).gain(MERGE_GAIN));
        }
        self.sustain_ring(ctx);

        self.side_panel(ctx);
        let (play_once, play_many) = self.one_shot_panel(ctx);

        if play_once {
            ctx.play(self.one_shot_cue());
        }
        if play_many {
            for _ in 0..32 {
                ctx.play(self.one_shot_cue());
            }
        }
    }
}