Skip to main content

sim_logic/ecs/
events.rs

1//! Count-bounded typed events visible only within one System-stage invocation.
2
3use std::{
4    any::{TypeId, type_name},
5    error::Error,
6    fmt,
7    sync::{
8        Mutex,
9        atomic::{AtomicBool, Ordering},
10    },
11};
12
13use bevy_ecs::{
14    prelude::{Res, ResMut, Resource},
15    system::SystemParam,
16    world::World,
17};
18
19/// A small value that can be broadcast between Systems in one World stage.
20///
21/// This first-slice contract requires `Copy` so an expired event cannot retain
22/// owned heap memory or defer user `Drop` code beyond its stage. Prefer compact
23/// values and opaque handles; the configured limit bounds record count, not
24/// `size_of::<E>()` bytes.
25///
26/// ```compile_fail
27/// use sim_logic::events::WorldEvent;
28///
29/// fn accepts_world_event<E: WorldEvent>() {}
30/// accepts_world_event::<String>();
31/// ```
32pub trait WorldEvent: Copy + Send + Sync + 'static {}
33
34impl<T: Copy + Send + Sync + 'static> WorldEvent for T {}
35
36/// A typed event could not be retained by the current stage invocation.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum EventSendError {
39    /// This event type already retained its configured maximum record count.
40    LimitExceeded {
41        /// Rust type name of the channel that first failed.
42        event: &'static str,
43        /// Maximum records for each event type in one stage invocation.
44        limit: usize,
45    },
46    /// The channel could not reserve storage for one more record.
47    AllocationFailed {
48        /// Rust type name of the channel that first failed.
49        event: &'static str,
50    },
51    /// An earlier event send already failed in this stage invocation.
52    StageAlreadyFailed,
53    /// The runtime did not expose an active event-delivery stage.
54    StageUnavailable {
55        /// Rust type name of the channel used outside a running stage.
56        event: &'static str,
57    },
58}
59
60impl fmt::Display for EventSendError {
61    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match self {
63            Self::LimitExceeded { event, limit } => {
64                write!(formatter, "event `{event}` exceeded its limit of {limit}")
65            }
66            Self::AllocationFailed { event } => {
67                write!(formatter, "event `{event}` could not reserve storage")
68            }
69            Self::StageAlreadyFailed => {
70                formatter.write_str("an earlier event send already failed in this stage")
71            }
72            Self::StageUnavailable { event } => {
73                write!(
74                    formatter,
75                    "event `{event}` cannot be sent outside a running stage"
76                )
77            }
78        }
79    }
80}
81
82impl Error for EventSendError {}
83
84#[derive(Resource)]
85struct EventChannel<E: WorldEvent> {
86    events: Vec<E>,
87    written_epoch: Option<u64>,
88    limit: usize,
89}
90
91impl<E: WorldEvent> EventChannel<E> {
92    const fn new(limit: usize) -> Self {
93        Self {
94            events: Vec::new(),
95            written_epoch: None,
96            limit,
97        }
98    }
99
100    fn begin_writing(&mut self, epoch: u64) {
101        if self.written_epoch != Some(epoch) {
102            self.events.clear();
103            self.written_epoch = Some(epoch);
104        }
105    }
106
107    fn current(&self, epoch: Option<u64>) -> &[E] {
108        if self.written_epoch == epoch && epoch.is_some() {
109            &self.events
110        } else {
111            &[]
112        }
113    }
114}
115
116#[derive(Debug, Default, Resource)]
117pub(crate) struct EventStageState {
118    last_epoch: u64,
119    active_epoch: Option<u64>,
120}
121
122impl EventStageState {
123    fn begin(&mut self) -> bool {
124        if self.active_epoch.is_some() {
125            return false;
126        }
127        let Some(epoch) = self.last_epoch.checked_add(1) else {
128            self.active_epoch = None;
129            return false;
130        };
131        self.last_epoch = epoch;
132        self.active_epoch = Some(epoch);
133        true
134    }
135
136    fn end(&mut self) -> bool {
137        self.active_epoch.take().is_some()
138    }
139
140    const fn active_epoch(&self) -> Option<u64> {
141        self.active_epoch
142    }
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub(crate) struct EventStageFailure {
147    error: EventSendError,
148}
149
150impl fmt::Display for EventStageFailure {
151    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
152        self.error.fmt(formatter)
153    }
154}
155
156#[derive(Debug, Default, Resource)]
157struct EventFailureState {
158    failed: AtomicBool,
159    first: Mutex<Option<EventStageFailure>>,
160}
161
162impl EventFailureState {
163    fn reset(&mut self) -> bool {
164        let Ok(first) = self.first.get_mut() else {
165            return false;
166        };
167        *first = None;
168        self.failed.store(false, Ordering::Release);
169        true
170    }
171
172    fn is_failed(&self) -> bool {
173        self.failed.load(Ordering::Acquire)
174    }
175
176    fn record(&self, error: EventSendError) {
177        let Ok(mut first) = self.first.lock() else {
178            self.failed.store(true, Ordering::Release);
179            return;
180        };
181        if first.is_none() {
182            *first = Some(EventStageFailure { error });
183        }
184        self.failed.store(true, Ordering::Release);
185    }
186
187    fn failure(&self) -> Result<Option<EventStageFailure>, ()> {
188        if !self.is_failed() {
189            return Ok(None);
190        }
191        self.first.lock().map(|first| *first).map_err(|_| ())
192    }
193}
194
195/// Writes ordered typed events for later Systems in the current stage.
196///
197/// A send failure poisons the complete stage even when its returned error is
198/// ignored. The scheduler stops before the next System and discards that
199/// stage's pending structural and transition Commands. Successful sends become
200/// immediately visible to later [`EventReader`] parameters of the same type.
201/// To inspect earlier events and then write the same type in one System, use
202/// this writer's [`Self::iter`] method. Requesting both `EventReader<E>` and
203/// `EventWriter<E>` in one System conflicts over the same ECS channel.
204#[derive(SystemParam)]
205pub struct EventWriter<'w, E: WorldEvent> {
206    channel: ResMut<'w, EventChannel<E>>,
207    stage: Res<'w, EventStageState>,
208    failure: Res<'w, EventFailureState>,
209}
210
211impl<E: WorldEvent> EventWriter<'_, E> {
212    /// Retains one event in call order for later Systems in this stage.
213    pub fn send(&mut self, event: E) -> Result<(), EventSendError> {
214        if self.failure.is_failed() {
215            return Err(EventSendError::StageAlreadyFailed);
216        }
217        let Some(epoch) = self.stage.active_epoch() else {
218            let error = EventSendError::StageUnavailable {
219                event: type_name::<E>(),
220            };
221            self.failure.record(error);
222            return Err(error);
223        };
224
225        self.channel.begin_writing(epoch);
226        if self.channel.events.len() >= self.channel.limit {
227            let error = EventSendError::LimitExceeded {
228                event: type_name::<E>(),
229                limit: self.channel.limit,
230            };
231            self.failure.record(error);
232            return Err(error);
233        }
234        if self.channel.events.try_reserve(1).is_err() {
235            let error = EventSendError::AllocationFailed {
236                event: type_name::<E>(),
237            };
238            self.failure.record(error);
239            return Err(error);
240        }
241        self.channel.events.push(event);
242        Ok(())
243    }
244
245    /// Iterates over events sent earlier in this stage, including by this writer.
246    pub fn iter(&self) -> std::slice::Iter<'_, E> {
247        self.channel.current(self.stage.active_epoch()).iter()
248    }
249
250    /// Returns the number of events currently visible to this writer.
251    pub fn len(&self) -> usize {
252        self.channel.current(self.stage.active_epoch()).len()
253    }
254
255    /// Returns `true` when this stage has not retained an event of this type.
256    pub fn is_empty(&self) -> bool {
257        self.len() == 0
258    }
259}
260
261impl<'a, E: WorldEvent> IntoIterator for &'a EventWriter<'_, E> {
262    type Item = &'a E;
263    type IntoIter = std::slice::Iter<'a, E>;
264
265    fn into_iter(self) -> Self::IntoIter {
266        self.iter()
267    }
268}
269
270/// A repeatable read-only view of events sent earlier in the current stage.
271///
272/// Reading does not consume records. Every later reader sees the same ordered
273/// slice, while a reader that ran before a writer is not invoked again. Do not
274/// request a reader and writer of the same event type in one System; use the
275/// writer's read-only methods when both operations are needed.
276#[derive(SystemParam)]
277pub struct EventReader<'w, E: WorldEvent> {
278    channel: Res<'w, EventChannel<E>>,
279    stage: Res<'w, EventStageState>,
280}
281
282impl<E: WorldEvent> EventReader<'_, E> {
283    /// Iterates over the complete event slice currently visible to this stage.
284    pub fn iter(&self) -> std::slice::Iter<'_, E> {
285        self.channel.current(self.stage.active_epoch()).iter()
286    }
287
288    /// Returns the number of events visible to this reader.
289    pub fn len(&self) -> usize {
290        self.channel.current(self.stage.active_epoch()).len()
291    }
292
293    /// Returns `true` when no earlier System sent this event type in the stage.
294    pub fn is_empty(&self) -> bool {
295        self.len() == 0
296    }
297}
298
299impl<'a, E: WorldEvent> IntoIterator for &'a EventReader<'_, E> {
300    type Item = &'a E;
301    type IntoIter = std::slice::Iter<'a, E>;
302
303    fn into_iter(self) -> Self::IntoIter {
304        self.iter()
305    }
306}
307
308struct RegisteredEvent {
309    type_id: TypeId,
310    install: fn(&mut World, usize),
311}
312
313#[derive(Default)]
314pub(crate) struct EventRegistry {
315    events: Vec<RegisteredEvent>,
316}
317
318impl EventRegistry {
319    pub(crate) fn register<E: WorldEvent>(&mut self) {
320        if self
321            .events
322            .iter()
323            .any(|event| event.type_id == TypeId::of::<E>())
324        {
325            return;
326        }
327        self.events.push(RegisteredEvent {
328            type_id: TypeId::of::<E>(),
329            install: install_channel::<E>,
330        });
331    }
332
333    pub(crate) fn install(&self, world: &mut World, event_limit: usize) {
334        world.insert_resource(EventStageState::default());
335        world.insert_resource(EventFailureState::default());
336        for event in &self.events {
337            (event.install)(world, event_limit);
338        }
339    }
340}
341
342fn install_channel<E: WorldEvent>(world: &mut World, limit: usize) {
343    world.insert_resource(EventChannel::<E>::new(limit));
344}
345
346pub(crate) fn begin_event_stage(world: &mut World) -> bool {
347    let reset = world
348        .get_resource_mut::<EventFailureState>()
349        .is_some_and(|mut failure| failure.reset());
350    reset
351        && world
352            .get_resource_mut::<EventStageState>()
353            .is_some_and(|mut stage| stage.begin())
354}
355
356pub(crate) fn end_event_stage(world: &mut World) -> bool {
357    let Some(mut stage) = world.get_resource_mut::<EventStageState>() else {
358        return false;
359    };
360    stage.end()
361}
362
363pub(crate) fn event_stage_failure(world: &World) -> Result<Option<EventStageFailure>, ()> {
364    world
365        .get_resource::<EventFailureState>()
366        .ok_or(())?
367        .failure()
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373
374    #[test]
375    fn epochs_hide_old_records_and_reuse_capacity() {
376        let mut channel = EventChannel::<u8>::new(2);
377        channel.begin_writing(1);
378        channel.events.extend([3, 4]);
379        let capacity = channel.events.capacity();
380
381        assert_eq!(channel.current(Some(1)), [3, 4]);
382        assert!(channel.current(None).is_empty());
383        assert!(channel.current(Some(2)).is_empty());
384
385        channel.begin_writing(2);
386        channel.events.push(9);
387        assert_eq!(channel.current(Some(2)), [9]);
388        assert_eq!(channel.events.capacity(), capacity);
389    }
390
391    #[test]
392    fn stage_epoch_exhaustion_closes_delivery() {
393        let mut stage = EventStageState {
394            last_epoch: u64::MAX,
395            active_epoch: None,
396        };
397
398        assert!(!stage.begin());
399        assert_eq!(stage.active_epoch(), None);
400    }
401
402    #[test]
403    fn stage_lifecycle_rejects_nested_begin_and_unmatched_end() {
404        let mut stage = EventStageState::default();
405
406        assert!(!stage.end());
407        assert!(stage.begin());
408        assert!(!stage.begin());
409        assert!(stage.end());
410        assert!(!stage.end());
411    }
412}