Crate bevy_extern_events

Source
Expand description

§Why

Because at some point you might want to interact with code outside of Bevy (External SDKs, Native Platform Code, non-Bevy crates). With the help of this crate you can queue events from anywhere and they will be available via the typical EventReader mechanism inside your Bevy Systems.

Note that this comes at the cost of us having a global static RwLock-based Queue that we poll every frame (PreUpdate) to forward into an EventWriter. Events are Boxed because I found no other way of having a global static generic Datatype without using Any.

Therefore I suggest using this for non-every-frame interaction and rolling a custom solution otherwise.

§Example:

use bevy::prelude::*;
use bevy_extern_events::{queue_event, ExternEvent, ExternEventsPlugin};

#[derive(Default)]
pub struct MyEvent;

#[derive(Resource, Reflect, Default)]
pub struct MyEventResource(i32);

pub fn event_system(
    mut res: ResMut<MyEventResource>,
    mut native_events: EventReader<ExternEvent<MyEvent>>,
) {
    for _e in native_events.read() {
        res.0 += 1;
    }
}

fn test() {
    let mut app = App::new();
    app.init_resource::<MyEventResource>()
        // register `ExternEventsPlugin` with our event type
        .add_plugins(ExternEventsPlugin::<MyEvent>::default())
        // register our system that will react to these events
        .add_systems(Update, event_system);
     
    // can be called any thread, from anywhere (for example c ffi)
    queue_event(MyEvent::default());

    // next pre-update will forward extern events to the bevy events system
    // this will trigger `event_system` of this example
    app.update();

    assert_eq!(app.world.resource::<MyEventResource>().0, 1);
}

Structs§

ExternEvent
wrapper from external events
ExternEventsPlugin
Bevy plugin for convenient proper installation. Registers the event and the polling systems.

Functions§

queue_event
external entry point to queue events from anywhere from any thread