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