Struct Time

Source
pub struct Time<T = ()>
where T: Default,
{ /* private fields */ }
Expand description

A generic clock resource that tracks how much it has advanced since its previous update and since its creation.

Multiple instances of this resource are inserted automatically by TimePlugin:

  • Time<Real> tracks real wall-clock time elapsed.
  • Time<Virtual> tracks virtual game time that may be paused or scaled.
  • Time<Fixed> tracks fixed timesteps based on virtual time.
  • Time is a generic clock that corresponds to “current” or “default” time for systems. It contains Time<Virtual> except inside the FixedMain schedule when it contains Time<Fixed>.

The time elapsed since the previous time this clock was advanced is saved as delta() and the total amount of time the clock has advanced is saved as elapsed(). Both are represented as exact Duration values with fixed nanosecond precision. The clock does not support time moving backwards, but it can be updated with Duration::ZERO which will set delta() to zero.

These values are also available in seconds as f32 via delta_secs() and elapsed_secs(), and also in seconds as f64 via delta_secs_f64() and elapsed_secs_f64().

Since elapsed_secs() will grow constantly and is f32, it will exhibit gradual precision loss. For applications that require an f32 value but suffer from gradual precision loss there is elapsed_secs_wrapped() available. The same wrapped value is also available as Duration and f64 for consistency. The wrap period is by default 1 hour, and can be set by set_wrap_period().

§Accessing clocks

By default, any systems requiring current delta() or elapsed() should use Res<Time> to access the default time configured for the program. By default, this refers to Time<Virtual> except during the FixedMain schedule when it refers to Time<Fixed>. This ensures your system can be used either in Update or FixedUpdate schedule depending on what is needed.

fn ambivalent_system(time: Res<Time>) {
    println!("this how I see time: delta {:?}, elapsed {:?}", time.delta(), time.elapsed());
}

If your system needs to react based on real time (wall clock time), like for user interfaces, it should use Res<Time<Real>>. The delta() and elapsed() values will always correspond to real time and will not be affected by pause, time scaling or other tweaks.

fn real_time_system(time: Res<Time<Real>>) {
    println!("this will always be real time: delta {:?}, elapsed {:?}", time.delta(), time.elapsed());
}

If your system specifically needs to access fixed timestep clock, even when placed in Update schedule, you should use Res<Time<Fixed>>. The delta() and elapsed() values will correspond to the latest fixed timestep that has been run.

fn fixed_time_system(time: Res<Time<Fixed>>) {
    println!("this will always be the last executed fixed timestep: delta {:?}, elapsed {:?}", time.delta(), time.elapsed());
}

Finally, if your system specifically needs to know the current virtual game time, even if placed inside FixedUpdate, for example to know if the game is was_paused() or to use effective_speed(), you can use Res<Time<Virtual>>. However, if the system is placed in FixedUpdate, extra care must be used because your system might be run multiple times with the same delta() and elapsed() values as the virtual game time has not changed between the iterations.

fn fixed_time_system(time: Res<Time<Virtual>>) {
    println!("this will be virtual time for this update: delta {:?}, elapsed {:?}", time.delta(), time.elapsed());
    println!("also the relative speed of the game is now {}", time.effective_speed());
}

If you need to change the settings for any of the clocks, for example to pause() the game, you should use ResMut<Time<Virtual>>.

#[derive(Event)]
struct PauseEvent(bool);

fn pause_system(mut time: ResMut<Time<Virtual>>, mut events: EventReader<PauseEvent>) {
    for ev in events.read() {
        if ev.0 {
            time.pause();
        } else {
            time.unpause();
        }
    }
}

§Adding custom clocks

New custom clocks can be created by creating your own struct as a context and passing it to new_with(). These clocks can be inserted as resources as normal and then accessed by systems. You can use the advance_by() or advance_to() methods to move the clock forwards based on your own logic.

If you want to add methods for your time instance and they require access to both your context and the generic time part, it’s probably simplest to add a custom trait for them and implement it for Time<Custom>.

Your context struct will need to implement the Default trait because Time structures support reflection. It also makes initialization trivial by being able to call app.init_resource::<Time<Custom>>().

You can also replace the “generic” Time clock resource if the “default” time for your game should not be the default virtual time provided. You can get a “generic” snapshot of your clock by calling as_generic() and then overwrite the Time resource with it. The default systems added by TimePlugin will overwrite the Time clock during First and FixedUpdate schedules.

#[derive(Debug)]
struct Custom {
    last_external_time: Instant,
}

impl Default for Custom {
    fn default() -> Self {
        Self {
            last_external_time: Instant::now(),
        }
    }
}

trait CustomTime {
    fn update_from_external(&mut self, instant: Instant);
}

impl CustomTime for Time<Custom> {
    fn update_from_external(&mut self, instant: Instant) {
         let delta = instant - self.context().last_external_time;
         self.advance_by(delta);
         self.context_mut().last_external_time = instant;
    }
}

Implementations§

Source§

impl Time<Fixed>

Source

pub fn from_duration(timestep: Duration) -> Time<Fixed>

Return new fixed time clock with given timestep as Duration

§Panics

Panics if timestep is zero.

Examples found in repository?
examples/time/time.rs (line 115)
111fn main() {
112    App::new()
113        .add_plugins(MinimalPlugins)
114        .insert_resource(Time::<Virtual>::from_max_delta(Duration::from_secs(5)))
115        .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs(1)))
116        .add_systems(PreUpdate, print_real_time)
117        .add_systems(FixedUpdate, print_fixed_time)
118        .add_systems(Update, print_time)
119        .set_runner(runner)
120        .run();
121}
More examples
Hide additional examples
examples/stress_tests/bevymark.rs (lines 168-170)
126fn main() {
127    // `from_env` panics on the web
128    #[cfg(not(target_arch = "wasm32"))]
129    let args: Args = argh::from_env();
130    #[cfg(target_arch = "wasm32")]
131    let args = Args::from_args(&[], &[]).unwrap();
132
133    App::new()
134        .add_plugins((
135            DefaultPlugins.set(WindowPlugin {
136                primary_window: Some(Window {
137                    title: "BevyMark".into(),
138                    resolution: WindowResolution::new(1920.0, 1080.0)
139                        .with_scale_factor_override(1.0),
140                    present_mode: PresentMode::AutoNoVsync,
141                    ..default()
142                }),
143                ..default()
144            }),
145            FrameTimeDiagnosticsPlugin::default(),
146            LogDiagnosticsPlugin::default(),
147        ))
148        .insert_resource(WinitSettings {
149            focused_mode: UpdateMode::Continuous,
150            unfocused_mode: UpdateMode::Continuous,
151        })
152        .insert_resource(args)
153        .insert_resource(BevyCounter {
154            count: 0,
155            color: Color::WHITE,
156        })
157        .add_systems(Startup, setup)
158        .add_systems(FixedUpdate, scheduled_spawner)
159        .add_systems(
160            Update,
161            (
162                mouse_handler,
163                movement_system,
164                collision_system,
165                counter_system,
166            ),
167        )
168        .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs_f32(
169            FIXED_TIMESTEP,
170        )))
171        .run();
172}
Source

pub fn from_seconds(seconds: f64) -> Time<Fixed>

Return new fixed time clock with given timestep seconds as f64

§Panics

Panics if seconds is zero, negative or not finite.

Examples found in repository?
examples/async_tasks/external_source_external_thread.rs (line 16)
9fn main() {
10    App::new()
11        .add_event::<StreamEvent>()
12        .add_plugins(DefaultPlugins)
13        .add_systems(Startup, setup)
14        .add_systems(Update, (spawn_text, move_text))
15        .add_systems(FixedUpdate, read_stream)
16        .insert_resource(Time::<Fixed>::from_seconds(0.5))
17        .run();
18}
More examples
Hide additional examples
examples/ecs/fixed_timestep.rs (line 13)
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        // this system will run once every update (it should match your screen's refresh rate)
9        .add_systems(Update, frame_update)
10        // add our system to the fixed timestep schedule
11        .add_systems(FixedUpdate, fixed_update)
12        // configure our fixed timestep schedule to run twice a second
13        .insert_resource(Time::<Fixed>::from_seconds(0.5))
14        .run();
15}
Source

pub fn from_hz(hz: f64) -> Time<Fixed>

Return new fixed time clock with given timestep frequency in Hertz (1/seconds)

§Panics

Panics if hz is zero, negative or not finite.

Examples found in repository?
examples/2d/rotation.rs (line 10)
7fn main() {
8    App::new()
9        .add_plugins(DefaultPlugins)
10        .insert_resource(Time::<Fixed>::from_hz(60.0))
11        .add_systems(Startup, setup)
12        .add_systems(
13            FixedUpdate,
14            (
15                player_movement_system,
16                snap_to_player_system,
17                rotate_to_player_system,
18            ),
19        )
20        .run();
21}
More examples
Hide additional examples
examples/2d/cpu_draw.rs (line 27)
20fn main() {
21    App::new()
22        .add_plugins(DefaultPlugins)
23        // In this example, we will use a fixed timestep to draw a pattern on the screen
24        // one pixel at a time, so the pattern will gradually emerge over time, and
25        // the speed at which it appears is not tied to the framerate.
26        // Let's make the fixed update very fast, so it doesn't take too long. :)
27        .insert_resource(Time::<Fixed>::from_hz(1024.0))
28        .add_systems(Startup, setup)
29        .add_systems(FixedUpdate, draw)
30        .run();
31}
Source

pub fn timestep(&self) -> Duration

Returns the amount of virtual time that must pass before the fixed timestep schedule is run again.

Examples found in repository?
examples/ecs/iter_combinations.rs (line 81)
38fn generate_bodies(
39    time: Res<Time<Fixed>>,
40    mut commands: Commands,
41    mut meshes: ResMut<Assets<Mesh>>,
42    mut materials: ResMut<Assets<StandardMaterial>>,
43) {
44    let mesh = meshes.add(Sphere::new(1.0).mesh().ico(3).unwrap());
45
46    let color_range = 0.5..1.0;
47    let vel_range = -0.5..0.5;
48
49    // We're seeding the PRNG here to make this example deterministic for testing purposes.
50    // This isn't strictly required in practical use unless you need your app to be deterministic.
51    let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
52    for _ in 0..NUM_BODIES {
53        let radius: f32 = rng.gen_range(0.1..0.7);
54        let mass_value = FloatPow::cubed(radius) * 10.;
55
56        let position = Vec3::new(
57            rng.gen_range(-1.0..1.0),
58            rng.gen_range(-1.0..1.0),
59            rng.gen_range(-1.0..1.0),
60        )
61        .normalize()
62            * ops::cbrt(rng.gen_range(0.2f32..1.0))
63            * 15.;
64
65        commands.spawn((
66            BodyBundle {
67                mesh: Mesh3d(mesh.clone()),
68                material: MeshMaterial3d(materials.add(Color::srgb(
69                    rng.gen_range(color_range.clone()),
70                    rng.gen_range(color_range.clone()),
71                    rng.gen_range(color_range.clone()),
72                ))),
73                mass: Mass(mass_value),
74                acceleration: Acceleration(Vec3::ZERO),
75                last_pos: LastPos(
76                    position
77                        - Vec3::new(
78                            rng.gen_range(vel_range.clone()),
79                            rng.gen_range(vel_range.clone()),
80                            rng.gen_range(vel_range.clone()),
81                        ) * time.timestep().as_secs_f32(),
82                ),
83            },
84            Transform {
85                translation: position,
86                scale: Vec3::splat(radius),
87                ..default()
88            },
89        ));
90    }
91
92    // add bigger "star" body in the center
93    let star_radius = 1.;
94    commands
95        .spawn((
96            BodyBundle {
97                mesh: Mesh3d(meshes.add(Sphere::new(1.0).mesh().ico(5).unwrap())),
98                material: MeshMaterial3d(materials.add(StandardMaterial {
99                    base_color: ORANGE_RED.into(),
100                    emissive: LinearRgba::from(ORANGE_RED) * 2.,
101                    ..default()
102                })),
103
104                mass: Mass(500.0),
105                ..default()
106            },
107            Transform::from_scale(Vec3::splat(star_radius)),
108            Star,
109        ))
110        .with_child(PointLight {
111            color: Color::WHITE,
112            range: 100.0,
113            radius: star_radius,
114            ..default()
115        });
116    commands.spawn((
117        Camera3d::default(),
118        Transform::from_xyz(0.0, 10.5, -30.0).looking_at(Vec3::ZERO, Vec3::Y),
119    ));
120}
Source

pub fn set_timestep(&mut self, timestep: Duration)

Sets the amount of virtual time that must pass before the fixed timestep schedule is run again, as Duration.

Takes effect immediately on the next run of the schedule, respecting what is currently in Self::overstep.

§Panics

Panics if timestep is zero.

Source

pub fn set_timestep_seconds(&mut self, seconds: f64)

Sets the amount of virtual time that must pass before the fixed timestep schedule is run again, as seconds.

Timestep is stored as a Duration, which has fixed nanosecond resolution and will be converted from the floating point number.

Takes effect immediately on the next run of the schedule, respecting what is currently in Self::overstep.

§Panics

Panics if seconds is zero, negative or not finite.

Source

pub fn set_timestep_hz(&mut self, hz: f64)

Sets the amount of virtual time that must pass before the fixed timestep schedule is run again, as frequency.

The timestep value is set to 1 / hz, converted to a Duration which has fixed nanosecond resolution.

Takes effect immediately on the next run of the schedule, respecting what is currently in Self::overstep.

§Panics

Panics if hz is zero, negative or not finite.

Source

pub fn overstep(&self) -> Duration

Returns the amount of overstep time accumulated toward new steps, as Duration.

Examples found in repository?
examples/ecs/fixed_timestep.rs (line 37)
26fn fixed_update(mut last_time: Local<f32>, time: Res<Time>, fixed_time: Res<Time<Fixed>>) {
27    // Default `Time`is `Time<Fixed>` here
28    info!(
29        "time since last fixed_update: {}\n",
30        time.elapsed_secs() - *last_time
31    );
32
33    info!("fixed timestep: {}\n", time.delta_secs());
34    // If we want to see the overstep, we need to access `Time<Fixed>` specifically
35    info!(
36        "time accrued toward next fixed_update: {}\n",
37        fixed_time.overstep().as_secs_f32()
38    );
39    *last_time = time.elapsed_secs();
40}
Source

pub fn discard_overstep(&mut self, discard: Duration)

Discard a part of the overstep amount.

If discard is higher than overstep, the overstep becomes zero.

Source

pub fn overstep_fraction(&self) -> f32

Returns the amount of overstep time accumulated toward new steps, as an f32 fraction of the timestep.

Examples found in repository?
examples/movement/physics_in_fixed_timestep.rs (line 238)
224fn interpolate_rendered_transform(
225    fixed_time: Res<Time<Fixed>>,
226    mut query: Query<(
227        &mut Transform,
228        &PhysicalTranslation,
229        &PreviousPhysicalTranslation,
230    )>,
231) {
232    for (mut transform, current_physical_translation, previous_physical_translation) in
233        query.iter_mut()
234    {
235        let previous = previous_physical_translation.0;
236        let current = current_physical_translation.0;
237        // The overstep fraction is a value between 0 and 1 that tells us how far we are between two fixed timesteps.
238        let alpha = fixed_time.overstep_fraction();
239
240        let rendered_translation = previous.lerp(current, alpha);
241        transform.translation = rendered_translation;
242    }
243}
Source

pub fn overstep_fraction_f64(&self) -> f64

Returns the amount of overstep time accumulated toward new steps, as an f64 fraction of the timestep.

Source§

impl Time<Real>

Source

pub fn new(startup: Instant) -> Time<Real>

Constructs a new Time<Real> instance with a specific startup Instant.

Source

pub fn update(&mut self)

Updates the internal time measurements.

Calling this method as part of your app will most likely result in inaccurate timekeeping, as the Time resource is ordinarily managed by the TimePlugin.

Source

pub fn update_with_duration(&mut self, duration: Duration)

Updates time with a specified Duration.

This method is provided for use in tests.

Calling this method as part of your app will most likely result in inaccurate timekeeping, as the Time resource is ordinarily managed by the TimePlugin.

Source

pub fn update_with_instant(&mut self, instant: Instant)

Updates time with a specified Instant.

This method is provided for use in tests.

Calling this method as part of your app will most likely result in inaccurate timekeeping, as the Time resource is ordinarily managed by the TimePlugin.

Source

pub fn startup(&self) -> Instant

Returns the Instant the clock was created.

This usually represents when the app was started.

Source

pub fn first_update(&self) -> Option<Instant>

Returns the Instant when Self::update was first called, if it exists.

This usually represents when the first app update started.

Source

pub fn last_update(&self) -> Option<Instant>

Returns the Instant when Self::update was last called, if it exists.

This usually represents when the current app update started.

Source§

impl<T> Time<T>
where T: Default,

Source

pub fn new_with(context: T) -> Time<T>

Create a new clock from context with Self::delta and Self::elapsed starting from zero.

Source

pub fn advance_by(&mut self, delta: Duration)

Advance this clock by adding a delta duration to it.

The added duration will be returned by Self::delta and Self::elapsed will be increased by the duration. Adding Duration::ZERO is allowed and will set Self::delta to zero.

Source

pub fn advance_to(&mut self, elapsed: Duration)

Advance this clock to a specific elapsed time.

Self::delta() will return the amount of time the clock was advanced and Self::elapsed() will be the elapsed value passed in. Cannot be used to move time backwards.

§Panics

Panics if elapsed is less than Self::elapsed().

Source

pub fn wrap_period(&self) -> Duration

Returns the modulus used to calculate elapsed_wrapped.

Note: The default modulus is one hour.

Source

pub fn set_wrap_period(&mut self, wrap_period: Duration)

Sets the modulus used to calculate elapsed_wrapped.

Note: This will not take effect until the next update.

§Panics

Panics if wrap_period is a zero-length duration.

Source

pub fn delta(&self) -> Duration

Returns how much time has advanced since the last update, as a Duration.

Examples found in repository?
examples/app/plugin.rs (line 49)
48fn print_message_system(mut state: ResMut<PrintMessageState>, time: Res<Time>) {
49    if state.timer.tick(time.delta()).finished() {
50        info!("{}", state.message);
51    }
52}
More examples
Hide additional examples
examples/time/time.rs (line 90)
87fn print_real_time(time: Res<Time<Real>>) {
88    println!(
89        "PreUpdate: this is real time clock, delta is {:?} and elapsed is {:?}",
90        time.delta(),
91        time.elapsed()
92    );
93}
94
95fn print_fixed_time(time: Res<Time>) {
96    println!(
97        "FixedUpdate: this is generic time clock inside fixed, delta is {:?} and elapsed is {:?}",
98        time.delta(),
99        time.elapsed()
100    );
101}
102
103fn print_time(time: Res<Time>) {
104    println!(
105        "Update: this is generic time clock, delta is {:?} and elapsed is {:?}",
106        time.delta(),
107        time.elapsed()
108    );
109}
examples/stress_tests/many_sprites.rs (line 124)
123fn print_sprite_count(time: Res<Time>, mut timer: Local<PrintingTimer>, sprites: Query<&Sprite>) {
124    timer.tick(time.delta());
125
126    if timer.just_finished() {
127        info!("Sprites: {}", sprites.iter().count());
128    }
129}
examples/stress_tests/many_lights.rs (line 146)
145fn print_light_count(time: Res<Time>, mut timer: Local<PrintingTimer>, lights: Query<&PointLight>) {
146    timer.0.tick(time.delta());
147
148    if timer.0.just_finished() {
149        info!("Lights: {}", lights.iter().len());
150    }
151}
152
153struct LogVisibleLights;
154
155impl Plugin for LogVisibleLights {
156    fn build(&self, app: &mut App) {
157        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
158            return;
159        };
160
161        render_app.add_systems(Render, print_visible_light_count.in_set(RenderSet::Prepare));
162    }
163}
164
165// System for printing the number of meshes on every tick of the timer
166fn print_visible_light_count(
167    time: Res<Time>,
168    mut timer: Local<PrintingTimer>,
169    visible: Query<&ExtractedPointLight>,
170    global_light_meta: Res<GlobalClusterableObjectMeta>,
171) {
172    timer.0.tick(time.delta());
173
174    if timer.0.just_finished() {
175        info!(
176            "Visible Lights: {}, Rendered Lights: {}",
177            visible.iter().len(),
178            global_light_meta.entity_to_index.len()
179        );
180    }
181}
examples/ecs/generic_system.rs (line 68)
66fn print_text_system(time: Res<Time>, mut query: Query<(&mut PrinterTick, &TextToPrint)>) {
67    for (mut timer, text) in &mut query {
68        if timer.tick(time.delta()).just_finished() {
69            info!("{}", text.0);
70        }
71    }
72}
examples/time/timers.rs (line 50)
48fn print_when_completed(time: Res<Time>, mut query: Query<&mut PrintOnCompletionTimer>) {
49    for mut timer in &mut query {
50        if timer.tick(time.delta()).just_finished() {
51            info!("Entity timer just finished");
52        }
53    }
54}
55
56/// This system controls ticking the timer within the countdown resource and
57/// handling its state.
58fn countdown(time: Res<Time>, mut countdown: ResMut<Countdown>) {
59    countdown.main_timer.tick(time.delta());
60
61    // The API encourages this kind of timer state checking (if you're only checking for one value)
62    // Additionally, `finished()` would accomplish the same thing as `just_finished` due to the
63    // timer being repeating, however this makes more sense visually.
64    if countdown.percent_trigger.tick(time.delta()).just_finished() {
65        if !countdown.main_timer.finished() {
66            // Print the percent complete the main timer is.
67            info!(
68                "Timer is {:0.0}% complete!",
69                countdown.main_timer.fraction() * 100.0
70            );
71        } else {
72            // The timer has finished so we pause the percent output timer
73            countdown.percent_trigger.pause();
74            info!("Paused percent trigger timer");
75        }
76    }
77}
Source

pub fn delta_secs(&self) -> f32

Returns how much time has advanced since the last update, as f32 seconds.

Examples found in repository?
examples/shader/extended_material.rs (line 68)
66fn rotate_things(mut q: Query<&mut Transform, With<Rotate>>, time: Res<Time>) {
67    for mut t in &mut q {
68        t.rotate_y(time.delta_secs());
69    }
70}
More examples
Hide additional examples
examples/3d/3d_shapes.rs (line 149)
147fn rotate(mut query: Query<&mut Transform, With<Shape>>, time: Res<Time>) {
148    for mut transform in &mut query {
149        transform.rotate_y(time.delta_secs() / 2.);
150    }
151}
examples/picking/mesh_picking.rs (line 188)
186fn rotate(mut query: Query<&mut Transform, With<Shape>>, time: Res<Time>) {
187    for mut transform in &mut query {
188        transform.rotate_y(time.delta_secs() / 2.);
189    }
190}
examples/gizmos/light_gizmos.rs (line 140)
139fn rotate_camera(mut transform: Single<&mut Transform, With<Camera>>, time: Res<Time>) {
140    transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(time.delta_secs() / 2.));
141}
142
143fn update_config(
144    mut config_store: ResMut<GizmoConfigStore>,
145    keyboard: Res<ButtonInput<KeyCode>>,
146    time: Res<Time>,
147    color_text_query: Single<Entity, With<GizmoColorText>>,
148    mut writer: TextUiWriter,
149) {
150    if keyboard.just_pressed(KeyCode::KeyD) {
151        for (_, config, _) in config_store.iter_mut() {
152            config.depth_bias = if config.depth_bias == 0. { -1. } else { 0. };
153        }
154    }
155
156    let (config, light_config) = config_store.config_mut::<LightGizmoConfigGroup>();
157    if keyboard.pressed(KeyCode::ArrowRight) {
158        config.line.width += 5. * time.delta_secs();
159        config.line.width = config.line.width.clamp(0., 50.);
160    }
161    if keyboard.pressed(KeyCode::ArrowLeft) {
162        config.line.width -= 5. * time.delta_secs();
163        config.line.width = config.line.width.clamp(0., 50.);
164    }
165    if keyboard.just_pressed(KeyCode::KeyA) {
166        config.enabled ^= true;
167    }
168    if keyboard.just_pressed(KeyCode::KeyC) {
169        light_config.color = match light_config.color {
170            LightGizmoColor::Manual(_) => LightGizmoColor::Varied,
171            LightGizmoColor::Varied => LightGizmoColor::MatchLightColor,
172            LightGizmoColor::MatchLightColor => LightGizmoColor::ByLightType,
173            LightGizmoColor::ByLightType => LightGizmoColor::Manual(GRAY.into()),
174        };
175        *writer.text(*color_text_query, 1) = gizmo_color_text(light_config);
176    }
177}
examples/3d/parenting.rs (line 21)
19fn rotator_system(time: Res<Time>, mut query: Query<&mut Transform, With<Rotator>>) {
20    for mut transform in &mut query {
21        transform.rotate_x(3.0 * time.delta_secs());
22    }
23}
examples/3d/atmosphere.rs (line 124)
122fn dynamic_scene(mut suns: Query<&mut Transform, With<DirectionalLight>>, time: Res<Time>) {
123    suns.iter_mut()
124        .for_each(|mut tf| tf.rotate_x(-time.delta_secs() * PI / 10.0));
125}
Source

pub fn delta_secs_f64(&self) -> f64

Returns how much time has advanced since the last update, as f64 seconds.

Examples found in repository?
examples/stress_tests/bevymark.rs (line 352)
325fn mouse_handler(
326    mut commands: Commands,
327    args: Res<Args>,
328    time: Res<Time>,
329    mouse_button_input: Res<ButtonInput<MouseButton>>,
330    window: Query<&Window>,
331    bird_resources: ResMut<BirdResources>,
332    mut counter: ResMut<BevyCounter>,
333    mut rng: Local<Option<ChaCha8Rng>>,
334    mut wave: Local<usize>,
335) {
336    let Ok(window) = window.single() else {
337        return;
338    };
339
340    if rng.is_none() {
341        // We're seeding the PRNG here to make this example deterministic for testing purposes.
342        // This isn't strictly required in practical use unless you need your app to be deterministic.
343        *rng = Some(ChaCha8Rng::seed_from_u64(42));
344    }
345    let rng = rng.as_mut().unwrap();
346
347    if mouse_button_input.just_released(MouseButton::Left) {
348        counter.color = Color::linear_rgb(rng.r#gen(), rng.r#gen(), rng.r#gen());
349    }
350
351    if mouse_button_input.pressed(MouseButton::Left) {
352        let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_secs_f64()) as usize;
353        spawn_birds(
354            &mut commands,
355            args.into_inner(),
356            &window.resolution,
357            &mut counter,
358            spawn_count,
359            bird_resources.into_inner(),
360            None,
361            *wave,
362        );
363        *wave += 1;
364    }
365}
More examples
Hide additional examples
examples/ui/text_debug.rs (line 275)
248fn change_text_system(
249    mut fps_history: Local<VecDeque<f64>>,
250    mut time_history: Local<VecDeque<Duration>>,
251    time: Res<Time>,
252    diagnostics: Res<DiagnosticsStore>,
253    query: Query<Entity, With<TextChanges>>,
254    mut writer: TextUiWriter,
255) {
256    time_history.push_front(time.elapsed());
257    time_history.truncate(120);
258    let avg_fps = (time_history.len() as f64)
259        / (time_history.front().copied().unwrap_or_default()
260            - time_history.back().copied().unwrap_or_default())
261        .as_secs_f64()
262        .max(0.0001);
263    fps_history.push_front(avg_fps);
264    fps_history.truncate(120);
265    let fps_variance = std_deviation(fps_history.make_contiguous()).unwrap_or_default();
266
267    for entity in &query {
268        let mut fps = 0.0;
269        if let Some(fps_diagnostic) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS) {
270            if let Some(fps_smoothed) = fps_diagnostic.smoothed() {
271                fps = fps_smoothed;
272            }
273        }
274
275        let mut frame_time = time.delta_secs_f64();
276        if let Some(frame_time_diagnostic) =
277            diagnostics.get(&FrameTimeDiagnosticsPlugin::FRAME_TIME)
278        {
279            if let Some(frame_time_smoothed) = frame_time_diagnostic.smoothed() {
280                frame_time = frame_time_smoothed;
281            }
282        }
283
284        *writer.text(entity, 0) =
285            format!("{avg_fps:.1} avg fps, {fps_variance:.1} frametime variance",);
286
287        *writer.text(entity, 1) = format!(
288            "\nThis text changes in the bottom right - {fps:.1} fps, {frame_time:.3} ms/frame",
289        );
290
291        *writer.text(entity, 4) = format!("{fps:.1}");
292
293        *writer.text(entity, 6) = format!("{frame_time:.3}");
294    }
295}
Source

pub fn elapsed(&self) -> Duration

Returns how much time has advanced since startup, as Duration.

Examples found in repository?
examples/window/window_settings.rs (line 127)
124fn change_title(mut window: Single<&mut Window>, time: Res<Time>) {
125    window.title = format!(
126        "Seconds since startup: {}",
127        time.elapsed().as_secs_f32().round()
128    );
129}
More examples
Hide additional examples
examples/time/time.rs (line 91)
87fn print_real_time(time: Res<Time<Real>>) {
88    println!(
89        "PreUpdate: this is real time clock, delta is {:?} and elapsed is {:?}",
90        time.delta(),
91        time.elapsed()
92    );
93}
94
95fn print_fixed_time(time: Res<Time>) {
96    println!(
97        "FixedUpdate: this is generic time clock inside fixed, delta is {:?} and elapsed is {:?}",
98        time.delta(),
99        time.elapsed()
100    );
101}
102
103fn print_time(time: Res<Time>) {
104    println!(
105        "Update: this is generic time clock, delta is {:?} and elapsed is {:?}",
106        time.delta(),
107        time.elapsed()
108    );
109}
examples/scene/scene.rs (line 93)
90    fn from_world(world: &mut World) -> Self {
91        let time = world.resource::<Time>();
92        ComponentB {
93            _time_since_startup: time.elapsed(),
94            value: "Default Value".to_string(),
95        }
96    }
examples/ui/text_debug.rs (line 256)
248fn change_text_system(
249    mut fps_history: Local<VecDeque<f64>>,
250    mut time_history: Local<VecDeque<Duration>>,
251    time: Res<Time>,
252    diagnostics: Res<DiagnosticsStore>,
253    query: Query<Entity, With<TextChanges>>,
254    mut writer: TextUiWriter,
255) {
256    time_history.push_front(time.elapsed());
257    time_history.truncate(120);
258    let avg_fps = (time_history.len() as f64)
259        / (time_history.front().copied().unwrap_or_default()
260            - time_history.back().copied().unwrap_or_default())
261        .as_secs_f64()
262        .max(0.0001);
263    fps_history.push_front(avg_fps);
264    fps_history.truncate(120);
265    let fps_variance = std_deviation(fps_history.make_contiguous()).unwrap_or_default();
266
267    for entity in &query {
268        let mut fps = 0.0;
269        if let Some(fps_diagnostic) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS) {
270            if let Some(fps_smoothed) = fps_diagnostic.smoothed() {
271                fps = fps_smoothed;
272            }
273        }
274
275        let mut frame_time = time.delta_secs_f64();
276        if let Some(frame_time_diagnostic) =
277            diagnostics.get(&FrameTimeDiagnosticsPlugin::FRAME_TIME)
278        {
279            if let Some(frame_time_smoothed) = frame_time_diagnostic.smoothed() {
280                frame_time = frame_time_smoothed;
281            }
282        }
283
284        *writer.text(entity, 0) =
285            format!("{avg_fps:.1} avg fps, {fps_variance:.1} frametime variance",);
286
287        *writer.text(entity, 1) = format!(
288            "\nThis text changes in the bottom right - {fps:.1} fps, {frame_time:.3} ms/frame",
289        );
290
291        *writer.text(entity, 4) = format!("{fps:.1}");
292
293        *writer.text(entity, 6) = format!("{frame_time:.3}");
294    }
295}
Source

pub fn elapsed_secs(&self) -> f32

Returns how much time has advanced since startup, as f32 seconds.

Note: This is a monotonically increasing value. Its precision will degrade over time. If you need an f32 but that precision loss is unacceptable, use elapsed_secs_wrapped.

Examples found in repository?
examples/remote/server.rs (line 80)
78fn move_cube(mut query: Query<&mut Transform, With<Cube>>, time: Res<Time>) {
79    for mut transform in &mut query {
80        transform.translation.y = -cos(time.elapsed_secs()) + 1.5;
81    }
82}
More examples
Hide additional examples
examples/audio/audio_control.rs (line 42)
37fn update_speed(music_controller: Query<&AudioSink, With<MyMusic>>, time: Res<Time>) {
38    let Ok(sink) = music_controller.single() else {
39        return;
40    };
41
42    sink.set_speed((ops::sin(time.elapsed_secs() / 5.0) + 1.0).max(0.1));
43}
examples/shader/extended_material_bindless.rs (line 154)
151fn rotate_sphere(mut meshes: Query<&mut Transform, With<Mesh3d>>, time: Res<Time>) {
152    for mut transform in &mut meshes {
153        transform.rotation =
154            Quat::from_euler(EulerRot::YXZ, -time.elapsed_secs(), FRAC_PI_2 * 3.0, 0.0);
155    }
156}
examples/ecs/fixed_timestep.rs (line 21)
17fn frame_update(mut last_time: Local<f32>, time: Res<Time>) {
18    // Default `Time` is `Time<Virtual>` here
19    info!(
20        "time since last frame_update: {}",
21        time.elapsed_secs() - *last_time
22    );
23    *last_time = time.elapsed_secs();
24}
25
26fn fixed_update(mut last_time: Local<f32>, time: Res<Time>, fixed_time: Res<Time<Fixed>>) {
27    // Default `Time`is `Time<Fixed>` here
28    info!(
29        "time since last fixed_update: {}\n",
30        time.elapsed_secs() - *last_time
31    );
32
33    info!("fixed timestep: {}\n", time.delta_secs());
34    // If we want to see the overstep, we need to access `Time<Fixed>` specifically
35    info!(
36        "time accrued toward next fixed_update: {}\n",
37        fixed_time.overstep().as_secs_f32()
38    );
39    *last_time = time.elapsed_secs();
40}
examples/shader/shader_prepass.rs (line 179)
177fn rotate(mut q: Query<&mut Transform, With<Rotates>>, time: Res<Time>) {
178    for mut t in q.iter_mut() {
179        let rot = (ops::sin(time.elapsed_secs()) * 0.5 + 0.5) * std::f32::consts::PI * 2.0;
180        t.rotation = Quat::from_rotation_z(rot);
181    }
182}
examples/3d/transparency_3d.rs (line 111)
110pub fn fade_transparency(time: Res<Time>, mut materials: ResMut<Assets<StandardMaterial>>) {
111    let alpha = (ops::sin(time.elapsed_secs()) / 2.0) + 0.5;
112    for (_, material) in materials.iter_mut() {
113        material.base_color.set_alpha(alpha);
114    }
115}
Source

pub fn elapsed_secs_f64(&self) -> f64

Returns how much time has advanced since startup, as f64 seconds.

Source

pub fn elapsed_wrapped(&self) -> Duration

Returns how much time has advanced since startup modulo the wrap_period, as Duration.

Source

pub fn elapsed_secs_wrapped(&self) -> f32

Returns how much time has advanced since startup modulo the wrap_period, as f32 seconds.

This method is intended for applications (e.g. shaders) that require an f32 value but suffer from the gradual precision loss of elapsed_secs.

Source

pub fn elapsed_secs_wrapped_f64(&self) -> f64

Returns how much time has advanced since startup modulo the wrap_period, as f64 seconds.

Source

pub fn context(&self) -> &T

Returns a reference to the context of this specific clock.

Source

pub fn context_mut(&mut self) -> &mut T

Returns a mutable reference to the context of this specific clock.

Source

pub fn as_generic(&self) -> Time

Returns a copy of this clock as fully generic clock without context.

Source§

impl Time<Virtual>

Source

pub fn from_max_delta(max_delta: Duration) -> Time<Virtual>

Create new virtual clock with given maximum delta step Duration

§Panics

Panics if max_delta is zero.

Examples found in repository?
examples/time/time.rs (line 114)
111fn main() {
112    App::new()
113        .add_plugins(MinimalPlugins)
114        .insert_resource(Time::<Virtual>::from_max_delta(Duration::from_secs(5)))
115        .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs(1)))
116        .add_systems(PreUpdate, print_real_time)
117        .add_systems(FixedUpdate, print_fixed_time)
118        .add_systems(Update, print_time)
119        .set_runner(runner)
120        .run();
121}
Source

pub fn max_delta(&self) -> Duration

Returns the maximum amount of time that can be added to this clock by a single update, as Duration.

This is the maximum value Self::delta() will return and also to maximum time Self::elapsed() will be increased by in a single update.

This ensures that even if no updates happen for an extended amount of time, the clock will not have a sudden, huge advance all at once. This also indirectly limits the maximum number of fixed update steps that can run in a single update.

The default value is 250 milliseconds.

Source

pub fn set_max_delta(&mut self, max_delta: Duration)

Sets the maximum amount of time that can be added to this clock by a single update, as Duration.

This is the maximum value Self::delta() will return and also to maximum time Self::elapsed() will be increased by in a single update.

This is used to ensure that even if the game freezes for a few seconds, or is suspended for hours or even days, the virtual clock doesn’t suddenly jump forward for that full amount, which would likely cause gameplay bugs or having to suddenly simulate all the intervening time.

If no updates happen for an extended amount of time, this limit prevents having a sudden, huge advance all at once. This also indirectly limits the maximum number of fixed update steps that can run in a single update.

The default value is 250 milliseconds. If you want to disable this feature, set the value to Duration::MAX.

§Panics

Panics if max_delta is zero.

Source

pub fn relative_speed(&self) -> f32

Returns the speed the clock advances relative to your system clock, as f32. This is known as “time scaling” or “time dilation” in other engines.

Examples found in repository?
examples/time/virtual_time.rs (line 158)
157fn change_time_speed<const DELTA: i8>(mut time: ResMut<Time<Virtual>>) {
158    let time_speed = (time.relative_speed() + DELTA as f32)
159        .round()
160        .clamp(0.25, 5.);
161
162    // set the speed of the virtual time to speed it up or slow it down
163    time.set_relative_speed(time_speed);
164}
165
166/// pause or resume `Relative` time
167fn toggle_pause(mut time: ResMut<Time<Virtual>>) {
168    if time.is_paused() {
169        time.unpause();
170    } else {
171        time.pause();
172    }
173}
174
175/// Update the `Real` time info text
176fn update_real_time_info_text(time: Res<Time<Real>>, mut query: Query<&mut Text, With<RealTime>>) {
177    for mut text in &mut query {
178        **text = format!(
179            "REAL TIME\nElapsed: {:.1}\nDelta: {:.5}\n",
180            time.elapsed_secs(),
181            time.delta_secs(),
182        );
183    }
184}
185
186/// Update the `Virtual` time info text
187fn update_virtual_time_info_text(
188    time: Res<Time<Virtual>>,
189    mut query: Query<&mut Text, With<VirtualTime>>,
190) {
191    for mut text in &mut query {
192        **text = format!(
193            "VIRTUAL TIME\nElapsed: {:.1}\nDelta: {:.5}\nSpeed: {:.2}",
194            time.elapsed_secs(),
195            time.delta_secs(),
196            time.relative_speed()
197        );
198    }
199}
Source

pub fn relative_speed_f64(&self) -> f64

Returns the speed the clock advances relative to your system clock, as f64. This is known as “time scaling” or “time dilation” in other engines.

Source

pub fn effective_speed(&self) -> f32

Returns the speed the clock advanced relative to your system clock in this update, as f32.

Returns 0.0 if the game was paused or what the relative_speed value was at the start of this update.

Source

pub fn effective_speed_f64(&self) -> f64

Returns the speed the clock advanced relative to your system clock in this update, as f64.

Returns 0.0 if the game was paused or what the relative_speed value was at the start of this update.

Source

pub fn set_relative_speed(&mut self, ratio: f32)

Sets the speed the clock advances relative to your system clock, given as an f32.

For example, setting this to 2.0 will make the clock advance twice as fast as your system clock.

§Panics

Panics if ratio is negative or not finite.

Examples found in repository?
examples/time/time.rs (line 52)
35fn runner(mut app: App) -> AppExit {
36    banner();
37    help();
38    let stdin = io::stdin();
39    for line in stdin.lock().lines() {
40        if let Err(err) = line {
41            println!("read err: {err:#}");
42            break;
43        }
44        match line.unwrap().as_str() {
45            "" => {
46                app.update();
47            }
48            "f" => {
49                println!("FAST: setting relative speed to 2x");
50                app.world_mut()
51                    .resource_mut::<Time<Virtual>>()
52                    .set_relative_speed(2.0);
53            }
54            "n" => {
55                println!("NORMAL: setting relative speed to 1x");
56                app.world_mut()
57                    .resource_mut::<Time<Virtual>>()
58                    .set_relative_speed(1.0);
59            }
60            "s" => {
61                println!("SLOW: setting relative speed to 0.5x");
62                app.world_mut()
63                    .resource_mut::<Time<Virtual>>()
64                    .set_relative_speed(0.5);
65            }
66            "p" => {
67                println!("PAUSE: pausing virtual clock");
68                app.world_mut().resource_mut::<Time<Virtual>>().pause();
69            }
70            "u" => {
71                println!("UNPAUSE: resuming virtual clock");
72                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
73            }
74            "q" => {
75                println!("QUITTING!");
76                break;
77            }
78            _ => {
79                help();
80            }
81        }
82    }
83
84    AppExit::Success
85}
More examples
Hide additional examples
examples/time/virtual_time.rs (line 46)
43fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut time: ResMut<Time<Virtual>>) {
44    // start with double `Virtual` time resulting in one of the sprites moving at twice the speed
45    // of the other sprite which moves based on `Real` (unscaled) time
46    time.set_relative_speed(2.);
47
48    commands.spawn(Camera2d);
49
50    let virtual_color = GOLD.into();
51    let sprite_scale = Vec2::splat(0.5).extend(1.);
52    let texture_handle = asset_server.load("branding/icon.png");
53
54    // the sprite moving based on real time
55    commands.spawn((
56        Sprite::from_image(texture_handle.clone()),
57        Transform::from_scale(sprite_scale),
58        RealTime,
59    ));
60
61    // the sprite moving based on virtual time
62    commands.spawn((
63        Sprite {
64            image: texture_handle,
65            color: virtual_color,
66            ..Default::default()
67        },
68        Transform {
69            scale: sprite_scale,
70            translation: Vec3::new(0., -160., 0.),
71            ..default()
72        },
73        VirtualTime,
74    ));
75
76    // info UI
77    let font_size = 33.;
78
79    commands.spawn((
80        Node {
81            display: Display::Flex,
82            justify_content: JustifyContent::SpaceBetween,
83            width: Val::Percent(100.),
84            position_type: PositionType::Absolute,
85            top: Val::Px(0.),
86            padding: UiRect::all(Val::Px(20.0)),
87            ..default()
88        },
89        children![
90            (
91                Text::default(),
92                TextFont {
93                    font_size,
94                    ..default()
95                },
96                RealTime,
97            ),
98            (
99                Text::new("CONTROLS\nUn/Pause: Space\nSpeed+: Up\nSpeed-: Down"),
100                TextFont {
101                    font_size,
102                    ..default()
103                },
104                TextColor(Color::srgb(0.85, 0.85, 0.85)),
105                TextLayout::new_with_justify(JustifyText::Center),
106            ),
107            (
108                Text::default(),
109                TextFont {
110                    font_size,
111                    ..default()
112                },
113                TextColor(virtual_color),
114                TextLayout::new_with_justify(JustifyText::Right),
115                VirtualTime,
116            ),
117        ],
118    ));
119}
120
121/// Move sprites using `Real` (unscaled) time
122fn move_real_time_sprites(
123    mut sprite_query: Query<&mut Transform, (With<Sprite>, With<RealTime>)>,
124    // `Real` time which is not scaled or paused
125    time: Res<Time<Real>>,
126) {
127    for mut transform in sprite_query.iter_mut() {
128        // move roughly half the screen in a `Real` second
129        // when the time is scaled the speed is going to change
130        // and the sprite will stay still the time is paused
131        transform.translation.x = get_sprite_translation_x(time.elapsed_secs());
132    }
133}
134
135/// Move sprites using `Virtual` (scaled) time
136fn move_virtual_time_sprites(
137    mut sprite_query: Query<&mut Transform, (With<Sprite>, With<VirtualTime>)>,
138    // the default `Time` is either `Time<Virtual>` in regular systems
139    // or `Time<Fixed>` in fixed timestep systems so `Time::delta()`,
140    // `Time::elapsed()` will return the appropriate values either way
141    time: Res<Time>,
142) {
143    for mut transform in sprite_query.iter_mut() {
144        // move roughly half the screen in a `Virtual` second
145        // when time is scaled using `Time<Virtual>::set_relative_speed` it's going
146        // to move at a different pace and the sprite will stay still when time is
147        // `Time<Virtual>::is_paused()`
148        transform.translation.x = get_sprite_translation_x(time.elapsed_secs());
149    }
150}
151
152fn get_sprite_translation_x(elapsed: f32) -> f32 {
153    ops::sin(elapsed) * 500.
154}
155
156/// Update the speed of `Time<Virtual>.` by `DELTA`
157fn change_time_speed<const DELTA: i8>(mut time: ResMut<Time<Virtual>>) {
158    let time_speed = (time.relative_speed() + DELTA as f32)
159        .round()
160        .clamp(0.25, 5.);
161
162    // set the speed of the virtual time to speed it up or slow it down
163    time.set_relative_speed(time_speed);
164}
Source

pub fn set_relative_speed_f64(&mut self, ratio: f64)

Sets the speed the clock advances relative to your system clock, given as an f64.

For example, setting this to 2.0 will make the clock advance twice as fast as your system clock.

§Panics

Panics if ratio is negative or not finite.

Source

pub fn pause(&mut self)

Stops the clock, preventing it from advancing until resumed.

Examples found in repository?
examples/time/virtual_time.rs (line 171)
167fn toggle_pause(mut time: ResMut<Time<Virtual>>) {
168    if time.is_paused() {
169        time.unpause();
170    } else {
171        time.pause();
172    }
173}
More examples
Hide additional examples
examples/time/time.rs (line 68)
35fn runner(mut app: App) -> AppExit {
36    banner();
37    help();
38    let stdin = io::stdin();
39    for line in stdin.lock().lines() {
40        if let Err(err) = line {
41            println!("read err: {err:#}");
42            break;
43        }
44        match line.unwrap().as_str() {
45            "" => {
46                app.update();
47            }
48            "f" => {
49                println!("FAST: setting relative speed to 2x");
50                app.world_mut()
51                    .resource_mut::<Time<Virtual>>()
52                    .set_relative_speed(2.0);
53            }
54            "n" => {
55                println!("NORMAL: setting relative speed to 1x");
56                app.world_mut()
57                    .resource_mut::<Time<Virtual>>()
58                    .set_relative_speed(1.0);
59            }
60            "s" => {
61                println!("SLOW: setting relative speed to 0.5x");
62                app.world_mut()
63                    .resource_mut::<Time<Virtual>>()
64                    .set_relative_speed(0.5);
65            }
66            "p" => {
67                println!("PAUSE: pausing virtual clock");
68                app.world_mut().resource_mut::<Time<Virtual>>().pause();
69            }
70            "u" => {
71                println!("UNPAUSE: resuming virtual clock");
72                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
73            }
74            "q" => {
75                println!("QUITTING!");
76                break;
77            }
78            _ => {
79                help();
80            }
81        }
82    }
83
84    AppExit::Success
85}
Source

pub fn unpause(&mut self)

Resumes the clock if paused.

Examples found in repository?
examples/time/virtual_time.rs (line 169)
167fn toggle_pause(mut time: ResMut<Time<Virtual>>) {
168    if time.is_paused() {
169        time.unpause();
170    } else {
171        time.pause();
172    }
173}
More examples
Hide additional examples
examples/time/time.rs (line 72)
35fn runner(mut app: App) -> AppExit {
36    banner();
37    help();
38    let stdin = io::stdin();
39    for line in stdin.lock().lines() {
40        if let Err(err) = line {
41            println!("read err: {err:#}");
42            break;
43        }
44        match line.unwrap().as_str() {
45            "" => {
46                app.update();
47            }
48            "f" => {
49                println!("FAST: setting relative speed to 2x");
50                app.world_mut()
51                    .resource_mut::<Time<Virtual>>()
52                    .set_relative_speed(2.0);
53            }
54            "n" => {
55                println!("NORMAL: setting relative speed to 1x");
56                app.world_mut()
57                    .resource_mut::<Time<Virtual>>()
58                    .set_relative_speed(1.0);
59            }
60            "s" => {
61                println!("SLOW: setting relative speed to 0.5x");
62                app.world_mut()
63                    .resource_mut::<Time<Virtual>>()
64                    .set_relative_speed(0.5);
65            }
66            "p" => {
67                println!("PAUSE: pausing virtual clock");
68                app.world_mut().resource_mut::<Time<Virtual>>().pause();
69            }
70            "u" => {
71                println!("UNPAUSE: resuming virtual clock");
72                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
73            }
74            "q" => {
75                println!("QUITTING!");
76                break;
77            }
78            _ => {
79                help();
80            }
81        }
82    }
83
84    AppExit::Success
85}
Source

pub fn is_paused(&self) -> bool

Returns true if the clock is currently paused.

Examples found in repository?
examples/time/virtual_time.rs (line 168)
167fn toggle_pause(mut time: ResMut<Time<Virtual>>) {
168    if time.is_paused() {
169        time.unpause();
170    } else {
171        time.pause();
172    }
173}
Source

pub fn was_paused(&self) -> bool

Returns true if the clock was paused at the start of this update.

Trait Implementations§

Source§

impl<T> Clone for Time<T>
where T: Clone + Default,

Source§

fn clone(&self) -> Time<T>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for Time<T>
where T: Debug + Default,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<T> Default for Time<T>
where T: Default,

Source§

fn default() -> Time<T>

Returns the “default value” for a type. Read more
Source§

impl<T> FromArg for &'static Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

type This<'from_arg> = &'from_arg Time<T>

The type to convert into. Read more
Source§

fn from_arg( arg: Arg<'_>, ) -> Result<<&'static Time<T> as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl<T> FromArg for &'static mut Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

type This<'from_arg> = &'from_arg mut Time<T>

The type to convert into. Read more
Source§

fn from_arg( arg: Arg<'_>, ) -> Result<<&'static mut Time<T> as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl<T> FromArg for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

type This<'from_arg> = Time<T>

The type to convert into. Read more
Source§

fn from_arg(arg: Arg<'_>) -> Result<<Time<T> as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl<T> FromReflect for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<Time<T>>

Constructs a concrete instance of Self from a reflected value.
Source§

fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>

Attempts to downcast the given value to Self using, constructing the value using from_reflect if that fails. Read more
Source§

impl<T> GetOwnership for &Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl<T> GetOwnership for &mut Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl<T> GetOwnership for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl<T> GetTypeRegistration for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn get_type_registration() -> TypeRegistration

Returns the default TypeRegistration for this type.
Source§

fn register_type_dependencies(registry: &mut TypeRegistry)

Registers other types needed by this type. Read more
Source§

impl<T> IntoReturn for &Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where &Time<T>: 'into_return,

Converts Self into a Return value.
Source§

impl<T> IntoReturn for &mut Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where &mut Time<T>: 'into_return,

Converts Self into a Return value.
Source§

impl<T> IntoReturn for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where Time<T>: 'into_return,

Converts Self into a Return value.
Source§

impl<T> PartialReflect for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn get_represented_type_info(&self) -> Option<&'static TypeInfo>

Returns the TypeInfo of the type represented by this value. Read more
Source§

fn try_apply( &mut self, value: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>

Tries to apply a reflected value to this value. Read more
Source§

fn reflect_kind(&self) -> ReflectKind

Returns a zero-sized enumeration of “kinds” of type. Read more
Source§

fn reflect_ref(&self) -> ReflectRef<'_>

Returns an immutable enumeration of “kinds” of type. Read more
Source§

fn reflect_mut(&mut self) -> ReflectMut<'_>

Returns a mutable enumeration of “kinds” of type. Read more
Source§

fn reflect_owned(self: Box<Time<T>>) -> ReflectOwned

Returns an owned enumeration of “kinds” of type. Read more
Source§

fn try_into_reflect( self: Box<Time<T>>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>

Attempts to cast this type to a boxed, fully-reflected value.
Source§

fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>

Attempts to cast this type to a fully-reflected value.
Source§

fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>

Attempts to cast this type to a mutable, fully-reflected value.
Source§

fn into_partial_reflect(self: Box<Time<T>>) -> Box<dyn PartialReflect>

Casts this type to a boxed, reflected value. Read more
Source§

fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)

Casts this type to a reflected value. Read more
Source§

fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)

Casts this type to a mutable, reflected value. Read more
Source§

fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>

Returns a “partial equality” comparison result. Read more
Source§

fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>

Attempts to clone Self using reflection. Read more
Source§

fn apply(&mut self, value: &(dyn PartialReflect + 'static))

Applies a reflected value to this value. Read more
Source§

fn clone_value(&self) -> Box<dyn PartialReflect>

👎Deprecated since 0.16.0: to clone reflected values, prefer using reflect_clone. To convert reflected values to dynamic ones, use to_dynamic.
Clones Self into its dynamic representation. Read more
Source§

fn to_dynamic(&self) -> Box<dyn PartialReflect>

Converts this reflected value into its dynamic representation based on its kind. Read more
Source§

fn reflect_hash(&self) -> Option<u64>

Returns a hash of the value (which includes the type). Read more
Source§

fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Debug formatter for the value. Read more
Source§

fn is_dynamic(&self) -> bool

Indicates whether or not this type is a dynamic type. Read more
Source§

impl<T> Reflect for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn into_any(self: Box<Time<T>>) -> Box<dyn Any>

Returns the value as a Box<dyn Any>. Read more
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Returns the value as a &dyn Any. Read more
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Returns the value as a &mut dyn Any. Read more
Source§

fn into_reflect(self: Box<Time<T>>) -> Box<dyn Reflect>

Casts this type to a boxed, fully-reflected value.
Source§

fn as_reflect(&self) -> &(dyn Reflect + 'static)

Casts this type to a fully-reflected value.
Source§

fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)

Casts this type to a mutable, fully-reflected value.
Source§

fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>

Performs a type-checked assignment of a reflected value to this value. Read more
Source§

impl<T> Struct for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn field(&self, name: &str) -> Option<&(dyn PartialReflect + 'static)>

Returns a reference to the value of the field named name as a &dyn PartialReflect.
Source§

fn field_mut( &mut self, name: &str, ) -> Option<&mut (dyn PartialReflect + 'static)>

Returns a mutable reference to the value of the field named name as a &mut dyn PartialReflect.
Source§

fn field_at(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>

Returns a reference to the value of the field with index index as a &dyn PartialReflect.
Source§

fn field_at_mut( &mut self, index: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>

Returns a mutable reference to the value of the field with index index as a &mut dyn PartialReflect.
Source§

fn name_at(&self, index: usize) -> Option<&str>

Returns the name of the field with index index.
Source§

fn field_len(&self) -> usize

Returns the number of fields in the struct.
Source§

fn iter_fields(&self) -> FieldIter<'_>

Returns an iterator over the values of the reflectable fields for this struct.
Source§

fn to_dynamic_struct(&self) -> DynamicStruct

Source§

fn clone_dynamic(&self) -> DynamicStruct

👎Deprecated since 0.16.0: use to_dynamic_struct instead
Clones the struct into a DynamicStruct.
Source§

fn get_represented_struct_info(&self) -> Option<&'static StructInfo>

Will return None if TypeInfo is not available.
Source§

impl<T> TypePath for Time<T>
where T: Default + TypePath, Time<T>: Any + Send + Sync,

Source§

fn type_path() -> &'static str

Returns the fully qualified path of the underlying type. Read more
Source§

fn short_type_path() -> &'static str

Returns a short, pretty-print enabled path to the type. Read more
Source§

fn type_ident() -> Option<&'static str>

Returns the name of the type, or None if it is anonymous. Read more
Source§

fn crate_name() -> Option<&'static str>

Returns the name of the crate the type is in, or None if it is anonymous. Read more
Source§

fn module_path() -> Option<&'static str>

Returns the path to the module the type is in, or None if it is anonymous. Read more
Source§

impl<T> Typed for Time<T>
where T: Default + TypePath + FromReflect + MaybeTyped + RegisterForReflection, Time<T>: Any + Send + Sync, Duration: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f32: FromReflect + TypePath + MaybeTyped + RegisterForReflection, f64: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn type_info() -> &'static TypeInfo

Returns the compile-time info for the underlying type.
Source§

impl<T> Copy for Time<T>
where T: Copy + Default,

Source§

impl<T> Resource for Time<T>
where T: Default, Time<T>: Send + Sync + 'static,

Auto Trait Implementations§

§

impl<T> Freeze for Time<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for Time<T>
where T: RefUnwindSafe,

§

impl<T> Send for Time<T>
where T: Send,

§

impl<T> Sync for Time<T>
where T: Sync,

§

impl<T> Unpin for Time<T>
where T: Unpin,

§

impl<T> UnwindSafe for Time<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

Source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DynamicTypePath for T
where T: TypePath,

Source§

impl<T> DynamicTyped for T
where T: Typed,

Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> FromWorld for T
where T: Default,

Source§

fn from_world(_world: &mut World) -> T

Creates Self using default().

Source§

impl<S> GetField for S
where S: Struct,

Source§

fn get_field<T>(&self, name: &str) -> Option<&T>
where T: Reflect,

Returns a reference to the value of the field named name, downcast to T.
Source§

fn get_field_mut<T>(&mut self, name: &str) -> Option<&mut T>
where T: Reflect,

Returns a mutable reference to the value of the field named name, downcast to T.
Source§

impl<T> GetPath for T
where T: Reflect + ?Sized,

Source§

fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a reference to the value specified by path. Read more
Source§

fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a mutable reference to the value specified by path. Read more
Source§

fn path<'p, T>( &self, path: impl ReflectPath<'p>, ) -> Result<&T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed reference to the value specified by path. Read more
Source§

fn path_mut<'p, T>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed mutable reference to the value specified by path. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> NoneValue for T
where T: Default,

Source§

type NoneType = T

Source§

fn null_value() -> T

The none-equivalent value.
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> TypeData for T
where T: 'static + Send + Sync + Clone,

Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> Reflectable for T

Source§

impl<T> Settings for T
where T: 'static + Send + Sync,

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,