use crate::bundle::{Bundle, Component};
use crate::entity::Entity;
use crate::world::World;
enum Op {
Despawn(Entity),
Run(Box<dyn FnOnce(&mut World) + Send>),
}
#[derive(Default)]
pub struct Commands {
ops: Vec<Op>,
}
impl Commands {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn spawn<B: Bundle>(&mut self, bundle: B) {
self.ops.push(Op::Run(Box::new(move |w| {
w.spawn(bundle);
})));
}
pub fn despawn(&mut self, e: Entity) {
self.ops.push(Op::Despawn(e));
}
pub fn insert<T: Component>(&mut self, e: Entity, value: T) {
self.ops.push(Op::Run(Box::new(move |w| {
w.insert(e, value);
})));
}
pub fn remove<T: Component>(&mut self, e: Entity) {
self.ops.push(Op::Run(Box::new(move |w| {
w.remove::<T>(e);
})));
}
pub fn add(&mut self, f: impl FnOnce(&mut World) + Send + 'static) {
self.ops.push(Op::Run(Box::new(f)));
}
#[must_use]
pub fn len(&self) -> usize {
self.ops.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.ops.is_empty()
}
pub(crate) fn apply(&mut self, world: &mut World) {
for op in self.ops.drain(..) {
match op {
Op::Despawn(e) => {
world.despawn(e);
}
Op::Run(f) => f(world),
}
}
}
}