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
//! Manages individual sfx event system, listens for sfx events, and requests
//! playback at the requested position and volume
//!
//! Veloren's sfx are managed through a configuration which lives in the
//! codebase under `/assets/voxygen/audio/sfx.ron`.
//!
//! If there are errors while reading or deserialising the configuration file, a
//! warning is logged and sfx will be disabled.
//!
//! Each entry in the configuration consists of an
//! [SfxEvent](../../../veloren_common/event/enum.SfxEvent.html) item, with some
//! additional information to allow playback:
//! - `files` - the paths to the `.wav` files to be played for the sfx. minus
//!   the file extension. This can be a single item if the same sound can be
//!   played each time, or a list of files from which one is chosen at random to
//!   be played.
//! - `threshold` - the time that the system should wait between successive
//!   plays. This avoids playing the sound with very fast successive repetition
//!   when the character can maintain a state over a long period, such as
//!   running or climbing.
//!
//! The following snippet details some entries in the configuration and how they
//! map to the sound files:
//! ```ignore
//! Run(Grass): ( // depends on underfoot block
//!    files: [
//!        "voxygen.audio.sfx.footsteps.stepgrass_1",
//!        "voxygen.audio.sfx.footsteps.stepgrass_2",
//!        "voxygen.audio.sfx.footsteps.stepgrass_3",
//!        "voxygen.audio.sfx.footsteps.stepgrass_4",
//!        "voxygen.audio.sfx.footsteps.stepgrass_5",
//!        "voxygen.audio.sfx.footsteps.stepgrass_6",
//!    ],
//!    threshold: 1.6, // travelled distance before next play
//! ),
//! Wield(Sword): ( // depends on the player's weapon
//!    files: [
//!        "voxygen.audio.sfx.weapon.sword_out",
//!    ],
//!    threshold: 0.5, // wait 0.5s between plays
//! ),
//! ...
//! ```
//!
//! These items (for example, the `Wield(Sword)` occasionally depend on some
//! property which varies in game. The
//! [SfxEvent](../../../veloren_common/event/enum.SfxEvent.html) documentation
//! provides links to those variables, some examples are provided her for longer
//! items:
//!
//! ```ignore
//! // An inventory action
//! Inventory(Dropped): (
//!     files: [
//!        "voxygen.audio.sfx.footsteps.stepgrass_4",
//!    ],
//!    threshold: 0.5,
//! ),
//! // An inventory action which depends upon the item
//! Inventory(Consumed(Apple)): (
//!    files: [
//!        "voxygen.audio.sfx.inventory.consumable.apple",
//!    ],
//!    threshold: 0.5
//! ),
//! // An attack ability which depends on the weapon
//! Attack(DashMelee, Sword): (
//!     files: [
//!         "voxygen.audio.sfx.weapon.sword_dash_01",
//!         "voxygen.audio.sfx.weapon.sword_dash_02",
//!     ],
//!     threshold: 1.2,
//! ),
//! ```

mod event_mapper;

use specs::WorldExt;

use crate::{
    audio::AudioFrontend,
    scene::{Camera, Terrain},
};

use client::Client;
use common::{
    assets::{self, AssetExt, AssetHandle},
    comp::{
        beam, biped_large, biped_small, bird_large, bird_medium, crustacean, humanoid,
        item::{item_key::ItemKey, AbilitySpec, ItemDefinitionId, ItemDesc, ItemKind, ToolKind},
        object,
        poise::PoiseState,
        quadruped_low, quadruped_medium, quadruped_small, Body, CharacterAbilityType, Health,
        InventoryUpdateEvent, UtteranceKind,
    },
    outcome::Outcome,
    terrain::{BlockKind, SpriteKind, TerrainChunk},
    uid::Uid,
    vol::ReadVol,
    DamageSource,
};
use common_state::State;
use event_mapper::SfxEventMapper;
use hashbrown::HashMap;
use rand::prelude::*;
use serde::Deserialize;
use tracing::{debug, error, warn};
use vek::*;

/// We watch the states of nearby entities in order to emit SFX at their
/// position based on their state. This constant limits the radius that we
/// observe to prevent tracking distant entities. It approximates the distance
/// at which the volume of the sfx emitted is too quiet to be meaningful for the
/// player.
const SFX_DIST_LIMIT_SQR: f32 = 20000.0;

#[derive(Clone, Debug, PartialEq, Deserialize, Hash, Eq)]
pub enum SfxEvent {
    Campfire,
    Embers,
    Birdcall,
    Owl,
    Cricket1,
    Cricket2,
    Cricket3,
    Frog,
    Bees,
    RunningWaterSlow,
    RunningWaterFast,
    Lavapool,
    Idle,
    Swim,
    SplashSmall,
    SplashMedium,
    SplashBig,
    Run(BlockKind),
    QuadRun(BlockKind),
    Roll,
    Sneak,
    Climb,
    GliderOpen,
    Glide,
    GliderClose,
    CatchAir,
    Jump,
    Fall,
    Attack(CharacterAbilityType, ToolKind),
    Wield(ToolKind),
    Unwield(ToolKind),
    Inventory(SfxInventoryEvent),
    Explosion,
    Damage,
    Death,
    Parry,
    Block,
    BreakBlock,
    PickaxeDamage,
    PickaxeDamageStrong,
    PickaxeBreakBlock,
    SceptreBeam,
    SkillPointGain,
    ArrowHit,
    ArrowMiss,
    ArrowShot,
    FireShot,
    FlameThrower,
    PoiseChange(PoiseState),
    GroundSlam,
    FlashFreeze,
    GigaRoar,
    IceSpikes,
    IceCrack,
    Utterance(UtteranceKind, VoiceKind),
    Lightning,
    CyclopsCharge,
    TerracottaStatueCharge,
    LaserBeam,
    Steam,
    FuseCharge,
    Music(ToolKind, AbilitySpec),
    Yeet,
    Hiss,
    Klonk,
    SmashKlonk,
    FireShockwave,
    DeepLaugh,
    Whoosh,
    Swoosh,
    GroundDig,
    PortalActivated,
    TeleportedByPortal,
    FromTheAshes,
    SurpriseEgg,
    Bleep,
    Charge,
    StrigoiHead,
    BloodmoonHeiressSummon,
}

#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Hash, Eq)]
pub enum VoiceKind {
    HumanFemale,
    HumanMale,
    BipedLarge,
    Wendigo,
    Reptile,
    Bird,
    Critter,
    Sheep,
    Pig,
    Cow,
    Canine,
    Dagon,
    Lion,
    Mindflayer,
    Marlin,
    Maneater,
    Adlet,
    Antelope,
    Alligator,
    SeaCrocodile,
    Saurok,
    Cat,
    Goat,
    Mandragora,
    Asp,
    Fungome,
    Truffler,
    Wolf,
    Wyvern,
    Phoenix,
    VampireBat,
}

fn body_to_voice(body: &Body) -> Option<VoiceKind> {
    Some(match body {
        Body::Humanoid(body) => match &body.body_type {
            humanoid::BodyType::Female => VoiceKind::HumanFemale,
            humanoid::BodyType::Male => VoiceKind::HumanMale,
        },
        Body::QuadrupedLow(body) => match body.species {
            quadruped_low::Species::Maneater => VoiceKind::Maneater,
            quadruped_low::Species::Alligator | quadruped_low::Species::Snaretongue => {
                VoiceKind::Alligator
            },
            quadruped_low::Species::SeaCrocodile => VoiceKind::SeaCrocodile,
            quadruped_low::Species::Dagon => VoiceKind::Dagon,
            quadruped_low::Species::Asp => VoiceKind::Asp,
            _ => return None,
        },
        Body::QuadrupedSmall(body) => match body.species {
            quadruped_small::Species::Truffler => VoiceKind::Truffler,
            quadruped_small::Species::Fungome => VoiceKind::Fungome,
            quadruped_small::Species::Sheep => VoiceKind::Sheep,
            quadruped_small::Species::Pig | quadruped_small::Species::Boar => VoiceKind::Pig,
            quadruped_small::Species::Cat => VoiceKind::Cat,
            quadruped_small::Species::Goat => VoiceKind::Goat,
            _ => VoiceKind::Critter,
        },
        Body::QuadrupedMedium(body) => match body.species {
            quadruped_medium::Species::Saber
            | quadruped_medium::Species::Tiger
            | quadruped_medium::Species::Lion
            | quadruped_medium::Species::Frostfang
            | quadruped_medium::Species::Snowleopard => VoiceKind::Lion,
            quadruped_medium::Species::Wolf => VoiceKind::Wolf,
            quadruped_medium::Species::Roshwalr
            | quadruped_medium::Species::Tarasque
            | quadruped_medium::Species::Darkhound
            | quadruped_medium::Species::Bonerattler
            | quadruped_medium::Species::Grolgar => VoiceKind::Canine,
            quadruped_medium::Species::Cattle
            | quadruped_medium::Species::Catoblepas
            | quadruped_medium::Species::Highland
            | quadruped_medium::Species::Yak
            | quadruped_medium::Species::Moose
            | quadruped_medium::Species::Dreadhorn => VoiceKind::Cow,
            quadruped_medium::Species::Antelope => VoiceKind::Antelope,
            _ => return None,
        },
        Body::BirdMedium(body) => match body.species {
            bird_medium::Species::BloodmoonBat | bird_medium::Species::VampireBat => {
                VoiceKind::VampireBat
            },
            _ => VoiceKind::Bird,
        },
        Body::BirdLarge(body) => match body.species {
            bird_large::Species::CloudWyvern
            | bird_large::Species::FlameWyvern
            | bird_large::Species::FrostWyvern
            | bird_large::Species::SeaWyvern
            | bird_large::Species::WealdWyvern => VoiceKind::Wyvern,
            bird_large::Species::Phoenix => VoiceKind::Phoenix,
            _ => VoiceKind::Bird,
        },
        Body::BipedSmall(body) => match body.species {
            biped_small::Species::Adlet => VoiceKind::Adlet,
            biped_small::Species::Mandragora => VoiceKind::Mandragora,
            biped_small::Species::Flamekeeper => VoiceKind::BipedLarge,
            _ => return None,
        },
        Body::BipedLarge(body) => match body.species {
            biped_large::Species::Wendigo => VoiceKind::Wendigo,
            biped_large::Species::Occultsaurok
            | biped_large::Species::Mightysaurok
            | biped_large::Species::Slysaurok => VoiceKind::Saurok,
            biped_large::Species::Mindflayer => VoiceKind::Mindflayer,
            _ => VoiceKind::BipedLarge,
        },
        Body::Theropod(_) | Body::Dragon(_) => VoiceKind::Reptile,
        Body::FishSmall(_) | Body::FishMedium(_) => VoiceKind::Marlin,
        _ => return None,
    })
}

#[derive(Clone, Debug, PartialEq, Deserialize, Hash, Eq)]
pub enum SfxInventoryEvent {
    Collected,
    CollectedTool(ToolKind),
    CollectedItem(String),
    CollectFailed,
    Consumed(ItemKey),
    Debug,
    Dropped,
    Given,
    Swapped,
    Craft,
}

// TODO Move to a separate event mapper?
impl From<&InventoryUpdateEvent> for SfxEvent {
    fn from(value: &InventoryUpdateEvent) -> Self {
        match value {
            InventoryUpdateEvent::Collected(item) => {
                // Handle sound effects for types of collected items, falling
                // back to the default Collected event
                match &*item.kind() {
                    ItemKind::Tool(tool) => {
                        SfxEvent::Inventory(SfxInventoryEvent::CollectedTool(tool.kind))
                    },
                    ItemKind::Ingredient { .. }
                        if matches!(
                            item.item_definition_id(),
                            ItemDefinitionId::Simple(id) if id.contains("mineral.gem.")
                        ) =>
                    {
                        SfxEvent::Inventory(SfxInventoryEvent::CollectedItem(String::from(
                            "Gemstone",
                        )))
                    },
                    _ => SfxEvent::Inventory(SfxInventoryEvent::Collected),
                }
            },
            InventoryUpdateEvent::BlockCollectFailed { .. }
            | InventoryUpdateEvent::EntityCollectFailed { .. } => {
                SfxEvent::Inventory(SfxInventoryEvent::CollectFailed)
            },
            InventoryUpdateEvent::Consumed(consumable) => {
                SfxEvent::Inventory(SfxInventoryEvent::Consumed(consumable.clone()))
            },
            InventoryUpdateEvent::Debug => SfxEvent::Inventory(SfxInventoryEvent::Debug),
            InventoryUpdateEvent::Dropped => SfxEvent::Inventory(SfxInventoryEvent::Dropped),
            InventoryUpdateEvent::Given => SfxEvent::Inventory(SfxInventoryEvent::Given),
            InventoryUpdateEvent::Swapped => SfxEvent::Inventory(SfxInventoryEvent::Swapped),
            InventoryUpdateEvent::Craft => SfxEvent::Inventory(SfxInventoryEvent::Craft),
            _ => SfxEvent::Inventory(SfxInventoryEvent::Swapped),
        }
    }
}

#[derive(Deserialize)]
pub struct SfxTriggerItem {
    /// A list of SFX filepaths for this event
    pub files: Vec<String>,
    /// The time to wait before repeating this SfxEvent
    pub threshold: f32,

    #[serde(default)]
    pub subtitle: Option<String>,
}

#[derive(Deserialize, Default)]
pub struct SfxTriggers(HashMap<SfxEvent, SfxTriggerItem>);

impl SfxTriggers {
    pub fn get_trigger(&self, trigger: &SfxEvent) -> Option<&SfxTriggerItem> { self.0.get(trigger) }

    pub fn get_key_value(&self, trigger: &SfxEvent) -> Option<(&SfxEvent, &SfxTriggerItem)> {
        self.0.get_key_value(trigger)
    }
}

pub struct SfxMgr {
    /// This is an `AssetHandle` so it is reloaded automatically
    /// when the manifest is edited.
    pub triggers: AssetHandle<SfxTriggers>,
    event_mapper: SfxEventMapper,
}

impl Default for SfxMgr {
    fn default() -> Self {
        Self {
            triggers: Self::load_sfx_items(),
            event_mapper: SfxEventMapper::new(),
        }
    }
}

impl SfxMgr {
    pub fn maintain(
        &mut self,
        audio: &mut AudioFrontend,
        state: &State,
        player_entity: specs::Entity,
        camera: &Camera,
        terrain: &Terrain<TerrainChunk>,
        client: &Client,
    ) {
        // Checks if the SFX volume is set to zero or audio is disabled
        // This prevents us from running all the following code unnecessarily
        if !audio.sfx_enabled() && !audio.subtitles_enabled {
            return;
        }

        let cam_pos = camera.get_pos_with_focus();

        // Sets the listener position to the camera position facing the
        // same direction as the camera
        audio.set_listener_pos(cam_pos, camera.dependents().cam_dir);

        let triggers = self.triggers.read();

        let underwater = state
            .terrain()
            .get(cam_pos.map(|e| e.floor() as i32))
            .map(|b| b.is_liquid())
            .unwrap_or(false);

        if underwater {
            audio.set_sfx_master_filter(888);
        } else {
            audio.set_sfx_master_filter(20000);
        }

        self.event_mapper.maintain(
            audio,
            state,
            player_entity,
            camera,
            &triggers,
            terrain,
            client,
        );
    }

    #[allow(clippy::single_match)]
    pub fn handle_outcome(
        &mut self,
        outcome: &Outcome,
        audio: &mut AudioFrontend,
        client: &Client,
    ) {
        if !audio.sfx_enabled() && !audio.subtitles_enabled {
            return;
        }
        let triggers = self.triggers.read();
        let uids = client.state().ecs().read_storage::<Uid>();
        if audio.get_listener().is_none() {
            return;
        }
        match outcome {
            Outcome::Explosion { pos, power, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Explosion);
                audio.emit_sfx(sfx_trigger_item, *pos, Some((power.abs() / 2.5).min(1.5)));
            },
            Outcome::Lightning { pos } => {
                let distance = pos.distance(audio.get_listener_pos());
                let power = (1.0 - distance / 6_000.0).max(0.0).powi(7);
                if power > 0.0 {
                    let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Lightning);
                    let volume = (power * 3.0).min(2.9);
                    // Delayed based on distance / speed of sound (approxmately 340 m/s)
                    audio.play_ambience_oneshot(
                        super::channel::AmbienceChannelTag::Thunder,
                        sfx_trigger_item,
                        Some(volume),
                        Some(distance / 340.0),
                    );
                }
            },
            Outcome::GroundSlam { pos, .. } | Outcome::ClayGolemDash { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::GroundSlam);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::SurpriseEgg { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::SurpriseEgg);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::LaserBeam { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::LaserBeam);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::CyclopsCharge { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::CyclopsCharge);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::FlamethrowerCharge { pos, .. }
            | Outcome::TerracottaStatueCharge { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::CyclopsCharge);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::FuseCharge { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::FuseCharge);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::Charge { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::CyclopsCharge);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::FlashFreeze { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::FlashFreeze);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::SummonedCreature { pos, body, .. } => {
                match body {
                    Body::BipedSmall(body) => match body.species {
                        biped_small::Species::IronDwarf => {
                            let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Bleep);
                            audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
                        },
                        biped_small::Species::Boreal => {
                            let sfx_trigger_item = triggers.get_key_value(&SfxEvent::GigaRoar);
                            audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
                        },
                        biped_small::Species::ShamanicSpirit | biped_small::Species::Jiangshi => {
                            let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Klonk);
                            audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
                        },
                        _ => {},
                    },
                    Body::BipedLarge(body) => match body.species {
                        biped_large::Species::TerracottaBesieger
                        | biped_large::Species::TerracottaPursuer => {
                            let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Klonk);
                            audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
                        },
                        _ => {},
                    },
                    Body::BirdMedium(body) => match body.species {
                        bird_medium::Species::Bat => {
                            let sfx_trigger_item =
                                triggers.get_key_value(&SfxEvent::BloodmoonHeiressSummon);
                            audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
                        },
                        _ => {},
                    },
                    Body::Crustacean(body) => match body.species {
                        crustacean::Species::SoldierCrab => {
                            let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Hiss);
                            audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
                        },
                        _ => {},
                    },
                    Body::Object(object::Body::Lavathrower) => {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::DeepLaugh);
                        audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
                    },
                    Body::Object(object::Body::Tornado)
                    | Body::Object(object::Body::FieryTornado) => {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Swoosh);
                        audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
                    },
                    _ => { // not mapped to sfx file
                    },
                }
            },
            Outcome::GroundDig { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::GroundDig);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::PortalActivated { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::PortalActivated);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::TeleportedByPortal { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::TeleportedByPortal);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::IceSpikes { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::IceSpikes);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::IceCrack { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::IceCrack);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::Steam { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Steam);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::FireShockwave { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::FlameThrower);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::FromTheAshes { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::FromTheAshes);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
            },
            Outcome::ProjectileShot { pos, body, .. } => {
                match body {
                    Body::Object(
                        object::Body::Arrow
                        | object::Body::MultiArrow
                        | object::Body::ArrowSnake
                        | object::Body::ArrowTurret
                        | object::Body::ArrowClay
                        | object::Body::BoltBesieger
                        | object::Body::HarlequinDagger
                        | object::Body::SpectralSwordSmall
                        | object::Body::SpectralSwordLarge,
                    ) => {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::ArrowShot);
                        audio.emit_sfx(sfx_trigger_item, *pos, None);
                    },
                    Body::Object(
                        object::Body::BoltFire
                        | object::Body::BoltFireBig
                        | object::Body::BoltNature
                        | object::Body::BoltIcicle
                        | object::Body::SpearIcicle
                        | object::Body::GrenadeClay
                        | object::Body::SpitPoison,
                    ) => {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::FireShot);
                        audio.emit_sfx(sfx_trigger_item, *pos, None);
                    },
                    Body::Object(
                        object::Body::IronPikeBomb
                        | object::Body::BubbleBomb
                        | object::Body::MinotaurAxe
                        | object::Body::Pebble,
                    ) => {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Whoosh);
                        audio.emit_sfx(sfx_trigger_item, *pos, None);
                    },
                    Body::Object(
                        object::Body::LaserBeam
                        | object::Body::LaserBeamSmall
                        | object::Body::LightningBolt,
                    ) => {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::LaserBeam);
                        audio.emit_sfx(sfx_trigger_item, *pos, None);
                    },
                    Body::Object(object::Body::AdletTrap | object::Body::Mine) => {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Yeet);
                        audio.emit_sfx(sfx_trigger_item, *pos, None);
                    },
                    Body::Object(object::Body::StrigoiHead) => {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::StrigoiHead);
                        audio.emit_sfx(sfx_trigger_item, *pos, None);
                    },
                    _ => {
                        // not mapped to sfx file
                    },
                }
            },
            Outcome::ProjectileHit {
                pos,
                body,
                source,
                target,
                ..
            } => match body {
                Body::Object(
                    object::Body::Arrow
                    | object::Body::MultiArrow
                    | object::Body::ArrowSnake
                    | object::Body::ArrowTurret
                    | object::Body::ArrowClay
                    | object::Body::BoltBesieger
                    | object::Body::HarlequinDagger
                    | object::Body::SpectralSwordSmall
                    | object::Body::SpectralSwordLarge
                    | object::Body::Pebble,
                ) => {
                    if target.is_none() {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::ArrowMiss);
                        audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
                    } else if *source == client.uid() {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::ArrowHit);
                        audio.emit_sfx(
                            sfx_trigger_item,
                            client.position().unwrap_or(*pos),
                            Some(2.0),
                        );
                    } else {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::ArrowHit);
                        audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
                    }
                },
                Body::Object(
                    object::Body::AdletTrap | object::Body::Mine | object::Body::StrigoiHead,
                ) => {
                    if target.is_none() {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Klonk);
                        audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
                    } else if *source == client.uid() {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::SmashKlonk);
                        audio.emit_sfx(
                            sfx_trigger_item,
                            client.position().unwrap_or(*pos),
                            Some(2.0),
                        );
                    } else {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::SmashKlonk);
                        audio.emit_sfx(sfx_trigger_item, *pos, Some(2.0));
                    }
                },
                _ => {},
            },
            Outcome::SkillPointGain { uid, .. } => {
                if let Some(client_uid) = uids.get(client.entity()) {
                    if uid == client_uid {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::SkillPointGain);
                        audio.emit_ui_sfx(sfx_trigger_item, Some(0.4));
                    }
                }
            },
            Outcome::Beam { pos, specifier } => match specifier {
                beam::FrontendSpecifier::LifestealBeam
                | beam::FrontendSpecifier::Steam
                | beam::FrontendSpecifier::Poison
                | beam::FrontendSpecifier::Ink
                | beam::FrontendSpecifier::Lightning
                | beam::FrontendSpecifier::Frost
                | beam::FrontendSpecifier::Bubbles => {
                    if thread_rng().gen_bool(0.5) {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::SceptreBeam);
                        audio.emit_sfx(sfx_trigger_item, *pos, None);
                    };
                },
                beam::FrontendSpecifier::Flamethrower
                | beam::FrontendSpecifier::Cultist
                | beam::FrontendSpecifier::PhoenixLaser => {
                    if thread_rng().gen_bool(0.5) {
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::FlameThrower);
                        audio.emit_sfx(sfx_trigger_item, *pos, None);
                    }
                },
                beam::FrontendSpecifier::Gravewarden | beam::FrontendSpecifier::WebStrand => {},
            },
            Outcome::SpriteUnlocked { pos } => {
                // TODO: Dedicated sound effect!
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::GliderOpen);
                audio.emit_sfx(sfx_trigger_item, pos.map(|e| e as f32 + 0.5), Some(2.0));
            },
            Outcome::FailedSpriteUnlock { pos } => {
                // TODO: Dedicated sound effect!
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::BreakBlock);
                audio.emit_sfx(sfx_trigger_item, pos.map(|e| e as f32 + 0.5), Some(2.0));
            },
            Outcome::BreakBlock { pos, tool, .. } => {
                let sfx_trigger_item =
                    triggers.get_key_value(&if matches!(tool, Some(ToolKind::Pick)) {
                        SfxEvent::PickaxeBreakBlock
                    } else {
                        SfxEvent::BreakBlock
                    });
                audio.emit_sfx(sfx_trigger_item, pos.map(|e| e as f32 + 0.5), Some(3.0));
            },
            Outcome::DamagedBlock {
                pos,
                stage_changed,
                tool,
                ..
            } => {
                let sfx_trigger_item = triggers.get_key_value(&match (stage_changed, tool) {
                    (false, Some(ToolKind::Pick)) => SfxEvent::PickaxeDamage,
                    (true, Some(ToolKind::Pick)) => SfxEvent::PickaxeDamageStrong,
                    // SFX already emitted by ability
                    (_, Some(ToolKind::Shovel)) => return,
                    (_, _) => SfxEvent::BreakBlock,
                });

                audio.emit_sfx(
                    sfx_trigger_item,
                    pos.map(|e| e as f32 + 0.5),
                    Some(if *stage_changed { 3.0 } else { 2.0 }),
                );
            },
            Outcome::HealthChange { pos, info, .. } => {
                // Ignore positive damage (healing) and buffs for now
                if info.amount < Health::HEALTH_EPSILON
                    && !matches!(info.cause, Some(DamageSource::Buff(_)))
                {
                    let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Damage);
                    audio.emit_sfx(sfx_trigger_item, *pos, Some(1.5));
                }
            },
            Outcome::Death { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Death);
                audio.emit_sfx(sfx_trigger_item, *pos, Some(1.5));
            },
            Outcome::Block { pos, parry, .. } => {
                if *parry {
                    let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Parry);
                    audio.emit_sfx(sfx_trigger_item, *pos, Some(1.5));
                } else {
                    let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Block);
                    audio.emit_sfx(sfx_trigger_item, *pos, Some(1.5));
                }
            },
            Outcome::PoiseChange { pos, state, .. } => match state {
                PoiseState::Normal => {},
                PoiseState::Interrupted => {
                    let sfx_trigger_item =
                        triggers.get_key_value(&SfxEvent::PoiseChange(PoiseState::Interrupted));
                    audio.emit_sfx(sfx_trigger_item, *pos, Some(1.5));
                },
                PoiseState::Stunned => {
                    let sfx_trigger_item =
                        triggers.get_key_value(&SfxEvent::PoiseChange(PoiseState::Stunned));
                    audio.emit_sfx(sfx_trigger_item, *pos, Some(1.5));
                },
                PoiseState::Dazed => {
                    let sfx_trigger_item =
                        triggers.get_key_value(&SfxEvent::PoiseChange(PoiseState::Dazed));
                    audio.emit_sfx(sfx_trigger_item, *pos, Some(1.5));
                },
                PoiseState::KnockedDown => {
                    let sfx_trigger_item =
                        triggers.get_key_value(&SfxEvent::PoiseChange(PoiseState::KnockedDown));
                    audio.emit_sfx(sfx_trigger_item, *pos, Some(1.5));
                },
            },
            Outcome::Utterance { pos, kind, body } => {
                if let Some(voice) = body_to_voice(body) {
                    let sfx_trigger_item =
                        triggers.get_key_value(&SfxEvent::Utterance(*kind, voice));
                    if let Some(sfx_trigger_item) = sfx_trigger_item {
                        audio.emit_sfx(Some(sfx_trigger_item), *pos, Some(1.5));
                    } else {
                        debug!(
                            "No utterance sound effect exists for ({:?}, {:?})",
                            kind, voice
                        );
                    }
                }
            },
            Outcome::Glider { pos, wielded } => {
                if *wielded {
                    let sfx_trigger_item = triggers.get_key_value(&SfxEvent::GliderOpen);
                    audio.emit_sfx(sfx_trigger_item, *pos, Some(1.0));
                } else {
                    let sfx_trigger_item = triggers.get_key_value(&SfxEvent::GliderClose);
                    audio.emit_sfx(sfx_trigger_item, *pos, Some(1.0));
                }
            },
            Outcome::SpriteDelete { pos, sprite } => {
                match sprite {
                    SpriteKind::SeaUrchin => {
                        let pos = pos.map(|e| e as f32 + 0.5);
                        let power = (0.6 - pos.distance(audio.get_listener_pos()) / 5_000.0)
                            .max(0.0)
                            .powi(7);
                        let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Explosion);
                        audio.emit_sfx(sfx_trigger_item, pos, Some((power.abs() / 2.5).min(0.3)));
                    },
                    _ => {},
                };
            },
            Outcome::Whoosh { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Whoosh);
                audio.emit_sfx(sfx_trigger_item, pos.map(|e| e + 0.5), Some(3.0));
            },
            Outcome::Swoosh { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Swoosh);
                audio.emit_sfx(sfx_trigger_item, pos.map(|e| e + 0.5), Some(3.0));
            },
            Outcome::Slash { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::SmashKlonk);
                audio.emit_sfx(sfx_trigger_item, pos.map(|e| e + 0.5), Some(3.0));
            },
            Outcome::Bleep { pos, .. } => {
                let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Bleep);
                audio.emit_sfx(sfx_trigger_item, pos.map(|e| e + 0.5), Some(3.0));
            },
            Outcome::HeadLost { uid, .. } => {
                let positions = client.state().ecs().read_storage::<common::comp::Pos>();
                if let Some(pos) = client
                    .state()
                    .ecs()
                    .read_resource::<common::uid::IdMaps>()
                    .uid_entity(*uid)
                    .and_then(|entity| positions.get(entity))
                {
                    let sfx_trigger_item = triggers.get_key_value(&SfxEvent::Death);
                    audio.emit_sfx(sfx_trigger_item, pos.0, Some(2.0));
                } else {
                    error!("Couldn't get position of entity that lost head");
                }
            },
            Outcome::Splash { vel, pos, mass, .. } => {
                let magnitude = (-vel.z).max(0.0);
                let energy = mass * magnitude;

                if energy > 0.0 {
                    let (sfx, volume) = if energy < 10.0 {
                        (SfxEvent::SplashSmall, energy / 20.0)
                    } else if energy < 100.0 {
                        (SfxEvent::SplashMedium, (energy - 10.0) / 90.0 + 0.5)
                    } else {
                        (SfxEvent::SplashBig, (energy / 100.0).sqrt() + 0.5)
                    };
                    let sfx_trigger_item = triggers.get_key_value(&sfx);
                    audio.emit_sfx(sfx_trigger_item, *pos, Some(volume.min(2.0)));
                }
            },
            Outcome::ExpChange { .. } | Outcome::ComboChange { .. } => {},
        }
    }

    fn load_sfx_items() -> AssetHandle<SfxTriggers> {
        SfxTriggers::load_or_insert_with("voxygen.audio.sfx", |error| {
            warn!(
                "Error reading sfx config file, sfx will not be available: {:#?}",
                error
            );

            SfxTriggers::default()
        })
    }
}

impl assets::Asset for SfxTriggers {
    type Loader = assets::RonLoader;

    const EXTENSION: &'static str = "ron";
}

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

    #[test]
    fn test_load_sfx_triggers() { let _ = SfxTriggers::load_expect("voxygen.audio.sfx"); }
}