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
15pub 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
31pub 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 message::{
42 message_update_system, signal_message_update_system, MessageRegistry, ShouldUpdateMessages,
43 },
44 prelude::*,
45};
46use bevy_platform::time::Instant;
47use core::time::Duration;
48
49#[cfg(feature = "std")]
50pub use crossbeam_channel::TrySendError;
51
52#[cfg(feature = "std")]
53use crossbeam_channel::{Receiver, Sender};
54
55#[derive(Default)]
57pub struct TimePlugin;
58
59#[derive(Debug, PartialEq, Eq, Clone, Hash, SystemSet)]
62pub struct TimeSystems;
63
64impl Plugin for TimePlugin {
65 fn build(&self, app: &mut App) {
66 app.init_resource::<Time>()
67 .init_resource::<Time<Real>>()
68 .init_resource::<Time<Virtual>>()
69 .init_resource::<Time<Fixed>>()
70 .init_resource::<TimeUpdateStrategy>();
71
72 #[cfg(feature = "bevy_reflect")]
73 {
74 app.register_type::<Time>()
75 .register_type::<Time<Real>>()
76 .register_type::<Time<Virtual>>()
77 .register_type::<Time<Fixed>>();
78 }
79
80 app.add_systems(
81 First,
82 time_system
83 .in_set(TimeSystems)
84 .ambiguous_with(message_update_system),
85 )
86 .add_systems(
87 RunFixedMainLoop,
88 run_fixed_main_schedule.in_set(RunFixedMainLoopSystems::FixedMainLoop),
89 );
90
91 app.add_systems(FixedPostUpdate, signal_message_update_system);
93 let mut message_registry = app.world_mut().resource_mut::<MessageRegistry>();
94 message_registry.should_update = ShouldUpdateMessages::Waiting;
96 }
97}
98
99#[derive(Resource, Default)]
104pub enum TimeUpdateStrategy {
105 #[cfg_attr(feature = "std", doc = "See [`TimeSender`] for more details.")]
108 #[default]
109 Automatic,
110 ManualInstant(Instant),
115 ManualDuration(Duration),
117 FixedTimesteps(u32),
120}
121
122#[cfg(feature = "std")]
124#[derive(Resource)]
125pub struct TimeReceiver(pub Receiver<Instant>);
126
127#[cfg(feature = "std")]
129#[derive(Resource)]
130pub struct TimeSender(pub Sender<Instant>);
131
132#[cfg(feature = "std")]
134pub fn create_time_channels() -> (TimeSender, TimeReceiver) {
135 let (s, r) = crossbeam_channel::bounded::<Instant>(2);
138 (TimeSender(s), TimeReceiver(r))
139}
140
141pub fn time_system(
144 mut real_time: ResMut<Time<Real>>,
145 mut virtual_time: ResMut<Time<Virtual>>,
146 fixed_time: Res<Time<Fixed>>,
147 mut time: ResMut<Time>,
148 update_strategy: Res<TimeUpdateStrategy>,
149 #[cfg(feature = "std")] time_recv: Option<Res<TimeReceiver>>,
150 #[cfg(feature = "std")] mut has_received_time: Local<bool>,
151) {
152 #[cfg(feature = "std")]
153 let sent_time = match time_recv.map(|res| res.0.try_recv()) {
155 Some(Ok(new_time)) => {
156 *has_received_time = true;
157 Some(new_time)
158 }
159 Some(Err(_)) => {
160 if *has_received_time {
161 log::warn!("time_system did not receive the time from the render world! Calculations depending on the time may be incorrect.");
162 }
163 None
164 }
165 None => None,
166 };
167
168 match update_strategy.as_ref() {
169 TimeUpdateStrategy::Automatic => {
170 #[cfg(feature = "std")]
171 real_time.update_with_instant(sent_time.unwrap_or_else(Instant::now));
172
173 #[cfg(not(feature = "std"))]
174 real_time.update_with_instant(Instant::now());
175 }
176 TimeUpdateStrategy::ManualInstant(instant) => real_time.update_with_instant(*instant),
177 TimeUpdateStrategy::ManualDuration(duration) => real_time.update_with_duration(*duration),
178 TimeUpdateStrategy::FixedTimesteps(factor) => {
179 real_time.update_with_duration(fixed_time.timestep() * *factor);
180 }
181 }
182
183 update_virtual_time(&mut time, &mut virtual_time, &real_time);
184}
185
186#[cfg(test)]
187#[expect(clippy::print_stdout, reason = "Allowed in tests.")]
188mod tests {
189 use crate::{Fixed, Time, TimePlugin, TimeUpdateStrategy, Virtual};
190 use bevy_app::{App, FixedUpdate, Startup, Update};
191 use bevy_ecs::{
192 message::{
193 Message, MessageReader, MessageRegistry, MessageWriter, Messages, ShouldUpdateMessages,
194 },
195 resource::Resource,
196 system::{Local, Res, ResMut},
197 };
198 use core::error::Error;
199 use core::time::Duration;
200 use std::println;
201
202 #[derive(Message)]
203 struct TestMessage<T: Default> {
204 sender: std::sync::mpsc::Sender<T>,
205 }
206
207 impl<T: Default> Drop for TestMessage<T> {
208 fn drop(&mut self) {
209 self.sender
210 .send(T::default())
211 .expect("Failed to send drop signal");
212 }
213 }
214
215 #[derive(Message)]
216 struct DummyMessage;
217
218 #[derive(Resource, Default)]
219 struct FixedUpdateCounter(u8);
220
221 fn count_fixed_updates(mut counter: ResMut<FixedUpdateCounter>) {
222 counter.0 += 1;
223 }
224
225 fn report_time(
226 mut frame_count: Local<u64>,
227 virtual_time: Res<Time<Virtual>>,
228 fixed_time: Res<Time<Fixed>>,
229 ) {
230 println!(
231 "Virtual time on frame {}: {:?}",
232 *frame_count,
233 virtual_time.elapsed()
234 );
235 println!(
236 "Fixed time on frame {}: {:?}",
237 *frame_count,
238 fixed_time.elapsed()
239 );
240
241 *frame_count += 1;
242 }
243
244 #[test]
245 fn fixed_main_schedule_should_run_with_time_plugin_enabled() {
246 let fixed_update_timestep = Time::<Fixed>::default().timestep();
250 let time_step = fixed_update_timestep / 2 + Duration::from_millis(1);
251
252 let mut app = App::new();
253 app.add_plugins(TimePlugin)
254 .add_systems(FixedUpdate, count_fixed_updates)
255 .add_systems(Update, report_time)
256 .init_resource::<FixedUpdateCounter>()
257 .insert_resource(TimeUpdateStrategy::ManualDuration(time_step));
258
259 app.update();
262
263 assert!(Duration::ZERO < fixed_update_timestep);
264 let counter = app.world().resource::<FixedUpdateCounter>();
265 assert_eq!(counter.0, 0, "Fixed update should not have run yet");
266
267 app.update();
270
271 assert!(time_step < fixed_update_timestep);
272 let counter = app.world().resource::<FixedUpdateCounter>();
273 assert_eq!(counter.0, 0, "Fixed update should not have run yet");
274
275 app.update();
278
279 assert!(2 * time_step > fixed_update_timestep);
280 let counter = app.world().resource::<FixedUpdateCounter>();
281 assert_eq!(counter.0, 1, "Fixed update should have run once");
282
283 app.update();
286
287 assert!(3 * time_step < 2 * fixed_update_timestep);
288 let counter = app.world().resource::<FixedUpdateCounter>();
289 assert_eq!(counter.0, 1, "Fixed update should have run once");
290
291 app.update();
294
295 assert!(4 * time_step > 2 * fixed_update_timestep);
296 let counter = app.world().resource::<FixedUpdateCounter>();
297 assert_eq!(counter.0, 2, "Fixed update should have run twice");
298 }
299
300 #[test]
301 fn events_get_dropped_regression_test_11528() -> Result<(), impl Error> {
302 let (tx1, rx1) = std::sync::mpsc::channel();
303 let (tx2, rx2) = std::sync::mpsc::channel();
304 let mut app = App::new();
305 app.add_plugins(TimePlugin)
306 .add_message::<TestMessage<i32>>()
307 .add_message::<TestMessage<()>>()
308 .add_systems(Startup, move |mut ev2: MessageWriter<TestMessage<()>>| {
309 ev2.write(TestMessage {
310 sender: tx2.clone(),
311 });
312 })
313 .add_systems(Update, move |mut ev1: MessageWriter<TestMessage<i32>>| {
314 ev1.write(TestMessage {
316 sender: tx1.clone(),
317 });
318 })
319 .add_systems(
320 Update,
321 |mut m1: MessageReader<TestMessage<i32>>,
322 mut m2: MessageReader<TestMessage<()>>| {
323 for _ in m1.read() {}
325 for _ in m2.read() {}
326 },
327 )
328 .insert_resource(TimeUpdateStrategy::ManualDuration(
329 Time::<Fixed>::default().timestep(),
330 ));
331
332 for _ in 0..10 {
333 app.update();
334 }
335
336 let _drop_signal = rx1.try_recv()?;
338 rx2.try_recv()
340 }
341
342 #[test]
343 fn event_update_should_wait_for_fixed_main() {
344 let fixed_update_timestep = Time::<Fixed>::default().timestep();
348 let time_step = fixed_update_timestep / 2 + Duration::from_millis(1);
349
350 fn write_message(mut messages: ResMut<Messages<DummyMessage>>) {
351 messages.write(DummyMessage);
352 }
353
354 let mut app = App::new();
355 app.add_plugins(TimePlugin)
356 .add_message::<DummyMessage>()
357 .init_resource::<FixedUpdateCounter>()
358 .add_systems(Startup, write_message)
359 .add_systems(FixedUpdate, count_fixed_updates)
360 .insert_resource(TimeUpdateStrategy::ManualDuration(time_step));
361
362 for frame in 0..10 {
363 app.update();
364 let fixed_updates_seen = app.world().resource::<FixedUpdateCounter>().0;
365 let messages = app.world().resource::<Messages<DummyMessage>>();
366 let n_total_messages = messages.len();
367 let n_current_messages = messages.iter_current_update_messages().count();
368 let message_registry = app.world().resource::<MessageRegistry>();
369 let should_update = message_registry.should_update;
370
371 println!("Frame {frame}, {fixed_updates_seen} fixed updates seen. Should update: {should_update:?}");
372 println!("Total messages: {n_total_messages} | Current messages: {n_current_messages}",);
373
374 match frame {
375 0 | 1 => {
376 assert_eq!(fixed_updates_seen, 0);
377 assert_eq!(n_total_messages, 1);
378 assert_eq!(n_current_messages, 1);
379 assert_eq!(should_update, ShouldUpdateMessages::Waiting);
380 }
381 2 => {
382 assert_eq!(fixed_updates_seen, 1); assert_eq!(n_total_messages, 1);
384 assert_eq!(n_current_messages, 1);
385 assert_eq!(should_update, ShouldUpdateMessages::Ready); }
387 3 => {
388 assert_eq!(fixed_updates_seen, 1);
389 assert_eq!(n_total_messages, 1);
390 assert_eq!(n_current_messages, 0); assert_eq!(should_update, ShouldUpdateMessages::Waiting);
392 }
393 4 => {
394 assert_eq!(fixed_updates_seen, 2); assert_eq!(n_total_messages, 1);
396 assert_eq!(n_current_messages, 0);
397 assert_eq!(should_update, ShouldUpdateMessages::Ready); }
399 5 => {
400 assert_eq!(fixed_updates_seen, 2);
401 assert_eq!(n_total_messages, 0); assert_eq!(n_current_messages, 0);
403 assert_eq!(should_update, ShouldUpdateMessages::Waiting);
404 }
405 _ => {
406 assert_eq!(n_total_messages, 0); assert_eq!(n_current_messages, 0);
408 }
409 }
410 }
411 }
412}