component_group
component_group copied to clipboard
Extension trait to add methods to World
It is kind of awkward sometimes to call group.create(&mut world). Some people might prefer the inverse of that API: world.create_group(group). This is possible via an extension trait:
trait WorldGroupExt {
fn first_group<G: ComponentGroup>(&self) -> Option<G>;
fn fetch_group<G: ComponentGroup>(&self, entity: Entity) -> G;
fn create_group<G: ComponentGroup>(&mut self, group: G) -> Entity;
fn update_group<G: ComponentGroup>(&mut self, entity: Entity, group: G) -> Result<(), <G as ComponentGroup>::UpdateError>;
fn remove_group<G: ComponentGroup>(&mut self, entity: Entity) -> G;
}
impl WorldGroupExt for World {
fn first_group<G: ComponentGroup>(&self) -> Option<G> {
G::first_from_world(self)
}
fn fetch_group<G: ComponentGroup>(&self, entity: Entity) -> G {
G::from_world(self, entity)
}
fn create_group<G: ComponentGroup>(&mut self, group: G) -> Entity {
group.create(self)
}
fn update_group<G: ComponentGroup>(&mut self, entity: Entity, group: G) -> Result<(), <G as ComponentGroup>::UpdateError> {
group.update(self, entity)
}
fn remove_group<G: ComponentGroup>(&mut self, entity: Entity) -> G {
G::remove(self, entity)
}
}
This extension trait needs to be imported every time it is used. (Not a huge deal at all.)
ComponentGroup trait |
WorldGroupExt trait |
|---|---|
MyGroup::first_from_world(&world) |
let group: MyGroup = world.first_group() |
MyGroup::from_world(&world, entity) |
let group: MyGroup = world.fetch_group(entity) |
group.create(&mut world) |
world.create_group(group) |
group.update(&mut world, entity) |
world.update_group(entity, group) |
MyGroup::remove(&mut world, entity) |
let group: MyGroup = world.remove_group(entity) |