//! This crate provides 'picking' capabilities for the Bevy game engine, allowing pointers to1//! interact with entities using hover, click, and drag events.2//!3//! ## Overview4//!5//! In the simplest case, this plugin allows you to click on things in the scene. However, it also6//! allows you to express more complex interactions, like detecting when a touch input drags a UI7//! element and drops it on a 3d mesh rendered to a different camera.8//!9//! Pointer events bubble up the entity hierarchy and can be used with observers, allowing you to10//! succinctly express rich interaction behaviors by attaching pointer callbacks to entities:11//!12//! ```rust13//! # use bevy_ecs::prelude::*;14//! # use bevy_picking::prelude::*;15//! # #[derive(Component)]16//! # struct MyComponent;17//! # let mut world = World::new();18//! world.spawn(MyComponent)19//! .observe(|mut event: On<Pointer<Click>>| {20//! // Read the underlying pointer event data21//! println!("Pointer {:?} was just clicked!", event.pointer_id);22//! // Stop the event from bubbling up the entity hierarchy23//! event.propagate(false);24//! });25//! ```26//!27//! At its core, this crate provides a robust abstraction for computing picking state regardless of28//! pointing devices, or what you are hit testing against. It is designed to work with any input,29//! including mouse, touch, pens, or virtual pointers controlled by gamepads.30//!31//! ## Expressive Events32//!33//! Although the events in this module (see [`events`]) can be listened to with normal34//! `MessageReader`s, using observers is often more expressive, with less boilerplate. This is because35//! observers allow you to attach event handling logic to specific entities, as well as make use of36//! event bubbling.37//!38//! When events are generated, they bubble up the entity hierarchy starting from their target, until39//! they reach the root or bubbling is halted with a call to40//! [`On::propagate`](bevy_ecs::observer::On::propagate). See [`Observer`] for details.41//!42//! This allows you to run callbacks when any children of an entity are interacted with, and leads43//! to succinct, expressive code:44//!45//! ```46//! # use bevy_ecs::prelude::*;47//! # use bevy_transform::prelude::*;48//! # use bevy_picking::prelude::*;49//! # #[derive(Message)]50//! # struct Greeting;51//! fn setup(mut commands: Commands) {52//! commands.spawn(Transform::default())53//! // Spawn your entity here, e.g. a `Mesh3d`.54//! // When dragged, mutate the `Transform` component on the dragged target entity:55//! .observe(|drag: On<Pointer<Drag>>, mut transforms: Query<&mut Transform>| {56//! let mut transform = transforms.get_mut(drag.entity).unwrap();57//! transform.rotate_local_y(drag.delta.x / 50.0);58//! })59//! .observe(|click: On<Pointer<Click>>, mut commands: Commands| {60//! println!("Entity {} goes BOOM!", click.entity);61//! commands.entity(click.entity).despawn();62//! })63//! .observe(|over: On<Pointer<Over>>, mut greetings: MessageWriter<Greeting>| {64//! greetings.write(Greeting);65//! });66//! }67//! ```68//!69//! ## Modularity70//!71//! #### Mix and Match Hit Testing Backends72//!73//! The plugin attempts to handle all the hard parts for you, all you need to do is tell it when a74//! pointer is hitting any entities. Multiple backends can be used at the same time! [Use this75//! simple API to write your own backend](crate::backend) in about 100 lines of code.76//!77//! #### Input Agnostic78//!79//! Picking provides a generic Pointer abstraction, which is useful for reacting to many different80//! types of input devices. Pointers can be controlled with anything, whether it's the included81//! mouse or touch inputs, or a custom gamepad input system you write yourself to control a virtual82//! pointer.83//!84//! ## Robustness85//!86//! In addition to these features, this plugin also correctly handles multitouch, multiple windows,87//! multiple cameras, viewports, and render layers. Using this as a library allows you to write a88//! picking backend that can interoperate with any other picking backend.89//!90//! # Getting Started91//!92//! TODO: This section will need to be re-written once more backends are introduced.93//!94//! #### Next Steps95//!96//! To learn more, take a look at the examples in the97//! [examples](https://github.com/bevyengine/bevy/tree/main/examples/picking). You can read the next98//! section to understand how the plugin works.99//!100//! # The Picking Pipeline101//!102//! This plugin is designed to be extremely modular. To do so, it works in well-defined stages that103//! form a pipeline, where events are used to pass data between each stage.104//!105//! #### Pointers ([`pointer`](mod@pointer))106//!107//! The first stage of the pipeline is to gather inputs and update pointers. This stage is108//! ultimately responsible for generating [`PointerInput`](pointer::PointerInput) events. The109//! provided crate does this automatically for mouse, touch, and pen inputs. If you wanted to110//! implement your own pointer, controlled by some other input, you can do that here. The ordering111//! of events within the [`PointerInput`](pointer::PointerInput) stream is meaningful for events112//! with the same [`PointerId`](pointer::PointerId), but not between different pointers.113//!114//! Because pointer positions and presses are driven by these events, you can use them to mock115//! inputs for testing.116//!117//! After inputs are generated, they are then collected to update the current118//! [`PointerLocation`](pointer::PointerLocation) for each pointer.119//!120//! #### Backend ([`backend`])121//!122//! A picking backend only has one job: reading [`PointerLocation`](pointer::PointerLocation)123//! components, and producing [`PointerHits`](backend::PointerHits). You can find all documentation124//! and types needed to implement a backend at [`backend`].125//!126//! You will eventually need to choose which picking backend(s) you want to use. This crate does not127//! supply any backends, and expects you to select some from the other bevy crates or the128//! third-party ecosystem.129//!130//! It's important to understand that you can mix and match backends! For example, you might have a131//! backend for your UI, and one for the 3d scene, with each being specialized for their purpose.132//! Bevy provides some backends out of the box, but you can even write your own. It's been made as133//! easy as possible intentionally; the `bevy_mod_raycast` backend is 50 lines of code.134//!135//! #### Hover ([`hover`])136//!137//! The next step is to use the data from the backends, combine and sort the results, and determine138//! what each cursor is hovering over, producing a [`HoverMap`](`crate::hover::HoverMap`). Note that139//! just because a pointer is over an entity, it is not necessarily *hovering* that entity. Although140//! multiple backends may be reporting that a pointer is hitting an entity, the hover system needs141//! to determine which entities are actually being hovered by this pointer based on the pick depth,142//! order of the backend, and the optional [`Pickable`] component of the entity. In other143//! words, if one entity is in front of another, usually only the topmost one will be hovered.144//!145//! #### Events ([`events`])146//!147//! In the final step, the high-level pointer events are generated, such as events that trigger when148//! a pointer hovers or clicks an entity. These simple events are then used to generate more complex149//! events for dragging and dropping.150//!151//! Because it is completely agnostic to the earlier stages of the pipeline, you can easily extend152//! the plugin with arbitrary backends and input methods, yet still use all the high level features.153154extern crate alloc;155156pub mod backend;157pub mod events;158pub mod hover;159pub mod input;160#[cfg(feature = "mesh_picking")]161pub mod mesh_picking;162pub mod pointer;163pub mod window;164165use bevy_app::{prelude::*, PluginGroupBuilder};166use bevy_ecs::prelude::*;167use bevy_reflect::prelude::*;168use hover::{update_is_directly_hovered, update_is_hovered};169170/// The picking prelude.171///172/// This includes the most common types in this crate, re-exported for your convenience.173pub mod prelude {174#[cfg(feature = "mesh_picking")]175#[doc(hidden)]176pub use crate::mesh_picking::{177ray_cast::{MeshRayCast, MeshRayCastSettings, RayCastBackfaces, RayCastVisibility},178MeshPickingCamera, MeshPickingPlugin, MeshPickingSettings,179};180#[doc(hidden)]181pub use crate::{182events::*, input::PointerInputPlugin, pointer::PointerButton, DefaultPickingPlugins,183InteractionPlugin, Pickable, PickingPlugin,184};185}186187/// An optional component that marks an entity as usable by a backend, and overrides default188/// picking behavior for an entity.189///190/// This allows you to make an entity non-hoverable, or allow items below it to be hovered.191///192/// See the documentation on the fields for more details.193#[derive(Component, Debug, Clone, Reflect, PartialEq, Eq)]194#[reflect(Component, Default, Debug, PartialEq, Clone)]195pub struct Pickable {196/// Should this entity block entities below it from being picked?197///198/// This is useful if you want picking to continue hitting entities below this one. Normally,199/// only the topmost entity under a pointer can be hovered, but this setting allows the pointer200/// to hover multiple entities, from nearest to farthest, stopping as soon as it hits an entity201/// that blocks lower entities.202///203/// Note that the word "lower" here refers to entities that have been reported as hit by any204/// picking backend, but are at a lower depth than the current one. This is different from the205/// concept of event bubbling, as it works irrespective of the entity hierarchy.206///207/// For example, if a pointer is over a UI element, as well as a 3d mesh, backends will report208/// hits for both of these entities. Additionally, the hits will be sorted by the camera order,209/// so if the UI is drawing on top of the 3d mesh, the UI will be "above" the mesh. When hovering210/// is computed, the UI element will be checked first to see if it this field is set to block211/// lower entities. If it does (default), the hovering system will stop there, and only the UI212/// element will be marked as hovered. However, if this field is set to `false`, both the UI213/// element *and* the mesh will be marked as hovered.214///215/// Entities without the [`Pickable`] component will block by default.216pub should_block_lower: bool,217218/// If this is set to `false` and `should_block_lower` is set to true, this entity will block219/// lower entities from being interacted and at the same time will itself not emit any events.220///221/// Note that the word "lower" here refers to entities that have been reported as hit by any222/// picking backend, but are at a lower depth than the current one. This is different from the223/// concept of event bubbling, as it works irrespective of the entity hierarchy.224///225/// For example, if a pointer is over a UI element, and this field is set to `false`, it will226/// not be marked as hovered, and consequently will not emit events nor will any picking227/// components mark it as hovered. This can be combined with the other field228/// [`Self::should_block_lower`], which is orthogonal to this one.229///230/// Entities without the [`Pickable`] component are hoverable by default.231pub is_hoverable: bool,232}233234impl Pickable {235/// This entity will not block entities beneath it, nor will it emit events.236///237/// If a backend reports this entity as being hit, the picking plugin will completely ignore it.238pub const IGNORE: Self = Self {239should_block_lower: false,240is_hoverable: false,241};242}243244impl Default for Pickable {245fn default() -> Self {246Self {247should_block_lower: true,248is_hoverable: true,249}250}251}252253/// Groups the stages of the picking process under shared labels.254#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]255pub enum PickingSystems {256/// Produces pointer input events. In the [`First`] schedule.257Input,258/// Runs after input events are generated but before commands are flushed. In the [`First`]259/// schedule.260PostInput,261/// Receives and processes pointer input events. In the [`PreUpdate`] schedule.262ProcessInput,263/// Reads inputs and produces [`backend::PointerHits`]s. In the [`PreUpdate`] schedule.264Backend,265/// Reads [`backend::PointerHits`]s, and updates the hovermap, selection, and highlighting states. In266/// the [`PreUpdate`] schedule.267Hover,268/// Runs after all the [`PickingSystems::Hover`] systems are done, before event listeners are triggered. In the269/// [`PreUpdate`] schedule.270PostHover,271/// Runs after all other picking sets. In the [`PreUpdate`] schedule.272Last,273}274275/// One plugin that contains the [`PointerInputPlugin`](input::PointerInputPlugin), [`PickingPlugin`]276/// and the [`InteractionPlugin`], this is probably the plugin that will be most used.277///278/// Note: for any of these plugins to work, they require a picking backend to be active,279/// The picking backend is responsible to turn an input, into a [`PointerHits`](`crate::backend::PointerHits`)280/// that [`PickingPlugin`] and [`InteractionPlugin`] will refine into [`bevy_ecs::observer::On`]s.281#[derive(Default)]282pub struct DefaultPickingPlugins;283284impl PluginGroup for DefaultPickingPlugins {285fn build(self) -> PluginGroupBuilder {286PluginGroupBuilder::start::<Self>()287.add(input::PointerInputPlugin)288.add(PickingPlugin)289.add(InteractionPlugin)290}291}292293#[derive(Copy, Clone, Debug, Resource, Reflect)]294#[reflect(Resource, Default, Debug, Clone)]295/// Controls the behavior of picking296///297/// ## Custom initialization298/// ```299/// # use bevy_app::App;300/// # use bevy_picking::{PickingSettings, PickingPlugin};301/// App::new()302/// .insert_resource(PickingSettings {303/// is_enabled: true,304/// is_input_enabled: false,305/// is_hover_enabled: true,306/// is_window_picking_enabled: false,307/// })308/// // or DefaultPlugins309/// .add_plugins(PickingPlugin);310/// ```311pub struct PickingSettings {312/// Enables and disables all picking features.313pub is_enabled: bool,314/// Enables and disables input collection.315pub is_input_enabled: bool,316/// Enables and disables updating interaction states of entities.317pub is_hover_enabled: bool,318/// Enables or disables picking for window entities.319pub is_window_picking_enabled: bool,320}321322impl PickingSettings {323/// Whether or not input collection systems should be running.324pub fn input_should_run(state: Res<Self>) -> bool {325state.is_input_enabled && state.is_enabled326}327328/// Whether or not systems updating entities' [`PickingInteraction`](hover::PickingInteraction)329/// component should be running.330pub fn hover_should_run(state: Res<Self>) -> bool {331state.is_hover_enabled && state.is_enabled332}333334/// Whether or not window entities should receive pick events.335pub fn window_picking_should_run(state: Res<Self>) -> bool {336state.is_window_picking_enabled && state.is_enabled337}338}339340impl Default for PickingSettings {341fn default() -> Self {342Self {343is_enabled: true,344is_input_enabled: true,345is_hover_enabled: true,346is_window_picking_enabled: true,347}348}349}350351/// This plugin sets up the core picking infrastructure. It receives input events, and provides the shared352/// types used by other picking plugins.353///354/// Behavior of picking can be controlled by modifying [`PickingSettings`].355///356/// [`PickingSettings`] will be initialized with default values if it357/// is not present at the moment this is added to the app.358pub struct PickingPlugin;359360impl Plugin for PickingPlugin {361fn build(&self, app: &mut App) {362app.init_resource::<PickingSettings>()363.init_resource::<pointer::PointerMap>()364.init_resource::<backend::ray::RayMap>()365.add_message::<pointer::PointerInput>()366.add_message::<backend::PointerHits>()367// Rather than try to mark all current and future backends as ambiguous with each other,368// we allow them to send their hits in any order. These are later sorted, so submission369// order doesn't matter. See `PointerHits` docs for caveats.370.allow_ambiguous_resource::<Messages<backend::PointerHits>>()371.add_systems(372PreUpdate,373(374pointer::update_pointer_map,375pointer::PointerInput::receive,376backend::ray::RayMap::repopulate.after(pointer::PointerInput::receive),377)378.in_set(PickingSystems::ProcessInput),379)380.add_systems(381PreUpdate,382window::update_window_hits383.run_if(PickingSettings::window_picking_should_run)384.in_set(PickingSystems::Backend),385)386.configure_sets(387First,388(PickingSystems::Input, PickingSystems::PostInput)389.after(bevy_time::TimeSystems)390.after(bevy_ecs::message::MessageUpdateSystems)391.chain(),392)393.configure_sets(394PreUpdate,395(396PickingSystems::ProcessInput.run_if(PickingSettings::input_should_run),397PickingSystems::Backend,398PickingSystems::Hover.run_if(PickingSettings::hover_should_run),399PickingSystems::PostHover,400PickingSystems::Last,401)402.chain(),403);404}405}406407/// Generates [`Pointer`](events::Pointer) events and handles event bubbling.408#[derive(Default)]409pub struct InteractionPlugin;410411impl Plugin for InteractionPlugin {412fn build(&self, app: &mut App) {413use events::*;414use hover::{generate_hovermap, update_interactions};415416app.init_resource::<hover::HoverMap>()417.init_resource::<hover::PreviousHoverMap>()418.init_resource::<PointerState>()419.add_message::<Pointer<Cancel>>()420.add_message::<Pointer<Click>>()421.add_message::<Pointer<Press>>()422.add_message::<Pointer<DragDrop>>()423.add_message::<Pointer<DragEnd>>()424.add_message::<Pointer<DragEnter>>()425.add_message::<Pointer<Drag>>()426.add_message::<Pointer<DragLeave>>()427.add_message::<Pointer<DragOver>>()428.add_message::<Pointer<DragStart>>()429.add_message::<Pointer<Move>>()430.add_message::<Pointer<Out>>()431.add_message::<Pointer<Over>>()432.add_message::<Pointer<Release>>()433.add_message::<Pointer<Scroll>>()434.add_systems(435PreUpdate,436(437generate_hovermap,438update_interactions,439(update_is_hovered, update_is_directly_hovered),440pointer_events,441)442.chain()443.in_set(PickingSystems::Hover),444);445}446}447448449