bevy/examples/tools/scene_viewer/animation_plugin.rs
DevinLeamy db5f80b2be
API updates to the AnimationPlayer (#9002)
# Objective

Added `AnimationPlayer` API UX improvements. 

- Succestor to https://github.com/bevyengine/bevy/pull/5912
- Fixes https://github.com/bevyengine/bevy/issues/5848

_(Credits to @asafigan for filing #5848, creating the initial pull
request, and the discussion in #5912)_
## Solution

- Created `RepeatAnimation` enum to describe an animation repetition
behavior.
- Added `is_finished()`, `set_repeat()`, and `is_playback_reversed()`
methods to the animation player.
- ~~Made the animation clip optional as per the comment from #5912~~
> ~~My problem is that the default handle [used the initialize a
`PlayingAnimation`] could actually refer to an actual animation if an
AnimationClip is set for the default handle, which leads me to ask,
"Should animation_clip should be an Option?"~~
- Added an accessor for the animation clip `animation_clip()` to the
animation player.

To determine if an animation is finished, we use the number of times the
animation has completed and the repetition behavior. If the animation is
playing in reverse then `elapsed < 0.0` counts as a completion.
Otherwise, `elapsed > animation.duration` counts as a completion. This
is what I would expect, personally. If there's any ambiguity, perhaps we
could add some `AnimationCompletionBehavior`, to specify that kind of
completion behavior to use.

Update: Previously `PlayingAnimation::elapsed` was being used as the
seek time into the animation clip. This was misleading because if you
increased the speed of the animation it would also increase (or
decrease) the elapsed time. In other words, the elapsed time was not
actually the elapsed time. To solve this, we introduce
`PlayingAnimation::seek_time` to serve as the value we manipulate the
move between keyframes. Consequently, `elapsed()` now returns the actual
elapsed time, and is not effected by the animation speed. Because
`set_elapsed` was being used to manipulate the displayed keyframe, we
introduce `AnimationPlayer::seek_to` and `AnimationPlayer::replay` to
provide this functionality.

## Migration Guide

- Removed `set_elapsed`.
- Removed `stop_repeating` in favour of
`AnimationPlayer::set_repeat(RepeatAnimation::Never)`.
- Introduced `seek_to` to seek to a given timestamp inside of the
animation.
- Introduced `seek_time` accessor for the `PlayingAnimation::seek_to`.
- Introduced `AnimationPlayer::replay` to reset the `PlayingAnimation`
to a state where no time has elapsed.

---------

Co-authored-by: Hennadii Chernyshchyk <genaloner@gmail.com>
Co-authored-by: François <mockersf@gmail.com>
2023-08-28 16:43:04 +00:00

111 lines
3.7 KiB
Rust

//! Control animations of entities in the loaded scene.
use bevy::{gltf::Gltf, prelude::*};
use crate::scene_viewer_plugin::SceneHandle;
/// Controls animation clips for a unique entity.
#[derive(Component)]
struct Clips {
clips: Vec<Handle<AnimationClip>>,
current: usize,
}
impl Clips {
fn new(clips: Vec<Handle<AnimationClip>>) -> Self {
Clips { clips, current: 0 }
}
/// # Panics
///
/// When no clips are present.
fn current(&self) -> Handle<AnimationClip> {
self.clips[self.current].clone_weak()
}
fn advance_to_next(&mut self) {
self.current = (self.current + 1) % self.clips.len();
}
}
/// Read [`AnimationClip`]s from the loaded [`Gltf`] and assign them to the
/// entities they control. [`AnimationClip`]s control specific entities, and
/// trying to play them on an [`AnimationPlayer`] controlling a different
/// entities will result in odd animations, we take extra care to store
/// animation clips for given entities in the [`Clips`] component we defined
/// earlier in this file.
fn assign_clips(
mut players: Query<(Entity, &mut AnimationPlayer, &Name)>,
scene_handle: Res<SceneHandle>,
clips: Res<Assets<AnimationClip>>,
gltf_assets: Res<Assets<Gltf>>,
mut commands: Commands,
mut setup: Local<bool>,
) {
if scene_handle.is_loaded && !*setup {
*setup = true;
} else {
return;
}
let gltf = gltf_assets.get(&scene_handle.gltf_handle).unwrap();
let animations = &gltf.animations;
if !animations.is_empty() {
let count = animations.len();
let plural = if count == 1 { "" } else { "s" };
info!("Found {} animation{plural}", animations.len());
let names: Vec<_> = gltf.named_animations.keys().collect();
info!("Animation names: {names:?}");
}
for (entity, mut player, name) in &mut players {
let clips = clips
.iter()
.filter_map(|(k, v)| v.compatible_with(name).then_some(k))
.map(|id| clips.get_handle(id))
.collect();
let animations = Clips::new(clips);
player.play(animations.current()).repeat();
commands.entity(entity).insert(animations);
}
}
fn handle_inputs(
keyboard_input: Res<Input<KeyCode>>,
mut animation_player: Query<(&mut AnimationPlayer, &mut Clips, Entity, Option<&Name>)>,
) {
for (mut player, mut clips, entity, name) in &mut animation_player {
let display_entity_name = match name {
Some(name) => name.to_string(),
None => format!("entity {entity:?}"),
};
if keyboard_input.just_pressed(KeyCode::Space) {
if player.is_paused() {
info!("resuming animation for {display_entity_name}");
player.resume();
} else {
info!("pausing animation for {display_entity_name}");
player.pause();
}
}
if clips.clips.len() <= 1 {
continue;
}
if keyboard_input.just_pressed(KeyCode::Return) {
info!("switching to new animation for {display_entity_name}");
let resume = !player.is_paused();
// set the current animation to its start and pause it to reset to its starting state
player.seek_to(0.0).pause();
clips.advance_to_next();
let current_clip = clips.current();
player.play(current_clip).repeat();
if resume {
player.resume();
}
}
}
}
pub struct AnimationManipulationPlugin;
impl Plugin for AnimationManipulationPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, (handle_inputs, assign_clips));
}
}