//! This module contains various tools to allow you to react to component insertion or removal,1//! as well as entity spawning and despawning.2//!3//! There are four main ways to react to these lifecycle events:4//!5//! 1. Using component hooks, which act as inherent constructors and destructors for components.6//! 2. Using [observers], which are a user-extensible way to respond to events, including component lifecycle events.7//! 3. Using the [`RemovedComponents`] system parameter, which offers an event-style interface.8//! 4. Using the [`Added`] query filter, which checks each component to see if it has been added since the last time a system ran.9//!10//! [observers]: crate::observer11//! [`Added`]: crate::query::Added12//!13//! # Types of lifecycle events14//!15//! There are five types of lifecycle events, split into two categories. First, we have lifecycle events that are triggered16//! when a component is added to an entity:17//!18//! - [`Add`]: Triggered when a component is added to an entity that did not already have it.19//! - [`Insert`]: Triggered when a component is added to an entity, regardless of whether it already had it.20//!21//! When both events occur, [`Add`] hooks are evaluated before [`Insert`].22//!23//! Next, we have lifecycle events that are triggered when a component is removed from an entity:24//!25//! - [`Discard`]: Triggered when a component is removed from an entity, regardless if it is then replaced with a new value.26//! - [`Remove`]: Triggered when a component is removed from an entity and not replaced, before the component is removed.27//! - [`Despawn`]: Triggered for each component on an entity when it is despawned.28//!29//! [`Discard`] hooks are evaluated before [`Remove`], then finally [`Despawn`] hooks are evaluated.30//!31//! [`Add`] and [`Remove`] are counterparts: they are only triggered when a component is added or removed32//! from an entity in such a way as to cause a change in the component's presence on that entity.33//! Similarly, [`Insert`] and [`Discard`] are counterparts: they are triggered when a component is added or overwritten34//! on an entity, regardless of whether this results in a change in the component's presence on that entity.35//!36//! To reliably synchronize data structures using with component lifecycle events,37//! you can combine [`Insert`] and [`Discard`] to fully capture any changes to the data.38//! This is particularly useful in combination with immutable components,39//! to avoid any lifecycle-bypassing mutations.40//!41//! ## Lifecycle events and component types42//!43//! Despite the absence of generics, each lifecycle event is associated with a specific component.44//! When defining a component hook for a [`Component`] type, that component is used.45//! When observers watch lifecycle events, the `B: Bundle` generic is used.46//!47//! Each of these lifecycle events also corresponds to a fixed [`ComponentId`],48//! which are assigned during [`World`] initialization.49//! For example, [`Add`] corresponds to [`ADD`].50//! This is used to skip [`TypeId`](core::any::TypeId) lookups in hot paths.51use crate::{52change_detection::{MaybeLocation, Tick},53component::{Component, ComponentId, ComponentIdFor},54entity::Entity,55event::{EntityComponentsTrigger, EntityEvent, EventKey},56message::{57Message, MessageCursor, MessageId, MessageIterator, MessageIteratorWithId, Messages,58},59query::FilteredAccessSet,60relationship::RelationshipHookMode,61storage::SparseSet,62system::{Local, ReadOnlySystemParam, SystemMeta, SystemParam},63world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World},64};6566use derive_more::derive::Into;6768#[cfg(feature = "bevy_reflect")]69use bevy_reflect::Reflect;70use core::{71fmt::Debug,72iter,73marker::PhantomData,74ops::{Deref, DerefMut},75option,76};7778/// The type used for [`Component`] lifecycle hooks such as `on_add`, `on_insert` or `on_remove`.79pub type ComponentHook = for<'w> fn(DeferredWorld<'w>, HookContext);8081/// Context provided to a [`ComponentHook`].82#[derive(Clone, Copy, Debug)]83pub struct HookContext {84/// The [`Entity`] this hook was invoked for.85pub entity: Entity,86/// The [`ComponentId`] this hook was invoked for.87pub component_id: ComponentId,88/// The caller location is `Some` if the `track_caller` feature is enabled.89pub caller: MaybeLocation,90/// Configures how relationship hooks will run91pub relationship_hook_mode: RelationshipHookMode,92}9394/// [`World`]-mutating functions that run as part of lifecycle events of a [`Component`].95///96/// Hooks are functions that run when a component is added, overwritten, or removed from an entity.97/// These are intended to be used for structural side effects that need to happen when a component is added or removed,98/// and are not intended for general-purpose logic.99///100/// For example, you might use a hook to update a cached index when a component is added,101/// to clean up resources when a component is removed,102/// or to keep hierarchical data structures across entities in sync.103///104/// This information is stored in the [`ComponentInfo`](crate::component::ComponentInfo) of the associated component.105///106/// There are two ways of configuring hooks for a component:107/// 1. Defining the relevant hooks on the [`Component`] implementation108/// 2. Using the [`World::register_component_hooks`] method109///110/// # Example111///112/// ```113/// use bevy_ecs::prelude::*;114/// use bevy_platform::collections::HashSet;115///116/// #[derive(Component)]117/// struct MyTrackedComponent;118///119/// #[derive(Resource, Default)]120/// struct TrackedEntities(HashSet<Entity>);121///122/// let mut world = World::new();123/// world.init_resource::<TrackedEntities>();124///125/// // No entities with `MyTrackedComponent` have been added yet, so we can safely add component hooks126/// let mut tracked_component_query = world.query::<&MyTrackedComponent>();127/// assert!(tracked_component_query.iter(&world).next().is_none());128///129/// world.register_component_hooks::<MyTrackedComponent>().on_add(|mut world, context| {130/// let mut tracked_entities = world.resource_mut::<TrackedEntities>();131/// tracked_entities.0.insert(context.entity);132/// });133///134/// world.register_component_hooks::<MyTrackedComponent>().on_remove(|mut world, context| {135/// let mut tracked_entities = world.resource_mut::<TrackedEntities>();136/// tracked_entities.0.remove(&context.entity);137/// });138///139/// let entity = world.spawn(MyTrackedComponent).id();140/// let tracked_entities = world.resource::<TrackedEntities>();141/// assert!(tracked_entities.0.contains(&entity));142///143/// world.despawn(entity);144/// let tracked_entities = world.resource::<TrackedEntities>();145/// assert!(!tracked_entities.0.contains(&entity));146/// ```147#[derive(Debug, Clone, Default)]148pub struct ComponentHooks {149pub(crate) on_add: Option<ComponentHook>,150pub(crate) on_insert: Option<ComponentHook>,151pub(crate) on_discard: Option<ComponentHook>,152pub(crate) on_remove: Option<ComponentHook>,153pub(crate) on_despawn: Option<ComponentHook>,154}155156impl ComponentHooks {157pub(crate) fn update_from_component<C: Component + ?Sized>(&mut self) -> &mut Self {158if let Some(hook) = C::on_add() {159self.on_add(hook);160}161if let Some(hook) = C::on_insert() {162self.on_insert(hook);163}164if let Some(hook) = C::on_discard() {165self.on_discard(hook);166}167if let Some(hook) = C::on_remove() {168self.on_remove(hook);169}170if let Some(hook) = C::on_despawn() {171self.on_despawn(hook);172}173174self175}176177/// Register a [`ComponentHook`] that will be run when this component is added to an entity.178/// An `on_add` hook will always run before `on_insert` hooks. Spawning an entity counts as179/// adding all of its components.180///181/// # Panics182///183/// Will panic if the component already has an `on_add` hook184pub fn on_add(&mut self, hook: ComponentHook) -> &mut Self {185self.try_on_add(hook)186.expect("Component already has an on_add hook")187}188189/// Register a [`ComponentHook`] that will be run when this component is added (with `.insert`)190/// or replaced.191///192/// An `on_insert` hook always runs after any `on_add` hooks (if the entity didn't already have the component).193///194/// # Warning195///196/// The hook won't run if the component is already present and is only mutated, such as in a system via a query.197/// As a result, this needs to be combined with immutable components to serve as a mechanism for reliably updating indexes and other caches.198///199/// # Panics200///201/// Will panic if the component already has an `on_insert` hook202pub fn on_insert(&mut self, hook: ComponentHook) -> &mut Self {203self.try_on_insert(hook)204.expect("Component already has an on_insert hook")205}206207/// Register a [`ComponentHook`] that will be run when this component is about to be dropped,208/// such as being replaced (with `.insert`) or removed.209///210/// If this component is inserted onto an entity that already has it, this hook will run before the value is replaced,211/// allowing access to the previous data just before it is dropped.212/// This hook does *not* run if the entity did not already have this component.213///214/// An `on_discard` hook always runs before any `on_remove` hooks (if the component is being removed from the entity).215///216/// # Warning217///218/// The hook won't run if the component is already present and is only mutated, such as in a system via a query.219/// As a result, this needs to be combined with immutable components to serve as a mechanism for reliably updating indexes and other caches.220///221/// # Panics222///223/// Will panic if the component already has an `on_discard` hook224pub fn on_discard(&mut self, hook: ComponentHook) -> &mut Self {225self.try_on_discard(hook)226.expect("Component already has an on_discard hook")227}228229/// Register a [`ComponentHook`] that will be run when this component is removed from an entity.230/// Despawning an entity counts as removing all of its components.231///232/// # Panics233///234/// Will panic if the component already has an `on_remove` hook235pub fn on_remove(&mut self, hook: ComponentHook) -> &mut Self {236self.try_on_remove(hook)237.expect("Component already has an on_remove hook")238}239240/// Register a [`ComponentHook`] that will be run for each component on an entity when it is despawned.241///242/// # Panics243///244/// Will panic if the component already has an `on_despawn` hook245pub fn on_despawn(&mut self, hook: ComponentHook) -> &mut Self {246self.try_on_despawn(hook)247.expect("Component already has an on_despawn hook")248}249250/// Attempt to register a [`ComponentHook`] that will be run when this component is added to an entity.251///252/// This is a fallible version of [`Self::on_add`].253///254/// Returns `None` if the component already has an `on_add` hook.255pub fn try_on_add(&mut self, hook: ComponentHook) -> Option<&mut Self> {256if self.on_add.is_some() {257return None;258}259self.on_add = Some(hook);260Some(self)261}262263/// Attempt to register a [`ComponentHook`] that will be run when this component is added (with `.insert`)264///265/// This is a fallible version of [`Self::on_insert`].266///267/// Returns `None` if the component already has an `on_insert` hook.268pub fn try_on_insert(&mut self, hook: ComponentHook) -> Option<&mut Self> {269if self.on_insert.is_some() {270return None;271}272self.on_insert = Some(hook);273Some(self)274}275276/// Attempt to register a [`ComponentHook`] that will be run when this component is replaced (with `.insert`) or removed277///278/// This is a fallible version of [`Self::on_discard`].279///280/// Returns `None` if the component already has an `on_discard` hook.281pub fn try_on_discard(&mut self, hook: ComponentHook) -> Option<&mut Self> {282if self.on_discard.is_some() {283return None;284}285self.on_discard = Some(hook);286Some(self)287}288289/// Attempt to register a [`ComponentHook`] that will be run when this component is removed from an entity.290///291/// This is a fallible version of [`Self::on_remove`].292///293/// Returns `None` if the component already has an `on_remove` hook.294pub fn try_on_remove(&mut self, hook: ComponentHook) -> Option<&mut Self> {295if self.on_remove.is_some() {296return None;297}298self.on_remove = Some(hook);299Some(self)300}301302/// Attempt to register a [`ComponentHook`] that will be run for each component on an entity when it is despawned.303///304/// This is a fallible version of [`Self::on_despawn`].305///306/// Returns `None` if the component already has an `on_despawn` hook.307pub fn try_on_despawn(&mut self, hook: ComponentHook) -> Option<&mut Self> {308if self.on_despawn.is_some() {309return None;310}311self.on_despawn = Some(hook);312Some(self)313}314}315316/// [`EventKey`] for [`Add`]317pub const ADD: EventKey = EventKey(ComponentId::new(crate::component::ADD));318/// [`EventKey`] for [`Insert`]319pub const INSERT: EventKey = EventKey(ComponentId::new(crate::component::INSERT));320/// [`EventKey`] for [`Discard`]321pub const DISCARD: EventKey = EventKey(ComponentId::new(crate::component::DISCARD));322/// [`EventKey`] for [`Remove`]323pub const REMOVE: EventKey = EventKey(ComponentId::new(crate::component::REMOVE));324/// [`EventKey`] for [`Despawn`]325pub const DESPAWN: EventKey = EventKey(ComponentId::new(crate::component::DESPAWN));326327/// Trigger emitted when a component is inserted onto an entity that does not already have that328/// component. Runs before `Insert`.329/// See [`ComponentHooks::on_add`](`crate::lifecycle::ComponentHooks::on_add`) for more information.330#[derive(Debug, Clone, EntityEvent)]331#[entity_event(trigger = EntityComponentsTrigger<'a>)]332#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]333#[cfg_attr(feature = "bevy_reflect", reflect(Debug))]334#[doc(alias = "OnAdd")]335pub struct Add {336/// The entity this component was added to.337pub entity: Entity,338}339340/// Trigger emitted when a component is inserted, regardless of whether or not the entity already341/// had that component. Runs after `Add`, if it ran.342/// See [`ComponentHooks::on_insert`](`crate::lifecycle::ComponentHooks::on_insert`) for more information.343#[derive(Debug, Clone, EntityEvent)]344#[entity_event(trigger = EntityComponentsTrigger<'a>)]345#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]346#[cfg_attr(feature = "bevy_reflect", reflect(Debug))]347#[doc(alias = "OnInsert")]348pub struct Insert {349/// The entity this component was inserted into.350pub entity: Entity,351}352353/// Trigger emitted when a component is removed from an entity, regardless354/// of whether or not it is later replaced.355///356/// Runs before the value is replaced, so you can still access the original component data.357/// See [`ComponentHooks::on_discard`](`crate::lifecycle::ComponentHooks::on_discard`) for more information.358#[derive(Debug, Clone, EntityEvent)]359#[entity_event(trigger = EntityComponentsTrigger<'a>)]360#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]361#[cfg_attr(feature = "bevy_reflect", reflect(Debug))]362#[doc(alias = "OnDiscard")]363#[doc(alias = "OnReplace")]364#[doc(alias = "Replace")]365pub struct Discard {366/// The entity that held this component before it was discarded.367pub entity: Entity,368}369370/// Trigger emitted when a component is removed from an entity, and runs before the component is371/// removed, so you can still access the component data.372/// See [`ComponentHooks::on_remove`](`crate::lifecycle::ComponentHooks::on_remove`) for more information.373#[derive(Debug, Clone, EntityEvent)]374#[entity_event(trigger = EntityComponentsTrigger<'a>)]375#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]376#[cfg_attr(feature = "bevy_reflect", reflect(Debug))]377#[doc(alias = "OnRemove")]378pub struct Remove {379/// The entity this component was removed from.380pub entity: Entity,381}382383/// [`EntityEvent`] emitted for each component on an entity when it is despawned.384/// See [`ComponentHooks::on_despawn`](`crate::lifecycle::ComponentHooks::on_despawn`) for more information.385#[derive(Debug, Clone, EntityEvent)]386#[entity_event(trigger = EntityComponentsTrigger<'a>)]387#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]388#[cfg_attr(feature = "bevy_reflect", reflect(Debug))]389#[doc(alias = "OnDespawn")]390pub struct Despawn {391/// The entity that held this component before it was despawned.392pub entity: Entity,393}394395/// Wrapper around [`Entity`] for [`RemovedComponents`].396/// Internally, `RemovedComponents` uses these as an [`Messages<RemovedComponentEntity>`].397#[derive(Message, Debug, Clone, Into)]398#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]399#[cfg_attr(feature = "bevy_reflect", reflect(Debug, Clone))]400pub struct RemovedComponentEntity(Entity);401402/// Wrapper around a [`MessageCursor<RemovedComponentEntity>`] so that we403/// can differentiate messages between components.404#[derive(Debug)]405pub struct RemovedComponentReader<T>406where407T: Component,408{409reader: MessageCursor<RemovedComponentEntity>,410marker: PhantomData<T>,411}412413impl<T: Component> Default for RemovedComponentReader<T> {414fn default() -> Self {415Self {416reader: Default::default(),417marker: PhantomData,418}419}420}421422impl<T: Component> Deref for RemovedComponentReader<T> {423type Target = MessageCursor<RemovedComponentEntity>;424fn deref(&self) -> &Self::Target {425&self.reader426}427}428429impl<T: Component> DerefMut for RemovedComponentReader<T> {430fn deref_mut(&mut self) -> &mut Self::Target {431&mut self.reader432}433}434435/// Stores the [`RemovedComponents`] event buffers for all types of component in a given [`World`].436#[derive(Default, Debug)]437pub struct RemovedComponentMessages {438event_sets: SparseSet<ComponentId, Messages<RemovedComponentEntity>>,439}440441impl RemovedComponentMessages {442/// Creates an empty storage buffer for component removal messages.443pub fn new() -> Self {444Self::default()445}446447/// For each type of component, swaps the event buffers and clears the oldest event buffer.448/// In general, this should be called once per frame/update.449pub fn update(&mut self) {450for (_component_id, messages) in self.event_sets.iter_mut() {451messages.update();452}453}454455/// Returns an iterator over components and their entity messages.456pub fn iter(&self) -> impl Iterator<Item = (&ComponentId, &Messages<RemovedComponentEntity>)> {457self.event_sets.iter()458}459460/// Gets the event storage for a given component.461pub fn get(462&self,463component_id: impl Into<ComponentId>,464) -> Option<&Messages<RemovedComponentEntity>> {465self.event_sets.get(component_id.into())466}467468/// Writes a removal message for the specified component.469pub fn write(&mut self, component_id: impl Into<ComponentId>, entity: Entity) {470self.event_sets471.get_or_insert_with(component_id.into(), Default::default)472.write(RemovedComponentEntity(entity));473}474}475476/// A [`SystemParam`] that yields entities that had their `T` [`Component`]477/// removed or have been despawned with it.478///479/// This acts effectively the same as a [`MessageReader`](crate::message::MessageReader).480///481/// Unlike hooks or observers (see the [lifecycle](crate) module docs),482/// this does not allow you to see which data existed before removal.483///484/// If you are using `bevy_ecs` as a standalone crate,485/// note that the [`RemovedComponents`] list will not be automatically cleared for you,486/// and will need to be manually flushed using [`World::clear_trackers`](World::clear_trackers).487///488/// For users of `bevy` and `bevy_app`, [`World::clear_trackers`](World::clear_trackers) is489/// automatically called by `bevy_app::App::update` and `bevy_app::SubApp::update`.490/// For the main world, this is delayed until after all `SubApp`s have run.491///492/// # Examples493///494/// Basic usage:495///496/// ```497/// # use bevy_ecs::component::Component;498/// # use bevy_ecs::system::IntoSystem;499/// # use bevy_ecs::lifecycle::RemovedComponents;500/// #501/// # #[derive(Component)]502/// # struct MyComponent;503/// fn react_on_removal(mut removed: RemovedComponents<MyComponent>) {504/// removed.read().for_each(|removed_entity| println!("{}", removed_entity));505/// }506/// # bevy_ecs::system::assert_is_system(react_on_removal);507/// ```508#[derive(SystemParam)]509pub struct RemovedComponents<'w, 's, T: Component> {510component_id: ComponentIdFor<'s, T>,511reader: Local<'s, RemovedComponentReader<T>>,512message_sets: &'w RemovedComponentMessages,513}514515/// Iterator over entities that had a specific component removed.516///517/// See [`RemovedComponents`].518pub type RemovedIter<'a> = iter::Map<519iter::Flatten<option::IntoIter<iter::Cloned<MessageIterator<'a, RemovedComponentEntity>>>>,520fn(RemovedComponentEntity) -> Entity,521>;522523/// Iterator over entities that had a specific component removed.524///525/// See [`RemovedComponents`].526pub type RemovedIterWithId<'a> = iter::Map<527iter::Flatten<option::IntoIter<MessageIteratorWithId<'a, RemovedComponentEntity>>>,528fn(529(&RemovedComponentEntity, MessageId<RemovedComponentEntity>),530) -> (Entity, MessageId<RemovedComponentEntity>),531>;532533fn map_id_messages(534(entity, id): (&RemovedComponentEntity, MessageId<RemovedComponentEntity>),535) -> (Entity, MessageId<RemovedComponentEntity>) {536(entity.clone().into(), id)537}538539// For all practical purposes, the api surface of `RemovedComponents<T>`540// should be similar to `MessageReader<T>` to reduce confusion.541impl<'w, 's, T: Component> RemovedComponents<'w, 's, T> {542/// Fetch underlying [`MessageCursor`].543pub fn reader(&self) -> &MessageCursor<RemovedComponentEntity> {544&self.reader545}546547/// Fetch underlying [`MessageCursor`] mutably.548pub fn reader_mut(&mut self) -> &mut MessageCursor<RemovedComponentEntity> {549&mut self.reader550}551552/// Fetch underlying [`Messages`].553pub fn messages(&self) -> Option<&Messages<RemovedComponentEntity>> {554self.message_sets.get(self.component_id.get())555}556557/// Destructures to get a mutable reference to the `MessageCursor`558/// and a reference to `Messages`.559///560/// This is necessary since Rust can't detect destructuring through methods and most561/// usecases of the reader uses the `Messages` as well.562pub fn reader_mut_with_messages(563&mut self,564) -> Option<(565&mut RemovedComponentReader<T>,566&Messages<RemovedComponentEntity>,567)> {568self.message_sets569.get(self.component_id.get())570.map(|messages| (&mut *self.reader, messages))571}572573/// Iterates over the messages this [`RemovedComponents`] has not seen yet. This updates the574/// [`RemovedComponents`]'s message counter, which means subsequent message reads will not include messages575/// that happened before now.576pub fn read(&mut self) -> RemovedIter<'_> {577self.reader_mut_with_messages()578.map(|(reader, messages)| reader.read(messages).cloned())579.into_iter()580.flatten()581.map(RemovedComponentEntity::into)582}583584/// Like [`read`](Self::read), except also returning the [`MessageId`] of the messages.585pub fn read_with_id(&mut self) -> RemovedIterWithId<'_> {586self.reader_mut_with_messages()587.map(|(reader, messages)| reader.read_with_id(messages))588.into_iter()589.flatten()590.map(map_id_messages)591}592593/// Determines the number of removal messages available to be read from this [`RemovedComponents`] without consuming any.594pub fn len(&self) -> usize {595self.messages()596.map(|messages| self.reader.len(messages))597.unwrap_or(0)598}599600/// Returns `true` if there are no messages available to read.601pub fn is_empty(&self) -> bool {602self.messages()603.is_none_or(|messages| self.reader.is_empty(messages))604}605606/// Consumes all available messages.607///608/// This means these messages will not appear in calls to [`RemovedComponents::read()`] or609/// [`RemovedComponents::read_with_id()`] and [`RemovedComponents::is_empty()`] will return `true`.610pub fn clear(&mut self) {611if let Some((reader, messages)) = self.reader_mut_with_messages() {612reader.clear(messages);613}614}615}616617// SAFETY: Only reads World removed component messages618unsafe impl<'a> ReadOnlySystemParam for &'a RemovedComponentMessages {}619620// SAFETY: no component value access.621unsafe impl<'a> SystemParam for &'a RemovedComponentMessages {622type State = ();623type Item<'w, 's> = &'w RemovedComponentMessages;624625fn init_state(_world: &mut World) -> Self::State {}626627fn init_access(628_state: &Self::State,629_system_meta: &mut SystemMeta,630_component_access_set: &mut FilteredAccessSet,631_world: &mut World,632) {633}634635#[inline]636unsafe fn get_param<'w, 's>(637_state: &'s mut Self::State,638_system_meta: &SystemMeta,639world: UnsafeWorldCell<'w>,640_change_tick: Tick,641) -> Self::Item<'w, 's> {642world.removed_components()643}644}645646647