forked from djeedai/bevy_tweening
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.rs
More file actions
452 lines (389 loc) · 15.7 KB
/
Copy pathplugin.rs
File metadata and controls
452 lines (389 loc) · 15.7 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
use bevy::{ecs::component::Mutable, prelude::*};
#[cfg(feature = "bevy_asset")]
use crate::{tweenable::AssetTarget, AssetAnimator};
use crate::{tweenable::ComponentTarget, Animator, AnimatorState, TweenCompleted};
/// Plugin to add systems related to tweening of common components and assets.
///
/// This plugin adds systems for a predefined set of components and assets, to
/// allow their respective animators to be updated each frame:
/// - [`Transform`]
/// - [`TextColor`]
/// - [`Node`]
/// - [`Sprite`]
/// - [`ColorMaterial`]
///
/// This ensures that all predefined lenses work as intended, as well as any
/// custom lens animating the same component or asset type.
///
/// For other components and assets, including custom ones, the relevant system
/// needs to be added manually by the application:
/// - For components, add [`component_animator_system::<T>`] where `T:
/// Component`
/// - For assets, add [`asset_animator_system::<T>`] where `T: Asset`
///
/// This plugin is entirely optional. If you want more control, you can instead
/// add manually the relevant systems for the exact set of components and assets
/// actually animated.
///
/// [`Transform`]: https://docs.rs/bevy/0.16.0/bevy/transform/components/struct.Transform.html
/// [`TextColor`]: https://docs.rs/bevy/0.16.0/bevy/text/struct.TextColor.html
/// [`Node`]: https://docs.rs/bevy/0.16.0/bevy/ui/struct.Node.html
/// [`Sprite`]: https://docs.rs/bevy/0.16.0/bevy/sprite/struct.Sprite.html
/// [`ColorMaterial`]: https://docs.rs/bevy/0.16.0/bevy/sprite/struct.ColorMaterial.html
#[derive(Debug, Clone, Copy)]
pub struct TweeningPlugin;
impl Plugin for TweeningPlugin {
fn build(&self, app: &mut App) {
app.add_event::<TweenCompleted>().add_systems(
Update,
component_animator_system::<Transform, ()>.in_set(AnimationSystem::AnimationUpdate),
);
#[cfg(feature = "bevy_ui")]
app.add_systems(
Update,
component_animator_system::<Node, ()>.in_set(AnimationSystem::AnimationUpdate),
);
#[cfg(feature = "bevy_ui")]
app.add_systems(
Update,
component_animator_system::<BackgroundColor, ()>
.in_set(AnimationSystem::AnimationUpdate),
);
#[cfg(feature = "bevy_sprite")]
app.add_systems(
Update,
component_animator_system::<Sprite, ()>.in_set(AnimationSystem::AnimationUpdate),
);
#[cfg(all(feature = "bevy_sprite", feature = "bevy_asset"))]
app.add_systems(
Update,
asset_animator_system::<ColorMaterial, MeshMaterial2d<ColorMaterial>>
.in_set(AnimationSystem::AnimationUpdate),
);
#[cfg(feature = "bevy_text")]
app.add_systems(
Update,
component_animator_system::<TextColor, ()>.in_set(AnimationSystem::AnimationUpdate),
);
}
}
/// Label enum for the systems relating to animations
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, SystemSet)]
pub enum AnimationSystem {
/// Ticks animations
AnimationUpdate,
}
/// Animator system for components.
///
/// This system extracts all components of type `T` with an [`Animator<T>`]
/// attached to the same entity, and tick the animator to animate the component.
pub fn component_animator_system<T: Component<Mutability = Mutable>, M: Send + Sync + 'static>(
time: Res<Time>,
mut animator_query: Query<(Entity, &mut Animator<T, M>)>,
mut target_query: Query<&mut T>,
events: ResMut<Events<TweenCompleted>>,
mut commands: Commands,
) {
let mut events: Mut<Events<TweenCompleted>> = events.into();
for (animator_entity, mut animator) in animator_query.iter_mut() {
if animator.state != AnimatorState::Paused {
let speed = animator.speed();
let entity = animator.target.unwrap_or(animator_entity);
let Ok(target) = target_query.get_mut(entity) else {
continue;
};
let mut target = ComponentTarget::new(target);
animator.tweenable_mut().tick(
time.delta().mul_f32(speed),
&mut target,
entity,
&mut events,
&mut commands,
);
}
}
}
#[cfg(feature = "bevy_asset")]
use std::ops::Deref;
/// Animator system for assets.
///
/// This system ticks all [`AssetAnimator<T>`] components to animate their
/// associated asset.
///
/// This requires the `bevy_asset` feature (enabled by default).
#[cfg(feature = "bevy_asset")]
pub fn asset_animator_system<T, M>(
time: Res<Time>,
mut assets: ResMut<Assets<T>>,
mut query: Query<(Entity, &M, &mut AssetAnimator<T>)>,
events: ResMut<Events<TweenCompleted>>,
mut commands: Commands,
) where
T: Asset,
M: Component + Deref<Target = Handle<T>>,
{
let mut events: Mut<Events<TweenCompleted>> = events.into();
let mut target = AssetTarget::new(assets.reborrow());
for (entity, handle, mut animator) in query.iter_mut() {
if animator.state != AnimatorState::Paused {
target.handle = handle.clone_weak();
if !target.is_valid() {
continue;
}
let speed = animator.speed();
animator.tweenable_mut().tick(
time.delta().mul_f32(speed),
&mut target,
entity,
&mut events,
&mut commands,
);
}
}
}
#[cfg(test)]
mod tests {
use std::{
marker::PhantomData,
ops::DerefMut,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use bevy::ecs::component::Mutable;
use crate::{lens::TransformPositionLens, *};
/// A simple isolated test environment with a [`World`] and a single
/// [`Entity`] in it.
struct TestEnv<T: Component> {
world: World,
animator_entity: Entity,
target_entity: Option<Entity>,
_phantom: PhantomData<T>,
}
impl<T: Component + Default> TestEnv<T> {
/// Create a new test environment containing a single entity with a
/// [`Transform`], and add the given animator on that same entity.
pub fn new(animator: Animator<T>) -> Self {
let mut world = World::new();
world.init_resource::<Events<TweenCompleted>>();
world.init_resource::<Time>();
let entity = world.spawn((T::default(), animator)).id();
Self {
world,
animator_entity: entity,
target_entity: None,
_phantom: PhantomData,
}
}
/// Like [`TestEnv::new`], but the component is placed on a separate entity.
pub fn new_separated(animator: Animator<T>) -> Self {
let mut world = World::new();
world.init_resource::<Events<TweenCompleted>>();
world.init_resource::<Time>();
let target = world.spawn(T::default()).id();
let entity = world.spawn(animator.with_target(target)).id();
Self {
world,
animator_entity: entity,
target_entity: Some(target),
_phantom: PhantomData,
}
}
}
impl<T: Component<Mutability = Mutable>> TestEnv<T> {
/// Get the test world.
pub fn world_mut(&mut self) -> &mut World {
&mut self.world
}
/// Tick the test environment, updating the simulation time and ticking
/// the given system.
pub fn tick(&mut self, duration: Duration, system: &mut dyn System<In = (), Out = ()>) {
// Simulate time passing by updating the simulation time resource
{
let mut time = self.world.resource_mut::<Time>();
time.advance_by(duration);
}
// Reset world-related change detection
self.world.clear_trackers();
assert!(!self.component_mut().is_changed());
// Tick system
system.run((), &mut self.world);
// Update events after system ticked, in case system emitted some events
let mut events = self.world.resource_mut::<Events<TweenCompleted>>();
events.update();
}
/// Get the animator for the component.
pub fn animator(&self) -> &Animator<T> {
self.world
.entity(self.animator_entity)
.get::<Animator<T>>()
.unwrap()
}
/// Get the component.
pub fn component_mut(&mut self) -> Mut<T> {
self.world
.get_mut::<T>(self.target_entity.unwrap_or(self.animator_entity))
.unwrap()
}
/// Get the emitted event count since last tick.
pub fn event_count(&self) -> usize {
let events = self.world.resource::<Events<TweenCompleted>>();
events.get_cursor().len(events)
}
}
#[test]
fn custom_target_entity() {
let tween = Tween::new(
EaseMethod::EaseFunction(EaseFunction::Linear),
Duration::from_secs(1),
TransformPositionLens {
start: Vec3::ZERO,
end: Vec3::ONE,
},
)
.with_completed_event(0);
let mut env = TestEnv::new_separated(Animator::new(tween));
let mut system = IntoSystem::into_system(component_animator_system::<Transform, ()>);
system.initialize(env.world_mut());
env.tick(Duration::ZERO, &mut system);
let transform = env.component_mut();
assert!(transform.translation.abs_diff_eq(Vec3::ZERO, 1e-5));
env.tick(Duration::from_millis(500), &mut system);
let transform = env.component_mut();
assert!(transform.translation.abs_diff_eq(Vec3::splat(0.5), 1e-5));
}
#[test]
fn change_detect_component() {
let tween = Tween::new(
EaseMethod::default(),
Duration::from_secs(1),
TransformPositionLens {
start: Vec3::ZERO,
end: Vec3::ONE,
},
)
.with_completed_event(0);
let mut env = TestEnv::new(Animator::new(tween));
// After being inserted, components are always considered changed
let transform = env.component_mut();
assert!(transform.is_changed());
// fn nit() {}
// let mut system = IntoSystem::into_system(nit);
let mut system = IntoSystem::into_system(component_animator_system::<Transform, ()>);
system.initialize(env.world_mut());
env.tick(Duration::ZERO, &mut system);
let animator = env.animator();
assert_eq!(animator.state, AnimatorState::Playing);
assert_eq!(animator.tweenable().times_completed(), 0);
let transform = env.component_mut();
assert!(transform.is_changed());
assert!(transform.translation.abs_diff_eq(Vec3::ZERO, 1e-5));
env.tick(Duration::from_millis(500), &mut system);
assert_eq!(env.event_count(), 0);
let animator = env.animator();
assert_eq!(animator.state, AnimatorState::Playing);
assert_eq!(animator.tweenable().times_completed(), 0);
let transform = env.component_mut();
assert!(transform.is_changed());
assert!(transform.translation.abs_diff_eq(Vec3::splat(0.5), 1e-5));
env.tick(Duration::from_millis(500), &mut system);
assert_eq!(env.event_count(), 1);
let animator = env.animator();
assert_eq!(animator.state, AnimatorState::Playing);
assert_eq!(animator.tweenable().times_completed(), 1);
let transform = env.component_mut();
assert!(transform.is_changed());
assert!(transform.translation.abs_diff_eq(Vec3::ONE, 1e-5));
env.tick(Duration::from_millis(100), &mut system);
assert_eq!(env.event_count(), 0);
let animator = env.animator();
assert_eq!(animator.state, AnimatorState::Playing);
assert_eq!(animator.tweenable().times_completed(), 1);
let transform = env.component_mut();
assert!(!transform.is_changed());
assert!(transform.translation.abs_diff_eq(Vec3::ONE, 1e-5));
}
#[derive(Debug, Default, Clone, Copy, Component)]
struct DummyComponent {
value: f32,
}
/// Test [`Lens`] which only access mutably the target component if `defer`
/// is `true`.
struct ConditionalDeferLens {
pub defer: Arc<AtomicBool>,
}
impl Lens<DummyComponent> for ConditionalDeferLens {
fn lerp(&mut self, target: &mut dyn Targetable<DummyComponent>, ratio: f32) {
if self.defer.load(Ordering::SeqCst) {
target.deref_mut().value += ratio;
}
}
}
#[test]
fn change_detect_component_conditional() {
let defer = Arc::new(AtomicBool::new(false));
let tween = Tween::new(
EaseMethod::default(),
Duration::from_secs(1),
ConditionalDeferLens {
defer: Arc::clone(&defer),
},
)
.with_completed_event(0);
let mut env = TestEnv::new(Animator::new(tween));
// After being inserted, components are always considered changed
let component = env.component_mut();
assert!(component.is_changed());
let mut system = IntoSystem::into_system(component_animator_system::<DummyComponent, ()>);
system.initialize(env.world_mut());
assert!(!defer.load(Ordering::SeqCst));
// Mutation disabled
env.tick(Duration::ZERO, &mut system);
let animator = env.animator();
assert_eq!(animator.state, AnimatorState::Playing);
assert_eq!(animator.tweenable().times_completed(), 0);
let component = env.component_mut();
assert!(!component.is_changed());
assert!((component.value - 0.).abs() <= 1e-5);
// Zero-length tick should not change the component
env.tick(Duration::from_millis(0), &mut system);
let animator = env.animator();
assert_eq!(animator.state, AnimatorState::Playing);
assert_eq!(animator.tweenable().times_completed(), 0);
let component = env.component_mut();
assert!(!component.is_changed());
assert!((component.value - 0.).abs() <= 1e-5);
// New tick, but lens mutation still disabled
env.tick(Duration::from_millis(200), &mut system);
let animator = env.animator();
assert_eq!(animator.state, AnimatorState::Playing);
assert_eq!(animator.tweenable().times_completed(), 0);
let component = env.component_mut();
assert!(!component.is_changed());
assert!((component.value - 0.).abs() <= 1e-5);
// Enable lens mutation
defer.store(true, Ordering::SeqCst);
// The current time is already at t=0.2s, so even if we don't increment it, for
// a tween duration of 1s the ratio is t=0.2, so the lens will actually
// increment the component's value.
env.tick(Duration::from_millis(0), &mut system);
let animator = env.animator();
assert_eq!(animator.state, AnimatorState::Playing);
assert_eq!(animator.tweenable().times_completed(), 0);
let component = env.component_mut();
assert!(component.is_changed());
assert!((component.value - 0.2).abs() <= 1e-5);
// 0.2s + 0.3s = 0.5s
// t = 0.5s / 1s = 0.5
// value += 0.5
// value == 0.7
env.tick(Duration::from_millis(300), &mut system);
let animator = env.animator();
assert_eq!(animator.state, AnimatorState::Playing);
assert_eq!(animator.tweenable().times_completed(), 0);
let component = env.component_mut();
assert!(component.is_changed());
assert!((component.value - 0.7).abs() <= 1e-5);
}
}