Skip to content

Commit

Permalink
Warning message for missing events (bevyengine#5730)
Browse files Browse the repository at this point in the history
# Objective
- Reduce debugging burden when using events by telling user when they missed an event.

## Solution

Co-authored-by: Carter Anderson <mcanders1@gmail.com>
  • Loading branch information
2 people authored and james7132 committed Oct 28, 2022
1 parent 8f77823 commit 5278d12
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion crates/bevy_ecs/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use crate as bevy_ecs;
use crate::system::{Local, Res, ResMut, Resource, SystemParam};
use bevy_utils::tracing::trace;
use bevy_utils::tracing::{trace, warn};
use std::ops::{Deref, DerefMut};
use std::{
fmt::{self},
Expand Down Expand Up @@ -149,6 +149,14 @@ impl<E: Event> Default for Events<E> {
}
}

impl<E: Event> Events<E> {
pub fn oldest_event_count(&self) -> usize {
self.events_a
.start_event_count
.min(self.events_b.start_event_count)
}
}

#[derive(Debug)]
struct EventSequence<E: Event> {
events: Vec<EventInstance<E>>,
Expand Down Expand Up @@ -351,10 +359,18 @@ impl<E: Event> ManualEventReader<E> {
+ ExactSizeIterator<Item = (&'a E, EventId<E>)> {
// if the reader has seen some of the events in a buffer, find the proper index offset.
// otherwise read all events in the buffer
let missed = self.missed_events(events);
if missed > 0 {
let plural = if missed == 1 { "event" } else { "events" };
let type_name = std::any::type_name::<E>();
warn!("Missed {missed} `{type_name}` {plural}. Consider reading from the `EventReader` more often (generally the best solution) or calling Events::update() less frequently (normally this is called once per frame). This problem is most likely due to run criteria/fixed timesteps or consuming events conditionally. See the Events documentation for more information.");
}

let a_index = (self.last_event_count).saturating_sub(events.events_a.start_event_count);
let b_index = (self.last_event_count).saturating_sub(events.events_b.start_event_count);
let a = events.events_a.get(a_index..).unwrap_or_default();
let b = events.events_b.get(b_index..).unwrap_or_default();

let unread_count = a.len() + b.len();
// Ensure `len` is implemented correctly
debug_assert_eq!(unread_count, self.len(events));
Expand All @@ -379,6 +395,13 @@ impl<E: Event> ManualEventReader<E> {
.min(events.len())
}

/// Amount of events we missed.
pub fn missed_events(&self, events: &Events<E>) -> usize {
events
.oldest_event_count()
.saturating_sub(self.last_event_count)
}

/// See [`EventReader::is_empty`]
pub fn is_empty(&self, events: &Events<E>) -> bool {
self.len(events) == 0
Expand Down

0 comments on commit 5278d12

Please sign in to comment.