use core::any::{Any, TypeId};
#[cfg(feature = "no_std")]
use alloc::collections::{BTreeMap, FxHashMap};
use crate::entity::*;
pub use self::component_store::*;
mod component_store;
pub struct EntityBuilder<'a, E>
where
E: EntityStore,
{
pub entity: Entity,
pub component_store: &'a mut ComponentStore,
pub entity_store: &'a mut E,
}
impl<'a, E> EntityBuilder<'a, E>
where
E: EntityStore,
{
pub fn components(self, components: (BuildComponents, BuildSharedComponents)) -> Self {
self.component_store.append(self.entity, components);
self
}
pub fn build(self) -> Entity {
self.entity_store.register_entity(self.entity);
self.entity
}
}
pub trait Component: Any {}
impl<E: Any> Component for E {}
pub struct ComponentBox {
component: Box<dyn Any>,
type_id: TypeId,
}
pub struct SharedComponentBox {
source: Entity,
type_id: TypeId,
}
impl SharedComponentBox {
pub fn new(type_id: TypeId, source: impl Into<Entity>) -> Self {
SharedComponentBox {
source: source.into(),
type_id,
}
}
pub fn consume(self) -> (TypeId, Entity) {
(self.type_id, self.source)
}
}
impl ComponentBox {
pub fn new<C: Component>(component: C) -> Self {
ComponentBox {
component: Box::new(component),
type_id: TypeId::of::<C>(),
}
}
pub fn consume(self) -> (TypeId, Box<dyn Any>) {
(self.type_id, self.component)
}
}
#[derive(Default)]
pub struct EntityComponentManager<E>
where
E: EntityStore,
{
component_store: ComponentStore,
entity_store: E,
entity_counter: u32,
}
impl<E> EntityComponentManager<E>
where
E: EntityStore,
{
pub fn new(entity_store: E) -> Self {
EntityComponentManager {
entity_counter: 0,
component_store: ComponentStore::default(),
entity_store,
}
}
pub fn stores(&self) -> (&E, &ComponentStore) {
(&self.entity_store, &self.component_store)
}
pub fn stores_mut(&mut self) -> (&mut E, &mut ComponentStore) {
(&mut self.entity_store, &mut self.component_store)
}
pub fn component_store(&self) -> &ComponentStore {
&self.component_store
}
pub fn component_store_mut(&mut self) -> &mut ComponentStore {
&mut self.component_store
}
pub fn entity_store(&mut self) -> &mut E {
&mut self.entity_store
}
pub fn entity_store_mut(&mut self) -> &mut E {
&mut self.entity_store
}
pub fn create_entity(&mut self) -> EntityBuilder<'_, E> {
let entity: Entity = self.entity_counter.into();
self.entity_counter += 1;
EntityBuilder {
entity,
component_store: &mut self.component_store,
entity_store: &mut self.entity_store,
}
}
pub fn register_entity(&mut self, entity: impl Into<Entity>) {
let entity = entity.into();
self.entity_store.register_entity(entity);
}
pub fn remove_entity(&mut self, entity: impl Into<Entity>) {
let entity = entity.into();
self.component_store.remove_entity(entity);
self.entity_store.remove_entity(entity);
}
}