forked from djeedai/bevy_tweening
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtweenable.rs
More file actions
2515 lines (2275 loc) · 94.1 KB
/
Copy pathtweenable.rs
File metadata and controls
2515 lines (2275 loc) · 94.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{any::TypeId, cmp::Ordering, time::Duration};
use bevy::{ecs::change_detection::MutUntyped, prelude::*};
use crate::{AnimTargetKind, EaseMethod, Lens, PlaybackDirection, RepeatCount, RepeatStrategy};
/// The dynamic tweenable type.
///
/// When creating lists of tweenables, you will need to box them to create a
/// homogeneous array like so:
///
/// ```no_run
/// # use bevy::prelude::Transform;
/// # use bevy_tweening::{BoxedTweenable, Delay, Sequence, Tween};
/// #
/// # let delay: Delay = unimplemented!();
/// # let tween: Tween = unimplemented!();
///
/// Sequence::new([Box::new(delay) as BoxedTweenable, tween.into()]);
/// ```
///
/// When using your own [`Tweenable`] types, APIs will be easier to use if you
/// implement [`From`]:
///
/// ```no_run
/// # use std::{any::TypeId, time::Duration};
/// # use bevy::ecs::{system::{Commands, SystemId}, change_detection::MutUntyped};
/// # use bevy::prelude::*;
/// # use bevy_tweening::{BoxedTweenable, Sequence, Tweenable, CycleCompletedEvent, TweenState, TotalDuration};
/// #
/// # #[derive(Debug)]
/// # struct MyTweenable;
/// # impl Tweenable for MyTweenable {
/// # fn cycle_duration(&self) -> Duration { unimplemented!() }
/// # fn total_duration(&self) -> TotalDuration { unimplemented!() }
/// # fn set_elapsed(&mut self, elapsed: Duration) { unimplemented!() }
/// # fn elapsed(&self) -> Duration { unimplemented!() }
/// # fn step(&mut self, tween_id: Entity, delta: Duration, target: MutUntyped, target_type_id: &TypeId, notify_cycle_completed: &mut dyn FnMut(),) -> (TweenState, bool) { unimplemented!() }
/// # fn rewind(&mut self) { unimplemented!() }
/// # fn cycles_completed(&self) -> u32 { unimplemented!() }
/// # fn cycle_fraction(&self) -> f32 { unimplemented!() }
/// # fn target_type_id(&self) -> Option<TypeId> { unimplemented!() }
/// # }
///
/// Sequence::new([Box::new(MyTweenable) as BoxedTweenable]);
///
/// // OR
///
/// Sequence::new([MyTweenable]);
///
/// impl From<MyTweenable> for BoxedTweenable {
/// fn from(t: MyTweenable) -> Self {
/// Box::new(t)
/// }
/// }
/// ```
pub type BoxedTweenable = Box<dyn Tweenable + 'static>;
/// Helper trait to accept boxed and non-boxed tweenables in various functions.
pub trait IntoBoxedTweenable {
/// Convert to a [`BoxedTweenable`].
fn into_boxed(self) -> BoxedTweenable;
}
impl IntoBoxedTweenable for BoxedTweenable {
fn into_boxed(self) -> BoxedTweenable {
self
}
}
impl<T: Tweenable + 'static> IntoBoxedTweenable for T {
fn into_boxed(self) -> BoxedTweenable {
Box::new(self)
}
}
/// Playback state of a [`Tweenable`].
///
/// This is returned by [`Tweenable::step()`] to allow the caller to execute
/// some logic based on the updated state of the tweenable, like advanding a
/// sequence to its next child tweenable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TweenState {
/// The tweenable is still active, and did not reach its end state yet.
Active,
/// Animation reached its end state. The tweenable is idling at its latest
/// time.
///
/// Note that [`RepeatCount::Infinite`] tweenables never reach this state.
Completed,
}
/// Event raised when an animation completed a single cycle.
///
/// This event is raised when a [`Tweenable`] animation completed a single
/// cycle. In case the animation direction changes each cycle
/// ([`RepeatStrategy::MirroredRepeat`]), a cycle corresponds to a single
/// progress from one endpoint value of the lens to the other, whatever the
/// direction. Therefore a complete loop start -> end -> start counts as 2
/// cycles and raises 2 events (one when reaching the end value, one when
/// reaching back the start value).
///
/// # Note
///
/// The semantic is different from [`TweenState::Completed`], which indicates
/// that the tweenable has finished stepping and do not need to be updated
/// anymore, a state which is never reached for looping animation. Here the
/// [`CycleCompletedEvent`] instead marks the end of a single cycle.
#[derive(Copy, Clone, EntityEvent, Message)]
pub struct CycleCompletedEvent {
/// The entity owning the tweenable animation which completed.
///
/// This is the entity owning the [`TweenAnim`] component that the tweenable
/// which completed is part of.
///
/// [`TweenAnim`]: crate::TweenAnim
#[event_target]
pub anim_entity: Entity,
/// The target the tweenable which completed and the [`TweenAnim`] it's
/// part of are mutating. Note that an actual [`AnimTarget`] component might
/// not be spawned in the ECS world, if the target is a component on the
/// same entity as the one owning the [`TweenAnim`] ("implicit component
/// targetting"). But this field is always equal to the valid value that
/// would otherwise exist as component.
///
/// [`TweenAnim`]: crate::TweenAnim
/// [`AnimTarget`]: crate::AnimTarget
pub target: AnimTargetKind,
}
#[derive(Debug)]
struct AnimClock {
elapsed: Duration,
cycle_duration: Duration,
total_duration: TotalDuration,
strategy: RepeatStrategy,
}
impl AnimClock {
fn new(cycle_duration: Duration) -> Self {
Self {
elapsed: Duration::ZERO,
cycle_duration,
total_duration: TotalDuration::from_cycles(cycle_duration, RepeatCount::default()),
strategy: RepeatStrategy::default(),
}
}
fn tick(&mut self, tick: Duration) -> (TweenState, i32) {
let mut next_elapsed = self.elapsed.saturating_add(tick);
let mut extra_completed: i32 = 0;
if !self.total_duration.is_finite() {
// Infinite tweens loops around...
let period = if self.strategy == RepeatStrategy::MirroredRepeat {
// ...over 2 cycles if mirrored
self.cycle_duration * 2
} else {
// ...over 1 cycle if not
self.cycle_duration
};
if next_elapsed >= period {
// Common case, just loop once
next_elapsed -= period;
extra_completed += 1;
// In case of very large jumps, handle arbitrary cycle count
if next_elapsed >= period {
let count = next_elapsed.div_duration_f64(period) as u32;
next_elapsed -= period * count;
extra_completed += count as i32;
debug_assert!(next_elapsed < period);
}
}
};
let (state, mut times_completed) =
self.set_elapsed(next_elapsed, PlaybackDirection::Forward);
if extra_completed > 0 && (times_completed < 0) {
// The clock looped around, so returns -1. But we're already counting that loop
// in the extra cycles calculated above. It can't return anything else than -1
// or 0 because we clamped next_elapsed.
debug_assert_eq!(-1, times_completed);
times_completed = 0;
}
(state, times_completed + extra_completed)
}
fn tick_back(&mut self, mut tick: Duration) -> (TweenState, i32) {
let mut next_elapsed = self.elapsed.saturating_sub(tick);
if !self.total_duration.is_finite() && (tick >= self.elapsed) {
// Infinite tweens loops around...
let period = if self.strategy == RepeatStrategy::MirroredRepeat {
// ...over 2 cycles if mirrored
self.cycle_duration * 2
} else {
// ...over 1 cycle if not
self.cycle_duration
};
// Consume some time to move back to t=0
tick -= self.elapsed;
// In case of very large jumps, handle arbitrary cycle count
if tick >= period {
let count = tick.div_duration_f64(period) as u32;
tick -= period * count;
}
// Common case, just loop once
debug_assert!(tick < period);
next_elapsed = if tick == Duration::ZERO {
Duration::ZERO
} else {
period - tick
};
};
self.set_elapsed(next_elapsed, PlaybackDirection::Backward)
}
/// Get the elapsed cycle index, accounting for finite clock endpoint.
fn cycle_index(&self) -> u32 {
let index = self.elapsed.div_duration_f64(self.cycle_duration) as u32;
if let TotalDuration::Finite(total_duration) = self.total_duration {
if self.elapsed >= total_duration {
return index - 1;
}
}
index
}
/// Get the elapsed cycle fraction, accounting for finite clock endpoint.
fn cycle_fraction(&self) -> f32 {
let factor = self.elapsed.div_duration_f64(self.cycle_duration).fract() as f32;
if let TotalDuration::Finite(total_duration) = self.total_duration {
if self.elapsed >= total_duration {
return 1.0;
}
}
factor
}
/// Get the mirroring-aware cycle fraction, accounting for finite clock
/// endpoint.
fn mirrored_cycle_fraction(&self) -> f32 {
let ratio = self.elapsed.div_duration_f64(self.cycle_duration);
let index = ratio as u32;
let factor = ratio.fract() as f32;
if let TotalDuration::Finite(total_duration) = self.total_duration {
if self.elapsed >= total_duration {
if self.is_cycle_mirrored(index - 1) {
return 0.0;
} else {
return 1.0;
}
}
}
if self.is_cycle_mirrored(index) {
1.0 - factor
} else {
factor
}
}
/// Check if the current cycle is a mirrored cycle.
#[must_use]
#[inline]
pub fn is_cycle_mirrored(&self, index: u32) -> bool {
if self.strategy == RepeatStrategy::MirroredRepeat {
(index & 1) != 0
} else {
false
}
}
fn times_completed(&self) -> u32 {
self.elapsed.div_duration_f64(self.cycle_duration) as u32
}
fn set_elapsed(
&mut self,
elapsed: Duration,
direction: PlaybackDirection,
) -> (TweenState, i32) {
let old_times_completed = self.times_completed();
self.elapsed = elapsed;
let state = match self.total_duration {
TotalDuration::Finite(total_duration) => {
// Always clamp
self.elapsed = self.elapsed.min(total_duration);
if (direction.is_forward() && self.elapsed >= total_duration)
|| (direction.is_backward() && self.elapsed == Duration::ZERO)
{
TweenState::Completed
} else {
TweenState::Active
}
}
TotalDuration::Infinite => TweenState::Active,
};
(
state,
self.times_completed() as i32 - old_times_completed as i32,
)
}
fn elapsed(&self) -> Duration {
self.elapsed
}
fn state(&self, playback_direction: PlaybackDirection) -> TweenState {
match self.total_duration {
TotalDuration::Finite(total_duration) => {
if (playback_direction.is_forward() && self.elapsed >= total_duration)
|| (playback_direction.is_backward() && self.elapsed == Duration::ZERO)
{
TweenState::Completed
} else {
TweenState::Active
}
}
TotalDuration::Infinite => TweenState::Active,
}
}
fn rewind(&mut self, direction: PlaybackDirection) {
self.elapsed = match direction {
PlaybackDirection::Forward => Duration::ZERO,
PlaybackDirection::Backward => self.total_duration.as_finite().unwrap(),
};
}
}
/// Possibly infinite duration of an animation.
///
/// Used to measure the total duration of an animation including any looping.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TotalDuration {
/// The duration is finite, of the given value.
Finite(Duration),
/// The duration is infinite.
Infinite,
}
impl TotalDuration {
/// Create a [`TotalDuration`] from single cycle duration and a
/// [`RepeatCount`].
pub fn from_cycles(cycle_duration: Duration, repeat_count: RepeatCount) -> Self {
match repeat_count {
RepeatCount::Finite(times) => {
TotalDuration::Finite(cycle_duration.saturating_mul(times))
}
RepeatCount::For(duration) => TotalDuration::Finite(duration),
RepeatCount::Infinite => TotalDuration::Infinite,
}
}
/// Return `true` if this is a [`TotalDuration::Finite`].
pub fn is_finite(&self) -> bool {
matches!(self, TotalDuration::Finite(_))
}
/// Return this duration as a [`Duration`] if it's finite.
pub fn as_finite(&self) -> Option<Duration> {
match self {
Self::Finite(duration) => Some(*duration),
Self::Infinite => None,
}
}
}
impl From<Duration> for TotalDuration {
fn from(value: Duration) -> Self {
TotalDuration::Finite(value)
}
}
impl std::ops::Add for TotalDuration {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
match (self, rhs) {
(TotalDuration::Finite(d0), TotalDuration::Finite(d1)) => {
TotalDuration::Finite(d0 + d1)
}
_ => TotalDuration::Infinite,
}
}
}
impl std::iter::Sum for TotalDuration {
fn sum<I: Iterator<Item = Self>>(mut iter: I) -> Self {
let Some(mut acc) = iter.next() else {
return TotalDuration::Finite(Duration::ZERO);
};
for td in iter {
acc = acc + td;
}
acc
}
}
impl PartialOrd for TotalDuration {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for TotalDuration {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(TotalDuration::Finite(d0), TotalDuration::Finite(d1)) => d0.cmp(d1),
(TotalDuration::Finite(_), TotalDuration::Infinite) => Ordering::Less,
(TotalDuration::Infinite, TotalDuration::Finite(_)) => Ordering::Greater,
(TotalDuration::Infinite, TotalDuration::Infinite) => Ordering::Equal,
}
}
}
/// Tweening animation description, either a single [`Tween`] or a collection of
/// them.
pub trait Tweenable: Send + Sync {
/// Get the duration of a single cycle of the animation.
///
/// Note that for [`RepeatStrategy::MirroredRepeat`], this is the duration
/// of a single way, either from start to end or back from end to start.
/// The total "loop" duration start -> end -> start to reach back the
/// same state in this case is the double of the cycle duration.
#[must_use]
fn cycle_duration(&self) -> Duration;
/// Get the total duration of the entire animation, including repeating.
///
/// For [`TotalDuration::Finite`], this is the number of repeats times the
/// duration of a single cycle ([`cycle_duration()`]).
///
/// [`cycle_duration()`]: Self::cycle_duration
#[must_use]
fn total_duration(&self) -> TotalDuration;
/// Set the current animation playback elapsed time.
///
/// See [`elapsed()`] for details on the meaning. For finite durations, if
/// `elapsed` is greater than or equal to [`total_duration()`], then the
/// animation completes. Animations with infinite duration never complete.
///
/// Setting the elapsed time seeks the animation to a new position, but does
/// not apply that change to the underlying component being animated yet. To
/// force the change to apply, call [`step()`] with a `delta` of
/// `Duration::ZERO`, or wait for it to be automatically called.
///
/// [`elapsed()`]: Tweenable::elapsed
/// [`total_duration()`]: Tweenable::total_duration
/// [`step()`]: Tweenable::step
fn set_elapsed(&mut self, elapsed: Duration);
/// Get the current elapsed duration.
///
/// The elapsed duration is the time from the start of the tweening
/// animation. It includes all cycles; if the animation repeats (has more
/// than one cycle), the value can be greater than one
/// [`cycle_duration()`]. The value differs depending on whether the
/// animation repeat infinitely or not:
/// - For **finite** repeat counts, including no repeat at all (count = 1),
/// the value is always between `0` and [`total_duration()`]. It
/// represents the absolute position over the timeline of all cycles.
/// - For **infinite** repeat, the value loops around after either 1 cycle
/// (for [`RepeatStrategy::Repeat`]) or 2 cycles (for
/// [`RepeatStrategy::MirroredRepeat`]). The latter is necessary to
/// account for one non-mirrored cycle and one mirrored one.
///
/// [`cycle_duration()`]: Tweenable::cycle_duration
/// [`total_duration()`]: Tweenable::total_duration
#[must_use]
fn elapsed(&self) -> Duration;
/// Step the tweenable.
///
/// Advance the internal clock of the animation by the specified amount of
/// time. If the animation is currently playing backward
/// ([`PlaybackDirection::Backward`]), the clock moves backward and the
/// `delta` duration is subtracted from the [`elapsed()`] time instead of
/// being added to it.
///
/// Note that `delta = Duration::ZERO` is valid, and is sometimes useful to
/// force applying the result of a state change to the underlying
/// animation target.
///
/// # Returns
///
/// Returns the state of the tweenable after the step.
///
/// [`elapsed()`]: Tweenable::elapsed
fn step(
&mut self,
tween_id: Entity,
delta: Duration,
target: MutUntyped,
target_type_id: &TypeId,
notify_cycle_completed: &mut dyn FnMut(),
) -> (TweenState, bool);
/// Rewind the animation to its starting state.
///
/// Note that the starting state depends on the current direction. For
/// [`PlaybackDirection::Forward`] this is the start point of the lens,
/// whereas for [`PlaybackDirection::Backward`] this is the end one.
///
/// # Panics
///
/// This panics if the current playback direction is
/// [`PlaybackDirection::Backward`] and the animation is infinitely
/// repeating.
fn rewind(&mut self);
/// Get the number of cycles completed.
///
/// For repeating animations, this returns the number of times a single
/// playback cycle was completed. In the case of
/// [`RepeatStrategy::MirroredRepeat`] this corresponds to a playback in
/// a single direction, so tweening from start to end and back to start
/// counts as two completed cycles (one forward, one backward).
#[must_use]
fn cycles_completed(&self) -> u32 {
self.elapsed().div_duration_f64(self.cycle_duration()) as u32
}
/// Get the completion fraction in `[0:1]` of the current cycle.
#[must_use]
fn cycle_fraction(&self) -> f32 {
self.elapsed()
.div_duration_f64(self.cycle_duration())
.fract() as f32
}
/// Get the [`TypeId`] this tweenable targets.
///
/// This returns the type of the component or asset that the [`TweenAnim`]
/// needs to fetch from the ECS `World` in order to resolve the animation
/// target.
///
/// # Returns
///
/// Returns the type of the target, if any, or `None` if this tweenable is
/// untyped. Typically only [`Delay`] is untyped, as this is the only
/// tweenable which doesn't actually mutate the target, so it doesn't
/// actually have any target type associated with it.
///
/// [`TweenAnim`]: crate::TweenAnim
#[must_use]
fn target_type_id(&self) -> Option<TypeId>;
}
macro_rules! impl_boxed {
($tweenable:ty) => {
impl From<$tweenable> for BoxedTweenable {
fn from(t: $tweenable) -> Self {
Box::new(t)
}
}
};
}
impl_boxed!(Tween);
impl_boxed!(Sequence);
impl_boxed!(Delay);
type TargetAction = dyn FnMut(MutUntyped, f32) + Send + Sync + 'static;
/// Configuration to create a [`Tween`].
///
/// This is largely an internal type, only exposed due to other constraints.
#[doc(hidden)]
#[derive(Default, Clone, Copy)]
pub struct TweenConfig {
/// Ease method.
pub ease_method: EaseMethod,
/// Playback direction.
pub playback_direction: PlaybackDirection,
/// Send [`CycleCompletedEvent`]?
pub send_cycle_completed_event: bool,
/// Cycle duration.
pub cycle_duration: Duration,
/// Repeat count.
pub repeat_count: RepeatCount,
/// Repeat strategy.
pub repeat_strategy: RepeatStrategy,
}
/// Single tweening animation description.
///
/// A _tween_ is the basic building block of an animation. It describes a single
/// tweening animation between two values, accessed through a given [`Lens`].
/// The animation is composed of one or more cycles, and can be played forward
/// or backward. On completion, you can be notified via events, observers, or
/// the execution of a one-shot system.
///
/// _If you're looking for the runtime representation of a tweenable animation,
/// see [`TweenAnim`] instead._
///
/// # Cycles
///
/// A tween can be configured to repeat multiple, or even an infinity, of times.
/// Each repeat iteration is called a _cycle_. The duration of a single cycle is
/// the _cycle duration_, and the duration of the entire tween animation
/// including all cycles is the _total duration_.
#[doc = include_str!("../images/tween_cycles.svg")]
///
/// _An example tween with 5 cycles._
///
/// The number of cycles is configured through the [`RepeatCount`].
///
/// - [`RepeatCount::Finite`] directly sets a number of cycles. The total
/// duration is inferred from the cycle duration and number of cycles.
/// - [`RepeatCount::For`] selects a total duration for the animation, from
/// which a number of cycles is derived. In that case, the number of cycles
/// may be a fractional number; the last cycle is only partial, and may not
/// reach the endpoint of the lens.
/// - [`RepeatCount::Infinite`] enables infinitely-repeating cycles. In that
/// case the total duration of the animation is infinite, and the animation
/// itself is said to be infinite.
///
/// The _repeat strategy_ determines whether cycles are mirrored when they
/// repeat. By default, all cycles produce a linear _ratio_ monotonically
/// increasing from `0` to `1`. When mirrored, every other cycle instead
/// produces a _decreasing_ ratio from `1` to `0`. The repeat strategy is
/// configured with [`RepeatStrategy`].
#[doc = include_str!("../images/tween_mirrored.svg")]
///
/// _A tween with 5 cycles, using the mirrored repeat strategy._
///
/// Once the ratio in `[0:1]` has been calculated, it's passed through the
/// easing function to obtain the final interpolation factor that
/// [`Lens::lerp()`] receives.
///
/// # Elapsed time and playback direction
///
/// The _elapsed time_ of an animation represents the current time since the
/// start of the animation. This includes all cycles, and is bound by the total
/// duration of the animation. This is a property of an active animation, and is
/// available per instance from the [`TweenAnim`] representing the instance. So
/// a tween itself, which describes an animation without a specific target to
/// animate, doesn't have an elapsed time. You can think of the elapsed time as
/// the current time position on some animation timeline.
///
/// The tween however has a _playback direction_. By default, the playback
/// direction is [`PlaybackDirection::Forward`], and the animation plays forward
/// as described above. By instead using [`PlaybackDirection::Backward`], the
/// tween plays in reverse from end to start. Practically, this means that the
/// elapsed time _decreases_ from its current value back to zero, and the
/// animation completes at `t=0`. You can think of the playback direction as the
/// direction in which the time position moves on some animation timeline. Note
/// that as a result, because infinite animations ([`RepeatCount::Infinite`])
/// don't have an end time, they cannot be rewinded when the playback direction
/// is backward.
///
/// # Completion events and one-shot systems
///
/// Sometimes, you want to be notified of the completion of an animation cycle,
/// or the completion of the entire animation itself. To that end, the [`Tween`]
/// supports several mechanisms:
///
/// - Each time a _single_ cycle is completed, the tween can emit a
/// [`CycleCompletedEvent`]. The event is emitted as a buffered event, to be
/// read by another system through an [`MessageReader`]. For component
/// targets, observers are also triggered. Both of these are enabled through
/// [`with_cycle_completed_event()`] and [`set_cycle_completed_event()`].
/// Per-cycle events are disabled by default.
/// - At the end of all cycles, when the animation itself completes, the tween
/// emits an [`AnimCompletedEvent`]. This event is always emitted.
///
/// [`TweenAnim`]: crate::TweenAnim
/// [`with_cycle_completed_event()`]: Self::with_cycle_completed_event
/// [`set_cycle_completed_event()`]: Self::set_cycle_completed_event
/// [`AnimCompletedEvent`]: crate::AnimCompletedEvent
pub struct Tween {
ease_method: EaseMethod,
clock: AnimClock,
/// Direction of playback the user asked for.
playback_direction: PlaybackDirection,
action: Box<TargetAction>,
send_cycle_completed_event: bool,
/// Type ID of the target.
type_id: TypeId,
}
impl Tween {
/// Create a new tween animation.
///
/// The new animation is described by a given cycle duration, a repeat count
/// which determines its total duration, as well as an easing function and a
/// lens describing how the cycles affect the animation target. The target
/// type is implicitly determined by the type `T` of the [`Lens<T>`]
/// argument.
///
/// # Example
///
/// ```
/// # use bevy_tweening::{lens::*, *};
/// # use bevy::math::{Vec3, curve::EaseFunction};
/// # use std::time::Duration;
/// let tween = Tween::new(
/// EaseFunction::QuadraticInOut,
/// Duration::from_secs(1),
/// TransformPositionLens {
/// start: Vec3::ZERO,
/// end: Vec3::new(3.5, 0., 0.),
/// },
/// );
/// ```
#[inline]
#[must_use]
pub fn new<T, L>(
ease_method: impl Into<EaseMethod>,
cycle_duration: Duration,
mut lens: L,
) -> Self
where
T: 'static,
L: Lens<T> + Send + Sync + 'static,
{
let action = move |ptr: MutUntyped, ratio: f32| {
// SAFETY: ptr was obtained from the same type, via the type_id saved below.
#[allow(unsafe_code)]
let target = unsafe { ptr.with_type::<T>() };
lens.lerp(target, ratio);
};
Self {
ease_method: ease_method.into(),
clock: AnimClock::new(cycle_duration),
playback_direction: PlaybackDirection::Forward,
action: Box::new(action),
send_cycle_completed_event: false,
type_id: TypeId::of::<T>(),
}
}
#[inline]
#[must_use]
pub(crate) fn from_config<T, L>(config: TweenConfig, mut lens: L) -> Self
where
T: 'static,
L: Lens<T> + Send + Sync + 'static,
{
let action = move |ptr: MutUntyped, ratio: f32| {
// SAFETY: ptr was obtained from the same type, via the type_id saved below.
#[allow(unsafe_code)]
let target = unsafe { ptr.with_type::<T>() };
lens.lerp(target, ratio);
};
let this = Self {
ease_method: config.ease_method,
clock: AnimClock::new(config.cycle_duration),
playback_direction: config.playback_direction,
action: Box::new(action),
send_cycle_completed_event: config.send_cycle_completed_event,
type_id: TypeId::of::<T>(),
};
this.with_repeat(config.repeat_count, config.repeat_strategy)
}
/// Set the number of times to repeat the animation.
///
/// The repeat count determines the number of cycles of the animation. See
/// [the top-level `Tween` documentation] for details.
///
/// [the top-level `Tween` documentation]: crate::Tween#cycles
#[must_use]
pub fn with_repeat_count(mut self, count: impl Into<RepeatCount>) -> Self {
self.clock.total_duration =
TotalDuration::from_cycles(self.clock.cycle_duration, count.into());
self
}
/// Set the number of times to repeat the animation.
///
/// The repeat count determines the number of cycles of the animation. See
/// [the top-level `Tween` documentation] for details.
///
/// [the top-level `Tween` documentation]: crate::Tween#cycles
pub fn set_repeat_count(&mut self, count: impl Into<RepeatCount>) {
self.clock.total_duration =
TotalDuration::from_cycles(self.clock.cycle_duration, count.into());
}
/// Configure how the cycles repeat.
///
/// This enables or disables cycle mirroring. See [the top-level `Tween`
/// documentation] for details.
///
/// [the top-level `Tween` documentation]: crate::Tween#cycles
#[must_use]
pub fn with_repeat_strategy(mut self, strategy: RepeatStrategy) -> Self {
self.clock.strategy = strategy;
self
}
/// Configure how the cycles repeat.
///
/// This enables or disables cycle mirroring. See [the top-level `Tween`
/// documentation] for details.
///
/// [the top-level `Tween` documentation]: crate::Tween#cycles
pub fn set_repeat_strategy(&mut self, strategy: RepeatStrategy) {
self.clock.strategy = strategy;
}
/// Configure the animation repeat parameters.
///
/// The repeat count determines the number of cycles of the animation. The
/// repeat strategy enables or disables cycle mirrored repeat. See
/// [the top-level `Tween` documentation] for details.
///
/// [the top-level `Tween` documentation]: crate::Tween#cycles
#[must_use]
#[inline]
pub fn with_repeat(self, count: impl Into<RepeatCount>, strategy: RepeatStrategy) -> Self {
self.with_repeat_count(count).with_repeat_strategy(strategy)
}
/// Configure the animation repeat parameters.
///
/// The repeat count determines the number of cycles of the animation. The
/// repeat strategy enables or disables cycle mirrored repeat. See
/// [the top-level `Tween` documentation] for details.
///
/// [the top-level `Tween` documentation]: crate::Tween#cycles
#[inline]
pub fn set_repeat(&mut self, count: impl Into<RepeatCount>, strategy: RepeatStrategy) {
self.set_repeat_count(count);
self.set_repeat_strategy(strategy);
}
/// Enable raising a event on cycle completion.
///
/// If enabled, the tween will raise a [`CycleCompletedEvent`] each time
/// the tween completes a cycle (reaches or passes its cycle duration). In
/// case of repeating tweens (repeat count > 1), the event is raised once
/// per cycle. For mirrored repeats, a cycle is one travel from start to
/// end **or** end to start, so the full loop start -> end -> start counts
/// as 2 cycles and raises 2 events.
///
/// # Example
///
/// ```
/// # use bevy_tweening::{lens::*, *};
/// # use bevy::{ecs::message::MessageReader, math::{Vec3, curve::EaseFunction}};
/// # use std::time::Duration;
/// let tween = Tween::new(
/// // [...]
/// # EaseFunction::QuadraticInOut,
/// # Duration::from_secs(1),
/// # TransformPositionLens {
/// # start: Vec3::ZERO,
/// # end: Vec3::new(3.5, 0., 0.),
/// # },
/// )
/// // Raise a CycleCompletedEvent each cycle
/// .with_cycle_completed_event(true);
///
/// fn my_system(mut reader: MessageReader<CycleCompletedEvent>) {
/// for ev in reader.read() {
/// println!(
/// "Tween animation {:?} raised CycleCompletedEvent for target {:?}!",
/// ev.anim_entity, ev.target
/// );
/// }
/// }
/// ```
#[must_use]
pub fn with_cycle_completed_event(mut self, send: bool) -> Self {
self.send_cycle_completed_event = send;
self
}
/// Set whether the tween emits [`CycleCompletedEvent`].
///
/// See [`with_cycle_completed_event()`] for details.
///
/// [`with_cycle_completed_event()`]: Self::with_cycle_completed_event
pub fn set_cycle_completed_event(&mut self, send: bool) {
self.send_cycle_completed_event = send;
}
/// Set the playback direction of the tween.
///
/// The playback direction controls whether the internal animation clock,
/// and therefore also the elapsed time, both move forward or backward.
///
/// Changing the direction doesn't change any target state, nor the elapsed
/// time of the tween. Only the direction of playback from this moment
/// potentially changes.
pub fn set_playback_direction(&mut self, direction: PlaybackDirection) {
self.playback_direction = direction;
}
/// Set the playback direction of the tween.
///
/// See [`set_playback_direction()`] for details.
///
/// [`set_playback_direction()`]: Self::set_playback_direction
#[must_use]
pub fn with_playback_direction(mut self, direction: PlaybackDirection) -> Self {
self.playback_direction = direction;
self
}
/// The current animation playback direction.
///
/// This is the value set by the user with [`with_playback_direction()`] and
/// [`set_playback_direction()`]. This is never changed by the animation
/// playback itself.
///
/// See [`PlaybackDirection`] for details.
///
/// [`with_playback_direction()`]: Self::with_playback_direction
/// [`set_playback_direction()`]: Self::set_playback_direction
#[must_use]
pub fn playback_direction(&self) -> PlaybackDirection {
self.playback_direction
}
/// Chain another [`Tweenable`] after this tween, making a [`Sequence`] with
/// the two.
///
/// # Example
/// ```
/// # use bevy_tweening::{lens::*, *};
/// # use bevy::math::{*,curve::EaseFunction};
/// # use std::time::Duration;
/// let tween1 = Tween::new(
/// EaseFunction::QuadraticInOut,
/// Duration::from_secs(1),
/// TransformPositionLens {
/// start: Vec3::ZERO,
/// end: Vec3::new(3.5, 0., 0.),
/// },
/// );
/// let tween2 = Tween::new(
/// EaseFunction::QuadraticInOut,
/// Duration::from_secs(1),
/// TransformRotationLens {
/// start: Quat::IDENTITY,
/// end: Quat::from_rotation_x(90.0_f32.to_radians()),
/// },
/// );
/// let seq = tween1.then(tween2);
/// ```
#[must_use]
pub fn then(self, tween: impl Tweenable + 'static) -> Sequence {
Sequence::with_capacity(2).then(self).then(tween)
}
/// Get the elapsed cycle index (numbered from 0), accounting for finite
/// endpoint.
///
/// If the elapsed time is equal to the total (finite) duration of the
/// tween, then the cycle index is capped at the total number of cycles
/// minus 1 (the tween doesn't loop when reaching the end of its last
/// cycle). This means that for a tween with N cycles, the index is always
/// in `0..N`, and therefore always `index < N`.
#[must_use]
#[inline]
pub fn cycle_index(&self) -> u32 {
self.clock.cycle_index()
}
/// Get the elapsed cycle fraction, accounting for finite endpoint.
///
/// The elapsed cycle fraction is the fraction alonside one cycle where the
/// tween currently is. This ignores any mirroring. If the elapsed time is
/// equal to the total (finite) duration of the tween, then the cycle
/// fraction is capped at `1.0` (the tween doesn't loop when reaching
/// the end of its last cycle).
///
/// The returned value is always in `[0:1]` for finite tweens, with the
/// value `1.0` returned only when the last cycle is completed, and in
/// `[0:1)` for infinite tweens as they never complete.
#[must_use]
#[inline]
pub fn cycle_fraction(&self) -> f32 {
self.clock.cycle_fraction()
}
/// Check if the current cycle is a mirrored cycle.
///
/// When the repeat strategy is [`RepeatStrategy::MirroredRepeat`], every
/// odd cycle index (numbered from 0) is mirrored when applying the tween's
/// lens. For any other strategy or single-cycle tween, this is always
/// `false`.
#[must_use]
#[inline]