bevy_time/
lib.rs

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