Skip to main content

mireforge_advanced_game/
audio.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/mireforge/mireforge
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5use crate::logic::GameLogic;
6use crate::{ApplicationAudio, ApplicationLogic};
7use limnus_app::prelude::{App, Plugin};
8use limnus_audio_mixer::{AudioMixer, StereoSample};
9use limnus_default_stages::FixedUpdate;
10use limnus_local_resource::prelude::LocalResource;
11use limnus_resource::ResourceStorage;
12use limnus_system_params::{LoRe, LoReM, Re};
13use mireforge_game_assets::GameAssets;
14use mireforge_game_audio::GameAudio;
15use monotonic_time_rs::{InstantMonotonicClock, MonotonicClock};
16use std::fmt::{Debug, Formatter};
17use std::marker::PhantomData;
18use tracing::trace;
19
20impl<A: ApplicationAudio<L>, L: ApplicationLogic> Debug for GameAudioRender<A, L> {
21    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
22        write!(f, "GameAudioRender")
23    }
24}
25
26pub fn advanced_game_audio_tick<R: ApplicationAudio<L>, L: ApplicationLogic>(
27    mut audio_render: LoReM<GameAudioRender<R, L>>,
28    logic: LoRe<GameLogic<L>>,
29    mut audio_mixer: LoReM<AudioMixer>,
30    stereo_samples: Re<limnus_assets::Assets<StereoSample>>,
31) {
32    let mut game_audio = GameAudio::new(&mut audio_mixer, &stereo_samples);
33    audio_render.audio.audio(&mut game_audio, &logic.logic);
34}
35
36#[derive(LocalResource)]
37pub struct GameAudioRender<A: ApplicationAudio<L>, L: ApplicationLogic> {
38    audio: A,
39    _phantom: PhantomData<L>,
40}
41
42impl<A: ApplicationAudio<L>, L: ApplicationLogic> GameAudioRender<A, L> {
43    pub fn new(all_resources: &mut ResourceStorage) -> Self {
44        let clock = InstantMonotonicClock::new();
45        let mut assets = GameAssets::new(all_resources, clock.now());
46        Self {
47            audio: A::new(&mut assets),
48            _phantom: PhantomData,
49        }
50    }
51}
52
53#[derive(Default)]
54pub struct GameAudioRenderPlugin<A: ApplicationAudio<L>, L: ApplicationLogic> {
55    _phantom: PhantomData<(A, L)>,
56}
57
58impl<A: ApplicationAudio<L>, L: ApplicationLogic> GameAudioRenderPlugin<A, L> {
59    #[must_use]
60    pub const fn new() -> Self {
61        Self {
62            _phantom: PhantomData,
63        }
64    }
65}
66
67impl<A: ApplicationAudio<L>, L: ApplicationLogic> Plugin for GameAudioRenderPlugin<A, L> {
68    fn post_initialization(&self, app: &mut App) {
69        trace!("GameAudioRenderPlugin startup");
70        let all_resources = app.resources_mut();
71        let internal_audio = GameAudioRender::<A, L>::new(all_resources);
72        app.insert_local_resource(internal_audio);
73
74        app.add_system(FixedUpdate, advanced_game_audio_tick::<A, L>);
75    }
76}