Skip to main content

mittens_engine/engine/ecs/component/
audio_mix.rs

1use crate::engine::ecs::ComponentId;
2use crate::engine::ecs::component::Component;
3
4#[derive(Debug, Clone)]
5pub struct AudioMixComponent {
6    pub weights: Vec<f32>,
7}
8
9impl AudioMixComponent {
10    pub fn new(weights: Vec<f32>) -> Self {
11        Self { weights }
12    }
13
14    pub fn weight_for_branch(&self, branch_index: usize) -> f32 {
15        self.weights.get(branch_index).copied().unwrap_or(1.0)
16    }
17}
18
19impl Default for AudioMixComponent {
20    fn default() -> Self {
21        Self { weights: vec![] }
22    }
23}
24
25impl Component for AudioMixComponent {
26    fn name(&self) -> &'static str {
27        "audio_mix"
28    }
29
30    fn as_any(&self) -> &dyn std::any::Any {
31        self
32    }
33
34    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
35        self
36    }
37
38    fn init(&mut self, emit: &mut dyn crate::engine::ecs::SignalEmitter, component: ComponentId) {
39        emit.push_intent_now(
40            component,
41            crate::engine::ecs::IntentValue::AudioGraphDirtyImmediate {
42                component_ids: vec![component],
43            },
44        );
45    }
46
47    fn encode(&self) -> std::collections::HashMap<String, serde_json::Value> {
48        let mut map = std::collections::HashMap::new();
49        map.insert("weights".to_string(), serde_json::json!(self.weights));
50        map
51    }
52
53    fn decode(
54        &mut self,
55        data: &std::collections::HashMap<String, serde_json::Value>,
56    ) -> Result<(), String> {
57        if let Some(v) = data.get("weights") {
58            self.weights = serde_json::from_value(v.clone())
59                .map_err(|e| format!("Failed to decode weights: {e}"))?;
60        }
61        Ok(())
62    }
63}