3 unstable releases

0.2.1 Nov 4, 2024
0.2.0 Nov 4, 2024
0.1.0 Mar 7, 2024

#1334 in Game dev


Used in wolf_engine_window

MIT/Apache

11KB
99 lines

Wolf Engine Events

Crates.io Crates.io

An event system for Wolf Engine.

Features

  • A simple, Channel-like API.
  • A Dynamically-typed Event API.

License

Wolf Engine Events is licensed under either:

At your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without additional terms or conditions.


lib.rs:

Provides an event system for Wolf Engine.

Examples

This module provides a FIFO (First-in, First-out) event system based on the sender / receiver / message channel found in std::sync::mpsc.

Create an Event Queue

#
let (event_sender, event_receiver) = mpsc::event_queue();
#

Handling Events

An EventReceiver will collect incoming events, and store them until they are ready to be processed. The order of incoming events is always preserved.

Queued events are queried in a loop. Querying events requires you have mutable access to the Event Queue.

#
#
while let Some(event) = event_receiver.next_event() {
    match event {
        EventType::Event => (), // Handle the event.
    }
}

Sending Events

To send an event to an EventReceiver, we use an EventSender. An event sender is like a tunnel, through which you can send data, and it will pop out on the other side.

#
event_sender.send_event(EventType::Event);

Cloning, and Transferring Ownership of an EventSender

Event Senders are extremely useful because they can be freely, and safely cloned, and their ownership moved to other code that needs to send events. This enables sending events from code that otherwise does not have access to the Event Queue.

#
#
#
#
#
// The EventSender can be cloned, and freely passed around.
let other_type = SomeOtherType::new(event_sender.clone());
some_other_function(&event_sender);

// The original EventSender is unaffected.
event_sender.send_event(EventType::Event);

Sending an EventSender to Another Thread

Event Senders can be safely sent to other threads.

#
// This EventSender stays on the main thread with the EventReceiver.
event_sender.send_event(EventType::Event);

// The clone is moved to the other thread.
let thread_sender = event_sender.clone();
std::thread::spawn(move || {
    thread_sender.send_event(EventType::Event);
}).join();

Dependencies

~33KB