mittens_engine/engine/ecs/component/
data.rs1use crate::engine::ecs::{ComponentId, World, component::Component};
2
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub enum DataValue {
5 Text(String),
6 Integer(i64),
7 Bool(bool),
8 Component(ComponentId),
9}
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct DataEntry {
13 pub key: String,
14 pub value: DataValue,
15}
16
17#[derive(Debug, Clone, Default, PartialEq, Eq)]
18pub struct DataComponent {
19 entries: Vec<DataEntry>,
20}
21
22impl DataComponent {
23 pub fn new() -> Self {
24 Self::default()
25 }
26
27 pub fn with_entry(mut self, key: impl Into<String>, value: DataValue) -> Self {
28 self.insert(key, value);
29 self
30 }
31
32 pub fn insert(&mut self, key: impl Into<String>, value: DataValue) {
33 let key = key.into();
34 if let Some(entry) = self.entries.iter_mut().find(|entry| entry.key == key) {
35 entry.value = value;
36 return;
37 }
38 self.entries.push(DataEntry { key, value });
39 }
40
41 pub fn get(&self, key: &str) -> Option<&DataValue> {
42 self.entries
43 .iter()
44 .find(|entry| entry.key == key)
45 .map(|entry| &entry.value)
46 }
47
48 pub fn get_component(&self, key: &str) -> Option<ComponentId> {
49 match self.get(key)? {
50 DataValue::Component(component_id) => Some(*component_id),
51 _ => None,
52 }
53 }
54
55 pub fn entries(&self) -> &[DataEntry] {
56 &self.entries
57 }
58
59 pub fn entry(&self, index: usize) -> Option<&DataEntry> {
60 self.entries.get(index)
61 }
62}
63
64impl Component for DataComponent {
65 fn set_id(&mut self, _id: ComponentId) {}
66
67 fn name(&self) -> &'static str {
68 "data"
69 }
70
71 fn as_any(&self) -> &dyn std::any::Any {
72 self
73 }
74
75 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
76 self
77 }
78
79 fn to_mms_ast(&self, _world: &World) -> crate::scripting::ast::ComponentExpression {
80 crate::engine::ecs::component::ce_helpers::ce("Data")
81 }
82}