mod fixed_timestep;
mod stopwatch;
#[allow(clippy::module_inception)]
mod time;
mod timer;
pub use fixed_timestep::*;
pub use stopwatch::*;
pub use time::*;
pub use timer::*;
use bevy_ecs::system::{Res, ResMut};
use bevy_utils::{tracing::warn, Duration, Instant};
use crossbeam_channel::{Receiver, Sender};
pub mod prelude {
#[doc(hidden)]
pub use crate::{Time, Timer, TimerMode};
}
use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
#[derive(Default)]
pub struct TimePlugin;
#[derive(Debug, PartialEq, Eq, Clone, Hash, SystemLabel)]
pub struct TimeSystem;
impl Plugin for TimePlugin {
fn build(&self, app: &mut App) {
app.init_resource::<Time>()
.init_resource::<TimeUpdateStrategy>()
.init_resource::<FixedTimesteps>()
.register_type::<Timer>()
.register_type::<Time>()
.register_type::<Stopwatch>()
.add_system_to_stage(CoreStage::First, time_system.at_start().label(TimeSystem));
}
}
#[derive(Resource, Default)]
pub enum TimeUpdateStrategy {
#[default]
Automatic,
ManualInstant(Instant),
ManualDuration(Duration),
}
#[derive(Resource)]
pub struct TimeReceiver(pub Receiver<Instant>);
#[derive(Resource)]
pub struct TimeSender(pub Sender<Instant>);
pub fn create_time_channels() -> (TimeSender, TimeReceiver) {
let (s, r) = crossbeam_channel::bounded::<Instant>(2);
(TimeSender(s), TimeReceiver(r))
}
fn time_system(
mut time: ResMut<Time>,
update_strategy: Res<TimeUpdateStrategy>,
time_recv: Option<Res<TimeReceiver>>,
mut has_received_time: Local<bool>,
) {
let new_time = if let Some(time_recv) = time_recv {
if let Ok(new_time) = time_recv.0.try_recv() {
*has_received_time = true;
new_time
} else {
if *has_received_time {
warn!("time_system did not receive the time from the render world! Calculations depending on the time may be incorrect.");
}
Instant::now()
}
} else {
Instant::now()
};
match update_strategy.as_ref() {
TimeUpdateStrategy::Automatic => time.update_with_instant(new_time),
TimeUpdateStrategy::ManualInstant(instant) => time.update_with_instant(*instant),
TimeUpdateStrategy::ManualDuration(duration) => {
time.update_with_instant(Instant::now() + *duration);
}
}
}