use bevy_app::FixedMain;1use bevy_ecs::world::World;2#[cfg(feature = "bevy_reflect")]3use bevy_reflect::Reflect;4use core::time::Duration;56use crate::{time::Time, virt::Virtual};78/// The fixed timestep game clock following virtual time.9///10/// A specialization of the [`Time`] structure. **For method documentation, see11/// [`Time<Fixed>#impl-Time<Fixed>`].**12///13/// It is automatically inserted as a resource by14/// [`TimePlugin`](crate::TimePlugin) and updated based on15/// [`Time<Virtual>`](Virtual). The fixed clock is automatically set as the16/// generic [`Time`] resource during [`FixedUpdate`](bevy_app::FixedUpdate)17/// schedule processing.18///19/// The fixed timestep clock advances in fixed-size increments, which is20/// extremely useful for writing logic (like physics) that should have21/// consistent behavior, regardless of framerate.22///23/// The default [`timestep()`](Time::timestep) is 64 hertz, or 1562524/// microseconds. This value was chosen because using 60 hertz has the potential25/// for a pathological interaction with the monitor refresh rate where the game26/// alternates between running two fixed timesteps and zero fixed timesteps per27/// frame (for example when running two fixed timesteps takes longer than a28/// frame). Additionally, the value is a power of two which losslessly converts29/// into [`f32`] and [`f64`].30///31/// To run a system on a fixed timestep, add it to one of the [`FixedMain`]32/// schedules, most commonly [`FixedUpdate`](bevy_app::FixedUpdate).33///34/// This schedule is run a number of times between35/// [`PreUpdate`](bevy_app::PreUpdate) and [`Update`](bevy_app::Update)36/// according to the accumulated [`overstep()`](Time::overstep) time divided by37/// the [`timestep()`](Time::timestep). This means the schedule may run 0, 1 or38/// more times during a single update (which typically corresponds to a rendered39/// frame).40///41/// `Time<Fixed>` and the generic [`Time`] resource will report a42/// [`delta()`](Time::delta) equal to [`timestep()`](Time::timestep) and always43/// grow [`elapsed()`](Time::elapsed) by one [`timestep()`](Time::timestep) per44/// iteration.45///46/// The fixed timestep clock follows the [`Time<Virtual>`](Virtual) clock, which47/// means it is affected by [`pause()`](Time::pause),48/// [`set_relative_speed()`](Time::set_relative_speed) and49/// [`set_max_delta()`](Time::set_max_delta) from virtual time. If the virtual50/// clock is paused, the [`FixedUpdate`](bevy_app::FixedUpdate) schedule will51/// not run. It is guaranteed that the [`elapsed()`](Time::elapsed) time in52/// `Time<Fixed>` is always between the previous `elapsed()` and the current53/// `elapsed()` value in `Time<Virtual>`, so the values are compatible.54///55/// Changing the timestep size while the game is running should not normally be56/// done, as having a regular interval is the point of this schedule, but it may57/// be necessary for effects like "bullet-time" if the normal granularity of the58/// fixed timestep is too big for the slowed down time. In this case,59/// [`set_timestep()`](Time::set_timestep) and be called to set a new value. The60/// new value will be used immediately for the next run of the61/// [`FixedUpdate`](bevy_app::FixedUpdate) schedule, meaning that it will affect62/// the [`delta()`](Time::delta) value for the very next63/// [`FixedUpdate`](bevy_app::FixedUpdate), even if it is still during the same64/// frame. Any [`overstep()`](Time::overstep) present in the accumulator will be65/// processed according to the new [`timestep()`](Time::timestep) value.66#[derive(Debug, Copy, Clone)]67#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Clone))]68pub struct Fixed {69timestep: Duration,70overstep: Duration,71}7273impl Time<Fixed> {74/// Corresponds to 64 Hz.75const DEFAULT_TIMESTEP: Duration = Duration::from_micros(15625);7677/// Return new fixed time clock with given timestep as [`Duration`]78///79/// # Panics80///81/// Panics if `timestep` is zero.82pub fn from_duration(timestep: Duration) -> Self {83let mut ret = Self::default();84ret.set_timestep(timestep);85ret86}8788/// Return new fixed time clock with given timestep seconds as `f64`89///90/// # Panics91///92/// Panics if `seconds` is zero, negative or not finite.93pub fn from_seconds(seconds: f64) -> Self {94let mut ret = Self::default();95ret.set_timestep_seconds(seconds);96ret97}9899/// Return new fixed time clock with given timestep frequency in Hertz (1/seconds)100///101/// # Panics102///103/// Panics if `hz` is zero, negative or not finite.104pub fn from_hz(hz: f64) -> Self {105let mut ret = Self::default();106ret.set_timestep_hz(hz);107ret108}109110/// Returns the amount of virtual time that must pass before the fixed111/// timestep schedule is run again.112#[inline]113pub fn timestep(&self) -> Duration {114self.context().timestep115}116117/// Sets the amount of virtual time that must pass before the fixed timestep118/// schedule is run again, as [`Duration`].119///120/// Takes effect immediately on the next run of the schedule, respecting121/// what is currently in [`Self::overstep`].122///123/// # Panics124///125/// Panics if `timestep` is zero.126#[inline]127pub fn set_timestep(&mut self, timestep: Duration) {128assert_ne!(129timestep,130Duration::ZERO,131"attempted to set fixed timestep to zero"132);133self.context_mut().timestep = timestep;134}135136/// Sets the amount of virtual time that must pass before the fixed timestep137/// schedule is run again, as seconds.138///139/// Timestep is stored as a [`Duration`], which has fixed nanosecond140/// resolution and will be converted from the floating point number.141///142/// Takes effect immediately on the next run of the schedule, respecting143/// what is currently in [`Self::overstep`].144///145/// # Panics146///147/// Panics if `seconds` is zero, negative or not finite.148#[inline]149pub fn set_timestep_seconds(&mut self, seconds: f64) {150assert!(151seconds.is_sign_positive(),152"seconds less than or equal to zero"153);154assert!(seconds.is_finite(), "seconds is infinite");155self.set_timestep(Duration::from_secs_f64(seconds));156}157158/// Sets the amount of virtual time that must pass before the fixed timestep159/// schedule is run again, as frequency.160///161/// The timestep value is set to `1 / hz`, converted to a [`Duration`] which162/// has fixed nanosecond resolution.163///164/// Takes effect immediately on the next run of the schedule, respecting165/// what is currently in [`Self::overstep`].166///167/// # Panics168///169/// Panics if `hz` is zero, negative or not finite.170#[inline]171pub fn set_timestep_hz(&mut self, hz: f64) {172assert!(hz.is_sign_positive(), "Hz less than or equal to zero");173assert!(hz.is_finite(), "Hz is infinite");174self.set_timestep_seconds(1.0 / hz);175}176177/// Returns the amount of overstep time accumulated toward new steps, as178/// [`Duration`].179#[inline]180pub fn overstep(&self) -> Duration {181self.context().overstep182}183184/// Discard a part of the overstep amount.185///186/// If `discard` is higher than overstep, the overstep becomes zero.187#[inline]188pub fn discard_overstep(&mut self, discard: Duration) {189let context = self.context_mut();190context.overstep = context.overstep.saturating_sub(discard);191}192193/// Returns the amount of overstep time accumulated toward new steps, as an194/// [`f32`] fraction of the timestep.195#[inline]196pub fn overstep_fraction(&self) -> f32 {197self.context().overstep.as_secs_f32() / self.context().timestep.as_secs_f32()198}199200/// Returns the amount of overstep time accumulated toward new steps, as an201/// [`f64`] fraction of the timestep.202#[inline]203pub fn overstep_fraction_f64(&self) -> f64 {204self.context().overstep.as_secs_f64() / self.context().timestep.as_secs_f64()205}206207fn accumulate(&mut self, delta: Duration) {208self.context_mut().overstep += delta;209}210211fn expend(&mut self) -> bool {212let timestep = self.timestep();213if let Some(new_value) = self.context_mut().overstep.checked_sub(timestep) {214// reduce accumulated and increase elapsed by period215self.context_mut().overstep = new_value;216self.advance_by(timestep);217true218} else {219// no more periods left in accumulated220false221}222}223}224225impl Default for Fixed {226fn default() -> Self {227Self {228timestep: Time::<Fixed>::DEFAULT_TIMESTEP,229overstep: Duration::ZERO,230}231}232}233234/// Runs [`FixedMain`] zero or more times based on delta of235/// [`Time<Virtual>`](Virtual) and [`Time::overstep`].236/// You can order your systems relative to this by using237/// [`RunFixedMainLoopSystems`](bevy_app::prelude::RunFixedMainLoopSystems).238pub(super) fn run_fixed_main_schedule(world: &mut World) {239let delta = world.resource::<Time<Virtual>>().delta();240world.resource_mut::<Time<Fixed>>().accumulate(delta);241242// Run the schedule until we run out of accumulated time243let _ = world.try_schedule_scope(FixedMain, |world, schedule| {244while world.resource_mut::<Time<Fixed>>().expend() {245*world.resource_mut::<Time>() = world.resource::<Time<Fixed>>().as_generic();246schedule.run(world);247}248});249250*world.resource_mut::<Time>() = world.resource::<Time<Virtual>>().as_generic();251}252253#[cfg(test)]254mod test {255use super::*;256257#[test]258fn test_set_timestep() {259let mut time = Time::<Fixed>::default();260261assert_eq!(time.timestep(), Time::<Fixed>::DEFAULT_TIMESTEP);262263time.set_timestep(Duration::from_millis(500));264assert_eq!(time.timestep(), Duration::from_millis(500));265266time.set_timestep_seconds(0.25);267assert_eq!(time.timestep(), Duration::from_millis(250));268269time.set_timestep_hz(8.0);270assert_eq!(time.timestep(), Duration::from_millis(125));271}272273#[test]274fn test_expend() {275let mut time = Time::<Fixed>::from_seconds(2.0);276277assert_eq!(time.delta(), Duration::ZERO);278assert_eq!(time.elapsed(), Duration::ZERO);279280time.accumulate(Duration::from_secs(1));281282assert_eq!(time.delta(), Duration::ZERO);283assert_eq!(time.elapsed(), Duration::ZERO);284assert_eq!(time.overstep(), Duration::from_secs(1));285assert_eq!(time.overstep_fraction(), 0.5);286assert_eq!(time.overstep_fraction_f64(), 0.5);287288assert!(!time.expend()); // false289290assert_eq!(time.delta(), Duration::ZERO);291assert_eq!(time.elapsed(), Duration::ZERO);292assert_eq!(time.overstep(), Duration::from_secs(1));293assert_eq!(time.overstep_fraction(), 0.5);294assert_eq!(time.overstep_fraction_f64(), 0.5);295296time.accumulate(Duration::from_secs(1));297298assert_eq!(time.delta(), Duration::ZERO);299assert_eq!(time.elapsed(), Duration::ZERO);300assert_eq!(time.overstep(), Duration::from_secs(2));301assert_eq!(time.overstep_fraction(), 1.0);302assert_eq!(time.overstep_fraction_f64(), 1.0);303304assert!(time.expend()); // true305306assert_eq!(time.delta(), Duration::from_secs(2));307assert_eq!(time.elapsed(), Duration::from_secs(2));308assert_eq!(time.overstep(), Duration::ZERO);309assert_eq!(time.overstep_fraction(), 0.0);310assert_eq!(time.overstep_fraction_f64(), 0.0);311312assert!(!time.expend()); // false313314assert_eq!(time.delta(), Duration::from_secs(2));315assert_eq!(time.elapsed(), Duration::from_secs(2));316assert_eq!(time.overstep(), Duration::ZERO);317assert_eq!(time.overstep_fraction(), 0.0);318assert_eq!(time.overstep_fraction_f64(), 0.0);319320time.accumulate(Duration::from_secs(1));321322assert_eq!(time.delta(), Duration::from_secs(2));323assert_eq!(time.elapsed(), Duration::from_secs(2));324assert_eq!(time.overstep(), Duration::from_secs(1));325assert_eq!(time.overstep_fraction(), 0.5);326assert_eq!(time.overstep_fraction_f64(), 0.5);327328assert!(!time.expend()); // false329330assert_eq!(time.delta(), Duration::from_secs(2));331assert_eq!(time.elapsed(), Duration::from_secs(2));332assert_eq!(time.overstep(), Duration::from_secs(1));333assert_eq!(time.overstep_fraction(), 0.5);334assert_eq!(time.overstep_fraction_f64(), 0.5);335}336337#[test]338fn test_expend_multiple() {339let mut time = Time::<Fixed>::from_seconds(2.0);340341time.accumulate(Duration::from_secs(7));342assert_eq!(time.overstep(), Duration::from_secs(7));343344assert!(time.expend()); // true345assert_eq!(time.elapsed(), Duration::from_secs(2));346assert_eq!(time.overstep(), Duration::from_secs(5));347348assert!(time.expend()); // true349assert_eq!(time.elapsed(), Duration::from_secs(4));350assert_eq!(time.overstep(), Duration::from_secs(3));351352assert!(time.expend()); // true353assert_eq!(time.elapsed(), Duration::from_secs(6));354assert_eq!(time.overstep(), Duration::from_secs(1));355356assert!(!time.expend()); // false357assert_eq!(time.elapsed(), Duration::from_secs(6));358assert_eq!(time.overstep(), Duration::from_secs(1));359}360}361362363