
# Objective Currently, the observer API looks like this: ```rust app.add_observer(|trigger: Trigger<Explode>| { info!("Entity {} exploded!", trigger.target()); }); ``` Future plans for observers also include "multi-event observers" with a trigger that looks like this (see [Cart's example](https://github.com/bevyengine/bevy/issues/14649#issuecomment-2960402508)): ```rust trigger: Trigger<( OnAdd<Pressed>, OnRemove<Pressed>, OnAdd<InteractionDisabled>, OnRemove<InteractionDisabled>, OnInsert<Hovered>, )>, ``` In scenarios like this, there is a lot of repetition of `On`. These are expected to be very high-traffic APIs especially in UI contexts, so ergonomics and readability are critical. By renaming `Trigger` to `On`, we can make these APIs read more cleanly and get rid of the repetition: ```rust app.add_observer(|trigger: On<Explode>| { info!("Entity {} exploded!", trigger.target()); }); ``` ```rust trigger: On<( Add<Pressed>, Remove<Pressed>, Add<InteractionDisabled>, Remove<InteractionDisabled>, Insert<Hovered>, )>, ``` Names like `On<Add<Pressed>>` emphasize the actual event listener nature more than `Trigger<OnAdd<Pressed>>`, and look cleaner. This *also* frees up the `Trigger` name if we want to use it for the observer event type, splitting them out from buffered events (bikeshedding this is out of scope for this PR though). For prior art: [`bevy_eventlistener`](https://github.com/aevyrie/bevy_eventlistener) used [`On`](https://docs.rs/bevy_eventlistener/latest/bevy_eventlistener/event_listener/struct.On.html) for its event listener type. Though in our case, the observer is the event listener, and `On` is just a type containing information about the triggered event. ## Solution Steal from `bevy_event_listener` by @aevyrie and use `On`. - Rename `Trigger` to `On` - Rename `OnAdd` to `Add` - Rename `OnInsert` to `Insert` - Rename `OnReplace` to `Replace` - Rename `OnRemove` to `Remove` - Rename `OnDespawn` to `Despawn` ## Discussion ### Naming Conflicts?? Using a name like `Add` might initially feel like a very bad idea, since it risks conflict with `core::ops::Add`. However, I don't expect this to be a big problem in practice. - You rarely need to actually implement the `Add` trait, especially in modules that would use the Bevy ECS. - In the rare cases where you *do* get a conflict, it is very easy to fix by just disambiguating, for example using `ops::Add`. - The `Add` event is a struct while the `Add` trait is a trait (duh), so the compiler error should be very obvious. For the record, renaming `OnAdd` to `Add`, I got exactly *zero* errors or conflicts within Bevy itself. But this is of course not entirely representative of actual projects *using* Bevy. You might then wonder, why not use `Added`? This would conflict with the `Added` query filter, so it wouldn't work. Additionally, the current naming convention for observer events does not use past tense. ### Documentation This does make documentation slightly more awkward when referring to `On` or its methods. Previous docs often referred to `Trigger::target` or "sends a `Trigger`" (which is... a bit strange anyway), which would now be `On::target` and "sends an observer `Event`". You can see the diff in this PR to see some of the effects. I think it should be fine though, we may just need to reword more documentation to read better.
130 lines
4.7 KiB
Rust
130 lines
4.7 KiB
Rust
//! Plays an animation on a skinned glTF model of a fox.
|
|
|
|
use std::f32::consts::PI;
|
|
|
|
use bevy::{pbr::CascadeShadowConfigBuilder, prelude::*, scene::SceneInstanceReady};
|
|
|
|
// An example asset that contains a mesh and animation.
|
|
const GLTF_PATH: &str = "models/animated/Fox.glb";
|
|
|
|
fn main() {
|
|
App::new()
|
|
.insert_resource(AmbientLight {
|
|
color: Color::WHITE,
|
|
brightness: 2000.,
|
|
..default()
|
|
})
|
|
.add_plugins(DefaultPlugins)
|
|
.add_systems(Startup, setup_mesh_and_animation)
|
|
.add_systems(Startup, setup_camera_and_environment)
|
|
.run();
|
|
}
|
|
|
|
// A component that stores a reference to an animation we want to play. This is
|
|
// created when we start loading the mesh (see `setup_mesh_and_animation`) and
|
|
// read when the mesh has spawned (see `play_animation_once_loaded`).
|
|
#[derive(Component)]
|
|
struct AnimationToPlay {
|
|
graph_handle: Handle<AnimationGraph>,
|
|
index: AnimationNodeIndex,
|
|
}
|
|
|
|
fn setup_mesh_and_animation(
|
|
mut commands: Commands,
|
|
asset_server: Res<AssetServer>,
|
|
mut graphs: ResMut<Assets<AnimationGraph>>,
|
|
) {
|
|
// Create an animation graph containing a single animation. We want the "run"
|
|
// animation from our example asset, which has an index of two.
|
|
let (graph, index) = AnimationGraph::from_clip(
|
|
asset_server.load(GltfAssetLabel::Animation(2).from_asset(GLTF_PATH)),
|
|
);
|
|
|
|
// Store the animation graph as an asset.
|
|
let graph_handle = graphs.add(graph);
|
|
|
|
// Create a component that stores a reference to our animation.
|
|
let animation_to_play = AnimationToPlay {
|
|
graph_handle,
|
|
index,
|
|
};
|
|
|
|
// Start loading the asset as a scene and store a reference to it in a
|
|
// SceneRoot component. This component will automatically spawn a scene
|
|
// containing our mesh once it has loaded.
|
|
let mesh_scene = SceneRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset(GLTF_PATH)));
|
|
|
|
// Spawn an entity with our components, and connect it to an observer that
|
|
// will trigger when the scene is loaded and spawned.
|
|
commands
|
|
.spawn((animation_to_play, mesh_scene))
|
|
.observe(play_animation_when_ready);
|
|
}
|
|
|
|
fn play_animation_when_ready(
|
|
trigger: On<SceneInstanceReady>,
|
|
mut commands: Commands,
|
|
children: Query<&Children>,
|
|
animations_to_play: Query<&AnimationToPlay>,
|
|
mut players: Query<&mut AnimationPlayer>,
|
|
) {
|
|
// The entity we spawned in `setup_mesh_and_animation` is the trigger's target.
|
|
// Start by finding the AnimationToPlay component we added to that entity.
|
|
if let Ok(animation_to_play) = animations_to_play.get(trigger.target().unwrap()) {
|
|
// The SceneRoot component will have spawned the scene as a hierarchy
|
|
// of entities parented to our entity. Since the asset contained a skinned
|
|
// mesh and animations, it will also have spawned an animation player
|
|
// component. Search our entity's descendants to find the animation player.
|
|
for child in children.iter_descendants(trigger.target().unwrap()) {
|
|
if let Ok(mut player) = players.get_mut(child) {
|
|
// Tell the animation player to start the animation and keep
|
|
// repeating it.
|
|
//
|
|
// If you want to try stopping and switching animations, see the
|
|
// `animated_mesh_control.rs` example.
|
|
player.play(animation_to_play.index).repeat();
|
|
|
|
// Add the animation graph. This only needs to be done once to
|
|
// connect the animation player to the mesh.
|
|
commands
|
|
.entity(child)
|
|
.insert(AnimationGraphHandle(animation_to_play.graph_handle.clone()));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Spawn a camera and a simple environment with a ground plane and light.
|
|
fn setup_camera_and_environment(
|
|
mut commands: Commands,
|
|
mut meshes: ResMut<Assets<Mesh>>,
|
|
mut materials: ResMut<Assets<StandardMaterial>>,
|
|
) {
|
|
// Camera
|
|
commands.spawn((
|
|
Camera3d::default(),
|
|
Transform::from_xyz(100.0, 100.0, 150.0).looking_at(Vec3::new(0.0, 20.0, 0.0), Vec3::Y),
|
|
));
|
|
|
|
// Plane
|
|
commands.spawn((
|
|
Mesh3d(meshes.add(Plane3d::default().mesh().size(500000.0, 500000.0))),
|
|
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
|
|
));
|
|
|
|
// Light
|
|
commands.spawn((
|
|
Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
|
|
DirectionalLight {
|
|
shadows_enabled: true,
|
|
..default()
|
|
},
|
|
CascadeShadowConfigBuilder {
|
|
first_cascade_far_bound: 200.0,
|
|
maximum_distance: 400.0,
|
|
..default()
|
|
}
|
|
.build(),
|
|
));
|
|
}
|