Skip to main content

bevy_time/
lib.rs

1#![doc = include_str!("../README.md")]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![forbid(unsafe_code)]
4#![doc(
5    html_logo_url = "https://bevy.org/assets/icon.png",
6    html_favicon_url = "https://bevy.org/assets/icon.png"
7)]
8#![no_std]
9
10#[cfg(feature = "std")]
11extern crate std;
12
13extern crate alloc;
14
15/// Common run conditions
16pub mod common_conditions;
17mod delayed_commands;
18mod fixed;
19mod real;
20mod stopwatch;
21mod time;
22mod timer;
23mod virt;
24
25pub use delayed_commands::*;
26pub use fixed::*;
27pub use real::*;
28pub use stopwatch::*;
29pub use time::*;
30pub use timer::*;
31pub use virt::*;
32
33/// The time prelude.
34///
35/// This includes the most common types in this crate, re-exported for your convenience.
36pub mod prelude {
37    #[doc(hidden)]
38    pub use crate::{DelayedCommandsExt, Fixed, Real, Time, Timer, TimerMode, Virtual};
39}
40
41use bevy_app::{prelude::*, RunFixedMainLoop};
42use bevy_ecs::{
43    message::{
44        message_update_system, signal_message_update_system, MessageRegistry, ShouldUpdateMessages,
45    },
46    prelude::*,
47};
48use bevy_platform::time::Instant;
49use core::time::Duration;
50
51#[cfg(feature = "std")]
52pub use crossbeam_channel::TrySendError;
53
54#[cfg(feature = "std")]
55use crossbeam_channel::{Receiver, Sender};
56
57/// Adds time functionality to Apps.
58#[derive(Default)]
59pub struct TimePlugin;
60
61/// Updates the elapsed time. Any system that interacts with [`Time`] component should run after
62/// this.
63#[derive(Debug, PartialEq, Eq, Clone, Hash, SystemSet)]
64pub struct TimeSystems;
65
66impl Plugin for TimePlugin {
67    fn build(&self, app: &mut App) {
68        app.init_resource::<Time>()
69            .init_resource::<Time<Real>>()
70            .init_resource::<Time<Virtual>>()
71            .init_resource::<Time<Fixed>>()
72            .init_resource::<TimeUpdateStrategy>();
73
74        #[cfg(feature = "bevy_reflect")]
75        {
76            app.register_type::<Time>()
77                .register_type::<Time<Real>>()
78                .register_type::<Time<Virtual>>()
79                .register_type::<Time<Fixed>>();
80        }
81
82        app.add_systems(
83            First,
84            time_system
85                .in_set(TimeSystems)
86                .ambiguous_with(message_update_system),
87        )
88        .add_systems(PreUpdate, check_delayed_command_queues)
89        .add_systems(
90            RunFixedMainLoop,
91            run_fixed_main_schedule.in_set(RunFixedMainLoopSystems::FixedMainLoop),
92        );
93
94        // Ensure the messages are not dropped until `FixedMain` systems can observe them
95        app.add_systems(FixedPostUpdate, signal_message_update_system);
96        let mut message_registry = app.world_mut().resource_mut::<MessageRegistry>();
97        // We need to start in a waiting state so that the messages are not updated until the first fixed update
98        message_registry.should_update = ShouldUpdateMessages::Waiting;
99    }
100}
101
102/// Configuration resource used to determine how the time system should run.
103///
104/// For most cases, [`TimeUpdateStrategy::Automatic`] is fine. When writing tests, dealing with
105/// networking or similar, you may prefer to set the next [`Time`] value manually.
106#[derive(Resource, Default)]
107pub enum TimeUpdateStrategy {
108    /// [`Time`] will be automatically updated each frame using an [`Instant`] sent from the render world.
109    /// If nothing is sent, the system clock will be used instead.
110    #[cfg_attr(feature = "std", doc = "See [`TimeSender`] for more details.")]
111    #[default]
112    Automatic,
113    /// [`Time`] will be updated to the specified [`Instant`] value each frame.
114    /// In order for time to progress, this value must be manually updated each frame.
115    ///
116    /// Note that the `Time` resource will not be updated until [`TimeSystems`] runs.
117    ManualInstant(Instant),
118    /// [`Time`] will be incremented by the specified [`Duration`] each frame.
119    ManualDuration(Duration),
120    /// [`Time`] will be incremented by the fixed timestep each frame, multiplied by the specified factor `n`.
121    /// This means that a call to [`App::update`] will always run the fixed loop exactly n times.
122    FixedTimesteps(u32),
123}
124
125/// Channel resource used to receive time from the render world.
126#[cfg(feature = "std")]
127#[derive(Resource)]
128pub struct TimeReceiver(pub Receiver<Instant>);
129
130/// Channel resource used to send time from the render world.
131#[cfg(feature = "std")]
132#[derive(Resource)]
133pub struct TimeSender(pub Sender<Instant>);
134
135/// Creates channels used for sending time between the render world and the main world.
136#[cfg(feature = "std")]
137pub fn create_time_channels() -> (TimeSender, TimeReceiver) {
138    // bound the channel to 2 since when pipelined the render phase can finish before
139    // the time system runs.
140    let (s, r) = crossbeam_channel::bounded::<Instant>(2);
141    (TimeSender(s), TimeReceiver(r))
142}
143
144/// The system used to update the [`Time`] used by app logic. If there is a render world the time is
145/// sent from there to this system through channels. Otherwise the time is updated in this system.
146pub fn time_system(
147    mut real_time: ResMut<Time<Real>>,
148    mut virtual_time: ResMut<Time<Virtual>>,
149    fixed_time: Res<Time<Fixed>>,
150    mut time: ResMut<Time>,
151    update_strategy: Res<TimeUpdateStrategy>,
152    #[cfg(feature = "std")] time_recv: Option<Res<TimeReceiver>>,
153    #[cfg(feature = "std")] mut has_received_time: Local<bool>,
154) {
155    #[cfg(feature = "std")]
156    // TODO: Figure out how to handle this when using pipelined rendering.
157    let sent_time = match time_recv.map(|res| res.0.try_recv()) {
158        Some(Ok(new_time)) => {
159            *has_received_time = true;
160            Some(new_time)
161        }
162        Some(Err(_)) => {
163            if *has_received_time {
164                log::warn!("time_system did not receive the time from the render world! Calculations depending on the time may be incorrect.");
165            }
166            None
167        }
168        None => None,
169    };
170
171    match update_strategy.as_ref() {
172        TimeUpdateStrategy::Automatic => {
173            #[cfg(feature = "std")]
174            real_time.update_with_instant(sent_time.unwrap_or_else(Instant::now));
175
176            #[cfg(not(feature = "std"))]
177            real_time.update_with_instant(Instant::now());
178        }
179        TimeUpdateStrategy::ManualInstant(instant) => real_time.update_with_instant(*instant),
180        TimeUpdateStrategy::ManualDuration(duration) => real_time.update_with_duration(*duration),
181        TimeUpdateStrategy::FixedTimesteps(factor) => {
182            real_time.update_with_duration(fixed_time.timestep() * *factor);
183        }
184    }
185
186    update_virtual_time(&mut time, &mut virtual_time, &real_time);
187}
188
189#[cfg(test)]
190#[expect(clippy::print_stdout, reason = "Allowed in tests.")]
191mod tests {
192    use crate::{Fixed, Time, TimePlugin, TimeUpdateStrategy, Virtual};
193    use bevy_app::{App, FixedUpdate, Startup, Update};
194    use bevy_ecs::{
195        message::{
196            Message, MessageReader, MessageRegistry, MessageWriter, Messages, ShouldUpdateMessages,
197        },
198        resource::Resource,
199        system::{Local, Res, ResMut},
200    };
201    use core::error::Error;
202    use core::time::Duration;
203    use std::println;
204
205    #[derive(Message)]
206    struct TestMessage<T: Default> {
207        sender: std::sync::mpsc::Sender<T>,
208    }
209
210    impl<T: Default> Drop for TestMessage<T> {
211        fn drop(&mut self) {
212            self.sender
213                .send(T::default())
214                .expect("Failed to send drop signal");
215        }
216    }
217
218    #[derive(Message)]
219    struct DummyMessage;
220
221    #[derive(Resource, Default)]
222    struct FixedUpdateCounter(u8);
223
224    fn count_fixed_updates(mut counter: ResMut<FixedUpdateCounter>) {
225        counter.0 += 1;
226    }
227
228    fn report_time(
229        mut frame_count: Local<u64>,
230        virtual_time: Res<Time<Virtual>>,
231        fixed_time: Res<Time<Fixed>>,
232    ) {
233        println!(
234            "Virtual time on frame {}: {:?}",
235            *frame_count,
236            virtual_time.elapsed()
237        );
238        println!(
239            "Fixed time on frame {}: {:?}",
240            *frame_count,
241            fixed_time.elapsed()
242        );
243
244        *frame_count += 1;
245    }
246
247    #[test]
248    fn fixed_main_schedule_should_run_with_time_plugin_enabled() {
249        // Set the time step to just over half the fixed update timestep
250        // This way, it will have not accumulated enough time to run the fixed update after one update
251        // But will definitely have enough time after two updates
252        let fixed_update_timestep = Time::<Fixed>::default().timestep();
253        let time_step = fixed_update_timestep / 2 + Duration::from_millis(1);
254
255        let mut app = App::new();
256        app.add_plugins(TimePlugin)
257            .add_systems(FixedUpdate, count_fixed_updates)
258            .add_systems(Update, report_time)
259            .init_resource::<FixedUpdateCounter>()
260            .insert_resource(TimeUpdateStrategy::ManualDuration(time_step));
261
262        // Frame 0
263        // Fixed update should not have run yet
264        app.update();
265
266        assert!(Duration::ZERO < fixed_update_timestep);
267        let counter = app.world().resource::<FixedUpdateCounter>();
268        assert_eq!(counter.0, 0, "Fixed update should not have run yet");
269
270        // Frame 1
271        // Fixed update should not have run yet
272        app.update();
273
274        assert!(time_step < fixed_update_timestep);
275        let counter = app.world().resource::<FixedUpdateCounter>();
276        assert_eq!(counter.0, 0, "Fixed update should not have run yet");
277
278        // Frame 2
279        // Fixed update should have run now
280        app.update();
281
282        assert!(2 * time_step > fixed_update_timestep);
283        let counter = app.world().resource::<FixedUpdateCounter>();
284        assert_eq!(counter.0, 1, "Fixed update should have run once");
285
286        // Frame 3
287        // Fixed update should have run exactly once still
288        app.update();
289
290        assert!(3 * time_step < 2 * fixed_update_timestep);
291        let counter = app.world().resource::<FixedUpdateCounter>();
292        assert_eq!(counter.0, 1, "Fixed update should have run once");
293
294        // Frame 4
295        // Fixed update should have run twice now
296        app.update();
297
298        assert!(4 * time_step > 2 * fixed_update_timestep);
299        let counter = app.world().resource::<FixedUpdateCounter>();
300        assert_eq!(counter.0, 2, "Fixed update should have run twice");
301    }
302
303    #[test]
304    fn events_get_dropped_regression_test_11528() -> Result<(), impl Error> {
305        let (tx1, rx1) = std::sync::mpsc::channel();
306        let (tx2, rx2) = std::sync::mpsc::channel();
307        let mut app = App::new();
308        app.add_plugins(TimePlugin)
309            .add_message::<TestMessage<i32>>()
310            .add_message::<TestMessage<()>>()
311            .add_systems(Startup, move |mut ev2: MessageWriter<TestMessage<()>>| {
312                ev2.write(TestMessage {
313                    sender: tx2.clone(),
314                });
315            })
316            .add_systems(Update, move |mut ev1: MessageWriter<TestMessage<i32>>| {
317                // Keep adding events so this event type is processed every update
318                ev1.write(TestMessage {
319                    sender: tx1.clone(),
320                });
321            })
322            .add_systems(
323                Update,
324                |mut m1: MessageReader<TestMessage<i32>>,
325                 mut m2: MessageReader<TestMessage<()>>| {
326                    // Read events so they can be dropped
327                    for _ in m1.read() {}
328                    for _ in m2.read() {}
329                },
330            )
331            .insert_resource(TimeUpdateStrategy::ManualDuration(
332                Time::<Fixed>::default().timestep(),
333            ));
334
335        for _ in 0..10 {
336            app.update();
337        }
338
339        // Check event type 1 as been dropped at least once
340        let _drop_signal = rx1.try_recv()?;
341        // Check event type 2 has been dropped
342        rx2.try_recv()
343    }
344
345    #[test]
346    fn event_update_should_wait_for_fixed_main() {
347        // Set the time step to just over half the fixed update timestep
348        // This way, it will have not accumulated enough time to run the fixed update after one update
349        // But will definitely have enough time after two updates
350        let fixed_update_timestep = Time::<Fixed>::default().timestep();
351        let time_step = fixed_update_timestep / 2 + Duration::from_millis(1);
352
353        fn write_message(mut messages: ResMut<Messages<DummyMessage>>) {
354            messages.write(DummyMessage);
355        }
356
357        let mut app = App::new();
358        app.add_plugins(TimePlugin)
359            .add_message::<DummyMessage>()
360            .init_resource::<FixedUpdateCounter>()
361            .add_systems(Startup, write_message)
362            .add_systems(FixedUpdate, count_fixed_updates)
363            .insert_resource(TimeUpdateStrategy::ManualDuration(time_step));
364
365        for frame in 0..10 {
366            app.update();
367            let fixed_updates_seen = app.world().resource::<FixedUpdateCounter>().0;
368            let messages = app.world().resource::<Messages<DummyMessage>>();
369            let n_total_messages = messages.len();
370            let n_current_messages = messages.iter_current_update_messages().count();
371            let message_registry = app.world().resource::<MessageRegistry>();
372            let should_update = message_registry.should_update;
373
374            println!("Frame {frame}, {fixed_updates_seen} fixed updates seen. Should update: {should_update:?}");
375            println!("Total messages: {n_total_messages} | Current messages: {n_current_messages}",);
376
377            match frame {
378                0 | 1 => {
379                    assert_eq!(fixed_updates_seen, 0);
380                    assert_eq!(n_total_messages, 1);
381                    assert_eq!(n_current_messages, 1);
382                    assert_eq!(should_update, ShouldUpdateMessages::Waiting);
383                }
384                2 => {
385                    assert_eq!(fixed_updates_seen, 1); // Time to trigger event updates
386                    assert_eq!(n_total_messages, 1);
387                    assert_eq!(n_current_messages, 1);
388                    assert_eq!(should_update, ShouldUpdateMessages::Ready); // Prepping first update
389                }
390                3 => {
391                    assert_eq!(fixed_updates_seen, 1);
392                    assert_eq!(n_total_messages, 1);
393                    assert_eq!(n_current_messages, 0); // First update has occurred
394                    assert_eq!(should_update, ShouldUpdateMessages::Waiting);
395                }
396                4 => {
397                    assert_eq!(fixed_updates_seen, 2); // Time to trigger the second update
398                    assert_eq!(n_total_messages, 1);
399                    assert_eq!(n_current_messages, 0);
400                    assert_eq!(should_update, ShouldUpdateMessages::Ready); // Prepping second update
401                }
402                5 => {
403                    assert_eq!(fixed_updates_seen, 2);
404                    assert_eq!(n_total_messages, 0); // Second update has occurred
405                    assert_eq!(n_current_messages, 0);
406                    assert_eq!(should_update, ShouldUpdateMessages::Waiting);
407                }
408                _ => {
409                    assert_eq!(n_total_messages, 0); // No more events are sent
410                    assert_eq!(n_current_messages, 0);
411                }
412            }
413        }
414    }
415}