Skip to main content

bevy_yoleck/
specs_registration.rs

1use 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
13/// A component that Yoleck will write to and read from `.yol` files.
14///
15/// Rather than being used for general ECS behavior definition, `YoleckComponent`s should be used
16/// for spawning the actual components using [populate
17/// systems](crate::prelude::YoleckSchedule::Populate).
18pub trait YoleckComponent:
19    Default + Clone + PartialEq + Component<Mutability = Mutable> + Serialize + for<'a> Deserialize<'a>
20{
21    const KEY: &'static str;
22}
23
24/// A type of entity that can be created and edited with the Yoleck level editor.
25///
26/// Yoleck will only read and write the components registered on the entity type with the
27/// [`with`](YoleckEntityType::with) method, even if the file has data of other components or if
28/// the Bevy entity has other [`YoleckComponent`]s inserted to it. These components will still take
29/// effect in edit and populate systems though, even if they are not registered on the entity.
30pub struct YoleckEntityType {
31    /// The `type_name` used to identify the entity type.
32    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    /// Register a [`YoleckComponent`] for entities of this type.
51    pub fn with<T: YoleckComponent>(mut self) -> Self {
52        self.components
53            .push(Box::<YoleckComponentHandlerImpl<T>>::default());
54        self
55    }
56
57    /// Automatically apply a Bevy scene when creating entities of this type.
58    ///
59    /// Do not use this to add the [`YoleckComponent`]s. Yoleck handles them differently.
60    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    /// Automatically spawn regular Bevy components when creating entities of this type.
71    ///
72    /// This is useful for marker components that don't carry data that needs to be saved to files.
73    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    /// Similar to [`insert_on_init`](Self::insert_on_init), but only applies for entities in the
84    /// editor. Will not be added during playtests or actual game.
85    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    /// Similar to [`insert_on_init`](Self::insert_on_init), but only applies for entities in
98    /// playtests or the actual game. Will not be added in the editor.
99    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    /// Give the entity a UUID, so that it can be persistently referred in `.yol` files.
112    ///
113    /// These entities will have a `uuid` field in their record header in the `.yol` file, and a
114    /// [`YoleckEntityUuid`](crate::prelude::YoleckEntityUuid) component that stores the same UUID
115    /// when loaded. The [`YoleckUuidRegistry`](crate::prelude::YoleckUuidRegistry) resource can be
116    /// used to resolve the entity from the UUID.
117    ///
118    /// # Required for Entity References
119    ///
120    /// **This method must be called for entity types that need to be referenced by other entities.**
121    /// Only entities with UUID can be:
122    /// - Referenced using [`YoleckEntityRef`](crate::prelude::YoleckEntityRef)
123    /// - Dragged and dropped onto entity reference fields in the editor
124    /// - Selected via the viewport click tool for entity references
125    ///
126    /// # Example
127    ///
128    /// ```no_run
129    /// # use bevy::prelude::*;
130    /// # use bevy_yoleck::prelude::*;
131    /// # let mut app = App::new();
132    /// // Planet can be referenced by other entities
133    /// app.add_yoleck_entity_type({
134    ///     YoleckEntityType::new("Planet")
135    ///         .with_uuid()  // Required for references!
136    /// #       ;YoleckEntityType::new("Planet")
137    /// });
138    /// ```
139    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}