Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_time/src/lib.rs
9331 views
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")]
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
message::{
42
message_update_system, signal_message_update_system, MessageRegistry, ShouldUpdateMessages,
43
},
44
prelude::*,
45
};
46
use bevy_platform::time::Instant;
47
use core::time::Duration;
48
49
#[cfg(feature = "std")]
50
pub use crossbeam_channel::TrySendError;
51
52
#[cfg(feature = "std")]
53
use crossbeam_channel::{Receiver, Sender};
54
55
/// Adds time functionality to Apps.
56
#[derive(Default)]
57
pub struct TimePlugin;
58
59
/// Updates the elapsed time. Any system that interacts with [`Time`] component should run after
60
/// this.
61
#[derive(Debug, PartialEq, Eq, Clone, Hash, SystemSet)]
62
pub struct TimeSystems;
63
64
impl 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
// Ensure the messages are not dropped until `FixedMain` systems can observe them
92
app.add_systems(FixedPostUpdate, signal_message_update_system);
93
let mut message_registry = app.world_mut().resource_mut::<MessageRegistry>();
94
// We need to start in a waiting state so that the messages are not updated until the first fixed update
95
message_registry.should_update = ShouldUpdateMessages::Waiting;
96
}
97
}
98
99
/// Configuration resource used to determine how the time system should run.
100
///
101
/// For most cases, [`TimeUpdateStrategy::Automatic`] is fine. When writing tests, dealing with
102
/// networking or similar, you may prefer to set the next [`Time`] value manually.
103
#[derive(Resource, Default)]
104
pub enum TimeUpdateStrategy {
105
/// [`Time`] will be automatically updated each frame using an [`Instant`] sent from the render world.
106
/// If nothing is sent, the system clock will be used instead.
107
#[cfg_attr(feature = "std", doc = "See [`TimeSender`] for more details.")]
108
#[default]
109
Automatic,
110
/// [`Time`] will be updated to the specified [`Instant`] value each frame.
111
/// In order for time to progress, this value must be manually updated each frame.
112
///
113
/// Note that the `Time` resource will not be updated until [`TimeSystems`] runs.
114
ManualInstant(Instant),
115
/// [`Time`] will be incremented by the specified [`Duration`] each frame.
116
ManualDuration(Duration),
117
/// [`Time`] will be incremented by the fixed timestep each frame, multiplied by the specified factor `n`.
118
/// This means that a call to [`App::update`] will always run the fixed loop exactly n times.
119
FixedTimesteps(u32),
120
}
121
122
/// Channel resource used to receive time from the render world.
123
#[cfg(feature = "std")]
124
#[derive(Resource)]
125
pub struct TimeReceiver(pub Receiver<Instant>);
126
127
/// Channel resource used to send time from the render world.
128
#[cfg(feature = "std")]
129
#[derive(Resource)]
130
pub struct TimeSender(pub Sender<Instant>);
131
132
/// Creates channels used for sending time between the render world and the main world.
133
#[cfg(feature = "std")]
134
pub fn create_time_channels() -> (TimeSender, TimeReceiver) {
135
// bound the channel to 2 since when pipelined the render phase can finish before
136
// the time system runs.
137
let (s, r) = crossbeam_channel::bounded::<Instant>(2);
138
(TimeSender(s), TimeReceiver(r))
139
}
140
141
/// The system used to update the [`Time`] used by app logic. If there is a render world the time is
142
/// sent from there to this system through channels. Otherwise the time is updated in this system.
143
pub 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
// TODO: Figure out how to handle this when using pipelined rendering.
154
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.")]
188
mod 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
// Set the time step to just over half the fixed update timestep
247
// This way, it will have not accumulated enough time to run the fixed update after one update
248
// But will definitely have enough time after two updates
249
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
// Frame 0
260
// Fixed update should not have run yet
261
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
// Frame 1
268
// Fixed update should not have run yet
269
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
// Frame 2
276
// Fixed update should have run now
277
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
// Frame 3
284
// Fixed update should have run exactly once still
285
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
// Frame 4
292
// Fixed update should have run twice now
293
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
// Keep adding events so this event type is processed every update
315
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
// Read events so they can be dropped
324
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
// Check event type 1 as been dropped at least once
337
let _drop_signal = rx1.try_recv()?;
338
// Check event type 2 has been dropped
339
rx2.try_recv()
340
}
341
342
#[test]
343
fn event_update_should_wait_for_fixed_main() {
344
// Set the time step to just over half the fixed update timestep
345
// This way, it will have not accumulated enough time to run the fixed update after one update
346
// But will definitely have enough time after two updates
347
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); // Time to trigger event updates
383
assert_eq!(n_total_messages, 1);
384
assert_eq!(n_current_messages, 1);
385
assert_eq!(should_update, ShouldUpdateMessages::Ready); // Prepping first update
386
}
387
3 => {
388
assert_eq!(fixed_updates_seen, 1);
389
assert_eq!(n_total_messages, 1);
390
assert_eq!(n_current_messages, 0); // First update has occurred
391
assert_eq!(should_update, ShouldUpdateMessages::Waiting);
392
}
393
4 => {
394
assert_eq!(fixed_updates_seen, 2); // Time to trigger the second update
395
assert_eq!(n_total_messages, 1);
396
assert_eq!(n_current_messages, 0);
397
assert_eq!(should_update, ShouldUpdateMessages::Ready); // Prepping second update
398
}
399
5 => {
400
assert_eq!(fixed_updates_seen, 2);
401
assert_eq!(n_total_messages, 0); // Second update has occurred
402
assert_eq!(n_current_messages, 0);
403
assert_eq!(should_update, ShouldUpdateMessages::Waiting);
404
}
405
_ => {
406
assert_eq!(n_total_messages, 0); // No more events are sent
407
assert_eq!(n_current_messages, 0);
408
}
409
}
410
}
411
}
412
}
413
414