bevy_ecs/message/
update.rs

1use crate::{
2    change_detection::Mut,
3    component::Tick,
4    message::{MessageRegistry, ShouldUpdateMessages},
5    system::{Local, Res, ResMut},
6    world::World,
7};
8use bevy_ecs_macros::SystemSet;
9#[cfg(feature = "bevy_reflect")]
10use core::hash::Hash;
11
12#[doc(hidden)]
13#[derive(SystemSet, Clone, Debug, PartialEq, Eq, Hash)]
14pub struct MessageUpdateSystems;
15
16/// Deprecated alias for [`MessageUpdateSystems`].
17#[deprecated(since = "0.17.0", note = "Renamed to `MessageUpdateSystems`.")]
18pub type EventUpdates = MessageUpdateSystems;
19
20/// Signals the [`message_update_system`] to run after `FixedUpdate` systems.
21///
22/// This will change the behavior of the [`MessageRegistry`] to only run after a fixed update cycle has passed.
23/// Normally, this will simply run every frame.
24pub fn signal_message_update_system(signal: Option<ResMut<MessageRegistry>>) {
25    if let Some(mut registry) = signal {
26        registry.should_update = ShouldUpdateMessages::Ready;
27    }
28}
29
30/// A system that calls [`Messages::update`](super::Messages::update) on all registered [`Messages`][super::Messages] in the world.
31pub fn message_update_system(world: &mut World, mut last_change_tick: Local<Tick>) {
32    world.try_resource_scope(|world, mut registry: Mut<MessageRegistry>| {
33        registry.run_updates(world, *last_change_tick);
34
35        registry.should_update = match registry.should_update {
36            // If we're always updating, keep doing so.
37            ShouldUpdateMessages::Always => ShouldUpdateMessages::Always,
38            // Disable the system until signal_message_update_system runs again.
39            ShouldUpdateMessages::Waiting | ShouldUpdateMessages::Ready => {
40                ShouldUpdateMessages::Waiting
41            }
42        };
43    });
44    *last_change_tick = world.change_tick();
45}
46
47/// A run condition for [`message_update_system`].
48///
49/// If [`signal_message_update_system`] has been run at least once,
50/// we will wait for it to be run again before updating the messages.
51///
52/// Otherwise, we will always update the messages.
53pub fn message_update_condition(maybe_signal: Option<Res<MessageRegistry>>) -> bool {
54    match maybe_signal {
55        Some(signal) => match signal.should_update {
56            ShouldUpdateMessages::Always | ShouldUpdateMessages::Ready => true,
57            ShouldUpdateMessages::Waiting => false,
58        },
59        None => true,
60    }
61}