
# 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.0 KiB
Rust
130 lines
4.0 KiB
Rust
//! A simple scene to demonstrate spawning a viewport widget. The example will demonstrate how to
|
|
//! pick entities visible in the widget's view.
|
|
|
|
use bevy::{
|
|
asset::RenderAssetUsages,
|
|
picking::pointer::PointerInteraction,
|
|
prelude::*,
|
|
render::{
|
|
camera::RenderTarget,
|
|
render_resource::{TextureDimension, TextureFormat, TextureUsages},
|
|
},
|
|
ui::widget::ViewportNode,
|
|
};
|
|
|
|
fn main() {
|
|
App::new()
|
|
.add_plugins((DefaultPlugins, MeshPickingPlugin))
|
|
.add_systems(Startup, test)
|
|
.add_systems(Update, draw_mesh_intersections)
|
|
.run();
|
|
}
|
|
|
|
#[derive(Component, Reflect, Debug)]
|
|
#[reflect(Component)]
|
|
struct Shape;
|
|
|
|
fn test(
|
|
mut commands: Commands,
|
|
mut images: ResMut<Assets<Image>>,
|
|
mut meshes: ResMut<Assets<Mesh>>,
|
|
mut materials: ResMut<Assets<StandardMaterial>>,
|
|
) {
|
|
// Spawn a UI camera
|
|
commands.spawn(Camera3d::default());
|
|
|
|
// Set up an texture for the 3D camera to render to.
|
|
// The size of the texture will be based on the viewport's ui size.
|
|
let mut image = Image::new_uninit(
|
|
default(),
|
|
TextureDimension::D2,
|
|
TextureFormat::Bgra8UnormSrgb,
|
|
RenderAssetUsages::all(),
|
|
);
|
|
image.texture_descriptor.usage =
|
|
TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST | TextureUsages::RENDER_ATTACHMENT;
|
|
let image_handle = images.add(image);
|
|
|
|
// Spawn the 3D camera
|
|
let camera = commands
|
|
.spawn((
|
|
Camera3d::default(),
|
|
Camera {
|
|
// Render this camera before our UI camera
|
|
order: -1,
|
|
target: RenderTarget::Image(image_handle.clone().into()),
|
|
..default()
|
|
},
|
|
))
|
|
.id();
|
|
|
|
// Spawn something for the 3D camera to look at
|
|
commands
|
|
.spawn((
|
|
Mesh3d(meshes.add(Cuboid::new(5.0, 5.0, 5.0))),
|
|
MeshMaterial3d(materials.add(Color::WHITE)),
|
|
Transform::from_xyz(0.0, 0.0, -10.0),
|
|
Shape,
|
|
))
|
|
// We can observe pointer events on our objects as normal, the
|
|
// `bevy::ui::widgets::viewport_picking` system will take care of ensuring our viewport
|
|
// clicks pass through
|
|
.observe(on_drag_cuboid);
|
|
|
|
// Spawn our viewport widget
|
|
commands
|
|
.spawn((
|
|
Node {
|
|
position_type: PositionType::Absolute,
|
|
top: Val::Px(50.0),
|
|
left: Val::Px(50.0),
|
|
width: Val::Px(200.0),
|
|
height: Val::Px(200.0),
|
|
border: UiRect::all(Val::Px(5.0)),
|
|
..default()
|
|
},
|
|
BorderColor::all(Color::WHITE),
|
|
ViewportNode::new(camera),
|
|
))
|
|
.observe(on_drag_viewport);
|
|
}
|
|
|
|
fn on_drag_viewport(drag: On<Pointer<Drag>>, mut node_query: Query<&mut Node>) {
|
|
if matches!(drag.button, PointerButton::Secondary) {
|
|
let mut node = node_query.get_mut(drag.target().unwrap()).unwrap();
|
|
|
|
if let (Val::Px(top), Val::Px(left)) = (node.top, node.left) {
|
|
node.left = Val::Px(left + drag.delta.x);
|
|
node.top = Val::Px(top + drag.delta.y);
|
|
};
|
|
}
|
|
}
|
|
|
|
fn on_drag_cuboid(drag: On<Pointer<Drag>>, mut transform_query: Query<&mut Transform>) {
|
|
if matches!(drag.button, PointerButton::Primary) {
|
|
let mut transform = transform_query.get_mut(drag.target().unwrap()).unwrap();
|
|
transform.rotate_y(drag.delta.x * 0.02);
|
|
transform.rotate_x(drag.delta.y * 0.02);
|
|
}
|
|
}
|
|
|
|
fn draw_mesh_intersections(
|
|
pointers: Query<&PointerInteraction>,
|
|
untargetable: Query<Entity, Without<Shape>>,
|
|
mut gizmos: Gizmos,
|
|
) {
|
|
for (point, normal) in pointers
|
|
.iter()
|
|
.flat_map(|interaction| interaction.iter())
|
|
.filter_map(|(entity, hit)| {
|
|
if !untargetable.contains(*entity) {
|
|
hit.position.zip(hit.normal)
|
|
} else {
|
|
None
|
|
}
|
|
})
|
|
{
|
|
gizmos.arrow(point, point + normal.normalize() * 0.5, Color::WHITE);
|
|
}
|
|
}
|