Path: blob/main/examples/ecs/send_and_receive_events.rs
6592 views
//! From time to time, you may find that you want to both send and receive an event of the same type in a single system.1//!2//! Of course, this results in an error: the borrows of [`EventWriter`] and [`EventReader`] overlap,3//! if and only if the [`BufferedEvent`] type is the same.4//! One system parameter borrows the [`Events`] resource mutably, and another system parameter borrows the [`Events`] resource immutably.5//! If Bevy allowed this, this would violate Rust's rules against aliased mutability.6//! In other words, this would be Undefined Behavior (UB)!7//!8//! There are two ways to solve this problem:9//!10//! 1. Use [`ParamSet`] to check out the [`EventWriter`] and [`EventReader`] one at a time.11//! 2. Use a [`Local`] [`EventCursor`] instead of an [`EventReader`], and use [`ResMut`] to access [`Events`].12//!13//! In the first case, you're being careful to only check out only one of the [`EventWriter`] or [`EventReader`] at a time.14//! By "temporally" separating them, you avoid the overlap.15//!16//! In the second case, you only ever have one access to the underlying [`Events`] resource at a time.17//! But in exchange, you have to manually keep track of which events you've already read.18//!19//! Let's look at an example of each.2021use bevy::{diagnostic::FrameCount, ecs::event::EventCursor, prelude::*};2223fn main() {24let mut app = App::new();25app.add_plugins(MinimalPlugins)26.add_event::<DebugEvent>()27.add_event::<A>()28.add_event::<B>()29.add_systems(Update, read_and_write_different_event_types)30.add_systems(31Update,32(33send_events,34debug_events,35send_and_receive_param_set,36debug_events,37send_and_receive_manual_event_reader,38debug_events,39)40.chain(),41);42// We're just going to run a few frames, so we can see and understand the output.43app.update();44// By running for longer than one frame, we can see that we're caching our cursor in the event queue properly.45app.update();46}4748#[derive(BufferedEvent)]49struct A;5051#[derive(BufferedEvent)]52struct B;5354// This works fine, because the types are different,55// so the borrows of the `EventWriter` and `EventReader` don't overlap.56// Note that these borrowing rules are checked at system initialization time,57// not at compile time, as Bevy uses internal unsafe code to split the `World` into disjoint pieces.58fn read_and_write_different_event_types(mut a: EventWriter<A>, mut b: EventReader<B>) {59for _ in b.read() {}60a.write(A);61}6263/// A dummy event type.64#[derive(Debug, Clone, BufferedEvent)]65struct DebugEvent {66resend_from_param_set: bool,67resend_from_local_event_reader: bool,68times_sent: u8,69}7071/// A system that sends all combinations of events.72fn send_events(mut events: EventWriter<DebugEvent>, frame_count: Res<FrameCount>) {73println!("Sending events for frame {}", frame_count.0);7475events.write(DebugEvent {76resend_from_param_set: false,77resend_from_local_event_reader: false,78times_sent: 1,79});80events.write(DebugEvent {81resend_from_param_set: true,82resend_from_local_event_reader: false,83times_sent: 1,84});85events.write(DebugEvent {86resend_from_param_set: false,87resend_from_local_event_reader: true,88times_sent: 1,89});90events.write(DebugEvent {91resend_from_param_set: true,92resend_from_local_event_reader: true,93times_sent: 1,94});95}9697/// A system that prints all events sent since the last time this system ran.98///99/// Note that some events will be printed twice, because they were sent twice.100fn debug_events(mut events: EventReader<DebugEvent>) {101for event in events.read() {102println!("{event:?}");103}104}105106/// A system that both sends and receives events using [`ParamSet`].107fn send_and_receive_param_set(108mut param_set: ParamSet<(EventReader<DebugEvent>, EventWriter<DebugEvent>)>,109frame_count: Res<FrameCount>,110) {111println!(112"Sending and receiving events for frame {} with a `ParamSet`",113frame_count.0114);115116// We must collect the events to resend, because we can't access the writer while we're iterating over the reader.117let mut events_to_resend = Vec::new();118119// This is p0, as the first parameter in the `ParamSet` is the reader.120for event in param_set.p0().read() {121if event.resend_from_param_set {122events_to_resend.push(event.clone());123}124}125126// This is p1, as the second parameter in the `ParamSet` is the writer.127for mut event in events_to_resend {128event.times_sent += 1;129param_set.p1().write(event);130}131}132133/// A system that both sends and receives events using a [`Local`] [`EventCursor`].134fn send_and_receive_manual_event_reader(135// The `Local` `SystemParam` stores state inside the system itself, rather than in the world.136// `EventCursor<T>` is the internal state of `EventReader<T>`, which tracks which events have been seen.137mut local_event_reader: Local<EventCursor<DebugEvent>>,138// We can access the `Events` resource mutably, allowing us to both read and write its contents.139mut events: ResMut<Events<DebugEvent>>,140frame_count: Res<FrameCount>,141) {142println!(143"Sending and receiving events for frame {} with a `Local<EventCursor>",144frame_count.0145);146147// We must collect the events to resend, because we can't mutate events while we're iterating over the events.148let mut events_to_resend = Vec::new();149150for event in local_event_reader.read(&events) {151if event.resend_from_local_event_reader {152// For simplicity, we're cloning the event.153// In this case, since we have mutable access to the `Events` resource,154// we could also just mutate the event in-place,155// or drain the event queue into our `events_to_resend` vector.156events_to_resend.push(event.clone());157}158}159160for mut event in events_to_resend {161event.times_sent += 1;162events.write(event);163}164}165166167