JoJoJet / bevy-trait-query

adds trait queries to the bevy game engine
Apache License 2.0
65 stars 11 forks source link

Semi-automatic registration #52

Open ItzShiney opened 5 months ago

ItzShiney commented 5 months ago

It is possible to make struct registration semi-automatic, using inventory crate. The solution simplifies registration a lot and does not require a centralized registration function with all the structs listed.

A feature (which may not be enabled by default) can be introduced to toggle this, since it requires an additional dependency which may not be wanted.

It can be achieved using these three things:

  1. A helper struct:
    pub struct Register(pub fn(&mut World));
  2. An attribute #[register] for impl Trait for Struct, which generates:
    inventory::submit!(bevy_trait_query::Register(|world| {
    use bevy_trait_query::RegisterExt;
    world.register_component_as::<dyn Trait, Struct>();
    }));
  3. A global registration function, which should be called manually (that's why the solution is semi-automatic):
    fn register_traits(world: &mut World) {
    inventory::collect!(Register);
    for callback in inventory::iter::<Register> {
        callback(world);
    }
    }