bevy_ecs/event/
event_cursor.rs

1use bevy_ecs::event::{
2    Event, EventIterator, EventIteratorWithId, EventMutIterator, EventMutIteratorWithId, Events,
3};
4#[cfg(feature = "multi_threaded")]
5use bevy_ecs::event::{EventMutParIter, EventParIter};
6use core::marker::PhantomData;
7
8/// Stores the state for an [`EventReader`] or [`EventMutator`].
9///
10/// Access to the [`Events<E>`] resource is required to read any incoming events.
11///
12/// In almost all cases, you should just use an [`EventReader`] or [`EventMutator`],
13/// which will automatically manage the state for you.
14///
15/// However, this type can be useful if you need to manually track events,
16/// such as when you're attempting to send and receive events of the same type in the same system.
17///
18/// # Example
19///
20/// ```
21/// use bevy_ecs::prelude::*;
22/// use bevy_ecs::event::{Event, Events, EventCursor};
23///
24/// #[derive(Event, Clone, Debug)]
25/// struct MyEvent;
26///
27/// /// A system that both sends and receives events using a [`Local`] [`EventCursor`].
28/// fn send_and_receive_events(
29///     // The `Local` `SystemParam` stores state inside the system itself, rather than in the world.
30///     // `EventCursor<T>` is the internal state of `EventMutator<T>`, which tracks which events have been seen.
31///     mut local_event_reader: Local<EventCursor<MyEvent>>,
32///     // We can access the `Events` resource mutably, allowing us to both read and write its contents.
33///     mut events: ResMut<Events<MyEvent>>,
34/// ) {
35///     // We must collect the events to resend, because we can't mutate events while we're iterating over the events.
36///     let mut events_to_resend = Vec::new();
37///
38///     for event in local_event_reader.read(&mut events) {
39///          events_to_resend.push(event.clone());
40///     }
41///
42///     for event in events_to_resend {
43///         events.send(MyEvent);
44///     }
45/// }
46///
47/// # bevy_ecs::system::assert_is_system(send_and_receive_events);
48/// ```
49///
50/// [`EventReader`]: super::EventReader
51/// [`EventMutator`]: super::EventMutator
52#[derive(Debug)]
53pub struct EventCursor<E: Event> {
54    pub(super) last_event_count: usize,
55    pub(super) _marker: PhantomData<E>,
56}
57
58impl<E: Event> Default for EventCursor<E> {
59    fn default() -> Self {
60        EventCursor {
61            last_event_count: 0,
62            _marker: Default::default(),
63        }
64    }
65}
66
67impl<E: Event> Clone for EventCursor<E> {
68    fn clone(&self) -> Self {
69        EventCursor {
70            last_event_count: self.last_event_count,
71            _marker: PhantomData,
72        }
73    }
74}
75
76impl<E: Event> EventCursor<E> {
77    /// See [`EventReader::read`](super::EventReader::read)
78    pub fn read<'a>(&'a mut self, events: &'a Events<E>) -> EventIterator<'a, E> {
79        self.read_with_id(events).without_id()
80    }
81
82    /// See [`EventMutator::read`](super::EventMutator::read)
83    pub fn read_mut<'a>(&'a mut self, events: &'a mut Events<E>) -> EventMutIterator<'a, E> {
84        self.read_mut_with_id(events).without_id()
85    }
86
87    /// See [`EventReader::read_with_id`](super::EventReader::read_with_id)
88    pub fn read_with_id<'a>(&'a mut self, events: &'a Events<E>) -> EventIteratorWithId<'a, E> {
89        EventIteratorWithId::new(self, events)
90    }
91
92    /// See [`EventMutator::read_with_id`](super::EventMutator::read_with_id)
93    pub fn read_mut_with_id<'a>(
94        &'a mut self,
95        events: &'a mut Events<E>,
96    ) -> EventMutIteratorWithId<'a, E> {
97        EventMutIteratorWithId::new(self, events)
98    }
99
100    /// See [`EventReader::par_read`](super::EventReader::par_read)
101    #[cfg(feature = "multi_threaded")]
102    pub fn par_read<'a>(&'a mut self, events: &'a Events<E>) -> EventParIter<'a, E> {
103        EventParIter::new(self, events)
104    }
105
106    /// See [`EventMutator::par_read`](super::EventMutator::par_read)
107    #[cfg(feature = "multi_threaded")]
108    pub fn par_read_mut<'a>(&'a mut self, events: &'a mut Events<E>) -> EventMutParIter<'a, E> {
109        EventMutParIter::new(self, events)
110    }
111
112    /// See [`EventReader::len`](super::EventReader::len)
113    pub fn len(&self, events: &Events<E>) -> usize {
114        // The number of events in this reader is the difference between the most recent event
115        // and the last event seen by it. This will be at most the number of events contained
116        // with the events (any others have already been dropped)
117        // TODO: Warn when there are dropped events, or return e.g. a `Result<usize, (usize, usize)>`
118        events
119            .event_count
120            .saturating_sub(self.last_event_count)
121            .min(events.len())
122    }
123
124    /// Amount of events we missed.
125    pub fn missed_events(&self, events: &Events<E>) -> usize {
126        events
127            .oldest_event_count()
128            .saturating_sub(self.last_event_count)
129    }
130
131    /// See [`EventReader::is_empty()`](super::EventReader::is_empty)
132    pub fn is_empty(&self, events: &Events<E>) -> bool {
133        self.len(events) == 0
134    }
135
136    /// See [`EventReader::clear()`](super::EventReader::clear)
137    pub fn clear(&mut self, events: &Events<E>) {
138        self.last_event_count = events.event_count;
139    }
140}