bevy_yoleck/
specs_registration.rs1use std::any::{Any, TypeId};
2use std::marker::PhantomData;
3
4use bevy::ecs::component::Mutable;
5use bevy::ecs::system::EntityCommands;
6use bevy::platform::collections::HashMap;
7use bevy::prelude::*;
8use serde::{Deserialize, Serialize};
9
10use crate::prelude::YoleckEditorState;
11use crate::{BoxedAny, YoleckEntityLifecycleStatus, YoleckInternalSchedule, YoleckManaged};
12
13pub trait YoleckComponent:
19 Default + Clone + PartialEq + Component<Mutability = Mutable> + Serialize + for<'a> Deserialize<'a>
20{
21 const KEY: &'static str;
22}
23
24pub struct YoleckEntityType {
31 pub name: String,
33 pub(crate) components: Vec<Box<dyn YoleckComponentHandler>>,
34 #[allow(clippy::type_complexity)]
35 pub(crate) on_init:
36 Vec<Box<dyn 'static + Sync + Send + Fn(YoleckEditorState, &mut EntityCommands)>>,
37 pub has_uuid: bool,
38}
39
40impl YoleckEntityType {
41 pub fn new(name: impl ToString) -> Self {
42 Self {
43 name: name.to_string(),
44 components: Default::default(),
45 on_init: Default::default(),
46 has_uuid: false,
47 }
48 }
49
50 pub fn with<T: YoleckComponent>(mut self) -> Self {
52 self.components
53 .push(Box::<YoleckComponentHandlerImpl<T>>::default());
54 self
55 }
56
57 pub fn apply_scene_on_init<T: Scene>(
61 mut self,
62 scene: impl 'static + Sync + Send + Fn() -> T,
63 ) -> Self {
64 self.on_init.push(Box::new(move |_, cmd| {
65 cmd.apply_scene(scene());
66 }));
67 self
68 }
69
70 pub fn insert_on_init<T: Bundle>(
74 mut self,
75 bundle_maker: impl 'static + Sync + Send + Fn() -> T,
76 ) -> Self {
77 self.on_init.push(Box::new(move |_, cmd| {
78 cmd.insert(bundle_maker());
79 }));
80 self
81 }
82
83 pub fn insert_on_init_during_editor<T: Bundle>(
86 mut self,
87 bundle_maker: impl 'static + Sync + Send + Fn() -> T,
88 ) -> Self {
89 self.on_init.push(Box::new(move |editor_state, cmd| {
90 if matches!(editor_state, YoleckEditorState::EditorActive) {
91 cmd.insert(bundle_maker());
92 }
93 }));
94 self
95 }
96
97 pub fn insert_on_init_during_game<T: Bundle>(
100 mut self,
101 bundle_maker: impl 'static + Sync + Send + Fn() -> T,
102 ) -> Self {
103 self.on_init.push(Box::new(move |editor_state, cmd| {
104 if matches!(editor_state, YoleckEditorState::GameActive) {
105 cmd.insert(bundle_maker());
106 }
107 }));
108 self
109 }
110
111 pub fn with_uuid(mut self) -> Self {
140 self.has_uuid = true;
141 self
142 }
143}
144
145pub(crate) trait YoleckComponentHandler: 'static + Sync + Send {
146 fn component_type(&self) -> TypeId;
147 fn key(&self) -> &'static str;
148 fn init_in_entity(
149 &self,
150 data: Option<serde_json::Value>,
151 cmd: &mut EntityCommands,
152 components_data: &mut HashMap<TypeId, BoxedAny>,
153 );
154 fn build_in_bevy_app(&self, app: &mut App);
155 fn serialize(&self, component: &dyn Any) -> serde_json::Value;
156}
157
158#[derive(Default)]
159struct YoleckComponentHandlerImpl<T: YoleckComponent> {
160 _phantom_data: PhantomData<T>,
161}
162
163impl<T: YoleckComponent> YoleckComponentHandler for YoleckComponentHandlerImpl<T> {
164 fn component_type(&self) -> TypeId {
165 TypeId::of::<T>()
166 }
167
168 fn key(&self) -> &'static str {
169 T::KEY
170 }
171
172 fn init_in_entity(
173 &self,
174 data: Option<serde_json::Value>,
175 cmd: &mut EntityCommands,
176 components_data: &mut HashMap<TypeId, BoxedAny>,
177 ) {
178 let component: T = if let Some(data) = data {
179 match serde_json::from_value(data) {
180 Ok(component) => component,
181 Err(err) => {
182 error!("Cannot load {:?}: {:?}", T::KEY, err);
183 return;
184 }
185 }
186 } else {
187 Default::default()
188 };
189 components_data.insert(self.component_type(), Box::new(component.clone()));
190 cmd.insert(component);
191 }
192
193 fn build_in_bevy_app(&self, app: &mut App) {
194 if let Some(schedule) =
195 app.get_schedule_mut(YoleckInternalSchedule::UpdateManagedDataFromComponents)
196 {
197 schedule.add_systems(Self::update_data_from_components);
198 }
199 }
200
201 fn serialize(&self, component: &dyn Any) -> serde_json::Value {
202 let concrete = component
203 .downcast_ref::<T>()
204 .expect("Serialize must be called with the correct type");
205 serde_json::to_value(concrete).expect("Component must always be serializable")
206 }
207}
208
209impl<T: YoleckComponent> YoleckComponentHandlerImpl<T> {
210 fn update_data_from_components(mut query: Query<(&mut YoleckManaged, &mut T)>) {
211 for (mut yoleck_managed, component) in query.iter_mut() {
212 let yoleck_managed = yoleck_managed.as_mut();
213 match yoleck_managed.components_data.entry(TypeId::of::<T>()) {
214 bevy::platform::collections::hash_map::Entry::Vacant(entry) => {
215 yoleck_managed.lifecycle_status = YoleckEntityLifecycleStatus::JustChanged;
216 entry.insert(Box::<T>::new(component.clone()));
217 }
218 bevy::platform::collections::hash_map::Entry::Occupied(mut entry) => {
219 let existing: &mut T = entry
220 .get_mut()
221 .downcast_mut()
222 .expect("Component data is of wrong type");
223 if existing != component.as_ref() {
224 yoleck_managed.lifecycle_status = YoleckEntityLifecycleStatus::JustChanged;
225 *existing = component.clone();
226 }
227 }
228 }
229 }
230 }
231}