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
//! Handles music playback and transitions
//!
//! Game music is controlled though a configuration file found in the source at
//! `/assets/voxygen/audio/soundtrack.ron`. Each track enabled in game has a
//! configuration corresponding to the
//! [`SoundtrackItem`](struct.SoundtrackItem.html) format, as well as the
//! corresponding `.ogg` file in the `/assets/voxygen/audio/soundtrack/`
//! directory.
//!
//! If there are errors while reading or deserialising the configuration file, a
//! warning is logged and music will be disabled.
//!
//! ## Adding new music
//!
//! To add a new item, append the details to the audio configuration file, and
//! add the audio file (in `.ogg` format) to the assets directory.
//!
//! The `length` should be provided in seconds. This allows us to know when to
//! transition to another track, without having to spend time determining track
//! length programmatically.
//!
//! An example of a new night time track:
//! ```text
//! (
//!     title: "Sleepy Song",
//!     path: "voxygen.audio.soundtrack.sleepy",
//!     length: 400.0,
//!     timing: Some(Night),
//!     biomes: [
//!         (Forest, 1),
//!         (Grassland, 2),
//!     ],
//!     site: None,
//!     activity: Explore,
//!     artist: "Elvis",
//! ),
//! ```
//!
//! Before sending an MR for your new track item:
//! - Be conscious of the file size for your new track. Assets contribute to
//!   download sizes
//! - Ensure that the track is mastered to a volume proportionate to other music
//!   tracks
//! - If you are not the author of the track, ensure that the song's licensing
//!   permits usage of the track for non-commercial use
use crate::audio::{AudioFrontend, MusicChannelTag};
use client::Client;
use common::{
    assets::{self, AssetExt, AssetHandle},
    calendar::{Calendar, CalendarEvent},
    terrain::{BiomeKind, SiteKindMeta},
    weather::WeatherKind,
};
use common_state::State;
use hashbrown::HashMap;
use kira::clock::ClockTime;
use rand::{prelude::SliceRandom, rngs::ThreadRng, thread_rng, Rng};
use serde::Deserialize;
use tracing::{debug, trace, warn};

/// Collection of all the tracks
#[derive(Debug, Deserialize)]
struct SoundtrackCollection<T> {
    /// List of tracks
    tracks: Vec<T>,
}

impl<T> Default for SoundtrackCollection<T> {
    fn default() -> Self { Self { tracks: Vec::new() } }
}

/// Configuration for a single music track in the soundtrack
#[derive(Clone, Debug, Deserialize)]
pub struct SoundtrackItem {
    /// Song title
    title: String,
    /// File path to asset
    path: String,
    /// Length of the track in seconds
    length: f32,
    loop_points: Option<(f32, f32)>,
    /// Whether this track should play during day or night
    timing: Option<DayPeriod>,
    /// Whether this track should play during a certain weather
    weather: Option<WeatherKind>,
    /// What biomes this track should play in with chance of play
    biomes: Vec<(BiomeKind, u8)>,
    /// Whether this track should play in a specific site
    sites: Vec<SiteKindMeta>,
    /// What the player is doing when the track is played (i.e. exploring,
    /// combat)
    music_state: MusicState,
    /// What activity to override the activity state with, if any (e.g. to make
    /// a long combat intro also act like the loop for the purposes of outro
    /// transitions)
    #[serde(default)]
    activity_override: Option<MusicActivity>,
    /// Song artist and website
    artist: (String, Option<String>),
}

#[derive(Clone, Debug, Deserialize)]
enum RawSoundtrackItem {
    Individual(SoundtrackItem),
    Segmented {
        title: String,
        timing: Option<DayPeriod>,
        weather: Option<WeatherKind>,
        biomes: Vec<(BiomeKind, u8)>,
        sites: Vec<SiteKindMeta>,
        segments: Vec<(String, f32, MusicState, Option<MusicActivity>)>,
        loop_points: (f32, f32),
        artist: (String, Option<String>),
    },
}

#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
enum CombatIntensity {
    Low,
    High,
}

#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
enum MusicActivity {
    Explore,
    Combat(CombatIntensity),
}

#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
enum MusicState {
    Activity(MusicActivity),
    Transition(MusicActivity, MusicActivity),
}

/// Allows control over when a track should play based on in-game time of day
#[derive(Clone, Debug, Deserialize, PartialEq)]
enum DayPeriod {
    /// 8:00 AM to 7:30 PM
    Day,
    /// 7:31 PM to 6:59 AM
    Night,
}

/// Provides methods to control music playback
pub struct MusicMgr {
    /// Collection of all the tracks
    soundtrack: SoundtrackCollection<SoundtrackItem>,
    /// Instant at which the current track began playing
    began_playing: Option<ClockTime>,
    /// Instant at which the current track should stop
    song_end: Option<ClockTime>,
    /// Time until the next track should be played after a track ends
    gap_length: f32,
    /// Time remaining for gap
    gap_time: f64,
    /// The title of the last track played. Used to prevent a track
    /// being played twice in a row
    last_track: String,
    last_combat_track: String,
    /// Time of the last interrupt (to avoid rapid switching)
    last_interrupt_attempt: Option<ClockTime>,
    /// The previous track's activity kind, for transitions
    last_activity: MusicState,
    // For debug menu
    current_track: String,
    current_artist: String,
    track_length: f32,
    loop_points: Option<(f32, f32)>,
}

#[derive(Deserialize)]
pub struct MusicTransitionManifest {
    /// Within what radius do enemies count towards combat music?
    combat_nearby_radius: f32,
    /// Each multiple of this factor that an enemy has health counts as an extra
    /// enemy
    combat_health_factor: f32,
    /// How many nearby enemies trigger High combat music
    combat_nearby_high_thresh: u32,
    /// How many nearby enemies trigger Low combat music
    combat_nearby_low_thresh: u32,
    /// Fade in and fade out timings for transitions between channels
    pub fade_timings: HashMap<(MusicChannelTag, MusicChannelTag), (f32, f32)>,
    /// How many seconds between interrupt checks
    pub interrupt_delay: f32,
}

impl Default for MusicTransitionManifest {
    fn default() -> MusicTransitionManifest {
        MusicTransitionManifest {
            combat_nearby_radius: 40.0,
            combat_health_factor: 100.0,
            combat_nearby_high_thresh: 3,
            combat_nearby_low_thresh: 1,
            fade_timings: HashMap::new(),
            interrupt_delay: 5.0,
        }
    }
}

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

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

fn time_f64(clock_time: ClockTime) -> f64 { clock_time.ticks as f64 + clock_time.fraction }

impl MusicMgr {
    pub fn new(calendar: &Calendar) -> Self {
        Self {
            soundtrack: Self::load_soundtrack_items(calendar),
            began_playing: None,
            song_end: None,
            gap_length: 0.0,
            gap_time: -1.0,
            last_track: String::from("None"),
            last_combat_track: String::from("None"),
            last_interrupt_attempt: None,
            last_activity: MusicState::Activity(MusicActivity::Explore),
            current_track: String::from("None"),
            current_artist: String::from("None"),
            track_length: 0.0,
            loop_points: None,
        }
    }

    /// Checks whether the previous track has completed. If so, sends a
    /// request to play the next (random) track
    pub fn maintain(&mut self, audio: &mut AudioFrontend, state: &State, client: &Client) {
        use common::comp::{group::ENEMY, Group, Health, Pos};
        use specs::{Join, WorldExt};

        if !audio.music_enabled() || audio.get_clock().is_none() || audio.get_clock_time().is_none()
        {
            return;
        }

        let mut activity_state = MusicActivity::Explore;

        let player = client.entity();
        let ecs = state.ecs();
        let entities = ecs.entities();
        let positions = ecs.read_component::<Pos>();
        let healths = ecs.read_component::<Health>();
        let groups = ecs.read_component::<Group>();
        let mtm = audio.mtm.read();
        let mut rng = thread_rng();

        if audio.combat_music_enabled {
            if let Some(player_pos) = positions.get(player) {
                // TODO: `group::ENEMY` will eventually be moved server-side with an
                // alignment/faction rework, so this will need an alternative way to measure
                // "in-combat-ness"
                let num_nearby_entities: u32 = (&entities, &positions, &healths, &groups)
                    .join()
                    .map(|(entity, pos, health, group)| {
                        if entity != player
                            && group == &ENEMY
                            && (player_pos.0 - pos.0).magnitude_squared()
                                < mtm.combat_nearby_radius.powf(2.0)
                        {
                            (health.maximum() / mtm.combat_health_factor).ceil() as u32
                        } else {
                            0
                        }
                    })
                    .sum();

                if num_nearby_entities >= mtm.combat_nearby_high_thresh {
                    activity_state = MusicActivity::Combat(CombatIntensity::High);
                } else if num_nearby_entities >= mtm.combat_nearby_low_thresh {
                    activity_state = MusicActivity::Combat(CombatIntensity::Low);
                }
            }
        }

        // Override combat music with explore music if the player is dead
        if let Some(health) = healths.get(player) {
            if health.is_dead {
                activity_state = MusicActivity::Explore;
            }
        }

        let mut music_state = match self.last_activity {
            MusicState::Activity(prev) => {
                if prev != activity_state {
                    MusicState::Transition(prev, activity_state)
                } else {
                    MusicState::Activity(activity_state)
                }
            },
            MusicState::Transition(_, next) => {
                warn!("Transitioning: {:?}", self.last_activity);
                MusicState::Activity(next)
            },
        };

        let now = audio.get_clock_time().unwrap();

        let began_playing = *self.began_playing.get_or_insert(now);
        let last_interrupt_attempt = *self.last_interrupt_attempt.get_or_insert(now);
        let song_end = *self.song_end.get_or_insert(now);
        let mut time_since_began_playing = time_f64(now) - time_f64(began_playing);

        // TODO: Instead of a constant tick, make this a timer that starts only when
        // combat might end, providing a proper "buffer".
        // interrupt_delay dictates the time between attempted interrupts
        let interrupt = matches!(music_state, MusicState::Transition(_, _))
            && time_f64(now) - time_f64(last_interrupt_attempt) > mtm.interrupt_delay as f64;

        // Hack to end combat music since there is currently nothing that detects
        // transitions away
        if matches!(
            music_state,
            MusicState::Transition(
                MusicActivity::Combat(CombatIntensity::High),
                MusicActivity::Explore
            )
        ) {
            music_state = MusicState::Activity(MusicActivity::Explore)
        }

        if audio.music_enabled()
            && !self.soundtrack.tracks.is_empty()
            && (time_since_began_playing
                > time_f64(song_end) - time_f64(began_playing) // Amount of time between when the song ends and when it began playing
                || interrupt)
        {
            time_since_began_playing = time_f64(now) - time_f64(began_playing);
            if time_since_began_playing > self.track_length as f64
                && self.last_activity
                    != MusicState::Activity(MusicActivity::Combat(CombatIntensity::High))
            {
                self.current_track = String::from("None");
                self.current_artist = String::from("None");
            }

            if interrupt {
                self.last_interrupt_attempt = Some(now);
                if let Ok(next_activity) =
                    self.play_random_track(audio, state, client, &music_state, &mut rng)
                {
                    trace!(
                        "pre-play_random_track: {:?} {:?}",
                        self.last_activity, music_state
                    );
                    self.last_activity = next_activity;
                }
            } else if music_state == MusicState::Activity(MusicActivity::Explore)
                || music_state
                    == MusicState::Transition(
                        MusicActivity::Explore,
                        MusicActivity::Combat(CombatIntensity::High),
                    )
            {
                // If current state is Explore, insert a gap now.
                if self.gap_time == 0.0 {
                    self.gap_length = self.generate_silence_between_tracks(
                        audio.music_spacing,
                        client,
                        &music_state,
                        &mut rng,
                    );
                    self.gap_time = self.gap_length as f64;
                    self.song_end = audio.get_clock_time();
                } else if self.gap_time < 0.0 {
                    // Gap time is up, play a track
                    // Hack to make combat situations not cancel explore music
                    if music_state
                        == MusicState::Transition(
                            MusicActivity::Explore,
                            MusicActivity::Combat(CombatIntensity::High),
                        )
                    {
                        music_state = MusicState::Activity(MusicActivity::Explore)
                    }
                    if let Ok(next_activity) =
                        self.play_random_track(audio, state, client, &music_state, &mut rng)
                    {
                        self.last_activity = next_activity;
                        self.gap_time = 0.0;
                        self.gap_length = 0.0;
                    }
                }
            } else if music_state
                == MusicState::Activity(MusicActivity::Combat(CombatIntensity::High))
            {
                // Keep playing! The track should loop automatically.
                self.began_playing = Some(now);
                self.song_end = Some(ClockTime::from_ticks_f64(
                    audio.get_clock().unwrap().id(),
                    time_f64(now) + self.loop_points.unwrap_or((0.0, 0.0)).1 as f64
                        - self.loop_points.unwrap_or((0.0, 0.0)).0 as f64,
                ));
            } else {
                trace!(
                    "pre-play_random_track: {:?} {:?}",
                    self.last_activity, music_state
                );
            }
        } else {
            if self.began_playing.is_none() {
                self.began_playing = Some(now)
            }
            if self.soundtrack.tracks.is_empty() {
                warn!("No tracks available to play")
            }
        }

        if time_since_began_playing > self.track_length as f64 {
            // Time remaining = Max time - (current time - time song ended)
            self.gap_time = (self.gap_length as f64) - (time_f64(now) - time_f64(song_end));
        }
    }

    fn play_random_track(
        &mut self,
        audio: &mut AudioFrontend,
        state: &State,
        client: &Client,
        music_state: &MusicState,
        rng: &mut ThreadRng,
    ) -> Result<MusicState, String> {
        let is_dark = state.get_day_period().is_dark();
        let current_period_of_day = Self::get_current_day_period(is_dark);
        let current_weather = client.weather_at_player();
        let current_biome = client.current_biome();
        let current_site = client.current_site();

        // Filter the soundtrack in stages, so that we don't overprune it if there are
        // too many constraints. Returning Err(()) signals that we couldn't find
        // an appropriate track for the current state, and hence the state
        // machine for the activity shouldn't be updated.
        // First, filter out tracks not matching the timing, site, biome, and current
        // activity
        let mut maybe_tracks = self
            .soundtrack
            .tracks
            .iter()
            .filter(|track| {
                (match &track.timing {
                    Some(period_of_day) => period_of_day == &current_period_of_day,
                    None => true,
                }) && match &track.weather {
                    Some(weather) => weather == &current_weather.get_kind(),
                    None => true,
                }
            })
            .filter(|track| track.sites.iter().any(|s| s == &current_site))
            .filter(|track| {
                track.biomes.is_empty() || track.biomes.iter().any(|b| b.0 == current_biome)
            })
            .filter(|track| &track.music_state == music_state)
            .collect::<Vec<&SoundtrackItem>>();
        if maybe_tracks.is_empty() {
            let error_string = format!(
                "No tracks for {:?}, {:?}, {:?}, {:?}, {:?}",
                &current_period_of_day,
                &current_weather,
                &current_site,
                &current_biome,
                &music_state
            );
            return Err(error_string);
        }
        // Second, prevent playing the last track (when not in combat, because then it
        // needs to loop)
        if matches!(
            music_state,
            &MusicState::Activity(MusicActivity::Combat(CombatIntensity::High))
                | &MusicState::Transition(
                    MusicActivity::Combat(CombatIntensity::High),
                    MusicActivity::Explore
                )
        ) {
            let filtered_tracks: Vec<_> = maybe_tracks
                .iter()
                .filter(|track| track.title.eq(&self.last_track))
                .copied()
                .collect();
            if !filtered_tracks.is_empty() {
                maybe_tracks = filtered_tracks;
            }
        } else {
            let filtered_tracks: Vec<_> = maybe_tracks
                .iter()
                .filter(|track| !track.title.eq(&self.last_track))
                .filter(|track| !track.title.eq(&self.last_combat_track))
                .copied()
                .collect();
            if !filtered_tracks.is_empty() {
                maybe_tracks = filtered_tracks;
            }
        }

        // Randomly selects a track from the remaining tracks weighted based
        // on the biome
        let new_maybe_track = maybe_tracks.choose_weighted(rng, |track| {
            // If no biome is listed, the song is still added to the
            // rotation to allow for site specific songs to play
            // in any biome
            track
                .biomes
                .iter()
                .find(|b| b.0 == current_biome)
                .map_or(1.0, |b| (1.0_f32 / (b.1 as f32)))
        });
        debug!(
            "selecting new track for {:?}: {:?}",
            music_state, new_maybe_track
        );

        if let Ok(track) = new_maybe_track {
            let now = audio.get_clock_time().unwrap();
            // println!("Now playing {:?}", track.title);
            self.last_track = String::from(&track.title);
            self.began_playing = Some(now);
            self.song_end = Some(ClockTime::from_ticks_f64(
                audio.get_clock().unwrap().id(),
                time_f64(now) + track.length as f64,
            ));
            self.track_length = track.length;
            self.gap_length = 0.0;
            if audio.music_enabled() {
                self.current_track = String::from(&track.title);
                self.current_artist = String::from(&track.artist.0);
            } else {
                self.current_track = String::from("None");
                self.current_artist = String::from("None");
            }

            let tag = if matches!(music_state, MusicState::Activity(MusicActivity::Explore)) {
                MusicChannelTag::Exploration
            } else {
                self.last_combat_track = String::from(&track.title);
                MusicChannelTag::Combat
            };
            audio.play_music(&track.path, tag, track.length);
            if tag == MusicChannelTag::Combat {
                audio.set_loop_points(
                    tag,
                    track.loop_points.unwrap_or((0.0, 0.0)).0,
                    track.loop_points.unwrap_or((0.0, 0.0)).1,
                );
                self.loop_points = track.loop_points
            } else {
                self.loop_points = None
            };

            if let Some(state) = track.activity_override {
                Ok(MusicState::Activity(state))
            } else {
                Ok(*music_state)
            }
        } else {
            Err(format!("{:?}", new_maybe_track))
        }
    }

    fn generate_silence_between_tracks(
        &self,
        spacing_multiplier: f32,
        client: &Client,
        music_state: &MusicState,
        rng: &mut ThreadRng,
    ) -> f32 {
        let mut silence_between_tracks_seconds: f32 = 0.0;
        if spacing_multiplier > f32::EPSILON {
            silence_between_tracks_seconds =
                if matches!(
                    music_state,
                    MusicState::Activity(MusicActivity::Explore)
                        | MusicState::Transition(
                            MusicActivity::Explore,
                            MusicActivity::Combat(CombatIntensity::High)
                        )
                ) && matches!(client.current_site(), SiteKindMeta::Settlement(_))
                {
                    rng.gen_range(120.0 * spacing_multiplier..180.0 * spacing_multiplier)
                } else if matches!(
                    music_state,
                    MusicState::Activity(MusicActivity::Explore)
                        | MusicState::Transition(
                            MusicActivity::Explore,
                            MusicActivity::Combat(CombatIntensity::High)
                        )
                ) && matches!(client.current_site(), SiteKindMeta::Dungeon(_))
                {
                    rng.gen_range(10.0 * spacing_multiplier..20.0 * spacing_multiplier)
                } else if matches!(
                    music_state,
                    MusicState::Activity(MusicActivity::Explore)
                        | MusicState::Transition(
                            MusicActivity::Explore,
                            MusicActivity::Combat(CombatIntensity::High)
                        )
                ) && matches!(client.current_site(), SiteKindMeta::Cave)
                {
                    rng.gen_range(20.0 * spacing_multiplier..40.0 * spacing_multiplier)
                } else if matches!(
                    music_state,
                    MusicState::Activity(MusicActivity::Explore)
                        | MusicState::Transition(
                            MusicActivity::Explore,
                            MusicActivity::Combat(CombatIntensity::High)
                        )
                ) {
                    rng.gen_range(120.0 * spacing_multiplier..240.0 * spacing_multiplier)
                } else if matches!(
                    music_state,
                    MusicState::Activity(MusicActivity::Combat(_)) | MusicState::Transition(_, _)
                ) {
                    0.0
                } else {
                    rng.gen_range(30.0 * spacing_multiplier..60.0 * spacing_multiplier)
                };
        }
        silence_between_tracks_seconds
    }

    fn get_current_day_period(is_dark: bool) -> DayPeriod {
        if is_dark {
            DayPeriod::Night
        } else {
            DayPeriod::Day
        }
    }

    pub fn current_track(&self) -> String { self.current_track.clone() }

    pub fn current_artist(&self) -> String { self.current_artist.clone() }

    pub fn reset_track(&mut self) {
        self.current_artist = String::from("None");
        self.current_track = String::from("None");
    }

    /// Loads default soundtrack if no events are active. Otherwise, attempts to
    /// compile and load all active event soundtracks, falling back to default
    /// if they are empty.
    fn load_soundtrack_items(calendar: &Calendar) -> SoundtrackCollection<SoundtrackItem> {
        let mut soundtrack = SoundtrackCollection::default();
        // Loads default soundtrack if no events are active
        if calendar.events().len() == 0 {
            for track in SoundtrackCollection::load_expect("voxygen.audio.soundtrack")
                .read()
                .tracks
                .clone()
            {
                soundtrack.tracks.push(track)
            }
        } else {
            // Compiles event-specific soundtracks if any are active
            for event in calendar.events() {
                match event {
                    CalendarEvent::Halloween => {
                        for track in SoundtrackCollection::load_expect(
                            "voxygen.audio.calendar.halloween.soundtrack",
                        )
                        .read()
                        .tracks
                        .clone()
                        {
                            soundtrack.tracks.push(track)
                        }
                    },
                    CalendarEvent::Christmas => {
                        for track in SoundtrackCollection::load_expect(
                            "voxygen.audio.calendar.christmas.soundtrack",
                        )
                        .read()
                        .tracks
                        .clone()
                        {
                            soundtrack.tracks.push(track)
                        }
                    },
                    _ => {
                        for track in SoundtrackCollection::load_expect("voxygen.audio.soundtrack")
                            .read()
                            .tracks
                            .clone()
                        {
                            soundtrack.tracks.push(track)
                        }
                    },
                }
            }
        }
        // Fallback if events are active but give an empty tracklist
        if soundtrack.tracks.is_empty() {
            for track in SoundtrackCollection::load_expect("voxygen.audio.soundtrack")
                .read()
                .tracks
                .clone()
            {
                soundtrack.tracks.push(track)
            }
            soundtrack
        } else {
            soundtrack
        }
    }
}
impl assets::Asset for SoundtrackCollection<RawSoundtrackItem> {
    type Loader = assets::RonLoader;

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

impl assets::Compound for SoundtrackCollection<SoundtrackItem> {
    fn load(_: assets::AnyCache, id: &assets::SharedString) -> Result<Self, assets::BoxedError> {
        let manifest: AssetHandle<SoundtrackCollection<RawSoundtrackItem>> = AssetExt::load(id)?;
        let mut soundtrack = SoundtrackCollection::default();
        for item in manifest.read().tracks.iter().cloned() {
            match item {
                RawSoundtrackItem::Individual(track) => soundtrack.tracks.push(track),
                RawSoundtrackItem::Segmented {
                    title,
                    timing,
                    weather,
                    biomes,
                    sites,
                    segments,
                    loop_points,
                    artist,
                } => {
                    for (path, length, music_state, activity_override) in segments.into_iter() {
                        soundtrack.tracks.push(SoundtrackItem {
                            title: title.clone(),
                            path,
                            length,
                            loop_points: Some(loop_points),
                            timing: timing.clone(),
                            weather,
                            biomes: biomes.clone(),
                            sites: sites.clone(),
                            music_state,
                            activity_override,
                            artist: artist.clone(),
                        });
                    }
                },
            }
        }
        Ok(soundtrack)
    }
}

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

    #[test]
    fn test_load_soundtracks() {
        let _: AssetHandle<SoundtrackCollection<SoundtrackItem>> =
            SoundtrackCollection::load_expect("voxygen.audio.soundtrack");
        for event in CalendarEvent::iter() {
            match event {
                CalendarEvent::Halloween => {
                    let _: AssetHandle<SoundtrackCollection<SoundtrackItem>> =
                        SoundtrackCollection::load_expect(
                            "voxygen.audio.calendar.halloween.soundtrack",
                        );
                },
                CalendarEvent::Christmas => {
                    let _: AssetHandle<SoundtrackCollection<SoundtrackItem>> =
                        SoundtrackCollection::load_expect(
                            "voxygen.audio.calendar.christmas.soundtrack",
                        );
                },
                _ => {},
            }
        }
    }
}