Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_picking/src/lib.rs
9330 views
1
//! This crate provides 'picking' capabilities for the Bevy game engine, allowing pointers to
2
//! interact with entities using hover, click, and drag events.
3
//!
4
//! ## Overview
5
//!
6
//! In the simplest case, this plugin allows you to click on things in the scene. However, it also
7
//! allows you to express more complex interactions, like detecting when a touch input drags a UI
8
//! element and drops it on a 3d mesh rendered to a different camera.
9
//!
10
//! Pointer events bubble up the entity hierarchy and can be used with observers, allowing you to
11
//! succinctly express rich interaction behaviors by attaching pointer callbacks to entities:
12
//!
13
//! ```rust
14
//! # use bevy_ecs::prelude::*;
15
//! # use bevy_picking::prelude::*;
16
//! # #[derive(Component)]
17
//! # struct MyComponent;
18
//! # let mut world = World::new();
19
//! world.spawn(MyComponent)
20
//! .observe(|mut event: On<Pointer<Click>>| {
21
//! // Read the underlying pointer event data
22
//! println!("Pointer {:?} was just clicked!", event.pointer_id);
23
//! // Stop the event from bubbling up the entity hierarchy
24
//! event.propagate(false);
25
//! });
26
//! ```
27
//!
28
//! At its core, this crate provides a robust abstraction for computing picking state regardless of
29
//! pointing devices, or what you are hit testing against. It is designed to work with any input,
30
//! including mouse, touch, pens, or virtual pointers controlled by gamepads.
31
//!
32
//! ## Expressive Events
33
//!
34
//! Although the events in this module (see [`events`]) can be listened to with normal
35
//! `MessageReader`s, using observers is often more expressive, with less boilerplate. This is because
36
//! observers allow you to attach event handling logic to specific entities, as well as make use of
37
//! event bubbling.
38
//!
39
//! When events are generated, they bubble up the entity hierarchy starting from their target, until
40
//! they reach the root or bubbling is halted with a call to
41
//! [`On::propagate`](bevy_ecs::observer::On::propagate). See [`Observer`] for details.
42
//!
43
//! This allows you to run callbacks when any children of an entity are interacted with, and leads
44
//! to succinct, expressive code:
45
//!
46
//! ```
47
//! # use bevy_ecs::prelude::*;
48
//! # use bevy_transform::prelude::*;
49
//! # use bevy_picking::prelude::*;
50
//! # #[derive(Message)]
51
//! # struct Greeting;
52
//! fn setup(mut commands: Commands) {
53
//! commands.spawn(Transform::default())
54
//! // Spawn your entity here, e.g. a `Mesh3d`.
55
//! // When dragged, mutate the `Transform` component on the dragged target entity:
56
//! .observe(|drag: On<Pointer<Drag>>, mut transforms: Query<&mut Transform>| {
57
//! let mut transform = transforms.get_mut(drag.entity).unwrap();
58
//! transform.rotate_local_y(drag.delta.x / 50.0);
59
//! })
60
//! .observe(|click: On<Pointer<Click>>, mut commands: Commands| {
61
//! println!("Entity {} goes BOOM!", click.entity);
62
//! commands.entity(click.entity).despawn();
63
//! })
64
//! .observe(|over: On<Pointer<Over>>, mut greetings: MessageWriter<Greeting>| {
65
//! greetings.write(Greeting);
66
//! });
67
//! }
68
//! ```
69
//!
70
//! ## Modularity
71
//!
72
//! #### Mix and Match Hit Testing Backends
73
//!
74
//! The plugin attempts to handle all the hard parts for you, all you need to do is tell it when a
75
//! pointer is hitting any entities. Multiple backends can be used at the same time! [Use this
76
//! simple API to write your own backend](crate::backend) in about 100 lines of code.
77
//!
78
//! #### Input Agnostic
79
//!
80
//! Picking provides a generic Pointer abstraction, which is useful for reacting to many different
81
//! types of input devices. Pointers can be controlled with anything, whether it's the included
82
//! mouse or touch inputs, or a custom gamepad input system you write yourself to control a virtual
83
//! pointer.
84
//!
85
//! ## Robustness
86
//!
87
//! In addition to these features, this plugin also correctly handles multitouch, multiple windows,
88
//! multiple cameras, viewports, and render layers. Using this as a library allows you to write a
89
//! picking backend that can interoperate with any other picking backend.
90
//!
91
//! # Getting Started
92
//!
93
//! TODO: This section will need to be re-written once more backends are introduced.
94
//!
95
//! #### Next Steps
96
//!
97
//! To learn more, take a look at the examples in the
98
//! [examples](https://github.com/bevyengine/bevy/tree/main/examples/picking). You can read the next
99
//! section to understand how the plugin works.
100
//!
101
//! # The Picking Pipeline
102
//!
103
//! This plugin is designed to be extremely modular. To do so, it works in well-defined stages that
104
//! form a pipeline, where events are used to pass data between each stage.
105
//!
106
//! #### Pointers ([`pointer`](mod@pointer))
107
//!
108
//! The first stage of the pipeline is to gather inputs and update pointers. This stage is
109
//! ultimately responsible for generating [`PointerInput`](pointer::PointerInput) events. The
110
//! provided crate does this automatically for mouse, touch, and pen inputs. If you wanted to
111
//! implement your own pointer, controlled by some other input, you can do that here. The ordering
112
//! of events within the [`PointerInput`](pointer::PointerInput) stream is meaningful for events
113
//! with the same [`PointerId`](pointer::PointerId), but not between different pointers.
114
//!
115
//! Because pointer positions and presses are driven by these events, you can use them to mock
116
//! inputs for testing.
117
//!
118
//! After inputs are generated, they are then collected to update the current
119
//! [`PointerLocation`](pointer::PointerLocation) for each pointer.
120
//!
121
//! #### Backend ([`backend`])
122
//!
123
//! A picking backend only has one job: reading [`PointerLocation`](pointer::PointerLocation)
124
//! components, and producing [`PointerHits`](backend::PointerHits). You can find all documentation
125
//! and types needed to implement a backend at [`backend`].
126
//!
127
//! You will eventually need to choose which picking backend(s) you want to use. This crate does not
128
//! supply any backends, and expects you to select some from the other bevy crates or the
129
//! third-party ecosystem.
130
//!
131
//! It's important to understand that you can mix and match backends! For example, you might have a
132
//! backend for your UI, and one for the 3d scene, with each being specialized for their purpose.
133
//! Bevy provides some backends out of the box, but you can even write your own. It's been made as
134
//! easy as possible intentionally; the `bevy_mod_raycast` backend is 50 lines of code.
135
//!
136
//! #### Hover ([`hover`])
137
//!
138
//! The next step is to use the data from the backends, combine and sort the results, and determine
139
//! what each cursor is hovering over, producing a [`HoverMap`](`crate::hover::HoverMap`). Note that
140
//! just because a pointer is over an entity, it is not necessarily *hovering* that entity. Although
141
//! multiple backends may be reporting that a pointer is hitting an entity, the hover system needs
142
//! to determine which entities are actually being hovered by this pointer based on the pick depth,
143
//! order of the backend, and the optional [`Pickable`] component of the entity. In other
144
//! words, if one entity is in front of another, usually only the topmost one will be hovered.
145
//!
146
//! #### Events ([`events`])
147
//!
148
//! In the final step, the high-level pointer events are generated, such as events that trigger when
149
//! a pointer hovers or clicks an entity. These simple events are then used to generate more complex
150
//! events for dragging and dropping.
151
//!
152
//! Because it is completely agnostic to the earlier stages of the pipeline, you can easily extend
153
//! the plugin with arbitrary backends and input methods, yet still use all the high level features.
154
155
extern crate alloc;
156
157
pub mod backend;
158
pub mod events;
159
pub mod hover;
160
pub mod input;
161
#[cfg(feature = "mesh_picking")]
162
pub mod mesh_picking;
163
pub mod pointer;
164
pub mod window;
165
166
use bevy_app::{prelude::*, PluginGroupBuilder};
167
use bevy_ecs::prelude::*;
168
use bevy_reflect::prelude::*;
169
use hover::{update_is_directly_hovered, update_is_hovered};
170
171
/// The picking prelude.
172
///
173
/// This includes the most common types in this crate, re-exported for your convenience.
174
pub mod prelude {
175
#[cfg(feature = "mesh_picking")]
176
#[doc(hidden)]
177
pub use crate::mesh_picking::{
178
ray_cast::{MeshRayCast, MeshRayCastSettings, RayCastBackfaces, RayCastVisibility},
179
MeshPickingCamera, MeshPickingPlugin, MeshPickingSettings,
180
};
181
#[doc(hidden)]
182
pub use crate::{
183
events::*, input::PointerInputPlugin, pointer::PointerButton, DefaultPickingPlugins,
184
InteractionPlugin, Pickable, PickingPlugin,
185
};
186
}
187
188
/// An optional component that marks an entity as usable by a backend, and overrides default
189
/// picking behavior for an entity.
190
///
191
/// This allows you to make an entity non-hoverable, or allow items below it to be hovered.
192
///
193
/// See the documentation on the fields for more details.
194
#[derive(Component, Debug, Clone, Reflect, PartialEq, Eq)]
195
#[reflect(Component, Default, Debug, PartialEq, Clone)]
196
pub struct Pickable {
197
/// Should this entity block entities below it from being picked?
198
///
199
/// This is useful if you want picking to continue hitting entities below this one. Normally,
200
/// only the topmost entity under a pointer can be hovered, but this setting allows the pointer
201
/// to hover multiple entities, from nearest to farthest, stopping as soon as it hits an entity
202
/// that blocks lower entities.
203
///
204
/// Note that the word "lower" here refers to entities that have been reported as hit by any
205
/// picking backend, but are at a lower depth than the current one. This is different from the
206
/// concept of event bubbling, as it works irrespective of the entity hierarchy.
207
///
208
/// For example, if a pointer is over a UI element, as well as a 3d mesh, backends will report
209
/// hits for both of these entities. Additionally, the hits will be sorted by the camera order,
210
/// so if the UI is drawing on top of the 3d mesh, the UI will be "above" the mesh. When hovering
211
/// is computed, the UI element will be checked first to see if it this field is set to block
212
/// lower entities. If it does (default), the hovering system will stop there, and only the UI
213
/// element will be marked as hovered. However, if this field is set to `false`, both the UI
214
/// element *and* the mesh will be marked as hovered.
215
///
216
/// Entities without the [`Pickable`] component will block by default.
217
pub should_block_lower: bool,
218
219
/// If this is set to `false` and `should_block_lower` is set to true, this entity will block
220
/// lower entities from being interacted and at the same time will itself not emit any events.
221
///
222
/// Note that the word "lower" here refers to entities that have been reported as hit by any
223
/// picking backend, but are at a lower depth than the current one. This is different from the
224
/// concept of event bubbling, as it works irrespective of the entity hierarchy.
225
///
226
/// For example, if a pointer is over a UI element, and this field is set to `false`, it will
227
/// not be marked as hovered, and consequently will not emit events nor will any picking
228
/// components mark it as hovered. This can be combined with the other field
229
/// [`Self::should_block_lower`], which is orthogonal to this one.
230
///
231
/// Entities without the [`Pickable`] component are hoverable by default.
232
pub is_hoverable: bool,
233
}
234
235
impl Pickable {
236
/// This entity will not block entities beneath it, nor will it emit events.
237
///
238
/// If a backend reports this entity as being hit, the picking plugin will completely ignore it.
239
pub const IGNORE: Self = Self {
240
should_block_lower: false,
241
is_hoverable: false,
242
};
243
}
244
245
impl Default for Pickable {
246
fn default() -> Self {
247
Self {
248
should_block_lower: true,
249
is_hoverable: true,
250
}
251
}
252
}
253
254
/// Groups the stages of the picking process under shared labels.
255
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
256
pub enum PickingSystems {
257
/// Produces pointer input events. In the [`First`] schedule.
258
Input,
259
/// Runs after input events are generated but before commands are flushed. In the [`First`]
260
/// schedule.
261
PostInput,
262
/// Receives and processes pointer input events. In the [`PreUpdate`] schedule.
263
ProcessInput,
264
/// Reads inputs and produces [`backend::PointerHits`]s. In the [`PreUpdate`] schedule.
265
Backend,
266
/// Reads [`backend::PointerHits`]s, and updates the hovermap, selection, and highlighting states. In
267
/// the [`PreUpdate`] schedule.
268
Hover,
269
/// Runs after all the [`PickingSystems::Hover`] systems are done, before event listeners are triggered. In the
270
/// [`PreUpdate`] schedule.
271
PostHover,
272
/// Runs after all other picking sets. In the [`PreUpdate`] schedule.
273
Last,
274
}
275
276
/// One plugin that contains the [`PointerInputPlugin`](input::PointerInputPlugin), [`PickingPlugin`]
277
/// and the [`InteractionPlugin`], this is probably the plugin that will be most used.
278
///
279
/// Note: for any of these plugins to work, they require a picking backend to be active,
280
/// The picking backend is responsible to turn an input, into a [`PointerHits`](`crate::backend::PointerHits`)
281
/// that [`PickingPlugin`] and [`InteractionPlugin`] will refine into [`bevy_ecs::observer::On`]s.
282
#[derive(Default)]
283
pub struct DefaultPickingPlugins;
284
285
impl PluginGroup for DefaultPickingPlugins {
286
fn build(self) -> PluginGroupBuilder {
287
PluginGroupBuilder::start::<Self>()
288
.add(input::PointerInputPlugin)
289
.add(PickingPlugin)
290
.add(InteractionPlugin)
291
}
292
}
293
294
#[derive(Copy, Clone, Debug, Resource, Reflect)]
295
#[reflect(Resource, Default, Debug, Clone)]
296
/// Controls the behavior of picking
297
///
298
/// ## Custom initialization
299
/// ```
300
/// # use bevy_app::App;
301
/// # use bevy_picking::{PickingSettings, PickingPlugin};
302
/// App::new()
303
/// .insert_resource(PickingSettings {
304
/// is_enabled: true,
305
/// is_input_enabled: false,
306
/// is_hover_enabled: true,
307
/// is_window_picking_enabled: false,
308
/// })
309
/// // or DefaultPlugins
310
/// .add_plugins(PickingPlugin);
311
/// ```
312
pub struct PickingSettings {
313
/// Enables and disables all picking features.
314
pub is_enabled: bool,
315
/// Enables and disables input collection.
316
pub is_input_enabled: bool,
317
/// Enables and disables updating interaction states of entities.
318
pub is_hover_enabled: bool,
319
/// Enables or disables picking for window entities.
320
pub is_window_picking_enabled: bool,
321
}
322
323
impl PickingSettings {
324
/// Whether or not input collection systems should be running.
325
pub fn input_should_run(state: Res<Self>) -> bool {
326
state.is_input_enabled && state.is_enabled
327
}
328
329
/// Whether or not systems updating entities' [`PickingInteraction`](hover::PickingInteraction)
330
/// component should be running.
331
pub fn hover_should_run(state: Res<Self>) -> bool {
332
state.is_hover_enabled && state.is_enabled
333
}
334
335
/// Whether or not window entities should receive pick events.
336
pub fn window_picking_should_run(state: Res<Self>) -> bool {
337
state.is_window_picking_enabled && state.is_enabled
338
}
339
}
340
341
impl Default for PickingSettings {
342
fn default() -> Self {
343
Self {
344
is_enabled: true,
345
is_input_enabled: true,
346
is_hover_enabled: true,
347
is_window_picking_enabled: true,
348
}
349
}
350
}
351
352
/// This plugin sets up the core picking infrastructure. It receives input events, and provides the shared
353
/// types used by other picking plugins.
354
///
355
/// Behavior of picking can be controlled by modifying [`PickingSettings`].
356
///
357
/// [`PickingSettings`] will be initialized with default values if it
358
/// is not present at the moment this is added to the app.
359
pub struct PickingPlugin;
360
361
impl Plugin for PickingPlugin {
362
fn build(&self, app: &mut App) {
363
app.init_resource::<PickingSettings>()
364
.init_resource::<pointer::PointerMap>()
365
.init_resource::<backend::ray::RayMap>()
366
.add_message::<pointer::PointerInput>()
367
.add_message::<backend::PointerHits>()
368
// Rather than try to mark all current and future backends as ambiguous with each other,
369
// we allow them to send their hits in any order. These are later sorted, so submission
370
// order doesn't matter. See `PointerHits` docs for caveats.
371
.allow_ambiguous_resource::<Messages<backend::PointerHits>>()
372
.add_systems(
373
PreUpdate,
374
(
375
pointer::update_pointer_map,
376
pointer::PointerInput::receive,
377
backend::ray::RayMap::repopulate.after(pointer::PointerInput::receive),
378
)
379
.in_set(PickingSystems::ProcessInput),
380
)
381
.add_systems(
382
PreUpdate,
383
window::update_window_hits
384
.run_if(PickingSettings::window_picking_should_run)
385
.in_set(PickingSystems::Backend),
386
)
387
.configure_sets(
388
First,
389
(PickingSystems::Input, PickingSystems::PostInput)
390
.after(bevy_time::TimeSystems)
391
.after(bevy_ecs::message::MessageUpdateSystems)
392
.chain(),
393
)
394
.configure_sets(
395
PreUpdate,
396
(
397
PickingSystems::ProcessInput.run_if(PickingSettings::input_should_run),
398
PickingSystems::Backend,
399
PickingSystems::Hover.run_if(PickingSettings::hover_should_run),
400
PickingSystems::PostHover,
401
PickingSystems::Last,
402
)
403
.chain(),
404
);
405
}
406
}
407
408
/// Generates [`Pointer`](events::Pointer) events and handles event bubbling.
409
#[derive(Default)]
410
pub struct InteractionPlugin;
411
412
impl Plugin for InteractionPlugin {
413
fn build(&self, app: &mut App) {
414
use events::*;
415
use hover::{generate_hovermap, update_interactions};
416
417
app.init_resource::<hover::HoverMap>()
418
.init_resource::<hover::PreviousHoverMap>()
419
.init_resource::<PointerState>()
420
.add_message::<Pointer<Cancel>>()
421
.add_message::<Pointer<Click>>()
422
.add_message::<Pointer<Press>>()
423
.add_message::<Pointer<DragDrop>>()
424
.add_message::<Pointer<DragEnd>>()
425
.add_message::<Pointer<DragEnter>>()
426
.add_message::<Pointer<Drag>>()
427
.add_message::<Pointer<DragLeave>>()
428
.add_message::<Pointer<DragOver>>()
429
.add_message::<Pointer<DragStart>>()
430
.add_message::<Pointer<Move>>()
431
.add_message::<Pointer<Out>>()
432
.add_message::<Pointer<Over>>()
433
.add_message::<Pointer<Release>>()
434
.add_message::<Pointer<Scroll>>()
435
.add_systems(
436
PreUpdate,
437
(
438
generate_hovermap,
439
update_interactions,
440
(update_is_hovered, update_is_directly_hovered),
441
pointer_events,
442
)
443
.chain()
444
.in_set(PickingSystems::Hover),
445
);
446
}
447
}
448
449