1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
use crate::{
    ecs::{ Scene, Entity, ComponentStorage, Component, EntityHandle, EntityBuilder, ComponentDestroyer }
};

use pill_core::{ EngineError, get_type_name, PillSlotMapKey };

use std::{ any::{ type_name, Any, TypeId }, collections::HashMap,  cell::RefCell };
use anyhow::{ Result, Context, Error };
use boolinator::Boolinator;

pill_core::define_new_pill_slotmap_key! { 
    pub struct SceneHandle;
}

pub struct SceneManager {
    pub(crate) scenes: pill_core::PillSlotMap<SceneHandle, Scene>, 
    pub(crate) mapping: pill_core::PillTwinMap<String, SceneHandle>, // Mapping from scene name to scene handle and vice versa
    pub(crate) max_entity_count: usize,
    active_scene_handle: Option<SceneHandle>,
}

impl SceneManager {
    pub fn new(max_entity_count: usize) -> Self {
	    Self { 
            scenes: pill_core::PillSlotMap::<SceneHandle, Scene>::with_key(),
            mapping: pill_core::PillTwinMap::<String, SceneHandle>::new(),
            max_entity_count,
            active_scene_handle: None,
        }
    }

    // --- Entity ---

    pub fn create_entity(&mut self, scene_handle: SceneHandle) -> Result<EntityHandle> {
        // Get maximum count of entities
        let max_entity_count = self.max_entity_count;

        // Get scene
        let target_scene = self.get_scene_mut(scene_handle)?;

        // Check if there is space for entity
        if target_scene.entities.len() >= max_entity_count {
            return Err(Error::new(EngineError::EntityLimitReached))
        }

        // Create new entity with empty bitmask
        let new_entity = Entity::new(scene_handle.clone());

        // Insert new entity into storage, with key as returned type
        let new_entity_handle = target_scene.entities.insert(new_entity);

        // Return handle to new entity
        Ok(new_entity_handle)
    }

    pub fn remove_entity(&mut self, scene_handle: SceneHandle, entity_handle: EntityHandle) -> Result<Vec::<Box<dyn ComponentDestroyer>>> {
        // Initialize collection for component destroyers to return to engine
        let mut component_destroyers = Vec::<Box<dyn ComponentDestroyer>>::new();
        
        // Get scene
        let target_scene = self.get_scene_mut(scene_handle)?;

        // Get entity bitmask
        let entity_bitmask = target_scene.entities.get_mut(entity_handle).unwrap().bitmask;

        // Get typeids of all components this entity has
        let components_typeids = target_scene.get_components_typeids_from_bitmask(entity_bitmask);

        // Get component destroyers to return to engine so it can call them
        for typeid in components_typeids {
            let component_destroyer = target_scene.get_component_destoyer(&typeid).unwrap();
            component_destroyers.push(component_destroyer);
        }
       
        // Remove entity from storage
        target_scene.entities.remove(entity_handle);

        Ok(component_destroyers)
    }

    // --- Component ---

    pub fn register_component<T>(&mut self, scene: SceneHandle) -> Result<()> 
        where T: Component<Storage = ComponentStorage::<T>>
    {
        // Prepare the capacity for component storage
        let component_storage_capacity = self.max_entity_count.clone();

        // Get scene
        let target_scene = self.get_scene_mut(scene)?;

        // Check if component is already registered
        if target_scene.is_component_registered::<T>() {
            return Err(Error::new(EngineError::ComponentAlreadyRegistered(get_type_name::<T>(), target_scene.name.clone())));
        }

        // Create new component storage
        let component_storage = ComponentStorage::<T>::new(component_storage_capacity);

        // Add component storage to scene
        target_scene.components.insert::<T>(component_storage);

        // Add bitmask for new component
        target_scene.add_component_bitmask::<T>();

        // Add component destroyer
        target_scene.add_component_destroyer::<T>();

        Ok(())
    }
    
    pub fn add_component_to_entity<T>(&mut self, scene_handle: SceneHandle, entity_handle: EntityHandle, component: T) -> Result<()> 
        where T: Component<Storage = ComponentStorage::<T>>
    {     
        // Get scene
        let target_scene = self.get_scene_mut(scene_handle)?;

        // Get component storage from scene
        let component_storage = target_scene.get_component_storage_mut::<T>()?;

        // Add component to storage
        let component_slot = component_storage.data.get_mut(entity_handle.data().index as usize).expect("Critical: Vector not initialized"); // TODO: Should not be called if entity limit is reached but it is
        let _ = component_slot.insert(component);
        
        // Get the component bitmask
        let component_bitmask = target_scene.get_component_bitmask::<T>()?;
        
        // Update entity bitmask
        target_scene.entities.get_mut(entity_handle).unwrap().bitmask |= component_bitmask;

        Ok(())
    }

    pub fn remove_component_from_entity<T>(&mut self, scene_handle: SceneHandle, entity_handle: EntityHandle) -> Result<T> 
        where T: Component<Storage = ComponentStorage::<T>>
    {
        // Get scene
        let target_scene = self.get_scene_mut(scene_handle)?;

        // Get component bitmask
        let component_bitmask = target_scene.get_component_bitmask::<T>()?;

        // Update entity bitmask
        target_scene.entities.get_mut(entity_handle).unwrap().bitmask -= component_bitmask;

        // Get component storage from scene
        let component_storage = target_scene.get_component_storage_mut::<T>()?;

        // Delete the component from storage
        let component_slot = component_storage.data.get_mut(entity_handle.data().index as usize).expect("Critical: Vector not initialized");
        let component: T = component_slot.take().unwrap();

        Ok(component)
    }

    // pub fn get_entity_component<T>(&self, entity_handle: EntityHandle, scene_handle: SceneHandle) -> Result<&T>
    //     where T: Component<Storage = ComponentStorage::<T>>
    // {
    //     // Get scene
    //     let target_scene = self.get_scene(scene_handle)?;

    //     // Get storage
    //     let storage = target_scene.components.get::<T>().unwrap();

    //     // Check if entity has requested component
    //     let entity = target_scene.entities.get(entity_handle).unwrap();

    //     // Get the bitmask mapped onto the given component to update entity's bitmask
    //     let component_bitmask = target_scene.get_component_bitmask::<T>()?;

    //     match entity.bitmask & component_bitmask != 0 {
    //         true => Ok(storage.data.get(entity_handle.0.index as usize).unwrap().unwrap()),
    //         false => Err(Error::msg("Not found")),
    //     }
    // }  

    // --- Scene ---

    pub fn create_scene(&mut self, name: &str) -> Result<SceneHandle> {
        // Check if scene with that name already exists
        if self.mapping.contains_key(&name.to_string()) {
            return Err(Error::new(EngineError::SceneAlreadyExists(name.to_string())))
        }

        // Create new scene
        let new_scene = Scene::new(name.to_string());

        // Insert new scene
        let scene_handle = self.scenes.insert(new_scene);
       
        // Insert new mapping
        self.mapping.insert(&name.to_string(), &scene_handle);

        Ok(scene_handle)
    }

    pub fn get_scene_handle(&self, name: &str) -> Result<SceneHandle> {
        let scene_handle = self.mapping.get_value(&name.to_string()).ok_or(EngineError::InvalidSceneName(name.to_string()))?.clone();

        Ok(scene_handle)
    }

    pub fn get_scene(&self, scene_handle: SceneHandle) -> Result<&Scene> {
        let scene = self.scenes.get(scene_handle).ok_or(Error::new(EngineError::InvalidSceneHandle))?;

        Ok(scene)
    }

    pub fn get_scene_mut(&mut self, scene_handle: SceneHandle) -> Result<&mut Scene> {
        let scene = self.scenes.get_mut(scene_handle).ok_or(Error::new(EngineError::InvalidSceneHandle))?;

        Ok(scene)
    }

    pub fn remove_scene(&mut self, scene_handle: SceneHandle) -> Result<Scene> {
        let scene = self.scenes.get_mut(scene_handle).ok_or(Error::new(EngineError::InvalidSceneHandle))?;

        // Remove scene
        let scene = self.scenes.remove(scene_handle).ok_or(Error::new(EngineError::InvalidSceneHandle))?;

        // Return deleted scene
        Ok(scene)
    }

    // --- Active scene ---
    
    pub fn set_active_scene(&mut self, scene_handle: SceneHandle) -> Result<()> {
        // Check if scene for that handle exists
        self.scenes.get_mut(scene_handle).ok_or(Error::new(EngineError::InvalidSceneHandle))?;

        // Set new active scene
        self.active_scene_handle = Some(scene_handle);

        Ok(())
    }

    pub fn get_active_scene_handle(&self) -> Result<SceneHandle> {
        match self.active_scene_handle {
            Some(v) =>  Ok(v.clone()),
            None => Err(Error::new(EngineError::NoActiveScene)),
        }
    }

    pub fn get_active_scene(&self) -> Result<&Scene> {
        // Check if active scene is set
        let active_scene_handle = self.active_scene_handle.ok_or(Error::new(EngineError::NoActiveScene))?;
        let active_scene = self.get_scene(active_scene_handle)?;

        Ok(active_scene)
    }

    pub fn get_active_scene_mut(&mut self) -> Result<&mut Scene> {
        // Check if active scene is set
        let active_scene_handle = self.active_scene_handle.ok_or(Error::new(EngineError::NoActiveScene))?;
        let active_scene = self.get_scene_mut(active_scene_handle)?;

        Ok(active_scene)
    }

    pub fn get_entity_component<T>(&mut self, entity_handle: EntityHandle, scene_handle: SceneHandle) -> Result<&mut T>
        where T: Component<Storage = ComponentStorage::<T>>
    {
        // Get scene
        let target_scene = self.get_scene_mut(scene_handle)?;

        // Get the bitmask mapped onto the given component to update entity's bitmask
        let component_bitmask = target_scene.get_component_bitmask::<T>()?;

        // Get storage
        let storage = target_scene.components.get_mut::<T>().unwrap();

        // Check if entity has requested component
        let entity = target_scene.entities.get(entity_handle).unwrap();

        match entity.bitmask & component_bitmask != 0 {
            true => Ok(storage.data.get_mut((entity_handle.0.index) as usize).unwrap().as_mut().unwrap()),
            false => Err(Error::msg("Component not found in Entity")),
        }
    }  

    // - Iterators

    #[inline]
    fn unsafe_mut_cast<T>(reference: &T) -> &mut T {
        unsafe {
            let const_ptr = reference as *const T;
            let mut_ptr = const_ptr as *mut T;
            &mut *mut_ptr
        }
    }

    pub fn get_one_component_iterator<A>(&self, scene_handle: SceneHandle) -> Result<impl Iterator<Item = (EntityHandle, &A)>> 
        where 
        A: Component<Storage = ComponentStorage::<A>>
    {
        // Get scene and iterator
        let target_scene = self.get_scene(scene_handle)?;
        target_scene.get_one_component_iterator::<A>()
    }

    pub fn get_one_component_iterator_mut<A>(&mut self, scene_handle: SceneHandle) -> Result<impl Iterator<Item = (EntityHandle, &mut A)>> 
        where 
        A: Component<Storage = ComponentStorage::<A>>
    {
        // Get scene and iterator
        let target_scene = self.get_scene_mut(scene_handle)?;
        target_scene.get_one_component_iterator_mut::<A>()
    }

    pub fn get_two_component_iterator<A, B>(&self, scene_handle: SceneHandle) -> Result<impl Iterator<Item = (EntityHandle, &A, &B)>> 
        where 
        A: Component<Storage = ComponentStorage::<A>>,
        B: Component<Storage = ComponentStorage::<B>>
    {
        // Get scene and iterator
        let target_scene = self.get_scene(scene_handle)?;
        target_scene.get_two_component_iterator::<A, B>()
    }

    pub fn get_two_component_iterator_mut<A, B>(&mut self, scene_handle: SceneHandle) -> Result<impl Iterator<Item = (EntityHandle, &mut A, &mut B)>> 
        where 
        A: Component<Storage = ComponentStorage::<A>>,
        B: Component<Storage = ComponentStorage::<B>>
    {
        // Get scene and iterator
        let target_scene = self.get_scene_mut(scene_handle)?;
        target_scene.get_two_component_iterator_mut::<A, B>()
    }

    pub fn get_three_component_iterator<A, B, C>(&self, scene_handle: SceneHandle) -> Result<impl Iterator<Item = (EntityHandle, &A, &B, &C)>> 
        where 
        A: Component<Storage = ComponentStorage::<A>>,
        B: Component<Storage = ComponentStorage::<B>>,
        C: Component<Storage = ComponentStorage::<C>>
    {
        // Get scene and iterator
        let target_scene = self.get_scene(scene_handle)?;
        target_scene.get_three_component_iterator::<A, B, C>()
    }

    pub fn get_three_component_iterator_mut<A, B, C>(&mut self, scene_handle: SceneHandle) -> Result<impl Iterator<Item = (EntityHandle, &mut A, &mut B, &mut C)>> 
        where 
        A: Component<Storage = ComponentStorage::<A>>,
        B: Component<Storage = ComponentStorage::<B>>,
        C: Component<Storage = ComponentStorage::<C>>
    {
        // Get scene and iterator
        let target_scene = self.get_scene_mut(scene_handle)?;
        target_scene.get_three_component_iterator_mut::<A, B, C>()
    }
}