• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

djeedai / bevy_tweening / 14694529280

27 Apr 2025 05:35PM UTC coverage: 81.978% (-9.4%) from 91.4%
14694529280

push

github

web-flow
Fix CI (#145)

373 of 455 relevant lines covered (81.98%)

307731.03 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.64
/src/tweenable.rs
1
use std::{
2
    ops::{Deref, DerefMut},
3
    time::Duration,
4
};
5

6
use bevy::{ecs::system::SystemId, prelude::*};
7

8
use crate::{EaseMethod, Lens, RepeatCount, RepeatStrategy, TweeningDirection};
9

10
/// The dynamic tweenable type.
11
///
12
/// When creating lists of tweenables, you will need to box them to create a
13
/// homogeneous array like so:
14
/// ```no_run
15
/// # use bevy::prelude::Transform;
16
/// # use bevy_tweening::{BoxedTweenable, Delay, Sequence, Tween};
17
/// #
18
/// # let delay: Delay<Transform> = unimplemented!();
19
/// # let tween: Tween<Transform> = unimplemented!();
20
///
21
/// Sequence::new([Box::new(delay) as BoxedTweenable<Transform>, tween.into()]);
22
/// ```
23
///
24
/// When using your own [`Tweenable`] types, APIs will be easier to use if you
25
/// implement [`From`]:
26
/// ```no_run
27
/// # use std::time::Duration;
28
/// # use bevy::ecs::system::Commands;
29
/// # use bevy::prelude::{Entity, Events, Mut, Transform};
30
/// # use bevy_tweening::{BoxedTweenable, Sequence, Tweenable, TweenCompleted, TweenState, Targetable, TotalDuration};
31
/// #
32
/// # struct MyTweenable;
33
/// # impl Tweenable<Transform> for MyTweenable {
34
/// #     fn duration(&self) -> Duration  { unimplemented!() }
35
/// #     fn total_duration(&self) -> TotalDuration  { unimplemented!() }
36
/// #     fn set_elapsed(&mut self, elapsed: Duration)  { unimplemented!() }
37
/// #     fn elapsed(&self) -> Duration  { unimplemented!() }
38
/// #     fn tick<'a>(&mut self, delta: Duration, target: &'a mut dyn Targetable<Transform>, entity: Entity, events: &mut Mut<Events<TweenCompleted>>, commands: &mut Commands) -> TweenState  { unimplemented!() }
39
/// #     fn rewind(&mut self) { unimplemented!() }
40
/// # }
41
///
42
/// Sequence::new([Box::new(MyTweenable) as BoxedTweenable<_>]);
43
///
44
/// // OR
45
///
46
/// Sequence::new([MyTweenable]);
47
///
48
/// impl From<MyTweenable> for BoxedTweenable<Transform> {
49
///     fn from(t: MyTweenable) -> Self {
50
///         Box::new(t)
51
///     }
52
/// }
53
/// ```
54
pub type BoxedTweenable<T> = Box<dyn Tweenable<T> + 'static>;
55

56
/// Playback state of a [`Tweenable`].
57
///
58
/// This is returned by [`Tweenable::tick()`] to allow the caller to execute
59
/// some logic based on the updated state of the tweenable, like advanding a
60
/// sequence to its next child tweenable.
61
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62
pub enum TweenState {
63
    /// The tweenable is still active, and did not reach its end state yet.
64
    Active,
65
    /// Animation reached its end state. The tweenable is idling at its latest
66
    /// time.
67
    ///
68
    /// Note that [`RepeatCount::Infinite`] tweenables never reach this state.
69
    Completed,
70
}
71

72
/// Event raised when a tween completed.
73
///
74
/// This event is raised when a tween completed. When looping, this is raised
75
/// once per iteration. In case the animation direction changes
76
/// ([`RepeatStrategy::MirroredRepeat`]), an iteration corresponds to a single
77
/// progress from one endpoint to the other, whatever the direction. Therefore a
78
/// complete cycle start -> end -> start counts as 2 iterations and raises 2
79
/// events (one when reaching the end, one when reaching back the start).
80
///
81
/// # Note
82
///
83
/// The semantic is slightly different from [`TweenState::Completed`], which
84
/// indicates that the tweenable has finished ticking and do not need to be
85
/// updated anymore, a state which is never reached for looping animation. Here
86
/// the [`TweenCompleted`] event instead marks the end of a single loop
87
/// iteration.
88
#[derive(Copy, Clone, Event)]
89
pub struct TweenCompleted {
90
    /// The [`Entity`] the tween which completed and its animator are attached
91
    /// to.
92
    pub entity: Entity,
93
    /// An opaque value set by the user when activating event raising, used to
94
    /// identify the particular tween which raised this event. The value is
95
    /// passed unmodified from a call to [`with_completed_event()`]
96
    /// or [`set_completed_event()`].
97
    ///
98
    /// [`with_completed_event()`]: Tween::with_completed_event
99
    /// [`set_completed_event()`]: Tween::set_completed_event
100
    pub user_data: u64,
101
}
102

103
/// Calculate the progress fraction in \[0:1\] of the ratio between two
104
/// [`Duration`]s.
105
fn fraction_progress(n: Duration, d: Duration) -> f32 {
300✔
106
    // TODO - Replace with div_duration_f32() once it's stable
107
    (n.as_secs_f64() / d.as_secs_f64()).fract() as f32
300✔
108
}
109

110
#[derive(Debug)]
111
struct AnimClock {
112
    elapsed: Duration,
113
    duration: Duration,
114
    total_duration: TotalDuration,
115
    strategy: RepeatStrategy,
116
}
117

118
impl AnimClock {
119
    fn new(duration: Duration) -> Self {
52✔
120
        Self {
121
            elapsed: Duration::ZERO,
122
            duration,
123
            total_duration: compute_total_duration(duration, RepeatCount::default()),
52✔
124
            strategy: RepeatStrategy::default(),
52✔
125
        }
126
    }
127

128
    fn tick(&mut self, tick: Duration) -> (TweenState, i32) {
10,000,149✔
129
        self.set_elapsed(self.elapsed.saturating_add(tick))
10,000,149✔
130
    }
131

132
    fn times_completed(&self) -> u32 {
20,000,397✔
133
        (self.elapsed.as_nanos() / self.duration.as_nanos()) as u32
20,000,397✔
134
    }
135

136
    fn set_elapsed(&mut self, elapsed: Duration) -> (TweenState, i32) {
10,000,195✔
137
        let old_times_completed = self.times_completed();
10,000,195✔
138

139
        self.elapsed = elapsed;
10,000,195✔
140

141
        let state = match self.total_duration {
20,000,390✔
142
            TotalDuration::Finite(total_duration) => {
147✔
143
                if self.elapsed >= total_duration {
147✔
144
                    self.elapsed = total_duration;
39✔
145
                    TweenState::Completed
39✔
146
                } else {
147
                    TweenState::Active
108✔
148
                }
149
            }
150
            TotalDuration::Infinite => TweenState::Active,
10,000,048✔
151
        };
152

153
        (
154
            state,
10,000,195✔
155
            self.times_completed() as i32 - old_times_completed as i32,
10,000,195✔
156
        )
157
    }
158

159
    fn elapsed(&self) -> Duration {
489✔
160
        self.elapsed
489✔
161
    }
162

163
    fn state(&self) -> TweenState {
179✔
164
        match self.total_duration {
179✔
165
            TotalDuration::Finite(total_duration) => {
129✔
166
                if self.elapsed >= total_duration {
129✔
167
                    TweenState::Completed
26✔
168
                } else {
169
                    TweenState::Active
103✔
170
                }
171
            }
172
            TotalDuration::Infinite => TweenState::Active,
50✔
173
        }
174
    }
175

176
    fn reset(&mut self) {
31✔
177
        self.elapsed = Duration::ZERO;
31✔
178
    }
179
}
180

181
/// Possibly infinite duration of an animation.
182
///
183
/// Used to measure the total duration of an animation including any looping.
184
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185
pub enum TotalDuration {
186
    /// The duration is finite, of the given value.
187
    Finite(Duration),
188
    /// The duration is infinite.
189
    Infinite,
190
}
191

192
fn compute_total_duration(duration: Duration, count: RepeatCount) -> TotalDuration {
69✔
193
    match count {
69✔
194
        RepeatCount::Finite(times) => TotalDuration::Finite(duration.saturating_mul(times)),
64✔
195
        RepeatCount::For(duration) => TotalDuration::Finite(duration),
1✔
196
        RepeatCount::Infinite => TotalDuration::Infinite,
4✔
197
    }
198
}
199

200
// TODO - Targetable et al. should be replaced with Mut->Mut from Bevy 0.9
201
// https://github.com/bevyengine/bevy/pull/6199
202

203
/// Trait to workaround the discrepancies of the change detection mechanisms of
204
/// assets and components.
205
pub trait Targetable<T> {
206
    /// Dereference the target and return a reference.
207
    fn target(&self) -> &T;
208

209
    /// Dereference the target, triggering any change detection, and return a
210
    /// mutable reference.
211
    fn target_mut(&mut self) -> &mut T;
212
}
213

214
impl<'a, T: 'a> Deref for dyn Targetable<T> + 'a {
215
    type Target = T;
216

217
    fn deref(&self) -> &Self::Target {
×
218
        self.target()
×
219
    }
220
}
221

222
impl<'a, T: 'a> DerefMut for dyn Targetable<T> + 'a {
223
    fn deref_mut(&mut self) -> &mut Self::Target {
214✔
224
        self.target_mut()
214✔
225
    }
226
}
227

228
/// Implementation of [`Targetable`] for a [`Component`].
229
pub struct ComponentTarget<'a, T: Component> {
230
    target: Mut<'a, T>,
231
}
232

233
impl<'a, T: Component> ComponentTarget<'a, T> {
234
    /// Create a new instance from a [`Component`].
235
    pub fn new(target: Mut<'a, T>) -> Self {
223✔
236
        Self { target }
237
    }
238

239
    /// Get a [`Mut`] for the current target.
240
    #[allow(dead_code)] // used mainly in tests
241
    pub fn to_mut(&mut self) -> Mut<'_, T> {
8✔
242
        self.target.reborrow()
8✔
243
    }
244
}
245

246
impl<T: Component> Targetable<T> for ComponentTarget<'_, T> {
247
    fn target(&self) -> &T {
×
248
        self.target.deref()
×
249
    }
250

251
    fn target_mut(&mut self) -> &mut T {
204✔
252
        self.target.deref_mut()
204✔
253
    }
254
}
255

256
/// Implementation of [`Targetable`] for an [`Asset`].
257
#[cfg(feature = "bevy_asset")]
258
pub struct AssetTarget<'a, T: Asset> {
259
    assets: Mut<'a, Assets<T>>,
260
    /// Handle to the asset to mutate.
261
    pub handle: Handle<T>,
262
}
263

264
#[cfg(feature = "bevy_asset")]
265
impl<'a, T: Asset> AssetTarget<'a, T> {
266
    /// Create a new instance from an [`Assets`].
267
    pub fn new(assets: Mut<'a, Assets<T>>) -> Self {
10✔
268
        Self {
269
            assets,
270
            handle: Handle::Weak(AssetId::default()),
10✔
271
        }
272
    }
273

274
    /// Check if the current target is valid given the value of [`handle`].
275
    ///
276
    /// [`handle`]: AssetTarget::handle
277
    pub fn is_valid(&self) -> bool {
×
278
        self.assets.contains(&self.handle)
×
279
    }
280
}
281

282
#[cfg(feature = "bevy_asset")]
283
impl<T: Asset> Targetable<T> for AssetTarget<'_, T> {
284
    fn target(&self) -> &T {
×
285
        self.assets.get(&self.handle).unwrap()
×
286
    }
287

288
    fn target_mut(&mut self) -> &mut T {
10✔
289
        self.assets.get_mut(&self.handle).unwrap()
10✔
290
    }
291
}
292

293
/// An animatable entity, either a single [`Tween`] or a collection of them.
294
pub trait Tweenable<T>: Send + Sync {
295
    /// Get the duration of a single iteration of the animation.
296
    ///
297
    /// Note that for [`RepeatStrategy::MirroredRepeat`], this is the duration
298
    /// of a single way, either from start to end or back from end to start.
299
    /// The total "loop" duration start -> end -> start to reach back the
300
    /// same state in this case is the double of the returned value.
301
    fn duration(&self) -> Duration;
302

303
    /// Get the total duration of the entire animation, including looping.
304
    ///
305
    /// For [`TotalDuration::Finite`], this is the number of repeats times the
306
    /// duration of a single iteration ([`duration()`]).
307
    ///
308
    /// [`duration()`]: Tweenable::duration
309
    fn total_duration(&self) -> TotalDuration;
310

311
    /// Set the current animation playback elapsed time.
312
    ///
313
    /// See [`elapsed()`] for details on the meaning. If `elapsed` is greater
314
    /// than or equal to [`duration()`], then the animation completes.
315
    ///
316
    /// Setting the elapsed time seeks the animation to a new position, but does
317
    /// not apply that change to the underlying component being animated. To
318
    /// force the change to apply, call [`tick()`] with a `delta` of
319
    /// `Duration::ZERO`.
320
    ///
321
    /// [`elapsed()`]: Tweenable::elapsed
322
    /// [`duration()`]: Tweenable::duration
323
    /// [`tick()`]: Tweenable::tick
324
    fn set_elapsed(&mut self, elapsed: Duration);
325

326
    /// Get the current elapsed duration.
327
    ///
328
    /// While looping, the exact value returned by [`duration()`] is never
329
    /// reached, since the tweenable loops over to zero immediately when it
330
    /// changes direction at either endpoint. Upon completion, the tweenable
331
    /// always reports the same value as [`duration()`].
332
    ///
333
    /// [`duration()`]: Tweenable::duration
334
    fn elapsed(&self) -> Duration;
335

336
    /// Tick the animation, advancing it by the given delta time and mutating
337
    /// the given target component or asset.
338
    ///
339
    /// This returns [`TweenState::Active`] if the tweenable didn't reach its
340
    /// final state yet (progress < `1.0`), or [`TweenState::Completed`] if
341
    /// the tweenable completed this tick. Only non-looping tweenables return
342
    /// a completed state, since looping ones continue forever.
343
    ///
344
    /// Calling this method with a duration of [`Duration::ZERO`] is valid, and
345
    /// updates the target to the current state of the tweenable without
346
    /// actually modifying the tweenable state. This is useful after certain
347
    /// operations like [`rewind()`] or [`set_progress()`] whose effect is
348
    /// otherwise only visible on target on next frame.
349
    ///
350
    /// [`rewind()`]: Tweenable::rewind
351
    /// [`set_progress()`]: Tweenable::set_progress
352
    fn tick(
353
        &mut self,
354
        delta: Duration,
355
        target: &mut dyn Targetable<T>,
356
        entity: Entity,
357
        events: &mut Mut<Events<TweenCompleted>>,
358
        commands: &mut Commands,
359
    ) -> TweenState;
360

361
    /// Rewind the animation to its starting state.
362
    ///
363
    /// Note that the starting state depends on the current direction. For
364
    /// [`TweeningDirection::Forward`] this is the start point of the lens,
365
    /// whereas for [`TweeningDirection::Backward`] this is the end one.
366
    fn rewind(&mut self);
367

368
    /// Set the current animation playback progress.
369
    ///
370
    /// See [`progress()`] for details on the meaning.
371
    ///
372
    /// Setting the progress seeks the animation to a new position, but does not
373
    /// apply that change to the underlying component being animated. To
374
    /// force the change to apply, call [`tick()`] with a `delta` of
375
    /// `Duration::ZERO`.
376
    ///
377
    /// [`progress()`]: Tweenable::progress
378
    /// [`tick()`]: Tweenable::tick
379
    fn set_progress(&mut self, progress: f32) {
14✔
380
        self.set_elapsed(self.duration().mul_f32(progress.max(0.)));
14✔
381
    }
382

383
    /// Get the current progress in \[0:1\] of the animation.
384
    ///
385
    /// While looping, the exact value `1.0` is never reached, since the
386
    /// tweenable loops over to `0.0` immediately when it changes direction at
387
    /// either endpoint. Upon completion, the tweenable always reports exactly
388
    /// `1.0`.
389
    fn progress(&self) -> f32 {
332✔
390
        let elapsed = self.elapsed();
332✔
391
        if let TotalDuration::Finite(total_duration) = self.total_duration() {
568✔
392
            if elapsed >= total_duration {
×
393
                return 1.;
32✔
394
            }
395
        }
396
        fraction_progress(elapsed, self.duration())
300✔
397
    }
398

399
    /// Get the number of times this tweenable completed.
400
    ///
401
    /// For looping animations, this returns the number of times a single
402
    /// playback was completed. In the case of
403
    /// [`RepeatStrategy::MirroredRepeat`] this corresponds to a playback in
404
    /// a single direction, so tweening from start to end and back to start
405
    /// counts as two completed times (one forward, one backward).
406
    fn times_completed(&self) -> u32 {
204✔
407
        (self.elapsed().as_nanos() / self.duration().as_nanos()) as u32
204✔
408
    }
409
}
410

411
macro_rules! impl_boxed {
412
    ($tweenable:ty) => {
413
        impl<T: 'static> From<$tweenable> for BoxedTweenable<T> {
414
            fn from(t: $tweenable) -> Self {
13✔
415
                Box::new(t)
13✔
416
            }
417
        }
418
    };
419
}
420

421
impl_boxed!(Tween<T>);
422
impl_boxed!(Sequence<T>);
423
impl_boxed!(Tracks<T>);
424
impl_boxed!(Delay<T>);
425

426
/// Type of a callback invoked when a [`Tween`] or [`Delay`] has completed.
427
///
428
/// See [`Tween::set_completed()`] or [`Delay::set_completed()`] for usage.
429
pub type CompletedCallback<T> = dyn Fn(Entity, &T) + Send + Sync + 'static;
430

431
/// Single tweening animation instance.
432
pub struct Tween<T> {
433
    ease_function: EaseMethod,
434
    clock: AnimClock,
435
    direction: TweeningDirection,
436
    lens: Box<dyn Lens<T> + Send + Sync + 'static>,
437
    on_completed: Option<Box<CompletedCallback<Tween<T>>>>,
438
    event_data: Option<u64>,
439
    system_id: Option<SystemId>,
440
}
441

442
impl<T: 'static> Tween<T> {
443
    /// Chain another [`Tweenable`] after this tween, making a [`Sequence`] with
444
    /// the two.
445
    ///
446
    /// # Example
447
    /// ```
448
    /// # use bevy_tweening::{lens::*, *};
449
    /// # use bevy::math::{*,curve::EaseFunction};
450
    /// # use std::time::Duration;
451
    /// let tween1 = Tween::new(
452
    ///     EaseFunction::QuadraticInOut,
453
    ///     Duration::from_secs(1),
454
    ///     TransformPositionLens {
455
    ///         start: Vec3::ZERO,
456
    ///         end: Vec3::new(3.5, 0., 0.),
457
    ///     },
458
    /// );
459
    /// let tween2 = Tween::new(
460
    ///     EaseFunction::QuadraticInOut,
461
    ///     Duration::from_secs(1),
462
    ///     TransformRotationLens {
463
    ///         start: Quat::IDENTITY,
464
    ///         end: Quat::from_rotation_x(90.0_f32.to_radians()),
465
    ///     },
466
    /// );
467
    /// let seq = tween1.then(tween2);
468
    /// ```
469
    #[must_use]
470
    pub fn then(self, tween: impl Tweenable<T> + 'static) -> Sequence<T> {
1✔
471
        Sequence::with_capacity(2).then(self).then(tween)
1✔
472
    }
473
}
474

475
impl<T> Tween<T> {
476
    /// Create a new tween animation.
477
    ///
478
    /// # Example
479
    /// ```
480
    /// # use bevy_tweening::{lens::*, *};
481
    /// # use bevy::math::{Vec3, curve::EaseFunction};
482
    /// # use std::time::Duration;
483
    /// let tween = Tween::new(
484
    ///     EaseFunction::QuadraticInOut,
485
    ///     Duration::from_secs(1),
486
    ///     TransformPositionLens {
487
    ///         start: Vec3::ZERO,
488
    ///         end: Vec3::new(3.5, 0., 0.),
489
    ///     },
490
    /// );
491
    /// ```
492
    #[must_use]
493
    pub fn new<L>(ease_function: impl Into<EaseMethod>, duration: Duration, lens: L) -> Self
51✔
494
    where
495
        L: Lens<T> + Send + Sync + 'static,
496
    {
497
        Self {
498
            ease_function: ease_function.into(),
51✔
499
            clock: AnimClock::new(duration),
51✔
500
            direction: TweeningDirection::Forward,
501
            lens: Box::new(lens),
51✔
502
            on_completed: None,
503
            event_data: None,
504
            system_id: None,
505
        }
506
    }
507

508
    /// Enable raising a completed event.
509
    ///
510
    /// If enabled, the tween will raise a [`TweenCompleted`] event when the
511
    /// animation completed. This is similar to the [`with_completed()`]
512
    /// callback, but uses Bevy events instead.
513
    ///
514
    /// # Example
515
    ///
516
    /// ```
517
    /// # use bevy_tweening::{lens::*, *};
518
    /// # use bevy::{ecs::event::EventReader, math::{Vec3, curve::EaseFunction}};
519
    /// # use std::time::Duration;
520
    /// let tween = Tween::new(
521
    ///     // [...]
522
    /// #    EaseFunction::QuadraticInOut,
523
    /// #    Duration::from_secs(1),
524
    /// #    TransformPositionLens {
525
    /// #        start: Vec3::ZERO,
526
    /// #        end: Vec3::new(3.5, 0., 0.),
527
    /// #    },
528
    /// )
529
    /// .with_completed_event(42);
530
    ///
531
    /// fn my_system(mut reader: EventReader<TweenCompleted>) {
532
    ///   for ev in reader.read() {
533
    ///     assert_eq!(ev.user_data, 42);
534
    ///     println!("Entity {:?} raised TweenCompleted!", ev.entity);
535
    ///   }
536
    /// }
537
    /// ```
538
    ///
539
    /// [`with_completed()`]: Tween::with_completed
540
    #[must_use]
541
    pub fn with_completed_event(mut self, user_data: u64) -> Self {
3✔
542
        self.event_data = Some(user_data);
3✔
543
        self
3✔
544
    }
545

546
    /// Set a callback invoked when the delay completes.
547
    ///
548
    /// The callback when invoked receives as parameters the [`Entity`] on which
549
    /// the target and the animator are, as well as a reference to the
550
    /// current [`Tween`]. This is similar to [`with_completed_event()`], but
551
    /// with a callback instead.
552
    ///
553
    /// Only non-looping tweenables can complete.
554
    ///
555
    /// # Example
556
    ///
557
    /// ```
558
    /// # use bevy_tweening::{lens::*, *};
559
    /// # use bevy::{ecs::event::EventReader, math::{Vec3, curve::EaseFunction}};
560
    /// # use std::time::Duration;
561
    /// let tween = Tween::new(
562
    ///     // [...]
563
    /// #    EaseFunction::QuadraticInOut,
564
    /// #    Duration::from_secs(1),
565
    /// #    TransformPositionLens {
566
    /// #        start: Vec3::ZERO,
567
    /// #        end: Vec3::new(3.5, 0., 0.),
568
    /// #    },
569
    /// )
570
    /// .with_completed(|entity, _tween| {
571
    ///   println!("Tween completed on entity {:?}", entity);
572
    /// });
573
    /// ```
574
    ///
575
    /// [`with_completed_event()`]: Tween::with_completed_event
576
    pub fn with_completed<C>(mut self, callback: C) -> Self
×
577
    where
578
        C: Fn(Entity, &Self) + Send + Sync + 'static,
579
    {
580
        self.on_completed = Some(Box::new(callback));
×
581
        self
×
582
    }
583

584
    /// Enable running a one-shot system upon completion.
585
    ///
586
    /// If enabled, the tween will run a system via a provided [`SystemId`] when
587
    /// the animation completes. This is similar to the
588
    /// [`with_completed()`], but uses a system registered by
589
    /// [`register_system()`] instead of a callback.
590
    ///
591
    /// # Example
592
    ///
593
    /// ```
594
    /// # use bevy_tweening::{lens::*, *};
595
    /// # use bevy::{ecs::event::EventReader, math::{Vec3, curve::EaseFunction}, ecs::world::World, ecs::system::Query, ecs::entity::Entity, ecs::query::With};
596
    /// # use std::time::Duration;
597
    /// let mut world = World::new();
598
    /// let test_system_system_id = world.register_system(test_system);
599
    /// let tween = Tween::new(
600
    ///     // [...]
601
    /// #    EaseFunction::QuadraticInOut,
602
    /// #    Duration::from_secs(1),
603
    /// #    TransformPositionLens {
604
    /// #        start: Vec3::ZERO,
605
    /// #        end: Vec3::new(3.5, 0., 0.),
606
    /// #    },
607
    /// )
608
    /// .with_completed_system(test_system_system_id);
609
    ///
610
    /// fn test_system(query: Query<Entity>) {
611
    ///    for entity in query.iter() {
612
    ///       println!("Found an entity!");
613
    ///    }
614
    /// }
615
    /// ```
616
    /// [`with_completed()`]: Tween::with_completed
617
    /// [`register_system()`]: bevy::ecs::world::World::register_system
618
    #[must_use]
619
    pub fn with_completed_system(mut self, system_id: SystemId) -> Self {
×
620
        self.system_id = Some(system_id);
×
621
        self
×
622
    }
623

624
    /// Set the playback direction of the tween.
625
    ///
626
    /// The playback direction influences the mapping of the progress ratio (in
627
    /// \[0:1\]) to the actual ratio passed to the lens.
628
    /// [`TweeningDirection::Forward`] maps the `0` value of progress to the
629
    /// `0` value of the lens ratio. Conversely, [`TweeningDirection::Backward`]
630
    /// reverses the mapping, which effectively makes the tween play reversed,
631
    /// going from end to start.
632
    ///
633
    /// Changing the direction doesn't change any target state, nor any progress
634
    /// of the tween. Only the direction of animation from this moment
635
    /// potentially changes. To force a target state change, call
636
    /// [`Tweenable::tick()`] with a zero delta (`Duration::ZERO`).
637
    pub fn set_direction(&mut self, direction: TweeningDirection) {
5✔
638
        self.direction = direction;
5✔
639
    }
640

641
    /// Set the playback direction of the tween.
642
    ///
643
    /// See [`Tween::set_direction()`].
644
    #[must_use]
645
    pub fn with_direction(mut self, direction: TweeningDirection) -> Self {
10✔
646
        self.direction = direction;
10✔
647
        self
10✔
648
    }
649

650
    /// The current animation direction.
651
    ///
652
    /// See [`TweeningDirection`] for details.
653
    #[must_use]
654
    pub fn direction(&self) -> TweeningDirection {
139✔
655
        self.direction
139✔
656
    }
657

658
    /// Set the number of times to repeat the animation.
659
    #[must_use]
660
    pub fn with_repeat_count(mut self, count: impl Into<RepeatCount>) -> Self {
17✔
661
        self.clock.total_duration = compute_total_duration(self.clock.duration, count.into());
17✔
662
        self
17✔
663
    }
664

665
    /// Choose how the animation behaves upon a repetition.
666
    #[must_use]
667
    pub fn with_repeat_strategy(mut self, strategy: RepeatStrategy) -> Self {
12✔
668
        self.clock.strategy = strategy;
12✔
669
        self
12✔
670
    }
671

672
    /// Set a callback invoked when the animation completes.
673
    ///
674
    /// The callback when invoked receives as parameters the [`Entity`] on which
675
    /// the target and the animator are, as well as a reference to the
676
    /// current [`Tween`].
677
    ///
678
    /// Only non-looping tweenables can complete.
679
    pub fn set_completed<C>(&mut self, callback: C)
10✔
680
    where
681
        C: Fn(Entity, &Self) + Send + Sync + 'static,
682
    {
683
        self.on_completed = Some(Box::new(callback));
10✔
684
    }
685

686
    /// Clear the callback invoked when the animation completes.
687
    ///
688
    /// See also [`set_completed()`].
689
    ///
690
    /// [`set_completed()`]: Tween::set_completed
691
    pub fn clear_completed(&mut self) {
10✔
692
        self.on_completed = None;
10✔
693
    }
694

695
    /// Enable or disable raising a completed event.
696
    ///
697
    /// If enabled, the tween will raise a [`TweenCompleted`] event when the
698
    /// animation completed. This is similar to the [`set_completed()`]
699
    /// callback, but uses Bevy events instead.
700
    ///
701
    /// See [`with_completed_event()`] for details.
702
    ///
703
    /// [`set_completed()`]: Tween::set_completed
704
    /// [`with_completed_event()`]: Tween::with_completed_event
705
    pub fn set_completed_event(&mut self, user_data: u64) {
10✔
706
        self.event_data = Some(user_data);
10✔
707
    }
708

709
    /// Clear the event sent when the animation completes.
710
    ///
711
    /// See also [`set_completed_event()`].
712
    ///
713
    /// [`set_completed_event()`]: Tween::set_completed_event
714
    pub fn clear_completed_event(&mut self) {
10✔
715
        self.event_data = None;
10✔
716
    }
717

718
    /// Enable running a one-shot system upon completion.
719
    ///
720
    /// If enabled, the tween will run a system via a provided [`SystemId`] when
721
    /// the animation completes. This is similar to the
722
    /// [`with_completed()`], but uses a system registered by
723
    /// [`register_system()`] instead of a callback.
724
    ///
725
    /// [`with_completed()`]: Tween::with_completed
726
    /// [`register_system()`]: bevy::ecs::world::World::register_system
727
    pub fn set_completed_system(&mut self, user_data: SystemId) {
10✔
728
        self.system_id = Some(user_data);
10✔
729
    }
730

731
    /// Clear the system that will execute when the animation completes.
732
    ///
733
    /// See also [`set_completed_system()`].
734
    ///
735
    /// [`set_completed_system()`]: Tween::set_completed_system
736
    pub fn clear_completed_system(&mut self) {
10✔
737
        self.system_id = None;
10✔
738
    }
739
}
740

741
impl<T> Tweenable<T> for Tween<T> {
742
    fn duration(&self) -> Duration {
532✔
743
        self.clock.duration
532✔
744
    }
745

746
    fn total_duration(&self) -> TotalDuration {
300✔
747
        self.clock.total_duration
300✔
748
    }
749

750
    fn set_elapsed(&mut self, elapsed: Duration) {
46✔
751
        self.clock.set_elapsed(elapsed);
46✔
752
    }
753

754
    fn elapsed(&self) -> Duration {
489✔
755
        self.clock.elapsed()
489✔
756
    }
757

758
    fn tick(
172✔
759
        &mut self,
760
        delta: Duration,
761
        target: &mut dyn Targetable<T>,
762
        entity: Entity,
763
        events: &mut Mut<Events<TweenCompleted>>,
764
        commands: &mut Commands,
765
    ) -> TweenState {
766
        if self.clock.state() == TweenState::Completed {
172✔
767
            return TweenState::Completed;
23✔
768
        }
769

770
        // Tick the animation clock
771
        let (state, times_completed) = self.clock.tick(delta);
149✔
772
        let (progress, times_completed_for_direction) = match state {
×
773
            TweenState::Active => (self.progress(), times_completed),
134✔
774
            TweenState::Completed => (1., times_completed.max(1) - 1), // ignore last
15✔
775
        };
776
        if self.clock.strategy == RepeatStrategy::MirroredRepeat
×
777
            && times_completed_for_direction & 1 != 0
49✔
778
        {
779
            self.direction = !self.direction;
8✔
780
        }
781

782
        // Apply the lens, even if the animation finished, to ensure the state is
783
        // consistent
784
        let mut factor = progress;
×
785
        if self.direction.is_backward() {
55✔
786
            factor = 1. - factor;
55✔
787
        }
788
        let factor = self.ease_function.sample(factor);
×
789
        self.lens.lerp(target, factor);
×
790

791
        // If completed at least once this frame, notify the user
792
        if times_completed > 0 {
×
793
            if let Some(user_data) = &self.event_data {
49✔
794
                let event = TweenCompleted {
795
                    entity,
796
                    user_data: *user_data,
×
797
                };
798

799
                // send regular event
800
                events.send(event);
×
801

802
                // trigger all entity-scoped observers
803
                commands.trigger_targets(event, entity);
×
804
            }
805
            if let Some(cb) = &self.on_completed {
48✔
806
                cb(entity, self);
×
807
            }
808
            if let Some(system_id) = &self.system_id {
48✔
809
                commands.run_system(*system_id);
×
810
            }
811
        }
812

813
        state
×
814
    }
815

816
    fn rewind(&mut self) {
31✔
817
        if self.clock.strategy == RepeatStrategy::MirroredRepeat {
31✔
818
            // In mirrored mode, direction alternates each loop. To reset to the original
819
            // direction on Tween creation, we count the number of completions, ignoring the
820
            // last one if the Tween is currently in TweenState::Completed because that one
821
            // freezes all parameters.
822
            let mut times_completed = self.clock.times_completed();
7✔
823
            if self.clock.state() == TweenState::Completed {
7✔
824
                debug_assert!(times_completed > 0);
6✔
825
                times_completed -= 1;
3✔
826
            }
827
            if times_completed & 1 != 0 {
11✔
828
                self.direction = !self.direction;
4✔
829
            }
830
        }
831
        self.clock.reset();
31✔
832
    }
833
}
834

835
/// A sequence of tweens played back in order one after the other.
836
pub struct Sequence<T> {
837
    tweens: Vec<BoxedTweenable<T>>,
838
    index: usize,
839
    duration: Duration,
840
    elapsed: Duration,
841
}
842

843
impl<T> Sequence<T> {
844
    /// Create a new sequence of tweens.
845
    ///
846
    /// This method panics if the input collection is empty.
847
    #[must_use]
848
    pub fn new(items: impl IntoIterator<Item = impl Into<BoxedTweenable<T>>>) -> Self {
3✔
849
        let tweens: Vec<_> = items.into_iter().map(Into::into).collect();
3✔
850
        assert!(!tweens.is_empty());
3✔
851
        let duration = tweens
3✔
852
            .iter()
853
            .map(AsRef::as_ref)
3✔
854
            .map(Tweenable::duration)
3✔
855
            .sum();
856
        Self {
857
            tweens,
858
            index: 0,
859
            duration,
860
            elapsed: Duration::ZERO,
861
        }
862
    }
863

864
    /// Create a new sequence containing a single tween.
865
    #[must_use]
866
    pub fn from_single(tween: impl Tweenable<T> + 'static) -> Self {
1✔
867
        let duration = tween.duration();
1✔
868
        let boxed: BoxedTweenable<T> = Box::new(tween);
1✔
869
        Self {
870
            tweens: vec![boxed],
1✔
871
            index: 0,
872
            duration,
873
            elapsed: Duration::ZERO,
874
        }
875
    }
876

877
    /// Create a new sequence with the specified capacity.
878
    #[must_use]
879
    pub fn with_capacity(capacity: usize) -> Self {
2✔
880
        Self {
881
            tweens: Vec::with_capacity(capacity),
2✔
882
            index: 0,
883
            duration: Duration::ZERO,
884
            elapsed: Duration::ZERO,
885
        }
886
    }
887

888
    /// Append a [`Tweenable`] to this sequence.
889
    #[must_use]
890
    pub fn then(mut self, tween: impl Tweenable<T> + 'static) -> Self {
4✔
891
        self.duration += tween.duration();
4✔
892
        self.tweens.push(Box::new(tween));
4✔
893
        self
4✔
894
    }
895

896
    /// Index of the current active tween in the sequence.
897
    #[must_use]
898
    pub fn index(&self) -> usize {
17✔
899
        self.index.min(self.tweens.len() - 1)
17✔
900
    }
901

902
    /// Get the current active tween in the sequence.
903
    #[must_use]
904
    pub fn current(&self) -> &dyn Tweenable<T> {
8✔
905
        self.tweens[self.index()].as_ref()
8✔
906
    }
907
}
908

909
impl<T> Tweenable<T> for Sequence<T> {
910
    fn duration(&self) -> Duration {
20✔
911
        self.duration
20✔
912
    }
913

914
    fn total_duration(&self) -> TotalDuration {
5✔
915
        TotalDuration::Finite(self.duration)
5✔
916
    }
917

918
    fn set_elapsed(&mut self, elapsed: Duration) {
8✔
919
        // Set the total sequence progress
920
        self.elapsed = elapsed;
8✔
921

922
        // Find which tween is active in the sequence
923
        let mut accum_duration = Duration::ZERO;
8✔
924
        for index in 0..self.tweens.len() {
34✔
925
            let tween = &mut self.tweens[index];
26✔
926
            let tween_duration = tween.duration();
26✔
927
            if elapsed < accum_duration + tween_duration {
26✔
928
                self.index = index;
6✔
929
                let local_duration = elapsed - accum_duration;
6✔
930
                tween.set_elapsed(local_duration);
6✔
931
                // TODO?? set progress of other tweens after that one to 0. ??
932
                return;
6✔
933
            }
934
            tween.set_elapsed(tween.duration()); // ?? to prepare for next loop/rewind?
20✔
935
            accum_duration += tween_duration;
20✔
936
        }
937

938
        // None found; sequence ended
939
        self.index = self.tweens.len();
2✔
940
    }
941

942
    fn elapsed(&self) -> Duration {
18✔
943
        self.elapsed
18✔
944
    }
945

946
    fn tick(
18✔
947
        &mut self,
948
        mut delta: Duration,
949
        target: &mut dyn Targetable<T>,
950
        entity: Entity,
951
        events: &mut Mut<Events<TweenCompleted>>,
952
        commands: &mut Commands,
953
    ) -> TweenState {
954
        self.elapsed = self.elapsed.saturating_add(delta).min(self.duration);
18✔
955
        while self.index < self.tweens.len() {
22✔
956
            let tween = &mut self.tweens[self.index];
15✔
957
            let tween_remaining = tween.duration() - tween.elapsed();
15✔
958
            if let TweenState::Active = tween.tick(delta, target, entity, events, commands) {
15✔
959
                return TweenState::Active;
11✔
960
            }
961

962
            tween.rewind();
4✔
963
            delta -= tween_remaining;
4✔
964
            self.index += 1;
4✔
965
        }
966

967
        TweenState::Completed
7✔
968
    }
969

970
    fn rewind(&mut self) {
1✔
971
        self.elapsed = Duration::ZERO;
1✔
972
        self.index = 0;
1✔
973
        for tween in &mut self.tweens {
9✔
974
            // or only first?
975
            tween.rewind();
×
976
        }
977
    }
978
}
979

980
/// A collection of [`Tweenable`] executing in parallel.
981
pub struct Tracks<T> {
982
    tracks: Vec<BoxedTweenable<T>>,
983
    duration: Duration,
984
    elapsed: Duration,
985
}
986

987
impl<T> Tracks<T> {
988
    /// Create a new [`Tracks`] from an iterator over a collection of
989
    /// [`Tweenable`].
990
    #[must_use]
991
    pub fn new(items: impl IntoIterator<Item = impl Into<BoxedTweenable<T>>>) -> Self {
1✔
992
        let tracks: Vec<_> = items.into_iter().map(Into::into).collect();
1✔
993
        let duration = tracks
1✔
994
            .iter()
995
            .map(AsRef::as_ref)
1✔
996
            .map(Tweenable::duration)
1✔
997
            .max()
998
            .unwrap();
999
        Self {
1000
            tracks,
1001
            duration,
1002
            elapsed: Duration::ZERO,
1003
        }
1004
    }
1005
}
1006

1007
impl<T> Tweenable<T> for Tracks<T> {
1008
    fn duration(&self) -> Duration {
21✔
1009
        self.duration
21✔
1010
    }
1011

1012
    fn total_duration(&self) -> TotalDuration {
10✔
1013
        TotalDuration::Finite(self.duration)
10✔
1014
    }
1015

1016
    fn set_elapsed(&mut self, elapsed: Duration) {
3✔
1017
        self.elapsed = elapsed;
3✔
1018

1019
        for tweenable in &mut self.tracks {
15✔
1020
            tweenable.set_elapsed(elapsed);
×
1021
        }
1022
    }
1023

1024
    fn elapsed(&self) -> Duration {
20✔
1025
        self.elapsed
20✔
1026
    }
1027

1028
    fn tick(
9✔
1029
        &mut self,
1030
        delta: Duration,
1031
        target: &mut dyn Targetable<T>,
1032
        entity: Entity,
1033
        events: &mut Mut<Events<TweenCompleted>>,
1034
        commands: &mut Commands,
1035
    ) -> TweenState {
1036
        self.elapsed = self.elapsed.saturating_add(delta).min(self.duration);
9✔
1037
        let mut any_active = false;
9✔
1038
        for tweenable in &mut self.tracks {
45✔
1039
            let state = tweenable.tick(delta, target, entity, events, commands);
×
1040
            any_active = any_active || (state == TweenState::Active);
12✔
1041
        }
1042
        if any_active {
9✔
1043
            TweenState::Active
6✔
1044
        } else {
1045
            TweenState::Completed
3✔
1046
        }
1047
    }
1048

1049
    fn rewind(&mut self) {
1✔
1050
        self.elapsed = Duration::ZERO;
1✔
1051
        for tween in &mut self.tracks {
5✔
1052
            tween.rewind();
×
1053
        }
1054
    }
1055
}
1056

1057
/// A time delay that doesn't animate anything.
1058
///
1059
/// This is generally useful for combining with other tweenables into sequences
1060
/// and tracks, for example to delay the start of a tween in a track relative to
1061
/// another track. The `menu` example (`examples/menu.rs`) uses this technique
1062
/// to delay the animation of its buttons.
1063
pub struct Delay<T> {
1064
    timer: Timer,
1065
    on_completed: Option<Box<CompletedCallback<Delay<T>>>>,
1066
    event_data: Option<u64>,
1067
    system_id: Option<SystemId>,
1068
}
1069

1070
impl<T: 'static> Delay<T> {
1071
    /// Chain another [`Tweenable`] after this tween, making a [`Sequence`] with
1072
    /// the two.
1073
    #[must_use]
1074
    pub fn then(self, tween: impl Tweenable<T> + 'static) -> Sequence<T> {
1✔
1075
        Sequence::with_capacity(2).then(self).then(tween)
1✔
1076
    }
1077
}
1078

1079
impl<T> Delay<T> {
1080
    /// Create a new [`Delay`] with a given duration.
1081
    ///
1082
    /// # Panics
1083
    ///
1084
    /// Panics if the duration is zero.
1085
    #[must_use]
1086
    pub fn new(duration: Duration) -> Self {
5✔
1087
        assert!(!duration.is_zero());
5✔
1088
        Self {
1089
            timer: Timer::new(duration, TimerMode::Once),
4✔
1090
            on_completed: None,
1091
            event_data: None,
1092
            system_id: None,
1093
        }
1094
    }
1095

1096
    /// Enable raising a completed event.
1097
    ///
1098
    /// If enabled, the tweenable will raise a [`TweenCompleted`] event when it
1099
    /// completed. This is similar to the [`set_completed()`] callback, but
1100
    /// uses Bevy events instead.
1101
    ///
1102
    /// # Example
1103
    ///
1104
    /// ```
1105
    /// # use bevy_tweening::{lens::*, *};
1106
    /// # use bevy::{ecs::event::EventReader, math::Vec3, transform::components::Transform};
1107
    /// # use std::time::Duration;
1108
    /// let delay: Delay<Transform> = Delay::new(Duration::from_secs(5))
1109
    ///   .with_completed_event(42);
1110
    ///
1111
    /// fn my_system(mut reader: EventReader<TweenCompleted>) {
1112
    ///   for ev in reader.read() {
1113
    ///     assert_eq!(ev.user_data, 42);
1114
    ///     println!("Entity {:?} raised TweenCompleted!", ev.entity);
1115
    ///   }
1116
    /// }
1117
    /// ```
1118
    ///
1119
    /// [`set_completed()`]: Delay::set_completed
1120
    #[must_use]
1121
    pub fn with_completed_event(mut self, user_data: u64) -> Self {
1✔
1122
        self.event_data = Some(user_data);
1✔
1123
        self
1✔
1124
    }
1125

1126
    /// Set a callback invoked when the delay completes.
1127
    ///
1128
    /// The callback when invoked receives as parameters the [`Entity`] on which
1129
    /// the target and the animator are, as well as a reference to the
1130
    /// current [`Delay`]. This is similar to [`with_completed_event()`], but
1131
    /// with a callback instead.
1132
    ///
1133
    /// Only non-looping tweenables can complete.
1134
    ///
1135
    /// # Example
1136
    ///
1137
    /// ```
1138
    /// # use bevy_tweening::{lens::*, *};
1139
    /// # use bevy::{ecs::event::EventReader, math::{Vec3, curve::EaseFunction}};
1140
    /// # use std::time::Duration;
1141
    /// let tween = Tween::new(
1142
    ///     // [...]
1143
    /// #    EaseFunction::QuadraticInOut,
1144
    /// #    Duration::from_secs(1),
1145
    /// #    TransformPositionLens {
1146
    /// #        start: Vec3::ZERO,
1147
    /// #        end: Vec3::new(3.5, 0., 0.),
1148
    /// #    },
1149
    /// )
1150
    /// .with_completed(|entity, delay| {
1151
    ///   println!("Delay of {} seconds elapsed on entity {:?}",
1152
    ///     delay.duration().as_secs(), entity);
1153
    /// });
1154
    /// ```
1155
    ///
1156
    /// [`with_completed_event()`]: Delay::with_completed_event
1157
    pub fn with_completed<C>(mut self, callback: C) -> Self
×
1158
    where
1159
        C: Fn(Entity, &Self) + Send + Sync + 'static,
1160
    {
1161
        self.on_completed = Some(Box::new(callback));
×
1162
        self
×
1163
    }
1164

1165
    /// Enable running a one-shot system upon completion.
1166
    ///
1167
    /// If enabled, the tween will run a system via a provided [`SystemId`] when
1168
    /// the animation completes. This is similar to the
1169
    /// [`with_completed()`], but uses a system registered by
1170
    /// [`register_system()`] instead.
1171
    ///
1172
    /// # Example
1173
    ///
1174
    /// ```
1175
    /// # use bevy_tweening::{lens::*, *};
1176
    /// # use bevy::{ecs::event::EventReader, math::{Vec3, curve::EaseFunction}, ecs::world::World, ecs::system::Query, ecs::entity::Entity};
1177
    /// # use std::time::Duration;
1178
    /// let mut world = World::new();
1179
    /// let test_system_system_id = world.register_system(test_system);
1180
    /// let tween = Tween::new(
1181
    ///     // [...]
1182
    /// #    EaseFunction::QuadraticInOut,
1183
    /// #    Duration::from_secs(1),
1184
    /// #    TransformPositionLens {
1185
    /// #        start: Vec3::ZERO,
1186
    /// #        end: Vec3::new(3.5, 0., 0.),
1187
    /// #    },
1188
    /// )
1189
    /// .with_completed_system(test_system_system_id);
1190
    ///
1191
    /// fn test_system(query: Query<Entity>) {
1192
    ///    for entity in query.iter() {
1193
    ///       println!("Found an Entity!");
1194
    ///    }
1195
    /// }
1196
    /// ```
1197
    ///
1198
    /// [`with_completed()`]: Delay::with_completed
1199
    /// [`register_system()`]: bevy::ecs::world::World::register_system
1200
    #[must_use]
1201
    pub fn with_completed_system(mut self, system_id: SystemId) -> Self {
1✔
1202
        self.system_id = Some(system_id);
1✔
1203
        self
1✔
1204
    }
1205

1206
    /// Check if the delay completed.
1207
    pub fn is_completed(&self) -> bool {
44✔
1208
        self.timer.finished()
44✔
1209
    }
1210

1211
    /// Get the current tweenable state.
1212
    pub fn state(&self) -> TweenState {
22✔
1213
        if self.is_completed() {
22✔
1214
            TweenState::Completed
5✔
1215
        } else {
1216
            TweenState::Active
17✔
1217
        }
1218
    }
1219

1220
    /// Set a callback invoked when the animation completes.
1221
    ///
1222
    /// The callback when invoked receives as parameters the [`Entity`] on which
1223
    /// the target and the animator are, as well as a reference to the
1224
    /// current [`Tween`].
1225
    ///
1226
    /// Only non-looping tweenables can complete.
1227
    pub fn set_completed<C>(&mut self, callback: C)
1✔
1228
    where
1229
        C: Fn(Entity, &Self) + Send + Sync + 'static,
1230
    {
1231
        self.on_completed = Some(Box::new(callback));
1✔
1232
    }
1233

1234
    /// Clear the callback invoked when the animation completes.
1235
    ///
1236
    /// See also [`set_completed()`].
1237
    ///
1238
    /// [`set_completed()`]: Delay::set_completed
1239
    pub fn clear_completed(&mut self) {
1✔
1240
        self.on_completed = None;
1✔
1241
    }
1242

1243
    /// Enable or disable raising a completed event.
1244
    ///
1245
    /// If enabled, the tween will raise a [`TweenCompleted`] event when the
1246
    /// animation completed. This is similar to the [`set_completed()`]
1247
    /// callback, but uses Bevy events instead.
1248
    ///
1249
    /// See [`with_completed_event()`] for details.
1250
    ///
1251
    /// [`set_completed()`]: Delay::set_completed
1252
    /// [`with_completed_event()`]: Delay::with_completed_event
1253
    pub fn set_completed_event(&mut self, user_data: u64) {
1✔
1254
        self.event_data = Some(user_data);
1✔
1255
    }
1256

1257
    /// Clear the event sent when the animation completes.
1258
    ///
1259
    /// See also [`set_completed_event()`].
1260
    ///
1261
    /// [`set_completed_event()`]: Delay::set_completed_event
1262
    pub fn clear_completed_event(&mut self) {
2✔
1263
        self.event_data = None;
2✔
1264
    }
1265

1266
    /// Enable running a one-shot system upon completion.
1267
    ///
1268
    /// If enabled, the tween will run a system via a provided [`SystemId`] when
1269
    /// the animation completes. This is similar to the
1270
    /// [`with_completed()`], but uses a system registered by
1271
    /// [`register_system()`] instead of a callback.
1272
    ///
1273
    /// See [`with_completed_system()`] for details.
1274
    ///
1275
    /// [`with_completed()`]: Delay::with_completed
1276
    /// [`with_completed_system()`]: Delay::with_completed_system
1277
    /// [`register_system()`]: bevy::ecs::world::World::register_system
1278
    pub fn set_completed_system(&mut self, system_id: SystemId) {
1✔
1279
        self.system_id = Some(system_id);
1✔
1280
    }
1281

1282
    /// Clear the system that will execute when the animation completes.
1283
    ///
1284
    /// See also [`set_completed_system()`].
1285
    ///
1286
    /// [`set_completed_system()`]: Delay::set_completed_system
1287
    pub fn clear_completed_system(&mut self) {
1✔
1288
        self.system_id = None;
1✔
1289
    }
1290
}
1291

1292
impl<T> Tweenable<T> for Delay<T> {
1293
    fn duration(&self) -> Duration {
61✔
1294
        self.timer.duration()
61✔
1295
    }
1296

1297
    fn total_duration(&self) -> TotalDuration {
19✔
1298
        TotalDuration::Finite(self.duration())
19✔
1299
    }
1300

1301
    fn set_elapsed(&mut self, elapsed: Duration) {
11✔
1302
        // need to reset() to clear finished() unfortunately
1303
        self.timer.reset();
11✔
1304
        self.timer.set_elapsed(elapsed);
11✔
1305
        // set_elapsed() does not update finished() etc. which we rely on
1306
        self.timer.tick(Duration::ZERO);
11✔
1307
    }
1308

1309
    fn elapsed(&self) -> Duration {
48✔
1310
        self.timer.elapsed()
48✔
1311
    }
1312

1313
    fn tick(
7✔
1314
        &mut self,
1315
        delta: Duration,
1316
        _target: &mut dyn Targetable<T>,
1317
        entity: Entity,
1318
        events: &mut Mut<Events<TweenCompleted>>,
1319
        commands: &mut Commands,
1320
    ) -> TweenState {
1321
        let was_completed = self.is_completed();
7✔
1322

1323
        self.timer.tick(delta);
7✔
1324

1325
        let state = self.state();
7✔
1326

1327
        // If completed this frame, notify the user
1328
        if (state == TweenState::Completed) && !was_completed {
9✔
1329
            if let Some(user_data) = &self.event_data {
2✔
1330
                let event = TweenCompleted {
1331
                    entity,
1332
                    user_data: *user_data,
×
1333
                };
1334

1335
                // send regular event
1336
                events.send(event);
×
1337

1338
                // trigger all entity-scoped observers
1339
                commands.trigger_targets(event, entity);
×
1340
            }
1341
            if let Some(cb) = &self.on_completed {
2✔
1342
                cb(entity, self);
×
1343
            }
1344
            if let Some(system_id) = &self.system_id {
2✔
1345
                commands.run_system(*system_id);
×
1346
            }
1347
        }
1348

1349
        state
7✔
1350
    }
1351

1352
    fn rewind(&mut self) {
1✔
1353
        self.timer.reset();
1✔
1354
    }
1355
}
1356

1357
#[cfg(test)]
1358
mod tests {
1359
    use std::sync::{Arc, Mutex};
1360

1361
    use bevy::ecs::{
1362
        change_detection::MaybeLocation,
1363
        component::{Mutable, Tick},
1364
        event::Events,
1365
        system::SystemState,
1366
        world::CommandQueue,
1367
    };
1368

1369
    use super::*;
1370
    use crate::{lens::*, test_utils::*};
1371

1372
    #[derive(Default, Copy, Clone)]
1373
    struct CallbackMonitor {
1374
        invoke_count: u64,
1375
        last_reported_count: u32,
1376
    }
1377

1378
    /// Utility to create a tween for testing.
1379
    fn make_test_tween() -> Tween<Transform> {
1380
        Tween::new(
1381
            EaseMethod::default(),
1382
            Duration::from_secs(1),
1383
            TransformPositionLens {
1384
                start: Vec3::ZERO,
1385
                end: Vec3::ONE,
1386
            },
1387
        )
1388
    }
1389

1390
    /// Utility to create a test environment to tick a tween.
1391
    fn make_test_env() -> (World, Entity, SystemId) {
1392
        let mut world = World::new();
1393
        world.init_resource::<Events<TweenCompleted>>();
1394
        let entity = world.spawn(Transform::default()).id();
1395
        let system_id = world.register_system(oneshot_test);
1396
        (world, entity, system_id)
1397
    }
1398

1399
    /// one-shot system to be used for testing
1400
    fn oneshot_test() {}
1401

1402
    /// Manually tick a test tweenable targeting a component.
1403
    fn manual_tick_component<T: Component<Mutability = Mutable>>(
1404
        duration: Duration,
1405
        tween: &mut dyn Tweenable<T>,
1406
        world: &mut World,
1407
        entity: Entity,
1408
    ) -> TweenState {
1409
        world.resource_scope(
1410
            |world: &mut World, mut events: Mut<Events<TweenCompleted>>| {
1411
                let transform = world.get_mut::<T>(entity).unwrap();
1412
                let mut target = ComponentTarget::new(transform);
1413
                // let command_queue = &mut CommandQueue::default(); // todo
1414
                // let mut asd = Commands::new(command_queue, world);
1415
                tween.tick(
1416
                    duration,
1417
                    &mut target,
1418
                    entity,
1419
                    &mut events,
1420
                    // passing dummy values to let things compile
1421
                    &mut Commands::new(&mut CommandQueue::default(), &World::default()),
1422
                )
1423
            },
1424
        )
1425
    }
1426

1427
    #[derive(Debug, Default, Clone, Copy, Component)]
1428
    struct DummyComponent {
1429
        _value: f32,
1430
    }
1431

1432
    #[test]
1433
    fn targetable_change_detect() {
1434
        let mut c = DummyComponent::default();
1435
        let mut added = Tick::new(0);
1436
        let mut last_changed = Tick::new(0);
1437
        let mut caller = MaybeLocation::caller();
1438
        let mut target = ComponentTarget::new(Mut::new(
1439
            &mut c,
1440
            &mut added,
1441
            &mut last_changed,
1442
            Tick::new(0),
1443
            Tick::new(1),
1444
            caller.as_mut(),
1445
        ));
1446
        let mut target = target.to_mut();
1447

1448
        // No-op at start
1449
        assert!(!target.is_added());
1450
        assert!(!target.is_changed());
1451

1452
        // Immutable deref doesn't trigger change detection
1453
        let _ = target.deref();
1454
        assert!(!target.is_added());
1455
        assert!(!target.is_changed());
1456

1457
        // Mutable deref triggers change detection
1458
        let _ = target.deref_mut();
1459
        assert!(!target.is_added());
1460
        assert!(target.is_changed());
1461
    }
1462

1463
    #[test]
1464
    fn anim_clock_precision() {
1465
        let duration = Duration::from_millis(1);
1466
        let mut clock = AnimClock::new(duration);
1467
        clock.total_duration = TotalDuration::Infinite;
1468

1469
        let test_ticks = [
1470
            Duration::from_micros(123),
1471
            Duration::from_millis(1),
1472
            Duration::from_secs_f32(1. / 24.),
1473
            Duration::from_secs_f32(1. / 30.),
1474
            Duration::from_secs_f32(1. / 60.),
1475
            Duration::from_secs_f32(1. / 120.),
1476
            Duration::from_secs_f32(1. / 144.),
1477
            Duration::from_secs_f32(1. / 240.),
1478
        ];
1479

1480
        let mut times_completed = 0;
1481
        let mut total_duration = Duration::ZERO;
1482
        for i in 0..10_000_000 {
1483
            let tick = test_ticks[i % test_ticks.len()];
1484
            times_completed += clock.tick(tick).1;
1485
            total_duration += tick;
1486
        }
1487

1488
        assert_eq!(
1489
            (total_duration.as_secs_f64() / duration.as_secs_f64()) as i32,
1490
            times_completed
1491
        );
1492
    }
1493

1494
    #[test]
1495
    fn into_repeat_count() {
1496
        let tween = Tween::new(
1497
            EaseMethod::default(),
1498
            Duration::from_secs(1),
1499
            TransformPositionLens {
1500
                start: Vec3::ZERO,
1501
                end: Vec3::ONE,
1502
            },
1503
        )
1504
        .with_repeat_count(5);
1505
        assert_eq!(
1506
            tween.total_duration(),
1507
            TotalDuration::Finite(Duration::from_secs(5))
1508
        );
1509

1510
        let tween = Tween::new(
1511
            EaseMethod::default(),
1512
            Duration::from_secs(1),
1513
            TransformPositionLens {
1514
                start: Vec3::ZERO,
1515
                end: Vec3::ONE,
1516
            },
1517
        )
1518
        .with_repeat_count(Duration::from_secs(3));
1519
        assert_eq!(
1520
            tween.total_duration(),
1521
            TotalDuration::Finite(Duration::from_secs(3))
1522
        );
1523
    }
1524

1525
    /// Test ticking of a single tween in isolation.
1526
    #[test]
1527
    fn tween_tick() {
1528
        for tweening_direction in &[TweeningDirection::Forward, TweeningDirection::Backward] {
1529
            for (count, strategy) in &[
1530
                (RepeatCount::Finite(1), RepeatStrategy::default()),
1531
                (RepeatCount::Infinite, RepeatStrategy::Repeat),
1532
                (RepeatCount::Finite(2), RepeatStrategy::Repeat),
1533
                (RepeatCount::Infinite, RepeatStrategy::MirroredRepeat),
1534
                (RepeatCount::Finite(2), RepeatStrategy::MirroredRepeat),
1535
            ] {
1536
                println!(
1537
                    "TweeningType: count={count:?} strategy={strategy:?} dir={tweening_direction:?}",
1538
                );
1539

1540
                // Create a linear tween over 1 second
1541
                let mut tween = make_test_tween()
1542
                    .with_direction(*tweening_direction)
1543
                    .with_repeat_count(*count)
1544
                    .with_repeat_strategy(*strategy);
1545
                assert_eq!(tween.direction(), *tweening_direction);
1546
                assert!(tween.on_completed.is_none());
1547
                assert!(tween.event_data.is_none());
1548

1549
                let (mut world, entity, system_id) = make_test_env();
1550
                let mut event_reader_system_state: SystemState<EventReader<TweenCompleted>> =
1551
                    SystemState::new(&mut world);
1552

1553
                // Register callbacks to count started/ended events
1554
                let callback_monitor = Arc::new(Mutex::new(CallbackMonitor::default()));
1555
                let cb_mon_ptr = Arc::clone(&callback_monitor);
1556
                let reference_entity = entity;
1557
                tween.set_completed(move |completed_entity, tween| {
1558
                    assert_eq!(completed_entity, reference_entity);
1559
                    let mut cb_mon = cb_mon_ptr.lock().unwrap();
1560
                    cb_mon.invoke_count += 1;
1561
                    cb_mon.last_reported_count = tween.times_completed();
1562
                });
1563
                assert!(tween.on_completed.is_some());
1564
                assert!(tween.event_data.is_none());
1565
                assert_eq!(callback_monitor.lock().unwrap().invoke_count, 0);
1566

1567
                // Activate event sending
1568
                const USER_DATA: u64 = 54789; // dummy
1569
                tween.set_completed_event(USER_DATA);
1570
                assert!(tween.event_data.is_some());
1571
                assert_eq!(tween.event_data.unwrap(), USER_DATA);
1572

1573
                // Activate oneshot system
1574
                tween.set_completed_system(system_id);
1575
                assert!(tween.system_id.is_some());
1576
                assert_eq!(tween.system_id.unwrap(), system_id);
1577

1578
                // Loop over 2.2 seconds, so greater than one ping-pong loop
1579
                let tick_duration = Duration::from_millis(200);
1580
                for i in 1..=11 {
1581
                    // Calculate expected values
1582
                    let (progress, times_completed, mut direction, expected_state, just_completed) =
1583
                        match count {
1584
                            RepeatCount::Finite(1) => {
1585
                                let progress = (i as f32 * 0.2).min(1.0);
1586
                                let times_completed = u32::from(i >= 5);
1587
                                let state = if i < 5 {
1588
                                    TweenState::Active
1589
                                } else {
1590
                                    TweenState::Completed
1591
                                };
1592
                                let just_completed = i == 5;
1593
                                (
1594
                                    progress,
1595
                                    times_completed,
1596
                                    TweeningDirection::Forward,
1597
                                    state,
1598
                                    just_completed,
1599
                                )
1600
                            }
1601
                            RepeatCount::Finite(count) => {
1602
                                let total_progress = i as f32 * 0.2;
1603
                                let progress = if total_progress >= *count as f32 {
1604
                                    1.
1605
                                } else {
1606
                                    total_progress.fract()
1607
                                };
1608
                                if *strategy == RepeatStrategy::Repeat {
1609
                                    let times_completed = i / 5;
1610
                                    let just_completed = i % 5 == 0;
1611
                                    (
1612
                                        progress,
1613
                                        times_completed,
1614
                                        TweeningDirection::Forward,
1615
                                        if i < 10 {
1616
                                            TweenState::Active
1617
                                        } else {
1618
                                            TweenState::Completed
1619
                                        },
1620
                                        just_completed,
1621
                                    )
1622
                                } else {
1623
                                    let i5 = i % 5;
1624
                                    let times_completed = i / 5;
1625
                                    // Once Completed, the direction doesn't change
1626
                                    let direction = if i >= 5 {
1627
                                        TweeningDirection::Backward
1628
                                    } else {
1629
                                        TweeningDirection::Forward
1630
                                    };
1631
                                    let just_completed = i5 == 0;
1632
                                    (
1633
                                        progress,
1634
                                        times_completed,
1635
                                        direction,
1636
                                        if i < 10 {
1637
                                            TweenState::Active
1638
                                        } else {
1639
                                            TweenState::Completed
1640
                                        },
1641
                                        just_completed,
1642
                                    )
1643
                                }
1644
                            }
1645
                            RepeatCount::Infinite => {
1646
                                let progress = (i as f32 * 0.2).fract();
1647
                                if *strategy == RepeatStrategy::Repeat {
1648
                                    let times_completed = i / 5;
1649
                                    let just_completed = i % 5 == 0;
1650
                                    (
1651
                                        progress,
1652
                                        times_completed,
1653
                                        TweeningDirection::Forward,
1654
                                        TweenState::Active,
1655
                                        just_completed,
1656
                                    )
1657
                                } else {
1658
                                    let i5 = i % 5;
1659
                                    let times_completed = i / 5;
1660
                                    let i10 = i % 10;
1661
                                    let direction = if i10 >= 5 {
1662
                                        TweeningDirection::Backward
1663
                                    } else {
1664
                                        TweeningDirection::Forward
1665
                                    };
1666
                                    let just_completed = i5 == 0;
1667
                                    (
1668
                                        progress,
1669
                                        times_completed,
1670
                                        direction,
1671
                                        TweenState::Active,
1672
                                        just_completed,
1673
                                    )
1674
                                }
1675
                            }
1676
                            RepeatCount::For(_) => panic!("Untested"),
1677
                        };
1678
                    let factor = if tweening_direction.is_backward() {
1679
                        direction = !direction;
1680
                        1. - progress
1681
                    } else {
1682
                        progress
1683
                    };
1684
                    let expected_translation = if direction.is_forward() {
1685
                        Vec3::splat(progress)
1686
                    } else {
1687
                        Vec3::splat(1. - progress)
1688
                    };
1689
                    println!(
1690
                        "Expected: progress={} factor={} times_completed={} direction={:?} state={:?} just_completed={} translation={:?}",
1691
                        progress, factor, times_completed, direction, expected_state, just_completed, expected_translation
1692
                    );
1693

1694
                    // Tick the tween
1695
                    let actual_state =
1696
                        manual_tick_component(tick_duration, &mut tween, &mut world, entity);
1697

1698
                    // Propagate events
1699
                    {
1700
                        let mut events = world.resource_mut::<Events<TweenCompleted>>();
1701
                        events.update();
1702
                    }
1703

1704
                    // Check actual values
1705
                    assert_eq!(tween.direction(), direction);
1706
                    assert_eq!(actual_state, expected_state);
1707
                    assert_approx_eq!(tween.progress(), progress);
1708
                    assert_eq!(tween.times_completed(), times_completed);
1709
                    let transform = world.entity(entity).get::<Transform>().unwrap();
1710
                    assert!(transform
1711
                        .translation
1712
                        .abs_diff_eq(expected_translation, 1e-5));
1713
                    assert!(transform.rotation.abs_diff_eq(Quat::IDENTITY, 1e-5));
1714
                    let cb_mon = callback_monitor.lock().unwrap();
1715
                    assert_eq!(cb_mon.invoke_count, times_completed as u64);
1716
                    assert_eq!(cb_mon.last_reported_count, times_completed);
1717
                    {
1718
                        let mut event_reader = event_reader_system_state.get_mut(&mut world);
1719
                        let event = event_reader.read().next();
1720
                        if just_completed {
1721
                            assert!(event.is_some());
1722
                            if let Some(event) = event {
1723
                                assert_eq!(event.entity, entity);
1724
                                assert_eq!(event.user_data, USER_DATA);
1725
                            }
1726
                        } else {
1727
                            assert!(event.is_none());
1728
                        }
1729
                    }
1730
                }
1731

1732
                // Rewind
1733
                tween.rewind();
1734
                assert_eq!(tween.direction(), *tweening_direction); // does not change
1735
                assert_approx_eq!(tween.progress(), 0.);
1736
                assert_eq!(tween.times_completed(), 0);
1737

1738
                // Dummy tick to update target
1739
                let actual_state =
1740
                    manual_tick_component(Duration::ZERO, &mut tween, &mut world, entity);
1741
                assert_eq!(actual_state, TweenState::Active);
1742
                let expected_translation = if tweening_direction.is_backward() {
1743
                    Vec3::ONE
1744
                } else {
1745
                    Vec3::ZERO
1746
                };
1747
                let transform = world.entity(entity).get::<Transform>().unwrap();
1748
                assert!(transform
1749
                    .translation
1750
                    .abs_diff_eq(expected_translation, 1e-5));
1751
                assert!(transform.rotation.abs_diff_eq(Quat::IDENTITY, 1e-5));
1752

1753
                // Clear callback
1754
                tween.clear_completed();
1755
                assert!(tween.on_completed.is_none());
1756

1757
                // Clear event sending
1758
                tween.clear_completed_event();
1759
                assert!(tween.event_data.is_none());
1760

1761
                // Clear oneshot system
1762
                tween.clear_completed_system();
1763
                assert!(tween.system_id.is_none());
1764
            }
1765
        }
1766
    }
1767

1768
    #[test]
1769
    fn tween_dir() {
1770
        let mut tween = make_test_tween();
1771

1772
        // Default
1773
        assert_eq!(tween.direction(), TweeningDirection::Forward);
1774
        assert_approx_eq!(tween.progress(), 0.0);
1775

1776
        // no-op
1777
        tween.set_direction(TweeningDirection::Forward);
1778
        assert_eq!(tween.direction(), TweeningDirection::Forward);
1779
        assert_approx_eq!(tween.progress(), 0.0);
1780

1781
        // Backward
1782
        tween.set_direction(TweeningDirection::Backward);
1783
        assert_eq!(tween.direction(), TweeningDirection::Backward);
1784
        // progress is independent of direction
1785
        assert_approx_eq!(tween.progress(), 0.0);
1786

1787
        // Progress-invariant
1788
        tween.set_direction(TweeningDirection::Forward);
1789
        tween.set_progress(0.3);
1790
        assert_approx_eq!(tween.progress(), 0.3);
1791
        tween.set_direction(TweeningDirection::Backward);
1792
        // progress is independent of direction
1793
        assert_approx_eq!(tween.progress(), 0.3);
1794

1795
        let (mut world, entity, _system_id) = make_test_env();
1796

1797
        // Progress always increases alongside the current direction
1798
        tween.set_direction(TweeningDirection::Backward);
1799
        assert_approx_eq!(tween.progress(), 0.3);
1800
        manual_tick_component(Duration::from_millis(100), &mut tween, &mut world, entity);
1801
        assert_approx_eq!(tween.progress(), 0.4);
1802
        let transform = world.entity(entity).get::<Transform>().unwrap();
1803
        assert!(transform.translation.abs_diff_eq(Vec3::splat(0.6), 1e-5));
1804
    }
1805

1806
    #[test]
1807
    fn tween_elapsed() {
1808
        let mut tween = make_test_tween();
1809

1810
        let duration = tween.duration();
1811
        let elapsed = tween.elapsed();
1812

1813
        assert_eq!(elapsed, Duration::ZERO);
1814
        assert_eq!(duration, Duration::from_secs(1));
1815

1816
        for ms in [0, 1, 500, 100, 300, 999, 847, 1000, 900] {
1817
            let elapsed = Duration::from_millis(ms);
1818
            tween.set_elapsed(elapsed);
1819
            assert_eq!(tween.elapsed(), elapsed);
1820

1821
            let progress = (elapsed.as_secs_f64() / duration.as_secs_f64()) as f32;
1822
            assert_approx_eq!(tween.progress(), progress);
1823

1824
            let times_completed = u32::from(ms == 1000);
1825
            assert_eq!(tween.times_completed(), times_completed);
1826
        }
1827
    }
1828

1829
    /// Test ticking a sequence of tweens.
1830
    #[test]
1831
    fn seq_tick() {
1832
        let tween1 = Tween::new(
1833
            EaseMethod::default(),
1834
            Duration::from_secs(1),
1835
            TransformPositionLens {
1836
                start: Vec3::ZERO,
1837
                end: Vec3::ONE,
1838
            },
1839
        );
1840
        let tween2 = Tween::new(
1841
            EaseMethod::default(),
1842
            Duration::from_secs(1),
1843
            TransformRotationLens {
1844
                start: Quat::IDENTITY,
1845
                end: Quat::from_rotation_x(90_f32.to_radians()),
1846
            },
1847
        );
1848
        let mut seq = tween1.then(tween2);
1849

1850
        let (mut world, entity, _system_id) = make_test_env();
1851

1852
        for i in 1..=16 {
1853
            let state =
1854
                manual_tick_component(Duration::from_millis(200), &mut seq, &mut world, entity);
1855
            let transform = world.entity(entity).get::<Transform>().unwrap();
1856
            if i < 5 {
1857
                assert_eq!(state, TweenState::Active);
1858
                let r = i as f32 * 0.2;
1859
                assert_eq!(*transform, Transform::from_translation(Vec3::splat(r)));
1860
            } else if i < 10 {
1861
                assert_eq!(state, TweenState::Active);
1862
                let alpha_deg = (18 * (i - 5)) as f32;
1863
                assert!(transform.translation.abs_diff_eq(Vec3::ONE, 1e-5));
1864
                assert!(transform
1865
                    .rotation
1866
                    .abs_diff_eq(Quat::from_rotation_x(alpha_deg.to_radians()), 1e-5));
1867
            } else {
1868
                assert_eq!(state, TweenState::Completed);
1869
                assert!(transform.translation.abs_diff_eq(Vec3::ONE, 1e-5));
1870
                assert!(transform
1871
                    .rotation
1872
                    .abs_diff_eq(Quat::from_rotation_x(90_f32.to_radians()), 1e-5));
1873
            }
1874
        }
1875
    }
1876

1877
    /// Test crossing tween boundaries in one tick.
1878
    #[test]
1879
    fn seq_tick_boundaries() {
1880
        let mut seq = Sequence::new((0..3).map(|i| {
1881
            Tween::new(
1882
                EaseMethod::default(),
1883
                Duration::from_secs(1),
1884
                TransformPositionLens {
1885
                    start: Vec3::splat(i as f32),
1886
                    end: Vec3::splat((i + 1) as f32),
1887
                },
1888
            )
1889
            .with_repeat_count(RepeatCount::Finite(1))
1890
        }));
1891

1892
        let (mut world, entity, _system_id) = make_test_env();
1893

1894
        // Tick halfway through the first tween, then in one tick:
1895
        // - Finish the first tween
1896
        // - Start and finish the second tween
1897
        // - Start the third tween
1898
        for delta_ms in [500, 2000] {
1899
            manual_tick_component(
1900
                Duration::from_millis(delta_ms),
1901
                &mut seq,
1902
                &mut world,
1903
                entity,
1904
            );
1905
        }
1906
        assert_eq!(seq.index(), 2);
1907
        let transform = world.entity(entity).get::<Transform>().unwrap();
1908
        assert!(transform.translation.abs_diff_eq(Vec3::splat(2.5), 1e-5));
1909
    }
1910

1911
    /// Sequence::new() and various Sequence-specific methods
1912
    #[test]
1913
    fn seq_iter() {
1914
        let mut seq = Sequence::new((1..5).map(|i| {
1915
            Tween::new(
1916
                EaseMethod::default(),
1917
                Duration::from_millis(200 * i),
1918
                TransformPositionLens {
1919
                    start: Vec3::ZERO,
1920
                    end: Vec3::ONE,
1921
                },
1922
            )
1923
        }));
1924

1925
        let mut progress = 0.;
1926
        for i in 1..5 {
1927
            assert_eq!(seq.index(), i - 1);
1928
            assert_approx_eq!(seq.progress(), progress);
1929
            let duration = Duration::from_millis(200 * i as u64);
1930
            assert_eq!(seq.current().duration(), duration);
1931
            progress += 0.25;
1932
            seq.set_progress(progress);
1933
            assert_eq!(seq.times_completed(), u32::from(i == 4));
1934
        }
1935

1936
        seq.rewind();
1937
        assert_eq!(seq.progress(), 0.);
1938
        assert_eq!(seq.times_completed(), 0);
1939
    }
1940

1941
    /// Sequence::from_single()
1942
    #[test]
1943
    fn seq_from_single() {
1944
        let tween = Tween::new(
1945
            EaseMethod::default(),
1946
            Duration::from_secs(1),
1947
            TransformPositionLens {
1948
                start: Vec3::ZERO,
1949
                end: Vec3::ONE,
1950
            },
1951
        );
1952
        let seq = Sequence::from_single(tween);
1953

1954
        assert_eq!(seq.duration(), Duration::from_secs(1));
1955
    }
1956

1957
    #[test]
1958
    fn seq_elapsed() {
1959
        let mut seq = Sequence::new((1..5).map(|i| {
1960
            Tween::new(
1961
                EaseMethod::default(),
1962
                Duration::from_millis(200 * i),
1963
                TransformPositionLens {
1964
                    start: Vec3::ZERO,
1965
                    end: Vec3::ONE,
1966
                },
1967
            )
1968
        }));
1969

1970
        let mut elapsed = Duration::ZERO;
1971
        for i in 1..5 {
1972
            assert_eq!(seq.index(), i - 1);
1973
            assert_eq!(seq.elapsed(), elapsed);
1974
            let duration = Duration::from_millis(200 * i as u64);
1975
            assert_eq!(seq.current().duration(), duration);
1976
            elapsed += duration;
1977
            seq.set_elapsed(elapsed);
1978
            assert_eq!(seq.times_completed(), u32::from(i == 4));
1979
        }
1980
    }
1981

1982
    /// Test ticking parallel tracks of tweens.
1983
    #[test]
1984
    fn tracks_tick() {
1985
        let tween1 = Tween::new(
1986
            EaseMethod::default(),
1987
            Duration::from_millis(1000),
1988
            TransformPositionLens {
1989
                start: Vec3::ZERO,
1990
                end: Vec3::ONE,
1991
            },
1992
        );
1993
        let tween2 = Tween::new(
1994
            EaseMethod::default(),
1995
            Duration::from_millis(800), // shorter
1996
            TransformRotationLens {
1997
                start: Quat::IDENTITY,
1998
                end: Quat::from_rotation_x(90_f32.to_radians()),
1999
            },
2000
        );
2001
        let mut tracks = Tracks::new([tween1, tween2]);
2002
        assert_eq!(tracks.duration(), Duration::from_secs(1)); // max(1., 0.8)
2003

2004
        let (mut world, entity, _system_id) = make_test_env();
2005

2006
        for i in 1..=6 {
2007
            let state =
2008
                manual_tick_component(Duration::from_millis(200), &mut tracks, &mut world, entity);
2009
            let transform = world.entity(entity).get::<Transform>().unwrap();
2010
            if i < 5 {
2011
                assert_eq!(state, TweenState::Active);
2012
                assert_eq!(tracks.times_completed(), 0);
2013
                let r = i as f32 * 0.2;
2014
                assert_approx_eq!(tracks.progress(), r);
2015
                let alpha_deg = 22.5 * i as f32;
2016
                assert!(transform.translation.abs_diff_eq(Vec3::splat(r), 1e-5));
2017
                assert!(transform
2018
                    .rotation
2019
                    .abs_diff_eq(Quat::from_rotation_x(alpha_deg.to_radians()), 1e-5));
2020
            } else {
2021
                assert_eq!(state, TweenState::Completed);
2022
                assert_eq!(tracks.times_completed(), 1);
2023
                assert_approx_eq!(tracks.progress(), 1.);
2024
                assert!(transform.translation.abs_diff_eq(Vec3::ONE, 1e-5));
2025
                assert!(transform
2026
                    .rotation
2027
                    .abs_diff_eq(Quat::from_rotation_x(90_f32.to_radians()), 1e-5));
2028
            }
2029
        }
2030

2031
        tracks.rewind();
2032
        assert_eq!(tracks.times_completed(), 0);
2033
        assert_approx_eq!(tracks.progress(), 0.);
2034

2035
        tracks.set_progress(0.9);
2036
        assert_approx_eq!(tracks.progress(), 0.9);
2037
        // tick to udpate state (set_progress() does not update state)
2038
        let state = manual_tick_component(Duration::ZERO, &mut tracks, &mut world, entity);
2039
        assert_eq!(state, TweenState::Active);
2040
        assert_eq!(tracks.times_completed(), 0);
2041

2042
        tracks.set_progress(3.2);
2043
        assert_approx_eq!(tracks.progress(), 1.);
2044
        // tick to udpate state (set_progress() does not update state)
2045
        let state = manual_tick_component(Duration::ZERO, &mut tracks, &mut world, entity);
2046
        assert_eq!(state, TweenState::Completed);
2047
        assert_eq!(tracks.times_completed(), 1); // no looping
2048

2049
        tracks.set_progress(-0.5);
2050
        assert_approx_eq!(tracks.progress(), 0.);
2051
        // tick to udpate state (set_progress() does not update state)
2052
        let state = manual_tick_component(Duration::ZERO, &mut tracks, &mut world, entity);
2053
        assert_eq!(state, TweenState::Active);
2054
        assert_eq!(tracks.times_completed(), 0); // no looping
2055
    }
2056

2057
    /// Delay::then()
2058
    #[test]
2059
    fn delay_then() {
2060
        let seq: Sequence<Transform> =
2061
            Delay::new(Duration::from_secs(1)).then(Delay::new(Duration::from_secs(2)));
2062
        assert_eq!(seq.duration(), Duration::from_secs(3));
2063
        assert_eq!(seq.tweens.len(), 2);
2064
        for (i, t) in seq.tweens.iter().enumerate() {
2065
            assert_eq!(t.duration(), Duration::from_secs(i as u64 + 1));
2066
        }
2067
    }
2068

2069
    /// Test ticking a delay.
2070
    #[test]
2071
    fn delay_tick() {
2072
        let duration = Duration::from_secs(1);
2073
        // Dummy world and registered oneshot system ID
2074
        let (mut world, entity, system_id) = make_test_env();
2075

2076
        const USER_DATA: u64 = 42;
2077
        let mut delay = Delay::new(duration)
2078
            .with_completed_event(USER_DATA)
2079
            .with_completed_system(system_id);
2080

2081
        assert!(delay.event_data.is_some());
2082
        assert_eq!(delay.event_data.unwrap(), USER_DATA);
2083

2084
        assert!(delay.system_id.is_some());
2085
        assert_eq!(delay.system_id.unwrap(), system_id);
2086

2087
        delay.clear_completed_event();
2088
        assert!(delay.event_data.is_none());
2089

2090
        delay.set_completed_event(USER_DATA);
2091
        assert!(delay.event_data.is_some());
2092
        assert_eq!(delay.event_data.unwrap(), USER_DATA);
2093

2094
        delay.clear_completed_system();
2095
        assert!(delay.system_id.is_none());
2096

2097
        delay.set_completed_system(system_id);
2098
        assert!(delay.system_id.is_some());
2099
        assert_eq!(delay.system_id.unwrap(), system_id);
2100

2101
        {
2102
            let tweenable: &dyn Tweenable<Transform> = &delay;
2103
            assert_eq!(tweenable.duration(), duration);
2104
            assert_approx_eq!(tweenable.progress(), 0.);
2105
            assert_eq!(tweenable.elapsed(), Duration::ZERO);
2106
        }
2107

2108
        // Dummy event writer
2109
        let mut event_reader_system_state: SystemState<EventReader<TweenCompleted>> =
2110
            SystemState::new(&mut world);
2111

2112
        // Register callbacks to count completed events
2113
        let callback_monitor = Arc::new(Mutex::new(CallbackMonitor::default()));
2114
        let cb_mon_ptr = Arc::clone(&callback_monitor);
2115
        let reference_entity = entity;
2116
        assert!(delay.on_completed.is_none());
2117
        delay.set_completed(move |completed_entity, delay| {
2118
            assert_eq!(completed_entity, reference_entity);
2119
            let mut cb_mon = cb_mon_ptr.lock().unwrap();
2120
            cb_mon.invoke_count += 1;
2121
            cb_mon.last_reported_count = delay.times_completed();
2122
        });
2123
        assert!(delay.on_completed.is_some());
2124
        assert_eq!(callback_monitor.lock().unwrap().invoke_count, 0);
2125

2126
        for i in 1..=6 {
2127
            let state = manual_tick_component::<Transform>(
2128
                Duration::from_millis(200),
2129
                &mut delay,
2130
                &mut world,
2131
                entity,
2132
            );
2133

2134
            // Propagate events
2135
            {
2136
                let mut events = world.resource_mut::<Events<TweenCompleted>>();
2137
                events.update();
2138
            }
2139

2140
            // Check state
2141
            {
2142
                assert_eq!(state, delay.state());
2143

2144
                let tweenable: &dyn Tweenable<Transform> = &delay;
2145

2146
                {
2147
                    let mut event_reader = event_reader_system_state.get_mut(&mut world);
2148
                    let event = event_reader.read().next();
2149
                    if i == 5 {
2150
                        assert!(event.is_some());
2151
                        let event = event.unwrap();
2152
                        assert_eq!(event.entity, entity);
2153
                        assert_eq!(event.user_data, USER_DATA);
2154
                    } else {
2155
                        assert!(event.is_none());
2156
                    }
2157
                }
2158

2159
                let times_completed = if i < 5 {
2160
                    assert_eq!(state, TweenState::Active);
2161
                    assert!(!delay.is_completed());
2162
                    assert_eq!(tweenable.times_completed(), 0);
2163
                    let r = i as f32 * 0.2;
2164
                    assert_approx_eq!(tweenable.progress(), r);
2165
                    0
2166
                } else {
2167
                    assert_eq!(state, TweenState::Completed);
2168
                    assert!(delay.is_completed());
2169
                    assert_eq!(tweenable.times_completed(), 1);
2170
                    assert_approx_eq!(tweenable.progress(), 1.);
2171
                    1
2172
                };
2173

2174
                let cb_mon = callback_monitor.lock().unwrap();
2175
                assert_eq!(cb_mon.invoke_count, times_completed as u64);
2176
                assert_eq!(cb_mon.last_reported_count, times_completed);
2177
            }
2178
        }
2179

2180
        delay.rewind();
2181
        assert_eq!(delay.times_completed(), 0);
2182
        assert_approx_eq!(delay.progress(), 0.);
2183
        let state = manual_tick_component(Duration::ZERO, &mut delay, &mut world, entity);
2184
        assert_eq!(state, TweenState::Active);
2185

2186
        delay.set_progress(0.3);
2187
        assert_eq!(delay.times_completed(), 0);
2188
        assert_approx_eq!(delay.progress(), 0.3);
2189
        delay.set_progress(1.);
2190
        assert_eq!(delay.times_completed(), 1);
2191
        assert_approx_eq!(delay.progress(), 1.);
2192

2193
        // Clear callback
2194
        delay.clear_completed();
2195
        assert!(delay.on_completed.is_none());
2196

2197
        // Clear event sending
2198
        delay.clear_completed_event();
2199
        assert!(delay.event_data.is_none());
2200
    }
2201

2202
    #[test]
2203
    fn delay_elapsed() {
2204
        let mut delay: Delay<f32> = Delay::new(Duration::from_secs(1));
2205
        let duration = delay.duration();
2206
        for ms in [0, 1, 500, 100, 300, 999, 847, 1000, 900] {
2207
            let elapsed = Duration::from_millis(ms);
2208
            delay.set_elapsed(elapsed);
2209
            assert_eq!(delay.elapsed(), elapsed);
2210

2211
            let progress = (elapsed.as_secs_f64() / duration.as_secs_f64()) as f32;
2212
            assert_approx_eq!(delay.progress(), progress);
2213

2214
            let times_completed = u32::from(ms == 1000);
2215
            assert_eq!(delay.times_completed(), times_completed);
2216

2217
            assert_eq!(delay.is_completed(), ms >= 1000);
2218
            assert_eq!(
2219
                delay.state(),
2220
                if ms >= 1000 {
2221
                    TweenState::Completed
2222
                } else {
2223
                    TweenState::Active
2224
                }
2225
            );
2226
        }
2227
    }
2228

2229
    #[test]
2230
    #[should_panic]
2231
    fn delay_zero_duration_panics() {
2232
        let _: Delay<f32> = Delay::new(Duration::ZERO);
2233
    }
2234

2235
    #[test]
2236
    fn tween_repeat() {
2237
        let mut tween = make_test_tween()
2238
            .with_repeat_count(RepeatCount::Finite(5))
2239
            .with_repeat_strategy(RepeatStrategy::Repeat);
2240

2241
        assert_approx_eq!(tween.progress(), 0.);
2242

2243
        let (mut world, entity, _system_id) = make_test_env();
2244

2245
        // 10%
2246
        let state =
2247
            manual_tick_component(Duration::from_millis(100), &mut tween, &mut world, entity);
2248
        assert_eq!(TweenState::Active, state);
2249
        assert_eq!(0, tween.times_completed());
2250
        assert_approx_eq!(tween.progress(), 0.1);
2251
        let transform = world.entity(entity).get::<Transform>().unwrap();
2252
        assert!(transform.translation.abs_diff_eq(Vec3::splat(0.1), 1e-5));
2253

2254
        // 130%
2255
        let state =
2256
            manual_tick_component(Duration::from_millis(1200), &mut tween, &mut world, entity);
2257
        assert_eq!(TweenState::Active, state);
2258
        assert_eq!(1, tween.times_completed());
2259
        assert_approx_eq!(tween.progress(), 0.3);
2260
        let transform = world.entity(entity).get::<Transform>().unwrap();
2261
        assert!(transform.translation.abs_diff_eq(Vec3::splat(0.3), 1e-5));
2262

2263
        // 480%
2264
        let state =
2265
            manual_tick_component(Duration::from_millis(3500), &mut tween, &mut world, entity);
2266
        assert_eq!(TweenState::Active, state);
2267
        assert_eq!(4, tween.times_completed());
2268
        assert_approx_eq!(tween.progress(), 0.8);
2269
        let transform = world.entity(entity).get::<Transform>().unwrap();
2270
        assert!(transform.translation.abs_diff_eq(Vec3::splat(0.8), 1e-5));
2271

2272
        // 500% - done
2273
        let state =
2274
            manual_tick_component(Duration::from_millis(200), &mut tween, &mut world, entity);
2275
        assert_eq!(TweenState::Completed, state);
2276
        assert_eq!(5, tween.times_completed());
2277
        assert_approx_eq!(tween.progress(), 1.0);
2278
        let transform = world.entity(entity).get::<Transform>().unwrap();
2279
        assert!(transform.translation.abs_diff_eq(Vec3::ONE, 1e-5));
2280
    }
2281

2282
    #[test]
2283
    fn tween_mirrored_rewind() {
2284
        let mut tween = make_test_tween()
2285
            .with_repeat_count(RepeatCount::Finite(4))
2286
            .with_repeat_strategy(RepeatStrategy::MirroredRepeat);
2287

2288
        assert_approx_eq!(tween.progress(), 0.);
2289

2290
        let (mut world, entity, _system_id) = make_test_env();
2291

2292
        // 10%
2293
        let state =
2294
            manual_tick_component(Duration::from_millis(100), &mut tween, &mut world, entity);
2295
        assert_eq!(TweenState::Active, state);
2296
        assert_eq!(TweeningDirection::Forward, tween.direction());
2297
        assert_eq!(0, tween.times_completed());
2298
        assert_approx_eq!(tween.progress(), 0.1);
2299
        let transform = world.entity(entity).get::<Transform>().unwrap();
2300
        assert!(transform.translation.abs_diff_eq(Vec3::splat(0.1), 1e-5));
2301

2302
        // rewind
2303
        tween.rewind();
2304
        assert_eq!(TweeningDirection::Forward, tween.direction());
2305
        assert_eq!(0, tween.times_completed());
2306
        assert_approx_eq!(tween.progress(), 0.);
2307
        let transform = world.entity(entity).get::<Transform>().unwrap();
2308
        assert!(transform.translation.abs_diff_eq(Vec3::splat(0.1), 1e-5)); // no-op, rewind doesn't apply Lens
2309

2310
        // 120% - mirror
2311
        let state =
2312
            manual_tick_component(Duration::from_millis(1200), &mut tween, &mut world, entity);
2313
        assert_eq!(TweeningDirection::Backward, tween.direction());
2314
        assert_eq!(TweenState::Active, state);
2315
        assert_eq!(1, tween.times_completed());
2316
        assert_approx_eq!(tween.progress(), 0.2);
2317
        let transform = world.entity(entity).get::<Transform>().unwrap();
2318
        assert!(transform.translation.abs_diff_eq(Vec3::splat(0.8), 1e-5));
2319

2320
        // rewind
2321
        tween.rewind();
2322
        assert_eq!(TweeningDirection::Forward, tween.direction()); // restored
2323
        assert_eq!(0, tween.times_completed());
2324
        assert_approx_eq!(tween.progress(), 0.);
2325
        let transform = world.entity(entity).get::<Transform>().unwrap();
2326
        assert!(transform.translation.abs_diff_eq(Vec3::splat(0.8), 1e-5)); // no-op, rewind doesn't apply Lens
2327

2328
        // 400% - done mirror (because Completed freezes the state)
2329
        let state =
2330
            manual_tick_component(Duration::from_millis(4000), &mut tween, &mut world, entity);
2331
        assert_eq!(TweenState::Completed, state);
2332
        assert_eq!(TweeningDirection::Backward, tween.direction()); // frozen from last loop
2333
        assert_eq!(4, tween.times_completed());
2334
        assert_approx_eq!(tween.progress(), 1.); // Completed
2335
        let transform = world.entity(entity).get::<Transform>().unwrap();
2336
        assert!(transform.translation.abs_diff_eq(Vec3::ZERO, 1e-5));
2337

2338
        // rewind
2339
        tween.rewind();
2340
        assert_eq!(TweeningDirection::Forward, tween.direction()); // restored
2341
        assert_eq!(0, tween.times_completed());
2342
        assert_approx_eq!(tween.progress(), 0.);
2343
        let transform = world.entity(entity).get::<Transform>().unwrap();
2344
        assert!(transform.translation.abs_diff_eq(Vec3::ZERO, 1e-5)); // no-op, rewind doesn't apply Lens
2345
    }
2346
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc