xuko_ecs/lib.rs
1//! Entity Component System
2//!
3//! # Examples
4//!
5//! ```
6//! use xuko_ecs::{World, Entity};
7//!
8//! let mut world = World::new();
9//!
10//! struct Monster;
11//! struct Position(i32, i32);
12//! struct Health(i32);
13//!
14//! {
15//! let entity = world.spawn();
16//! let components = world.get_entity_mut(entity).unwrap();
17//!
18//! // Anything can be used as a component, without any trait implementation.
19//! // As long as the type is `Send + Sync + 'static`
20//! components.add(Monster);
21//! components.add(Position(43, 59));
22//! components.add(Health(5));
23//! }
24//!
25//! {
26//! let entity = world.spawn();
27//! let components = world.get_entity_mut(entity).unwrap();
28//! components.add(Monster);
29//! components.add(Position(55, 30));
30//! components.add(Health(3));
31//! }
32//! ```
33
34use std::any::TypeId;
35
36/// Component id, used as index to [`EntityData`]
37#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
38pub struct ComponentId {
39 type_id: TypeId,
40 name: &'static str,
41}
42
43impl ComponentId {
44 /// Create [`ComponentId`] from type `C`
45 pub fn from_type<T: 'static>() -> Self {
46 let type_id = TypeId::of::<T>();
47 let name = std::any::type_name::<T>();
48 Self { type_id, name }
49 }
50
51 /// Create [`ComponentId`] from value `c`
52 pub fn from_value<T: 'static>(val: &T) -> Self {
53 let _ = val;
54 let type_id = TypeId::of::<T>();
55 let name = std::any::type_name::<T>();
56 Self { type_id, name }
57 }
58}
59
60/// Get the [`ComponentId`] for `type`
61///
62/// # Examples
63///
64/// ```
65/// use xuko_ecs::component_id;
66///
67/// component_id!(i32); // Get component info for a type
68///
69/// let x = 54;
70/// component_id!(expr: &x); // Get component info for a expression
71/// ```
72#[macro_export]
73macro_rules! component_id {
74 ($type:ty) => {
75 $crate::ComponentId::from_type::<$type>()
76 };
77
78 (expr: $expr:expr) => {
79 $crate::ComponentId::from_value($expr)
80 };
81}
82
83/// Items related to components
84pub mod component;
85/// Items related to events
86pub mod events;
87/// World Queries
88pub mod query;
89/// Global Resources
90pub mod resource;
91/// Scheduling System
92pub mod schedule;
93/// The [`World`]
94pub mod world;
95
96/// Contains re-exports for the most used parts of the library
97pub mod prelude {
98 pub use crate::{
99 component::{Entity, EntityData},
100 component_id,
101 query::{Query, QueryFilter},
102 resource::Resource,
103 schedule::{FnMutSystem, FnSystem, Schedule, Scheduler, System},
104 world::World,
105 };
106}
107
108pub use component::{Entity, EntityData};
109pub use query::{Query, QueryFilter};
110pub use resource::Resource;
111pub use world::World;