use std::collections::HashMap;
use std::fmt;
use std::hash::Hasher;
use crcbl_reflect::Reflect;
use crate::access::Access;
use crate::component_hash::ComponentHash;
use crate::entity::Entity;
#[derive(Debug)]
pub struct DebugCtx;
pub type DebugDrawFn = Box<dyn FnMut(&DebugCtx) + Send>;
pub trait SystemTrait: Send {
fn name(&self) -> &str;
fn tick(&mut self, dt: f64);
fn access(&self) -> Access;
fn entity_count(&self) -> usize;
fn sweep(&mut self, dead: &[Entity]);
fn debug_draw(&mut self, ctx: &DebugCtx);
fn hash_state(&self, _hasher: &mut dyn Hasher) {}
fn contributes_to_hash(&self) -> bool {
false
}
fn replicate(&self, _out: &mut Vec<u8>) -> bool {
false
}
fn debug_fields(&self, _entity: Entity) -> Option<&dyn Reflect> {
None
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
}
impl fmt::Debug for dyn SystemTrait {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("dyn SystemTrait")
.field("name", &self.name())
.field("entity_count", &self.entity_count())
.finish()
}
}
pub struct System<T> {
name: String,
data: Vec<T>,
entity_to_index: HashMap<Entity, usize>,
index_to_entity: Vec<Entity>,
debug_draw_fn: Option<DebugDrawFn>,
reflect: Option<ReflectRow<T>>,
}
type ReflectRow<T> = fn(&T) -> &dyn Reflect;
fn reflect_row<T: Reflect>(row: &T) -> &dyn Reflect {
row
}
impl<T> System<T> {
#[must_use]
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
data: Vec::new(),
entity_to_index: HashMap::new(),
index_to_entity: Vec::new(),
debug_draw_fn: None,
reflect: None,
}
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
pub fn attach(&mut self, entity: Entity, data: T) {
if let Some(&index) = self.entity_to_index.get(&entity) {
self.data[index] = data;
} else {
let index = self.data.len();
self.data.push(data);
self.index_to_entity.push(entity);
self.entity_to_index.insert(entity, index);
}
}
pub fn detach(&mut self, entity: Entity) -> Option<T> {
let index = self.entity_to_index.remove(&entity)?;
let last = self.data.len() - 1;
if index != last {
self.data.swap(index, last);
self.index_to_entity.swap(index, last);
let moved_entity = self.index_to_entity[index];
self.entity_to_index.insert(moved_entity, index);
}
self.index_to_entity.pop();
Some(self.data.pop().unwrap())
}
#[must_use]
pub fn get(&self, entity: Entity) -> Option<&T> {
let &index = self.entity_to_index.get(&entity)?;
Some(&self.data[index])
}
#[must_use]
pub fn get_mut(&mut self, entity: Entity) -> Option<&mut T> {
let &index = self.entity_to_index.get(&entity)?;
Some(&mut self.data[index])
}
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.data.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
self.data.iter_mut()
}
pub fn iter_entities(&self) -> impl Iterator<Item = (Entity, &T)> {
self.index_to_entity.iter().copied().zip(self.data.iter())
}
pub fn set_debug_draw(&mut self, f: Option<DebugDrawFn>) {
self.debug_draw_fn = f;
}
}
impl<T: Reflect> System<T> {
#[must_use]
pub fn reflected(name: impl Into<String>) -> Self {
Self {
reflect: Some(reflect_row::<T>),
..Self::new(name)
}
}
}
impl<T: ComponentHash + Send + 'static> SystemTrait for System<T> {
fn name(&self) -> &str {
&self.name
}
fn tick(&mut self, _dt: f64) {
}
fn access(&self) -> Access {
Access::none()
}
fn entity_count(&self) -> usize {
self.data.len()
}
fn sweep(&mut self, dead: &[Entity]) {
for &entity in dead {
self.detach(entity);
}
}
fn debug_draw(&mut self, ctx: &DebugCtx) {
if let Some(ref mut f) = self.debug_draw_fn {
f(ctx);
}
}
fn hash_state(&self, hasher: &mut dyn Hasher) {
let mut order: Vec<usize> = (0..self.data.len()).collect();
order.sort_unstable_by_key(|&i| self.index_to_entity[i].to_bits());
for i in order {
hasher.write(&self.index_to_entity[i].to_bits().to_le_bytes());
self.data[i].hash_component(hasher);
}
}
fn contributes_to_hash(&self) -> bool {
true
}
fn debug_fields(&self, entity: Entity) -> Option<&dyn Reflect> {
let reflect = self.reflect?;
self.get(entity).map(reflect)
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
impl<T> fmt::Debug for System<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("System")
.field("name", &self.name)
.field("entity_count", &self.data.len())
.finish()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use super::*;
fn e(idx: u32) -> Entity {
crate::test_entity(idx, 1)
}
#[test]
fn a_component_attached_to_an_entity_is_what_get_answers_with() {
let mut sys = System::<i32>::new("test");
let ent = e(1);
sys.attach(ent, 42);
assert_eq!(sys.get(ent), Some(&42));
}
#[test]
fn attaching_twice_to_one_entity_replaces_the_value_without_adding_a_row() {
let mut sys = System::<i32>::new("test");
let ent = e(1);
sys.attach(ent, 10);
sys.attach(ent, 99);
assert_eq!(sys.entity_count(), 1);
assert_eq!(sys.get(ent), Some(&99));
}
#[test]
fn detach_removes_and_reorders() {
let mut sys = System::<i32>::new("test");
let a = e(1);
let b = e(2);
let c = e(3);
sys.attach(a, 1);
sys.attach(b, 2);
sys.attach(c, 3);
assert_eq!(sys.detach(b), Some(2));
assert_eq!(sys.entity_count(), 2);
assert_eq!(sys.get(b), None);
assert!(sys.get(a).is_some());
assert!(sys.get(c).is_some());
}
#[test]
fn detach_unknown_returns_none() {
let mut sys = System::<i32>::new("test");
let ent = e(42);
assert_eq!(sys.detach(ent), None);
}
#[test]
fn double_detach_is_safe() {
let mut sys = System::<i32>::new("test");
let ent = e(1);
sys.attach(ent, 7);
assert_eq!(sys.detach(ent), Some(7));
assert_eq!(sys.detach(ent), None);
assert_eq!(sys.entity_count(), 0);
}
#[test]
fn iter_yields_all_values() {
let mut sys = System::<i32>::new("test");
sys.attach(e(1), 10);
sys.attach(e(2), 20);
let mut sum = 0;
for v in sys.iter() {
sum += *v;
}
assert_eq!(sum, 30);
}
#[test]
fn iter_mut_allows_mutation() {
let mut sys = System::<i32>::new("test");
let a = e(1);
let b = e(2);
sys.attach(a, 1);
sys.attach(b, 2);
for v in sys.iter_mut() {
*v *= 10;
}
assert_eq!(sys.get(a), Some(&10));
assert_eq!(sys.get(b), Some(&20));
}
#[test]
fn iter_entities_yields_pairs() {
let mut sys = System::<&str>::new("test");
let a = e(10);
let b = e(20);
sys.attach(a, "alpha");
sys.attach(b, "beta");
let mut pairs: Vec<_> = sys.iter_entities().map(|(ent, d)| (ent, *d)).collect();
pairs.sort_by_key(|(ent, _)| ent.to_bits());
assert_eq!(pairs, vec![(a, "alpha"), (b, "beta")]);
}
#[test]
fn sweep_removes_dead_entities() {
let mut sys = System::<i32>::new("test");
let a = e(1);
let b = e(2);
let c = e(3);
sys.attach(a, 1);
sys.attach(b, 2);
sys.attach(c, 3);
sys.sweep(&[b, c]);
assert_eq!(sys.entity_count(), 1);
assert!(sys.get(a).is_some());
assert!(sys.get(b).is_none());
assert!(sys.get(c).is_none());
}
#[test]
fn sweep_empty_dead_list_is_noop() {
let mut sys = System::<i32>::new("test");
sys.attach(e(1), 42);
sys.sweep(&[]);
assert_eq!(sys.entity_count(), 1);
}
#[test]
fn sweep_unknown_entity_is_noop() {
let mut sys = System::<i32>::new("test");
sys.attach(e(1), 42);
let ghost = e(999);
sys.sweep(&[ghost]);
assert_eq!(sys.entity_count(), 1);
}
#[test]
fn debug_draw_callback_is_called() {
let mut sys = System::<i32>::new("test");
let called = Arc::new(AtomicBool::new(false));
let called2 = Arc::clone(&called);
sys.set_debug_draw(Some(Box::new(move |_ctx| {
called2.store(true, Ordering::SeqCst);
})));
sys.debug_draw(&DebugCtx);
assert!(called.load(Ordering::SeqCst));
}
#[test]
fn debug_draw_without_a_callback_calls_nothing() {
let mut sys = System::<i32>::new("test");
let called = Arc::new(AtomicBool::new(false));
let called2 = Arc::clone(&called);
sys.set_debug_draw(Some(Box::new(move |_ctx| {
called2.store(true, Ordering::SeqCst);
})));
sys.set_debug_draw(None);
sys.debug_draw(&DebugCtx);
assert!(
!called.load(Ordering::SeqCst),
"a callback that has been taken away must not still run"
);
}
#[test]
fn hash_state_ignores_attach_and_detach_history() {
use std::collections::hash_map::DefaultHasher;
fn hash(sys: &System<i32>) -> u64 {
let mut h = DefaultHasher::new();
sys.hash_state(&mut h);
h.finish()
}
let (a, b, c) = (e(1), e(2), e(3));
let mut direct = System::<i32>::new("s");
direct.attach(a, 10);
direct.attach(b, 20);
direct.attach(c, 30);
let mut churned = System::<i32>::new("s");
churned.attach(c, 30);
churned.attach(e(4), 40);
churned.attach(a, 10);
churned.detach(e(4));
churned.attach(b, 20);
assert_eq!(hash(&direct), hash(&churned));
let mut changed = System::<i32>::new("s");
changed.attach(a, 10);
changed.attach(b, 20);
changed.attach(c, 31);
assert_ne!(hash(&direct), hash(&changed));
}
#[test]
fn a_system_reports_the_name_it_was_built_with() {
let sys = System::<i32>::new("physics");
assert_eq!(sys.name(), "physics");
}
#[derive(crcbl_reflect::Reflect, Clone, Copy, Debug, PartialEq)]
struct Health {
current: i32,
#[reflect(name = "Max")]
max: i32,
}
impl ComponentHash for Health {
fn hash_component(&self, hasher: &mut dyn Hasher) {
self.current.hash_component(hasher);
self.max.hash_component(hasher);
}
}
#[test]
fn a_reflected_system_lends_the_entitys_own_row_and_nothing_for_others() {
use crcbl_reflect::{Value, get_path};
let (held, other, absent) = (e(1), e(2), e(3));
let mut sys = System::<Health>::reflected("health");
sys.attach(other, Health { current: 1, max: 2 });
sys.attach(held, Health { current: 7, max: 9 });
let row = sys
.debug_fields(held)
.expect("the system holds this entity");
assert_eq!(row.type_name(), "Health");
assert_eq!(row.fields()[1].label, "Max");
assert_eq!(
get_path(row, "current"),
Ok(Value::Int(7)),
"the row is this entity's, not the first one stored"
);
assert_eq!(get_path(row, "max"), Ok(Value::Int(9)));
assert!(
sys.debug_fields(absent).is_none(),
"an entity the system does not hold has no row to lend"
);
}
#[test]
fn a_system_that_lends_nothing_answers_none() {
struct Silent;
impl SystemTrait for Silent {
fn name(&self) -> &str {
"silent"
}
fn access(&self) -> Access {
Access::none()
}
fn tick(&mut self, _dt: f64) {}
fn entity_count(&self) -> usize {
1
}
fn sweep(&mut self, _dead: &[Entity]) {}
fn debug_draw(&mut self, _ctx: &DebugCtx) {}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
assert!(
Silent.debug_fields(e(1)).is_none(),
"the default lends nothing, whatever the system holds"
);
let mut plain = System::<Health>::new("plain");
plain.attach(e(1), Health { current: 1, max: 1 });
assert!(plain.debug_fields(e(1)).is_none());
}
#[test]
fn a_systems_debug_output_names_it_and_reports_its_entity_count() {
let mut sys = System::<i32>::new("render");
sys.attach(e(7), 1);
let s = format!("{sys:?}");
assert!(s.contains("render"));
assert!(s.contains("entity_count: 1"));
}
}