Skip to main content

mittens_engine/engine/ecs/component/
audio_buffer_size.rs

1use super::Component;
2use crate::engine::ecs::ComponentId;
3
4#[derive(Debug, Clone, Copy)]
5pub struct AudioBufferSizeComponent {
6    /// Requested output buffer size in frames.
7    ///
8    /// If present alongside an `AudioOutputComponent`, the most recently
9    /// registered buffer size wins.
10    pub frames: u32,
11
12    component: Option<ComponentId>,
13}
14
15impl AudioBufferSizeComponent {
16    pub fn new(frames: u32) -> Self {
17        Self {
18            frames,
19            component: None,
20        }
21    }
22
23    pub fn id(&self) -> Option<ComponentId> {
24        self.component
25    }
26}
27
28impl Default for AudioBufferSizeComponent {
29    fn default() -> Self {
30        Self::new(0)
31    }
32}
33
34impl Component for AudioBufferSizeComponent {
35    fn set_id(&mut self, component: ComponentId) {
36        self.component = Some(component);
37    }
38
39    fn name(&self) -> &'static str {
40        "audio_buffer_size"
41    }
42
43    fn init(&mut self, emit: &mut dyn crate::engine::ecs::SignalEmitter, component: ComponentId) {
44        if self.frames > 0 {
45            emit.push_intent_now(
46                component,
47                crate::engine::ecs::IntentValue::RegisterAudioBufferSize {
48                    component_ids: vec![component],
49                },
50            );
51        }
52    }
53
54    fn as_any(&self) -> &dyn std::any::Any {
55        self
56    }
57
58    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
59        self
60    }
61
62    fn encode(&self) -> std::collections::HashMap<String, serde_json::Value> {
63        let mut map = std::collections::HashMap::new();
64        map.insert("frames".to_string(), serde_json::json!(self.frames));
65        map
66    }
67
68    fn decode(
69        &mut self,
70        data: &std::collections::HashMap<String, serde_json::Value>,
71    ) -> Result<(), String> {
72        if let Some(frames) = data.get("frames") {
73            self.frames = serde_json::from_value(frames.clone())
74                .map_err(|e| format!("Failed to decode frames: {}", e))?;
75        }
76        Ok(())
77    }
78}