Path: blob/main/crates/bevy_ecs/src/observer/centralized_storage.rs
6604 views
//! Centralized storage for observers, allowing for efficient look-ups.1//!2//! This has multiple levels:3//! - [`World::observers`] provides access to [`Observers`], which is a central storage for all observers.4//! - [`Observers`] contains multiple distinct caches in the form of [`CachedObservers`].5//! - Most observers are looked up by the [`ComponentId`] of the event they are observing6//! - Lifecycle observers have their own fields to save lookups.7//! - [`CachedObservers`] contains maps of [`ObserverRunner`]s, which are the actual functions that will be run when the observer is triggered.8//! - These are split by target type, in order to allow for different lookup strategies.9//! - [`CachedComponentObservers`] is one of these maps, which contains observers that are specifically targeted at a component.1011use bevy_platform::collections::HashMap;1213use crate::{14archetype::ArchetypeFlags, component::ComponentId, entity::EntityHashMap,15observer::ObserverRunner, prelude::*,16};1718/// An internal lookup table tracking all of the observers in the world.19///20/// Stores a cache mapping event ids to their registered observers.21/// Some observer kinds (like [lifecycle](crate::lifecycle) observers) have a dedicated field,22/// saving lookups for the most common triggers.23///24/// This can be accessed via [`World::observers`].25#[derive(Default, Debug)]26pub struct Observers {27// Cached ECS observers to save a lookup for high-traffic built-in event types.28add: CachedObservers,29insert: CachedObservers,30replace: CachedObservers,31remove: CachedObservers,32despawn: CachedObservers,33// Map from event type to set of observers watching for that event34cache: HashMap<EventKey, CachedObservers>,35}3637impl Observers {38pub(crate) fn get_observers_mut(&mut self, event_key: EventKey) -> &mut CachedObservers {39use crate::lifecycle::*;4041match event_key {42ADD => &mut self.add,43INSERT => &mut self.insert,44REPLACE => &mut self.replace,45REMOVE => &mut self.remove,46DESPAWN => &mut self.despawn,47_ => self.cache.entry(event_key).or_default(),48}49}5051/// Attempts to get the observers for the given `event_key`.52///53/// When accessing the observers for lifecycle events, such as [`Add`], [`Insert`], [`Replace`], [`Remove`], and [`Despawn`],54/// use the [`EventKey`] constants from the [`lifecycle`](crate::lifecycle) module.55pub fn try_get_observers(&self, event_key: EventKey) -> Option<&CachedObservers> {56use crate::lifecycle::*;5758match event_key {59ADD => Some(&self.add),60INSERT => Some(&self.insert),61REPLACE => Some(&self.replace),62REMOVE => Some(&self.remove),63DESPAWN => Some(&self.despawn),64_ => self.cache.get(&event_key),65}66}6768pub(crate) fn is_archetype_cached(event_key: EventKey) -> Option<ArchetypeFlags> {69use crate::lifecycle::*;7071match event_key {72ADD => Some(ArchetypeFlags::ON_ADD_OBSERVER),73INSERT => Some(ArchetypeFlags::ON_INSERT_OBSERVER),74REPLACE => Some(ArchetypeFlags::ON_REPLACE_OBSERVER),75REMOVE => Some(ArchetypeFlags::ON_REMOVE_OBSERVER),76DESPAWN => Some(ArchetypeFlags::ON_DESPAWN_OBSERVER),77_ => None,78}79}8081pub(crate) fn update_archetype_flags(82&self,83component_id: ComponentId,84flags: &mut ArchetypeFlags,85) {86if self.add.component_observers.contains_key(&component_id) {87flags.insert(ArchetypeFlags::ON_ADD_OBSERVER);88}8990if self.insert.component_observers.contains_key(&component_id) {91flags.insert(ArchetypeFlags::ON_INSERT_OBSERVER);92}9394if self.replace.component_observers.contains_key(&component_id) {95flags.insert(ArchetypeFlags::ON_REPLACE_OBSERVER);96}9798if self.remove.component_observers.contains_key(&component_id) {99flags.insert(ArchetypeFlags::ON_REMOVE_OBSERVER);100}101102if self.despawn.component_observers.contains_key(&component_id) {103flags.insert(ArchetypeFlags::ON_DESPAWN_OBSERVER);104}105}106}107108/// Collection of [`ObserverRunner`] for [`Observer`] registered to a particular event.109///110/// This is stored inside of [`Observers`], specialized for each kind of observer.111#[derive(Default, Debug)]112pub struct CachedObservers {113/// Observers watching for any time this event is triggered, regardless of target.114/// These will also respond to events targeting specific components or entities115pub(super) global_observers: ObserverMap,116/// Observers watching for triggers of events for a specific component117pub(super) component_observers: HashMap<ComponentId, CachedComponentObservers>,118/// Observers watching for triggers of events for a specific entity119pub(super) entity_observers: EntityHashMap<ObserverMap>,120}121122impl CachedObservers {123/// Observers watching for any time this event is triggered, regardless of target.124/// These will also respond to events targeting specific components or entities125pub fn global_observers(&self) -> &ObserverMap {126&self.global_observers127}128129/// Returns observers watching for triggers of events for a specific component.130pub fn component_observers(&self) -> &HashMap<ComponentId, CachedComponentObservers> {131&self.component_observers132}133134/// Returns observers watching for triggers of events for a specific entity.135pub fn entity_observers(&self) -> &EntityHashMap<ObserverMap> {136&self.entity_observers137}138}139140/// Map between an observer entity and its [`ObserverRunner`]141pub type ObserverMap = EntityHashMap<ObserverRunner>;142143/// Collection of [`ObserverRunner`] for [`Observer`] registered to a particular event targeted at a specific component.144///145/// This is stored inside of [`CachedObservers`].146#[derive(Default, Debug)]147pub struct CachedComponentObservers {148// Observers watching for events targeting this component, but not a specific entity149pub(super) global_observers: ObserverMap,150// Observers watching for events targeting this component on a specific entity151pub(super) entity_component_observers: EntityHashMap<ObserverMap>,152}153154impl CachedComponentObservers {155/// Returns observers watching for events targeting this component, but not a specific entity156pub fn global_observers(&self) -> &ObserverMap {157&self.global_observers158}159160/// Returns observers watching for events targeting this component on a specific entity161pub fn entity_component_observers(&self) -> &EntityHashMap<ObserverMap> {162&self.entity_component_observers163}164}165166167