bevy_ecs/world/
entity_ref.rs

1use crate::{
2    archetype::Archetype,
3    bundle::{
4        Bundle, BundleFromComponents, BundleInserter, BundleRemover, DynamicBundle, InsertMode,
5    },
6    change_detection::{MaybeLocation, MutUntyped},
7    component::{Component, ComponentId, ComponentTicks, Components, Mutable, StorageType, Tick},
8    entity::{
9        ContainsEntity, Entity, EntityCloner, EntityClonerBuilder, EntityEquivalent,
10        EntityIdLocation, EntityLocation, OptIn, OptOut,
11    },
12    event::{EntityComponentsTrigger, EntityEvent},
13    lifecycle::{Despawn, Remove, Replace, DESPAWN, REMOVE, REPLACE},
14    observer::Observer,
15    query::{Access, DebugCheckedUnwrap, ReadOnlyQueryData, ReleaseStateQueryData},
16    relationship::RelationshipHookMode,
17    resource::Resource,
18    storage::{SparseSets, Table},
19    system::IntoObserverSystem,
20    world::{error::EntityComponentError, unsafe_world_cell::UnsafeEntityCell, Mut, Ref, World},
21};
22use alloc::vec::Vec;
23use bevy_platform::collections::{HashMap, HashSet};
24use bevy_ptr::{move_as_ptr, MovingPtr, OwningPtr, Ptr};
25use core::{
26    any::TypeId,
27    cmp::Ordering,
28    hash::{Hash, Hasher},
29    marker::PhantomData,
30    mem::MaybeUninit,
31};
32use thiserror::Error;
33
34/// A read-only reference to a particular [`Entity`] and all of its components.
35///
36/// # Examples
37///
38/// Read-only access disjoint with mutable access.
39///
40/// ```
41/// # use bevy_ecs::prelude::*;
42/// # #[derive(Component)] pub struct A;
43/// # #[derive(Component)] pub struct B;
44/// fn disjoint_system(
45///     query1: Query<&mut A>,
46///     query2: Query<EntityRef, Without<A>>,
47/// ) {
48///     // ...
49/// }
50/// # bevy_ecs::system::assert_is_system(disjoint_system);
51/// ```
52#[derive(Copy, Clone)]
53pub struct EntityRef<'w> {
54    cell: UnsafeEntityCell<'w>,
55}
56
57impl<'w> EntityRef<'w> {
58    /// # Safety
59    /// - `cell` must have permission to read every component of the entity.
60    /// - No mutable accesses to any of the entity's components may exist
61    ///   at the same time as the returned [`EntityRef`].
62    #[inline]
63    pub(crate) unsafe fn new(cell: UnsafeEntityCell<'w>) -> Self {
64        Self { cell }
65    }
66
67    /// Returns the [ID](Entity) of the current entity.
68    #[inline]
69    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
70    pub fn id(&self) -> Entity {
71        self.cell.id()
72    }
73
74    /// Gets metadata indicating the location where the current entity is stored.
75    #[inline]
76    pub fn location(&self) -> EntityLocation {
77        self.cell.location()
78    }
79
80    /// Returns the archetype that the current entity belongs to.
81    #[inline]
82    pub fn archetype(&self) -> &Archetype {
83        self.cell.archetype()
84    }
85
86    /// Returns `true` if the current entity has a component of type `T`.
87    /// Otherwise, this returns `false`.
88    ///
89    /// ## Notes
90    ///
91    /// If you do not know the concrete type of a component, consider using
92    /// [`Self::contains_id`] or [`Self::contains_type_id`].
93    #[inline]
94    pub fn contains<T: Component>(&self) -> bool {
95        self.contains_type_id(TypeId::of::<T>())
96    }
97
98    /// Returns `true` if the current entity has a component identified by `component_id`.
99    /// Otherwise, this returns false.
100    ///
101    /// ## Notes
102    ///
103    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
104    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
105    ///   [`Self::contains_type_id`].
106    #[inline]
107    pub fn contains_id(&self, component_id: ComponentId) -> bool {
108        self.cell.contains_id(component_id)
109    }
110
111    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
112    /// Otherwise, this returns false.
113    ///
114    /// ## Notes
115    ///
116    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
117    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
118    #[inline]
119    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
120        self.cell.contains_type_id(type_id)
121    }
122
123    /// Gets access to the component of type `T` for the current entity.
124    /// Returns `None` if the entity does not have a component of type `T`.
125    #[inline]
126    pub fn get<T: Component>(&self) -> Option<&'w T> {
127        // SAFETY: We have read-only access to all components of this entity.
128        unsafe { self.cell.get::<T>() }
129    }
130
131    /// Gets access to the component of type `T` for the current entity,
132    /// including change detection information as a [`Ref`].
133    ///
134    /// Returns `None` if the entity does not have a component of type `T`.
135    #[inline]
136    pub fn get_ref<T: Component>(&self) -> Option<Ref<'w, T>> {
137        // SAFETY: We have read-only access to all components of this entity.
138        unsafe { self.cell.get_ref::<T>() }
139    }
140
141    /// Retrieves the change ticks for the given component. This can be useful for implementing change
142    /// detection in custom runtimes.
143    #[inline]
144    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
145        // SAFETY: We have read-only access to all components of this entity.
146        unsafe { self.cell.get_change_ticks::<T>() }
147    }
148
149    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
150    /// detection in custom runtimes.
151    ///
152    /// **You should prefer to use the typed API [`EntityRef::get_change_ticks`] where possible and only
153    /// use this in cases where the actual component types are not known at
154    /// compile time.**
155    #[inline]
156    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
157        // SAFETY: We have read-only access to all components of this entity.
158        unsafe { self.cell.get_change_ticks_by_id(component_id) }
159    }
160
161    /// Returns [untyped read-only reference(s)](Ptr) to component(s) for the
162    /// current entity, based on the given [`ComponentId`]s.
163    ///
164    /// **You should prefer to use the typed API [`EntityRef::get`] where
165    /// possible and only use this in cases where the actual component types
166    /// are not known at compile time.**
167    ///
168    /// Unlike [`EntityRef::get`], this returns untyped reference(s) to
169    /// component(s), and it's the job of the caller to ensure the correct
170    /// type(s) are dereferenced (if necessary).
171    ///
172    /// # Errors
173    ///
174    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
175    /// not have a component.
176    ///
177    /// # Examples
178    ///
179    /// ## Single [`ComponentId`]
180    ///
181    /// ```
182    /// # use bevy_ecs::prelude::*;
183    /// #
184    /// # #[derive(Component, PartialEq, Debug)]
185    /// # pub struct Foo(i32);
186    /// # let mut world = World::new();
187    /// let entity = world.spawn(Foo(42)).id();
188    ///
189    /// // Grab the component ID for `Foo` in whatever way you like.
190    /// let component_id = world.register_component::<Foo>();
191    ///
192    /// // Then, get the component by ID.
193    /// let ptr = world.entity(entity).get_by_id(component_id);
194    /// # assert_eq!(unsafe { ptr.unwrap().deref::<Foo>() }, &Foo(42));
195    /// ```
196    ///
197    /// ## Array of [`ComponentId`]s
198    ///
199    /// ```
200    /// # use bevy_ecs::prelude::*;
201    /// #
202    /// # #[derive(Component, PartialEq, Debug)]
203    /// # pub struct X(i32);
204    /// # #[derive(Component, PartialEq, Debug)]
205    /// # pub struct Y(i32);
206    /// # let mut world = World::new();
207    /// let entity = world.spawn((X(42), Y(10))).id();
208    ///
209    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
210    /// let x_id = world.register_component::<X>();
211    /// let y_id = world.register_component::<Y>();
212    ///
213    /// // Then, get the components by ID. You'll receive a same-sized array.
214    /// let Ok([x_ptr, y_ptr]) = world.entity(entity).get_by_id([x_id, y_id]) else {
215    ///     // Up to you to handle if a component is missing from the entity.
216    /// #   unreachable!();
217    /// };
218    /// # assert_eq!((unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() }), (&X(42), &Y(10)));
219    /// ```
220    ///
221    /// ## Slice of [`ComponentId`]s
222    ///
223    /// ```
224    /// # use bevy_ecs::{prelude::*, component::ComponentId};
225    /// #
226    /// # #[derive(Component, PartialEq, Debug)]
227    /// # pub struct X(i32);
228    /// # #[derive(Component, PartialEq, Debug)]
229    /// # pub struct Y(i32);
230    /// # let mut world = World::new();
231    /// let entity = world.spawn((X(42), Y(10))).id();
232    ///
233    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
234    /// let x_id = world.register_component::<X>();
235    /// let y_id = world.register_component::<Y>();
236    ///
237    /// // Then, get the components by ID. You'll receive a vec of ptrs.
238    /// let ptrs = world.entity(entity).get_by_id(&[x_id, y_id] as &[ComponentId]);
239    /// # let ptrs = ptrs.unwrap();
240    /// # assert_eq!((unsafe { ptrs[0].deref::<X>() }, unsafe { ptrs[1].deref::<Y>() }), (&X(42), &Y(10)));
241    /// ```
242    ///
243    /// ## [`HashSet`] of [`ComponentId`]s
244    ///
245    /// ```
246    /// # use bevy_platform::collections::HashSet;
247    /// # use bevy_ecs::{prelude::*, component::ComponentId};
248    /// #
249    /// # #[derive(Component, PartialEq, Debug)]
250    /// # pub struct X(i32);
251    /// # #[derive(Component, PartialEq, Debug)]
252    /// # pub struct Y(i32);
253    /// # let mut world = World::new();
254    /// let entity = world.spawn((X(42), Y(10))).id();
255    ///
256    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
257    /// let x_id = world.register_component::<X>();
258    /// let y_id = world.register_component::<Y>();
259    ///
260    /// // Then, get the components by ID. You'll receive a vec of ptrs.
261    /// let ptrs = world.entity(entity).get_by_id(&HashSet::from_iter([x_id, y_id]));
262    /// # let ptrs = ptrs.unwrap();
263    /// # assert_eq!((unsafe { ptrs[&x_id].deref::<X>() }, unsafe { ptrs[&y_id].deref::<Y>() }), (&X(42), &Y(10)));
264    /// ```
265    #[inline]
266    pub fn get_by_id<F: DynamicComponentFetch>(
267        &self,
268        component_ids: F,
269    ) -> Result<F::Ref<'w>, EntityComponentError> {
270        // SAFETY: We have read-only access to all components of this entity.
271        unsafe { component_ids.fetch_ref(self.cell) }
272    }
273
274    /// Returns read-only components for the current entity that match the query `Q`.
275    ///
276    /// # Panics
277    ///
278    /// If the entity does not have the components required by the query `Q`.
279    pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(&self) -> Q::Item<'w, 'static> {
280        self.get_components::<Q>()
281            .expect("Query does not match the current entity")
282    }
283
284    /// Returns read-only components for the current entity that match the query `Q`,
285    /// or `None` if the entity does not have the components required by the query `Q`.
286    pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(
287        &self,
288    ) -> Option<Q::Item<'w, 'static>> {
289        // SAFETY:
290        // - We have read-only access to all components of this entity.
291        // - The query is read-only, and read-only references cannot have conflicts.
292        unsafe { self.cell.get_components::<Q>() }
293    }
294
295    /// Returns the source code location from which this entity has been spawned.
296    pub fn spawned_by(&self) -> MaybeLocation {
297        self.cell.spawned_by()
298    }
299
300    /// Returns the [`Tick`] at which this entity has been spawned.
301    pub fn spawn_tick(&self) -> Tick {
302        self.cell.spawn_tick()
303    }
304}
305
306impl<'w> From<EntityWorldMut<'w>> for EntityRef<'w> {
307    fn from(entity: EntityWorldMut<'w>) -> EntityRef<'w> {
308        // SAFETY:
309        // - `EntityWorldMut` guarantees exclusive access to the entire world.
310        unsafe { EntityRef::new(entity.into_unsafe_entity_cell()) }
311    }
312}
313
314impl<'a> From<&'a EntityWorldMut<'_>> for EntityRef<'a> {
315    fn from(entity: &'a EntityWorldMut<'_>) -> Self {
316        // SAFETY:
317        // - `EntityWorldMut` guarantees exclusive access to the entire world.
318        // - `&entity` ensures no mutable accesses are active.
319        unsafe { EntityRef::new(entity.as_unsafe_entity_cell_readonly()) }
320    }
321}
322
323impl<'w> From<EntityMut<'w>> for EntityRef<'w> {
324    fn from(entity: EntityMut<'w>) -> Self {
325        // SAFETY:
326        // - `EntityMut` guarantees exclusive access to all of the entity's components.
327        unsafe { EntityRef::new(entity.cell) }
328    }
329}
330
331impl<'a> From<&'a EntityMut<'_>> for EntityRef<'a> {
332    fn from(entity: &'a EntityMut<'_>) -> Self {
333        // SAFETY:
334        // - `EntityMut` guarantees exclusive access to all of the entity's components.
335        // - `&entity` ensures there are no mutable accesses.
336        unsafe { EntityRef::new(entity.cell) }
337    }
338}
339
340impl<'a> TryFrom<FilteredEntityRef<'a, '_>> for EntityRef<'a> {
341    type Error = TryFromFilteredError;
342
343    fn try_from(entity: FilteredEntityRef<'a, '_>) -> Result<Self, Self::Error> {
344        if !entity.access.has_read_all() {
345            Err(TryFromFilteredError::MissingReadAllAccess)
346        } else {
347            // SAFETY: check above guarantees read-only access to all components of the entity.
348            Ok(unsafe { EntityRef::new(entity.entity) })
349        }
350    }
351}
352
353impl<'a> TryFrom<&'a FilteredEntityRef<'_, '_>> for EntityRef<'a> {
354    type Error = TryFromFilteredError;
355
356    fn try_from(entity: &'a FilteredEntityRef<'_, '_>) -> Result<Self, Self::Error> {
357        if !entity.access.has_read_all() {
358            Err(TryFromFilteredError::MissingReadAllAccess)
359        } else {
360            // SAFETY: check above guarantees read-only access to all components of the entity.
361            Ok(unsafe { EntityRef::new(entity.entity) })
362        }
363    }
364}
365
366impl<'a> TryFrom<FilteredEntityMut<'a, '_>> for EntityRef<'a> {
367    type Error = TryFromFilteredError;
368
369    fn try_from(entity: FilteredEntityMut<'a, '_>) -> Result<Self, Self::Error> {
370        if !entity.access.has_read_all() {
371            Err(TryFromFilteredError::MissingReadAllAccess)
372        } else {
373            // SAFETY: check above guarantees read-only access to all components of the entity.
374            Ok(unsafe { EntityRef::new(entity.entity) })
375        }
376    }
377}
378
379impl<'a> TryFrom<&'a FilteredEntityMut<'_, '_>> for EntityRef<'a> {
380    type Error = TryFromFilteredError;
381
382    fn try_from(entity: &'a FilteredEntityMut<'_, '_>) -> Result<Self, Self::Error> {
383        if !entity.access.has_read_all() {
384            Err(TryFromFilteredError::MissingReadAllAccess)
385        } else {
386            // SAFETY: check above guarantees read-only access to all components of the entity.
387            Ok(unsafe { EntityRef::new(entity.entity) })
388        }
389    }
390}
391
392impl PartialEq for EntityRef<'_> {
393    fn eq(&self, other: &Self) -> bool {
394        self.entity() == other.entity()
395    }
396}
397
398impl Eq for EntityRef<'_> {}
399
400impl PartialOrd for EntityRef<'_> {
401    /// [`EntityRef`]'s comparison trait implementations match the underlying [`Entity`],
402    /// and cannot discern between different worlds.
403    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
404        Some(self.cmp(other))
405    }
406}
407
408impl Ord for EntityRef<'_> {
409    fn cmp(&self, other: &Self) -> Ordering {
410        self.entity().cmp(&other.entity())
411    }
412}
413
414impl Hash for EntityRef<'_> {
415    fn hash<H: Hasher>(&self, state: &mut H) {
416        self.entity().hash(state);
417    }
418}
419
420impl ContainsEntity for EntityRef<'_> {
421    fn entity(&self) -> Entity {
422        self.id()
423    }
424}
425
426// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
427unsafe impl EntityEquivalent for EntityRef<'_> {}
428
429/// Provides mutable access to a single entity and all of its components.
430///
431/// Contrast with [`EntityWorldMut`], which allows adding and removing components,
432/// despawning the entity, and provides mutable access to the entire world.
433/// Because of this, `EntityWorldMut` cannot coexist with any other world accesses.
434///
435/// # Examples
436///
437/// Disjoint mutable access.
438///
439/// ```
440/// # use bevy_ecs::prelude::*;
441/// # #[derive(Component)] pub struct A;
442/// fn disjoint_system(
443///     query1: Query<EntityMut, With<A>>,
444///     query2: Query<EntityMut, Without<A>>,
445/// ) {
446///     // ...
447/// }
448/// # bevy_ecs::system::assert_is_system(disjoint_system);
449/// ```
450pub struct EntityMut<'w> {
451    cell: UnsafeEntityCell<'w>,
452}
453
454impl<'w> EntityMut<'w> {
455    /// # Safety
456    /// - `cell` must have permission to mutate every component of the entity.
457    /// - No accesses to any of the entity's components may exist
458    ///   at the same time as the returned [`EntityMut`].
459    #[inline]
460    pub(crate) unsafe fn new(cell: UnsafeEntityCell<'w>) -> Self {
461        Self { cell }
462    }
463
464    /// Returns a new instance with a shorter lifetime.
465    /// This is useful if you have `&mut EntityMut`, but you need `EntityMut`.
466    pub fn reborrow(&mut self) -> EntityMut<'_> {
467        // SAFETY: We have exclusive access to the entire entity and its components.
468        unsafe { Self::new(self.cell) }
469    }
470
471    /// Consumes `self` and returns read-only access to all of the entity's
472    /// components, with the world `'w` lifetime.
473    pub fn into_readonly(self) -> EntityRef<'w> {
474        EntityRef::from(self)
475    }
476
477    /// Gets read-only access to all of the entity's components.
478    pub fn as_readonly(&self) -> EntityRef<'_> {
479        EntityRef::from(self)
480    }
481
482    /// Returns the [ID](Entity) of the current entity.
483    #[inline]
484    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
485    pub fn id(&self) -> Entity {
486        self.cell.id()
487    }
488
489    /// Gets metadata indicating the location where the current entity is stored.
490    #[inline]
491    pub fn location(&self) -> EntityLocation {
492        self.cell.location()
493    }
494
495    /// Returns the archetype that the current entity belongs to.
496    #[inline]
497    pub fn archetype(&self) -> &Archetype {
498        self.cell.archetype()
499    }
500
501    /// Returns `true` if the current entity has a component of type `T`.
502    /// Otherwise, this returns `false`.
503    ///
504    /// ## Notes
505    ///
506    /// If you do not know the concrete type of a component, consider using
507    /// [`Self::contains_id`] or [`Self::contains_type_id`].
508    #[inline]
509    pub fn contains<T: Component>(&self) -> bool {
510        self.contains_type_id(TypeId::of::<T>())
511    }
512
513    /// Returns `true` if the current entity has a component identified by `component_id`.
514    /// Otherwise, this returns false.
515    ///
516    /// ## Notes
517    ///
518    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
519    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
520    ///   [`Self::contains_type_id`].
521    #[inline]
522    pub fn contains_id(&self, component_id: ComponentId) -> bool {
523        self.cell.contains_id(component_id)
524    }
525
526    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
527    /// Otherwise, this returns false.
528    ///
529    /// ## Notes
530    ///
531    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
532    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
533    #[inline]
534    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
535        self.cell.contains_type_id(type_id)
536    }
537
538    /// Gets access to the component of type `T` for the current entity.
539    /// Returns `None` if the entity does not have a component of type `T`.
540    #[inline]
541    pub fn get<T: Component>(&self) -> Option<&'_ T> {
542        self.as_readonly().get()
543    }
544
545    /// Returns read-only components for the current entity that match the query `Q`.
546    ///
547    /// # Panics
548    ///
549    /// If the entity does not have the components required by the query `Q`.
550    pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(&self) -> Q::Item<'_, 'static> {
551        self.as_readonly().components::<Q>()
552    }
553
554    /// Returns read-only components for the current entity that match the query `Q`,
555    /// or `None` if the entity does not have the components required by the query `Q`.
556    pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(
557        &self,
558    ) -> Option<Q::Item<'_, 'static>> {
559        self.as_readonly().get_components::<Q>()
560    }
561
562    /// Returns components for the current entity that match the query `Q`,
563    /// or `None` if the entity does not have the components required by the query `Q`.
564    ///
565    /// # Example
566    ///
567    /// ```
568    /// # use bevy_ecs::prelude::*;
569    /// #
570    /// #[derive(Component)]
571    /// struct X(usize);
572    /// #[derive(Component)]
573    /// struct Y(usize);
574    ///
575    /// # let mut world = World::default();
576    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
577    /// // Get mutable access to two components at once
578    /// // SAFETY: X and Y are different components
579    /// let (mut x, mut y) =
580    ///     unsafe { entity.get_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
581    /// *x = X(1);
582    /// *y = Y(1);
583    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
584    /// // entity.get_components_mut_unchecked::<(&mut X, &mut X)>();
585    /// ```
586    ///
587    /// # Safety
588    /// It is the caller's responsibility to ensure that
589    /// the `QueryData` does not provide aliasing mutable references to the same component.
590    pub unsafe fn get_components_mut_unchecked<Q: ReleaseStateQueryData>(
591        &mut self,
592    ) -> Option<Q::Item<'_, 'static>> {
593        // SAFETY: Caller the `QueryData` does not provide aliasing mutable references to the same component
594        unsafe { self.reborrow().into_components_mut_unchecked::<Q>() }
595    }
596
597    /// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
598    /// or `None` if the entity does not have the components required by the query `Q`.
599    ///
600    /// # Example
601    ///
602    /// ```
603    /// # use bevy_ecs::prelude::*;
604    /// #
605    /// #[derive(Component)]
606    /// struct X(usize);
607    /// #[derive(Component)]
608    /// struct Y(usize);
609    ///
610    /// # let mut world = World::default();
611    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
612    /// // Get mutable access to two components at once
613    /// // SAFETY: X and Y are different components
614    /// let (mut x, mut y) =
615    ///     unsafe { entity.into_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
616    /// *x = X(1);
617    /// *y = Y(1);
618    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
619    /// // entity.into_components_mut_unchecked::<(&mut X, &mut X)>();
620    /// ```
621    ///
622    /// # Safety
623    /// It is the caller's responsibility to ensure that
624    /// the `QueryData` does not provide aliasing mutable references to the same component.
625    pub unsafe fn into_components_mut_unchecked<Q: ReleaseStateQueryData>(
626        self,
627    ) -> Option<Q::Item<'w, 'static>> {
628        // SAFETY:
629        // - We have mutable access to all components of this entity.
630        // - Caller asserts the `QueryData` does not provide aliasing mutable references to the same component
631        unsafe { self.cell.get_components::<Q>() }
632    }
633
634    /// Consumes `self` and gets access to the component of type `T` with the
635    /// world `'w` lifetime for the current entity.
636    ///
637    /// Returns `None` if the entity does not have a component of type `T`.
638    #[inline]
639    pub fn into_borrow<T: Component>(self) -> Option<&'w T> {
640        self.into_readonly().get()
641    }
642
643    /// Gets access to the component of type `T` for the current entity,
644    /// including change detection information as a [`Ref`].
645    ///
646    /// Returns `None` if the entity does not have a component of type `T`.
647    #[inline]
648    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
649        self.as_readonly().get_ref()
650    }
651
652    /// Consumes `self` and gets access to the component of type `T` with world
653    /// `'w` lifetime for the current entity, including change detection information
654    /// as a [`Ref<'w>`].
655    ///
656    /// Returns `None` if the entity does not have a component of type `T`.
657    #[inline]
658    pub fn into_ref<T: Component>(self) -> Option<Ref<'w, T>> {
659        self.into_readonly().get_ref()
660    }
661
662    /// Gets mutable access to the component of type `T` for the current entity.
663    /// Returns `None` if the entity does not have a component of type `T`.
664    #[inline]
665    pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
666        // SAFETY: &mut self implies exclusive access for duration of returned value
667        unsafe { self.cell.get_mut() }
668    }
669
670    /// Gets mutable access to the component of type `T` for the current entity.
671    /// Returns `None` if the entity does not have a component of type `T`.
672    ///
673    /// # Safety
674    ///
675    /// - `T` must be a mutable component
676    #[inline]
677    pub unsafe fn get_mut_assume_mutable<T: Component>(&mut self) -> Option<Mut<'_, T>> {
678        // SAFETY:
679        // - &mut self implies exclusive access for duration of returned value
680        // - Caller ensures `T` is a mutable component
681        unsafe { self.cell.get_mut_assume_mutable() }
682    }
683
684    /// Consumes self and gets mutable access to the component of type `T`
685    /// with the world `'w` lifetime for the current entity.
686    /// Returns `None` if the entity does not have a component of type `T`.
687    #[inline]
688    pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
689        // SAFETY: consuming `self` implies exclusive access
690        unsafe { self.cell.get_mut() }
691    }
692
693    /// Gets mutable access to the component of type `T` for the current entity.
694    /// Returns `None` if the entity does not have a component of type `T`.
695    ///
696    /// # Safety
697    ///
698    /// - `T` must be a mutable component
699    #[inline]
700    pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
701        // SAFETY:
702        // - Consuming `self` implies exclusive access
703        // - Caller ensures `T` is a mutable component
704        unsafe { self.cell.get_mut_assume_mutable() }
705    }
706
707    /// Retrieves the change ticks for the given component. This can be useful for implementing change
708    /// detection in custom runtimes.
709    #[inline]
710    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
711        self.as_readonly().get_change_ticks::<T>()
712    }
713
714    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
715    /// detection in custom runtimes.
716    ///
717    /// **You should prefer to use the typed API [`EntityWorldMut::get_change_ticks`] where possible and only
718    /// use this in cases where the actual component types are not known at
719    /// compile time.**
720    #[inline]
721    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
722        self.as_readonly().get_change_ticks_by_id(component_id)
723    }
724
725    /// Returns [untyped read-only reference(s)](Ptr) to component(s) for the
726    /// current entity, based on the given [`ComponentId`]s.
727    ///
728    /// **You should prefer to use the typed API [`EntityMut::get`] where
729    /// possible and only use this in cases where the actual component types
730    /// are not known at compile time.**
731    ///
732    /// Unlike [`EntityMut::get`], this returns untyped reference(s) to
733    /// component(s), and it's the job of the caller to ensure the correct
734    /// type(s) are dereferenced (if necessary).
735    ///
736    /// # Errors
737    ///
738    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
739    /// not have a component.
740    ///
741    /// # Examples
742    ///
743    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
744    #[inline]
745    pub fn get_by_id<F: DynamicComponentFetch>(
746        &self,
747        component_ids: F,
748    ) -> Result<F::Ref<'_>, EntityComponentError> {
749        self.as_readonly().get_by_id(component_ids)
750    }
751
752    /// Consumes `self` and returns [untyped read-only reference(s)](Ptr) to
753    /// component(s) with lifetime `'w` for the current entity, based on the
754    /// given [`ComponentId`]s.
755    ///
756    /// **You should prefer to use the typed API [`EntityMut::into_borrow`]
757    /// where possible and only use this in cases where the actual component
758    /// types are not known at compile time.**
759    ///
760    /// Unlike [`EntityMut::into_borrow`], this returns untyped reference(s) to
761    /// component(s), and it's the job of the caller to ensure the correct
762    /// type(s) are dereferenced (if necessary).
763    ///
764    /// # Errors
765    ///
766    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
767    /// not have a component.
768    ///
769    /// # Examples
770    ///
771    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
772    #[inline]
773    pub fn into_borrow_by_id<F: DynamicComponentFetch>(
774        self,
775        component_ids: F,
776    ) -> Result<F::Ref<'w>, EntityComponentError> {
777        self.into_readonly().get_by_id(component_ids)
778    }
779
780    /// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
781    /// the current entity, based on the given [`ComponentId`]s.
782    ///
783    /// **You should prefer to use the typed API [`EntityMut::get_mut`] where
784    /// possible and only use this in cases where the actual component types
785    /// are not known at compile time.**
786    ///
787    /// Unlike [`EntityMut::get_mut`], this returns untyped reference(s) to
788    /// component(s), and it's the job of the caller to ensure the correct
789    /// type(s) are dereferenced (if necessary).
790    ///
791    /// # Errors
792    ///
793    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
794    ///   not have a component.
795    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
796    ///   is requested multiple times.
797    ///
798    /// # Examples
799    ///
800    /// ## Single [`ComponentId`]
801    ///
802    /// ```
803    /// # use bevy_ecs::prelude::*;
804    /// #
805    /// # #[derive(Component, PartialEq, Debug)]
806    /// # pub struct Foo(i32);
807    /// # let mut world = World::new();
808    /// let entity = world.spawn(Foo(42)).id();
809    ///
810    /// // Grab the component ID for `Foo` in whatever way you like.
811    /// let component_id = world.register_component::<Foo>();
812    ///
813    /// // Then, get the component by ID.
814    /// let mut entity_mut = world.entity_mut(entity);
815    /// let mut ptr = entity_mut.get_mut_by_id(component_id)
816    /// #   .unwrap();
817    /// # assert_eq!(unsafe { ptr.as_mut().deref_mut::<Foo>() }, &mut Foo(42));
818    /// ```
819    ///
820    /// ## Array of [`ComponentId`]s
821    ///
822    /// ```
823    /// # use bevy_ecs::prelude::*;
824    /// #
825    /// # #[derive(Component, PartialEq, Debug)]
826    /// # pub struct X(i32);
827    /// # #[derive(Component, PartialEq, Debug)]
828    /// # pub struct Y(i32);
829    /// # let mut world = World::new();
830    /// let entity = world.spawn((X(42), Y(10))).id();
831    ///
832    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
833    /// let x_id = world.register_component::<X>();
834    /// let y_id = world.register_component::<Y>();
835    ///
836    /// // Then, get the components by ID. You'll receive a same-sized array.
837    /// let mut entity_mut = world.entity_mut(entity);
838    /// let Ok([mut x_ptr, mut y_ptr]) = entity_mut.get_mut_by_id([x_id, y_id]) else {
839    ///     // Up to you to handle if a component is missing from the entity.
840    /// #   unreachable!();
841    /// };
842    /// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
843    /// ```
844    ///
845    /// ## Slice of [`ComponentId`]s
846    ///
847    /// ```
848    /// # use bevy_ecs::{prelude::*, component::ComponentId, change_detection::MutUntyped};
849    /// #
850    /// # #[derive(Component, PartialEq, Debug)]
851    /// # pub struct X(i32);
852    /// # #[derive(Component, PartialEq, Debug)]
853    /// # pub struct Y(i32);
854    /// # let mut world = World::new();
855    /// let entity = world.spawn((X(42), Y(10))).id();
856    ///
857    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
858    /// let x_id = world.register_component::<X>();
859    /// let y_id = world.register_component::<Y>();
860    ///
861    /// // Then, get the components by ID. You'll receive a vec of ptrs.
862    /// let mut entity_mut = world.entity_mut(entity);
863    /// let ptrs = entity_mut.get_mut_by_id(&[x_id, y_id] as &[ComponentId])
864    /// #   .unwrap();
865    /// # let [mut x_ptr, mut y_ptr]: [MutUntyped; 2] = ptrs.try_into().unwrap();
866    /// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
867    /// ```
868    ///
869    /// ## [`HashSet`] of [`ComponentId`]s
870    ///
871    /// ```
872    /// # use bevy_platform::collections::HashSet;
873    /// # use bevy_ecs::{prelude::*, component::ComponentId};
874    /// #
875    /// # #[derive(Component, PartialEq, Debug)]
876    /// # pub struct X(i32);
877    /// # #[derive(Component, PartialEq, Debug)]
878    /// # pub struct Y(i32);
879    /// # let mut world = World::new();
880    /// let entity = world.spawn((X(42), Y(10))).id();
881    ///
882    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
883    /// let x_id = world.register_component::<X>();
884    /// let y_id = world.register_component::<Y>();
885    ///
886    /// // Then, get the components by ID. You'll receive a `HashMap` of ptrs.
887    /// let mut entity_mut = world.entity_mut(entity);
888    /// let mut ptrs = entity_mut.get_mut_by_id(&HashSet::from_iter([x_id, y_id]))
889    /// #   .unwrap();
890    /// # let [Some(mut x_ptr), Some(mut y_ptr)] = ptrs.get_many_mut([&x_id, &y_id]) else { unreachable!() };
891    /// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
892    /// ```
893    #[inline]
894    pub fn get_mut_by_id<F: DynamicComponentFetch>(
895        &mut self,
896        component_ids: F,
897    ) -> Result<F::Mut<'_>, EntityComponentError> {
898        // SAFETY:
899        // - `&mut self` ensures that no references exist to this entity's components.
900        // - We have exclusive access to all components of this entity.
901        unsafe { component_ids.fetch_mut(self.cell) }
902    }
903
904    /// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
905    /// the current entity, based on the given [`ComponentId`]s.
906    /// Assumes the given [`ComponentId`]s refer to mutable components.
907    ///
908    /// **You should prefer to use the typed API [`EntityMut::get_mut_assume_mutable`] where
909    /// possible and only use this in cases where the actual component types
910    /// are not known at compile time.**
911    ///
912    /// Unlike [`EntityMut::get_mut_assume_mutable`], this returns untyped reference(s) to
913    /// component(s), and it's the job of the caller to ensure the correct
914    /// type(s) are dereferenced (if necessary).
915    ///
916    /// # Errors
917    ///
918    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
919    ///   not have a component.
920    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
921    ///   is requested multiple times.
922    ///
923    /// # Safety
924    /// It is the callers responsibility to ensure that
925    /// - the provided [`ComponentId`]s must refer to mutable components.
926    #[inline]
927    pub unsafe fn get_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
928        &mut self,
929        component_ids: F,
930    ) -> Result<F::Mut<'_>, EntityComponentError> {
931        // SAFETY:
932        // - `&mut self` ensures that no references exist to this entity's components.
933        // - We have exclusive access to all components of this entity.
934        unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
935    }
936
937    /// Returns [untyped mutable reference](MutUntyped) to component for
938    /// the current entity, based on the given [`ComponentId`].
939    ///
940    /// Unlike [`EntityMut::get_mut_by_id`], this method borrows &self instead of
941    /// &mut self, allowing the caller to access multiple components simultaneously.
942    ///
943    /// # Errors
944    ///
945    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
946    ///   not have a component.
947    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
948    ///   is requested multiple times.
949    ///
950    /// # Safety
951    /// It is the callers responsibility to ensure that
952    /// - the [`UnsafeEntityCell`] has permission to access the component mutably
953    /// - no other references to the component exist at the same time
954    #[inline]
955    pub unsafe fn get_mut_by_id_unchecked<F: DynamicComponentFetch>(
956        &self,
957        component_ids: F,
958    ) -> Result<F::Mut<'_>, EntityComponentError> {
959        // SAFETY:
960        // - The caller must ensure simultaneous access is limited
961        // - to components that are mutually independent.
962        unsafe { component_ids.fetch_mut(self.cell) }
963    }
964
965    /// Returns [untyped mutable reference](MutUntyped) to component for
966    /// the current entity, based on the given [`ComponentId`].
967    /// Assumes the given [`ComponentId`]s refer to mutable components.
968    ///
969    /// Unlike [`EntityMut::get_mut_assume_mutable_by_id`], this method borrows &self instead of
970    /// &mut self, allowing the caller to access multiple components simultaneously.
971    ///
972    /// # Errors
973    ///
974    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
975    ///   not have a component.
976    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
977    ///   is requested multiple times.
978    ///
979    /// # Safety
980    /// It is the callers responsibility to ensure that
981    /// - the [`UnsafeEntityCell`] has permission to access the component mutably
982    /// - no other references to the component exist at the same time
983    /// - the provided [`ComponentId`]s must refer to mutable components.
984    #[inline]
985    pub unsafe fn get_mut_assume_mutable_by_id_unchecked<F: DynamicComponentFetch>(
986        &self,
987        component_ids: F,
988    ) -> Result<F::Mut<'_>, EntityComponentError> {
989        // SAFETY:
990        // - The caller must ensure simultaneous access is limited
991        // - to components that are mutually independent.
992        unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
993    }
994
995    /// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
996    /// to component(s) with lifetime `'w` for the current entity, based on the
997    /// given [`ComponentId`]s.
998    ///
999    /// **You should prefer to use the typed API [`EntityMut::into_mut`] where
1000    /// possible and only use this in cases where the actual component types
1001    /// are not known at compile time.**
1002    ///
1003    /// Unlike [`EntityMut::into_mut`], this returns untyped reference(s) to
1004    /// component(s), and it's the job of the caller to ensure the correct
1005    /// type(s) are dereferenced (if necessary).
1006    ///
1007    /// # Errors
1008    ///
1009    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
1010    ///   not have a component.
1011    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
1012    ///   is requested multiple times.
1013    ///
1014    /// # Examples
1015    ///
1016    /// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
1017    #[inline]
1018    pub fn into_mut_by_id<F: DynamicComponentFetch>(
1019        self,
1020        component_ids: F,
1021    ) -> Result<F::Mut<'w>, EntityComponentError> {
1022        // SAFETY:
1023        // - consuming `self` ensures that no references exist to this entity's components.
1024        // - We have exclusive access to all components of this entity.
1025        unsafe { component_ids.fetch_mut(self.cell) }
1026    }
1027
1028    /// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
1029    /// to component(s) with lifetime `'w` for the current entity, based on the
1030    /// given [`ComponentId`]s.
1031    /// Assumes the given [`ComponentId`]s refer to mutable components.
1032    ///
1033    /// **You should prefer to use the typed API [`EntityMut::into_mut_assume_mutable`] where
1034    /// possible and only use this in cases where the actual component types
1035    /// are not known at compile time.**
1036    ///
1037    /// Unlike [`EntityMut::into_mut_assume_mutable`], this returns untyped reference(s) to
1038    /// component(s), and it's the job of the caller to ensure the correct
1039    /// type(s) are dereferenced (if necessary).
1040    ///
1041    /// # Errors
1042    ///
1043    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
1044    ///   not have a component.
1045    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
1046    ///   is requested multiple times.
1047    ///
1048    /// # Safety
1049    /// It is the callers responsibility to ensure that
1050    /// - the provided [`ComponentId`]s must refer to mutable components.
1051    #[inline]
1052    pub unsafe fn into_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
1053        self,
1054        component_ids: F,
1055    ) -> Result<F::Mut<'w>, EntityComponentError> {
1056        // SAFETY:
1057        // - consuming `self` ensures that no references exist to this entity's components.
1058        // - We have exclusive access to all components of this entity.
1059        unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
1060    }
1061
1062    /// Returns the source code location from which this entity has been spawned.
1063    pub fn spawned_by(&self) -> MaybeLocation {
1064        self.cell.spawned_by()
1065    }
1066
1067    /// Returns the [`Tick`] at which this entity has been spawned.
1068    pub fn spawn_tick(&self) -> Tick {
1069        self.cell.spawn_tick()
1070    }
1071}
1072
1073impl<'w> From<&'w mut EntityMut<'_>> for EntityMut<'w> {
1074    fn from(entity: &'w mut EntityMut<'_>) -> Self {
1075        entity.reborrow()
1076    }
1077}
1078
1079impl<'w> From<EntityWorldMut<'w>> for EntityMut<'w> {
1080    fn from(entity: EntityWorldMut<'w>) -> Self {
1081        // SAFETY: `EntityWorldMut` guarantees exclusive access to the entire world.
1082        unsafe { EntityMut::new(entity.into_unsafe_entity_cell()) }
1083    }
1084}
1085
1086impl<'a> From<&'a mut EntityWorldMut<'_>> for EntityMut<'a> {
1087    #[inline]
1088    fn from(entity: &'a mut EntityWorldMut<'_>) -> Self {
1089        // SAFETY: `EntityWorldMut` guarantees exclusive access to the entire world.
1090        unsafe { EntityMut::new(entity.as_unsafe_entity_cell()) }
1091    }
1092}
1093
1094impl<'a> TryFrom<FilteredEntityMut<'a, '_>> for EntityMut<'a> {
1095    type Error = TryFromFilteredError;
1096
1097    fn try_from(entity: FilteredEntityMut<'a, '_>) -> Result<Self, Self::Error> {
1098        if !entity.access.has_read_all() {
1099            Err(TryFromFilteredError::MissingReadAllAccess)
1100        } else if !entity.access.has_write_all() {
1101            Err(TryFromFilteredError::MissingWriteAllAccess)
1102        } else {
1103            // SAFETY: check above guarantees exclusive access to all components of the entity.
1104            Ok(unsafe { EntityMut::new(entity.entity) })
1105        }
1106    }
1107}
1108
1109impl<'a> TryFrom<&'a mut FilteredEntityMut<'_, '_>> for EntityMut<'a> {
1110    type Error = TryFromFilteredError;
1111
1112    fn try_from(entity: &'a mut FilteredEntityMut<'_, '_>) -> Result<Self, Self::Error> {
1113        if !entity.access.has_read_all() {
1114            Err(TryFromFilteredError::MissingReadAllAccess)
1115        } else if !entity.access.has_write_all() {
1116            Err(TryFromFilteredError::MissingWriteAllAccess)
1117        } else {
1118            // SAFETY: check above guarantees exclusive access to all components of the entity.
1119            Ok(unsafe { EntityMut::new(entity.entity) })
1120        }
1121    }
1122}
1123
1124impl PartialEq for EntityMut<'_> {
1125    fn eq(&self, other: &Self) -> bool {
1126        self.entity() == other.entity()
1127    }
1128}
1129
1130impl Eq for EntityMut<'_> {}
1131
1132impl PartialOrd for EntityMut<'_> {
1133    /// [`EntityMut`]'s comparison trait implementations match the underlying [`Entity`],
1134    /// and cannot discern between different worlds.
1135    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1136        Some(self.cmp(other))
1137    }
1138}
1139
1140impl Ord for EntityMut<'_> {
1141    fn cmp(&self, other: &Self) -> Ordering {
1142        self.entity().cmp(&other.entity())
1143    }
1144}
1145
1146impl Hash for EntityMut<'_> {
1147    fn hash<H: Hasher>(&self, state: &mut H) {
1148        self.entity().hash(state);
1149    }
1150}
1151
1152impl ContainsEntity for EntityMut<'_> {
1153    fn entity(&self) -> Entity {
1154        self.id()
1155    }
1156}
1157
1158// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
1159unsafe impl EntityEquivalent for EntityMut<'_> {}
1160
1161/// A mutable reference to a particular [`Entity`], and the entire world.
1162///
1163/// This is essentially a performance-optimized `(Entity, &mut World)` tuple,
1164/// which caches the [`EntityLocation`] to reduce duplicate lookups.
1165///
1166/// Since this type provides mutable access to the entire world, only one
1167/// [`EntityWorldMut`] can exist at a time for a given world.
1168///
1169/// See also [`EntityMut`], which allows disjoint mutable access to multiple
1170/// entities at once.  Unlike `EntityMut`, this type allows adding and
1171/// removing components, and despawning the entity.
1172pub struct EntityWorldMut<'w> {
1173    world: &'w mut World,
1174    entity: Entity,
1175    location: EntityIdLocation,
1176}
1177
1178impl<'w> EntityWorldMut<'w> {
1179    #[track_caller]
1180    #[inline(never)]
1181    #[cold]
1182    fn panic_despawned(&self) -> ! {
1183        panic!(
1184            "Entity {} {}",
1185            self.entity,
1186            self.world
1187                .entities()
1188                .entity_does_not_exist_error_details(self.entity)
1189        );
1190    }
1191
1192    #[inline(always)]
1193    #[track_caller]
1194    pub(crate) fn assert_not_despawned(&self) {
1195        if self.location.is_none() {
1196            self.panic_despawned()
1197        }
1198    }
1199
1200    #[inline(always)]
1201    fn as_unsafe_entity_cell_readonly(&self) -> UnsafeEntityCell<'_> {
1202        let location = self.location();
1203        let last_change_tick = self.world.last_change_tick;
1204        let change_tick = self.world.read_change_tick();
1205        UnsafeEntityCell::new(
1206            self.world.as_unsafe_world_cell_readonly(),
1207            self.entity,
1208            location,
1209            last_change_tick,
1210            change_tick,
1211        )
1212    }
1213
1214    #[inline(always)]
1215    fn as_unsafe_entity_cell(&mut self) -> UnsafeEntityCell<'_> {
1216        let location = self.location();
1217        let last_change_tick = self.world.last_change_tick;
1218        let change_tick = self.world.change_tick();
1219        UnsafeEntityCell::new(
1220            self.world.as_unsafe_world_cell(),
1221            self.entity,
1222            location,
1223            last_change_tick,
1224            change_tick,
1225        )
1226    }
1227
1228    #[inline(always)]
1229    fn into_unsafe_entity_cell(self) -> UnsafeEntityCell<'w> {
1230        let location = self.location();
1231        let last_change_tick = self.world.last_change_tick;
1232        let change_tick = self.world.change_tick();
1233        UnsafeEntityCell::new(
1234            self.world.as_unsafe_world_cell(),
1235            self.entity,
1236            location,
1237            last_change_tick,
1238            change_tick,
1239        )
1240    }
1241
1242    /// # Safety
1243    ///
1244    ///  - `entity` must be valid for `world`: the generation should match that of the entity at the same index.
1245    ///  - `location` must be sourced from `world`'s `Entities` and must exactly match the location for `entity`
1246    ///
1247    ///  The above is trivially satisfied if `location` was sourced from `world.entities().get(entity)`.
1248    #[inline]
1249    pub(crate) unsafe fn new(
1250        world: &'w mut World,
1251        entity: Entity,
1252        location: Option<EntityLocation>,
1253    ) -> Self {
1254        debug_assert!(world.entities().contains(entity));
1255        debug_assert_eq!(world.entities().get(entity), location);
1256
1257        EntityWorldMut {
1258            world,
1259            entity,
1260            location,
1261        }
1262    }
1263
1264    /// Consumes `self` and returns read-only access to all of the entity's
1265    /// components, with the world `'w` lifetime.
1266    pub fn into_readonly(self) -> EntityRef<'w> {
1267        EntityRef::from(self)
1268    }
1269
1270    /// Gets read-only access to all of the entity's components.
1271    #[inline]
1272    pub fn as_readonly(&self) -> EntityRef<'_> {
1273        EntityRef::from(self)
1274    }
1275
1276    /// Consumes `self` and returns non-structural mutable access to all of the
1277    /// entity's components, with the world `'w` lifetime.
1278    pub fn into_mutable(self) -> EntityMut<'w> {
1279        EntityMut::from(self)
1280    }
1281
1282    /// Gets non-structural mutable access to all of the entity's components.
1283    #[inline]
1284    pub fn as_mutable(&mut self) -> EntityMut<'_> {
1285        EntityMut::from(self)
1286    }
1287
1288    /// Returns the [ID](Entity) of the current entity.
1289    #[inline]
1290    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
1291    pub fn id(&self) -> Entity {
1292        self.entity
1293    }
1294
1295    /// Gets metadata indicating the location where the current entity is stored.
1296    ///
1297    /// # Panics
1298    ///
1299    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1300    #[inline]
1301    pub fn location(&self) -> EntityLocation {
1302        match self.location {
1303            Some(loc) => loc,
1304            None => self.panic_despawned(),
1305        }
1306    }
1307
1308    /// Returns the archetype that the current entity belongs to.
1309    ///
1310    /// # Panics
1311    ///
1312    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1313    #[inline]
1314    pub fn archetype(&self) -> &Archetype {
1315        let location = self.location();
1316        &self.world.archetypes[location.archetype_id]
1317    }
1318
1319    /// Returns `true` if the current entity has a component of type `T`.
1320    /// Otherwise, this returns `false`.
1321    ///
1322    /// ## Notes
1323    ///
1324    /// If you do not know the concrete type of a component, consider using
1325    /// [`Self::contains_id`] or [`Self::contains_type_id`].
1326    ///
1327    /// # Panics
1328    ///
1329    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1330    #[inline]
1331    pub fn contains<T: Component>(&self) -> bool {
1332        self.contains_type_id(TypeId::of::<T>())
1333    }
1334
1335    /// Returns `true` if the current entity has a component identified by `component_id`.
1336    /// Otherwise, this returns false.
1337    ///
1338    /// ## Notes
1339    ///
1340    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
1341    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
1342    ///   [`Self::contains_type_id`].
1343    ///
1344    /// # Panics
1345    ///
1346    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1347    #[inline]
1348    pub fn contains_id(&self, component_id: ComponentId) -> bool {
1349        self.as_unsafe_entity_cell_readonly()
1350            .contains_id(component_id)
1351    }
1352
1353    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
1354    /// Otherwise, this returns false.
1355    ///
1356    /// ## Notes
1357    ///
1358    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
1359    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
1360    ///
1361    /// # Panics
1362    ///
1363    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1364    #[inline]
1365    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
1366        self.as_unsafe_entity_cell_readonly()
1367            .contains_type_id(type_id)
1368    }
1369
1370    /// Gets access to the component of type `T` for the current entity.
1371    /// Returns `None` if the entity does not have a component of type `T`.
1372    ///
1373    /// # Panics
1374    ///
1375    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1376    #[inline]
1377    pub fn get<T: Component>(&self) -> Option<&'_ T> {
1378        self.as_readonly().get()
1379    }
1380
1381    /// Returns read-only components for the current entity that match the query `Q`.
1382    ///
1383    /// # Panics
1384    ///
1385    /// If the entity does not have the components required by the query `Q` or if the entity
1386    /// has been despawned while this `EntityWorldMut` is still alive.
1387    #[inline]
1388    pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(&self) -> Q::Item<'_, 'static> {
1389        self.as_readonly().components::<Q>()
1390    }
1391
1392    /// Returns read-only components for the current entity that match the query `Q`,
1393    /// or `None` if the entity does not have the components required by the query `Q`.
1394    ///
1395    /// # Panics
1396    ///
1397    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1398    #[inline]
1399    pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(
1400        &self,
1401    ) -> Option<Q::Item<'_, 'static>> {
1402        self.as_readonly().get_components::<Q>()
1403    }
1404
1405    /// Returns components for the current entity that match the query `Q`,
1406    /// or `None` if the entity does not have the components required by the query `Q`.
1407    ///
1408    /// # Example
1409    ///
1410    /// ```
1411    /// # use bevy_ecs::prelude::*;
1412    /// #
1413    /// #[derive(Component)]
1414    /// struct X(usize);
1415    /// #[derive(Component)]
1416    /// struct Y(usize);
1417    ///
1418    /// # let mut world = World::default();
1419    /// let mut entity = world.spawn((X(0), Y(0)));
1420    /// // Get mutable access to two components at once
1421    /// // SAFETY: X and Y are different components
1422    /// let (mut x, mut y) =
1423    ///     unsafe { entity.get_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
1424    /// *x = X(1);
1425    /// *y = Y(1);
1426    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
1427    /// // entity.get_components_mut_unchecked::<(&mut X, &mut X)>();
1428    /// ```
1429    ///
1430    /// # Safety
1431    /// It is the caller's responsibility to ensure that
1432    /// the `QueryData` does not provide aliasing mutable references to the same component.
1433    pub unsafe fn get_components_mut_unchecked<Q: ReleaseStateQueryData>(
1434        &mut self,
1435    ) -> Option<Q::Item<'_, 'static>> {
1436        // SAFETY: Caller the `QueryData` does not provide aliasing mutable references to the same component
1437        unsafe { self.as_mutable().into_components_mut_unchecked::<Q>() }
1438    }
1439
1440    /// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
1441    /// or `None` if the entity does not have the components required by the query `Q`.
1442    ///
1443    /// # Example
1444    ///
1445    /// ```
1446    /// # use bevy_ecs::prelude::*;
1447    /// #
1448    /// #[derive(Component)]
1449    /// struct X(usize);
1450    /// #[derive(Component)]
1451    /// struct Y(usize);
1452    ///
1453    /// # let mut world = World::default();
1454    /// let mut entity = world.spawn((X(0), Y(0)));
1455    /// // Get mutable access to two components at once
1456    /// // SAFETY: X and Y are different components
1457    /// let (mut x, mut y) =
1458    ///     unsafe { entity.into_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
1459    /// *x = X(1);
1460    /// *y = Y(1);
1461    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
1462    /// // entity.into_components_mut_unchecked::<(&mut X, &mut X)>();
1463    /// ```
1464    ///
1465    /// # Safety
1466    /// It is the caller's responsibility to ensure that
1467    /// the `QueryData` does not provide aliasing mutable references to the same component.
1468    pub unsafe fn into_components_mut_unchecked<Q: ReleaseStateQueryData>(
1469        self,
1470    ) -> Option<Q::Item<'w, 'static>> {
1471        // SAFETY: Caller the `QueryData` does not provide aliasing mutable references to the same component
1472        unsafe { self.into_mutable().into_components_mut_unchecked::<Q>() }
1473    }
1474
1475    /// Consumes `self` and gets access to the component of type `T` with
1476    /// the world `'w` lifetime for the current entity.
1477    /// Returns `None` if the entity does not have a component of type `T`.
1478    ///
1479    /// # Panics
1480    ///
1481    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1482    #[inline]
1483    pub fn into_borrow<T: Component>(self) -> Option<&'w T> {
1484        self.into_readonly().get()
1485    }
1486
1487    /// Gets access to the component of type `T` for the current entity,
1488    /// including change detection information as a [`Ref`].
1489    ///
1490    /// Returns `None` if the entity does not have a component of type `T`.
1491    ///
1492    /// # Panics
1493    ///
1494    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1495    #[inline]
1496    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
1497        self.as_readonly().get_ref()
1498    }
1499
1500    /// Consumes `self` and gets access to the component of type `T`
1501    /// with the world `'w` lifetime for the current entity,
1502    /// including change detection information as a [`Ref`].
1503    ///
1504    /// Returns `None` if the entity does not have a component of type `T`.
1505    ///
1506    /// # Panics
1507    ///
1508    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1509    #[inline]
1510    pub fn into_ref<T: Component>(self) -> Option<Ref<'w, T>> {
1511        self.into_readonly().get_ref()
1512    }
1513
1514    /// Gets mutable access to the component of type `T` for the current entity.
1515    /// Returns `None` if the entity does not have a component of type `T`.
1516    ///
1517    /// # Panics
1518    ///
1519    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1520    #[inline]
1521    pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
1522        self.as_mutable().into_mut()
1523    }
1524
1525    /// Temporarily removes a [`Component`] `T` from this [`Entity`] and runs the
1526    /// provided closure on it, returning the result if `T` was available.
1527    /// This will trigger the `Remove` and `Replace` component hooks without
1528    /// causing an archetype move.
1529    ///
1530    /// This is most useful with immutable components, where removal and reinsertion
1531    /// is the only way to modify a value.
1532    ///
1533    /// If you do not need to ensure the above hooks are triggered, and your component
1534    /// is mutable, prefer using [`get_mut`](EntityWorldMut::get_mut).
1535    ///
1536    /// # Examples
1537    ///
1538    /// ```rust
1539    /// # use bevy_ecs::prelude::*;
1540    /// #
1541    /// #[derive(Component, PartialEq, Eq, Debug)]
1542    /// #[component(immutable)]
1543    /// struct Foo(bool);
1544    ///
1545    /// # let mut world = World::default();
1546    /// # world.register_component::<Foo>();
1547    /// #
1548    /// # let entity = world.spawn(Foo(false)).id();
1549    /// #
1550    /// # let mut entity = world.entity_mut(entity);
1551    /// #
1552    /// # assert_eq!(entity.get::<Foo>(), Some(&Foo(false)));
1553    /// #
1554    /// entity.modify_component(|foo: &mut Foo| {
1555    ///     foo.0 = true;
1556    /// });
1557    /// #
1558    /// # assert_eq!(entity.get::<Foo>(), Some(&Foo(true)));
1559    /// ```
1560    ///
1561    /// # Panics
1562    ///
1563    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1564    #[inline]
1565    pub fn modify_component<T: Component, R>(&mut self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
1566        self.assert_not_despawned();
1567
1568        let result = self
1569            .world
1570            .modify_component(self.entity, f)
1571            .expect("entity access must be valid")?;
1572
1573        self.update_location();
1574
1575        Some(result)
1576    }
1577
1578    /// Temporarily removes a [`Component`] `T` from this [`Entity`] and runs the
1579    /// provided closure on it, returning the result if `T` was available.
1580    /// This will trigger the `Remove` and `Replace` component hooks without
1581    /// causing an archetype move.
1582    ///
1583    /// This is most useful with immutable components, where removal and reinsertion
1584    /// is the only way to modify a value.
1585    ///
1586    /// If you do not need to ensure the above hooks are triggered, and your component
1587    /// is mutable, prefer using [`get_mut`](EntityWorldMut::get_mut).
1588    ///
1589    /// # Panics
1590    ///
1591    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1592    #[inline]
1593    pub fn modify_component_by_id<R>(
1594        &mut self,
1595        component_id: ComponentId,
1596        f: impl for<'a> FnOnce(MutUntyped<'a>) -> R,
1597    ) -> Option<R> {
1598        self.assert_not_despawned();
1599
1600        let result = self
1601            .world
1602            .modify_component_by_id(self.entity, component_id, f)
1603            .expect("entity access must be valid")?;
1604
1605        self.update_location();
1606
1607        Some(result)
1608    }
1609
1610    /// Gets mutable access to the component of type `T` for the current entity.
1611    /// Returns `None` if the entity does not have a component of type `T`.
1612    ///
1613    /// # Safety
1614    ///
1615    /// - `T` must be a mutable component
1616    #[inline]
1617    pub unsafe fn get_mut_assume_mutable<T: Component>(&mut self) -> Option<Mut<'_, T>> {
1618        self.as_mutable().into_mut_assume_mutable()
1619    }
1620
1621    /// Consumes `self` and gets mutable access to the component of type `T`
1622    /// with the world `'w` lifetime for the current entity.
1623    /// Returns `None` if the entity does not have a component of type `T`.
1624    ///
1625    /// # Panics
1626    ///
1627    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1628    #[inline]
1629    pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
1630        // SAFETY: consuming `self` implies exclusive access
1631        unsafe { self.into_unsafe_entity_cell().get_mut() }
1632    }
1633
1634    /// Consumes `self` and gets mutable access to the component of type `T`
1635    /// with the world `'w` lifetime for the current entity.
1636    /// Returns `None` if the entity does not have a component of type `T`.
1637    ///
1638    /// # Panics
1639    ///
1640    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1641    ///
1642    /// # Safety
1643    ///
1644    /// - `T` must be a mutable component
1645    #[inline]
1646    pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
1647        // SAFETY: consuming `self` implies exclusive access
1648        unsafe { self.into_unsafe_entity_cell().get_mut_assume_mutable() }
1649    }
1650
1651    /// Gets a reference to the resource of the given type
1652    ///
1653    /// # Panics
1654    ///
1655    /// Panics if the resource does not exist.
1656    /// Use [`get_resource`](EntityWorldMut::get_resource) instead if you want to handle this case.
1657    #[inline]
1658    #[track_caller]
1659    pub fn resource<R: Resource>(&self) -> &R {
1660        self.world.resource::<R>()
1661    }
1662
1663    /// Gets a mutable reference to the resource of the given type
1664    ///
1665    /// # Panics
1666    ///
1667    /// Panics if the resource does not exist.
1668    /// Use [`get_resource_mut`](World::get_resource_mut) instead if you want to handle this case.
1669    ///
1670    /// If you want to instead insert a value if the resource does not exist,
1671    /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
1672    #[inline]
1673    #[track_caller]
1674    pub fn resource_mut<R: Resource>(&mut self) -> Mut<'_, R> {
1675        self.world.resource_mut::<R>()
1676    }
1677
1678    /// Gets a reference to the resource of the given type if it exists
1679    #[inline]
1680    pub fn get_resource<R: Resource>(&self) -> Option<&R> {
1681        self.world.get_resource()
1682    }
1683
1684    /// Gets a mutable reference to the resource of the given type if it exists
1685    #[inline]
1686    pub fn get_resource_mut<R: Resource>(&mut self) -> Option<Mut<'_, R>> {
1687        self.world.get_resource_mut()
1688    }
1689
1690    /// Temporarily removes the requested resource from the [`World`], runs custom user code,
1691    /// then re-adds the resource before returning.
1692    ///
1693    /// # Panics
1694    ///
1695    /// Panics if the resource does not exist.
1696    /// Use [`try_resource_scope`](Self::try_resource_scope) instead if you want to handle this case.
1697    ///
1698    /// See [`World::resource_scope`] for further details.
1699    #[track_caller]
1700    pub fn resource_scope<R: Resource, U>(
1701        &mut self,
1702        f: impl FnOnce(&mut EntityWorldMut, Mut<R>) -> U,
1703    ) -> U {
1704        let id = self.id();
1705        self.world_scope(|world| {
1706            world.resource_scope(|world, res| {
1707                // Acquiring a new EntityWorldMut here and using that instead of `self` is fine because
1708                // the outer `world_scope` will handle updating our location if it gets changed by the user code
1709                let mut this = world.entity_mut(id);
1710                f(&mut this, res)
1711            })
1712        })
1713    }
1714
1715    /// Temporarily removes the requested resource from the [`World`] if it exists, runs custom user code,
1716    /// then re-adds the resource before returning. Returns `None` if the resource does not exist in the [`World`].
1717    ///
1718    /// See [`World::try_resource_scope`] for further details.
1719    pub fn try_resource_scope<R: Resource, U>(
1720        &mut self,
1721        f: impl FnOnce(&mut EntityWorldMut, Mut<R>) -> U,
1722    ) -> Option<U> {
1723        let id = self.id();
1724        self.world_scope(|world| {
1725            world.try_resource_scope(|world, res| {
1726                // Acquiring a new EntityWorldMut here and using that instead of `self` is fine because
1727                // the outer `world_scope` will handle updating our location if it gets changed by the user code
1728                let mut this = world.entity_mut(id);
1729                f(&mut this, res)
1730            })
1731        })
1732    }
1733
1734    /// Retrieves the change ticks for the given component. This can be useful for implementing change
1735    /// detection in custom runtimes.
1736    ///
1737    /// # Panics
1738    ///
1739    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1740    #[inline]
1741    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
1742        self.as_readonly().get_change_ticks::<T>()
1743    }
1744
1745    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
1746    /// detection in custom runtimes.
1747    ///
1748    /// **You should prefer to use the typed API [`EntityWorldMut::get_change_ticks`] where possible and only
1749    /// use this in cases where the actual component types are not known at
1750    /// compile time.**
1751    ///
1752    /// # Panics
1753    ///
1754    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1755    #[inline]
1756    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
1757        self.as_readonly().get_change_ticks_by_id(component_id)
1758    }
1759
1760    /// Returns [untyped read-only reference(s)](Ptr) to component(s) for the
1761    /// current entity, based on the given [`ComponentId`]s.
1762    ///
1763    /// **You should prefer to use the typed API [`EntityWorldMut::get`] where
1764    /// possible and only use this in cases where the actual component types
1765    /// are not known at compile time.**
1766    ///
1767    /// Unlike [`EntityWorldMut::get`], this returns untyped reference(s) to
1768    /// component(s), and it's the job of the caller to ensure the correct
1769    /// type(s) are dereferenced (if necessary).
1770    ///
1771    /// # Errors
1772    ///
1773    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
1774    /// not have a component.
1775    ///
1776    /// # Examples
1777    ///
1778    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
1779    ///
1780    /// # Panics
1781    ///
1782    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1783    #[inline]
1784    pub fn get_by_id<F: DynamicComponentFetch>(
1785        &self,
1786        component_ids: F,
1787    ) -> Result<F::Ref<'_>, EntityComponentError> {
1788        self.as_readonly().get_by_id(component_ids)
1789    }
1790
1791    /// Consumes `self` and returns [untyped read-only reference(s)](Ptr) to
1792    /// component(s) with lifetime `'w` for the current entity, based on the
1793    /// given [`ComponentId`]s.
1794    ///
1795    /// **You should prefer to use the typed API [`EntityWorldMut::into_borrow`]
1796    /// where possible and only use this in cases where the actual component
1797    /// types are not known at compile time.**
1798    ///
1799    /// Unlike [`EntityWorldMut::into_borrow`], this returns untyped reference(s) to
1800    /// component(s), and it's the job of the caller to ensure the correct
1801    /// type(s) are dereferenced (if necessary).
1802    ///
1803    /// # Errors
1804    ///
1805    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
1806    /// not have a component.
1807    ///
1808    /// # Examples
1809    ///
1810    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
1811    ///
1812    /// # Panics
1813    ///
1814    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1815    #[inline]
1816    pub fn into_borrow_by_id<F: DynamicComponentFetch>(
1817        self,
1818        component_ids: F,
1819    ) -> Result<F::Ref<'w>, EntityComponentError> {
1820        self.into_readonly().get_by_id(component_ids)
1821    }
1822
1823    /// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
1824    /// the current entity, based on the given [`ComponentId`]s.
1825    ///
1826    /// **You should prefer to use the typed API [`EntityWorldMut::get_mut`] where
1827    /// possible and only use this in cases where the actual component types
1828    /// are not known at compile time.**
1829    ///
1830    /// Unlike [`EntityWorldMut::get_mut`], this returns untyped reference(s) to
1831    /// component(s), and it's the job of the caller to ensure the correct
1832    /// type(s) are dereferenced (if necessary).
1833    ///
1834    /// # Errors
1835    ///
1836    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
1837    ///   not have a component.
1838    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
1839    ///   is requested multiple times.
1840    ///
1841    /// # Examples
1842    ///
1843    /// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
1844    ///
1845    /// # Panics
1846    ///
1847    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1848    #[inline]
1849    pub fn get_mut_by_id<F: DynamicComponentFetch>(
1850        &mut self,
1851        component_ids: F,
1852    ) -> Result<F::Mut<'_>, EntityComponentError> {
1853        self.as_mutable().into_mut_by_id(component_ids)
1854    }
1855
1856    /// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
1857    /// the current entity, based on the given [`ComponentId`]s.
1858    /// Assumes the given [`ComponentId`]s refer to mutable components.
1859    ///
1860    /// **You should prefer to use the typed API [`EntityWorldMut::get_mut_assume_mutable`] where
1861    /// possible and only use this in cases where the actual component types
1862    /// are not known at compile time.**
1863    ///
1864    /// Unlike [`EntityWorldMut::get_mut_assume_mutable`], this returns untyped reference(s) to
1865    /// component(s), and it's the job of the caller to ensure the correct
1866    /// type(s) are dereferenced (if necessary).
1867    ///
1868    /// # Errors
1869    ///
1870    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
1871    ///   not have a component.
1872    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
1873    ///   is requested multiple times.
1874    ///
1875    /// # Panics
1876    ///
1877    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1878    ///
1879    /// # Safety
1880    /// It is the callers responsibility to ensure that
1881    /// - the provided [`ComponentId`]s must refer to mutable components.
1882    #[inline]
1883    pub unsafe fn get_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
1884        &mut self,
1885        component_ids: F,
1886    ) -> Result<F::Mut<'_>, EntityComponentError> {
1887        self.as_mutable()
1888            .into_mut_assume_mutable_by_id(component_ids)
1889    }
1890
1891    /// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
1892    /// to component(s) with lifetime `'w` for the current entity, based on the
1893    /// given [`ComponentId`]s.
1894    ///
1895    /// **You should prefer to use the typed API [`EntityWorldMut::into_mut`] where
1896    /// possible and only use this in cases where the actual component types
1897    /// are not known at compile time.**
1898    ///
1899    /// Unlike [`EntityWorldMut::into_mut`], this returns untyped reference(s) to
1900    /// component(s), and it's the job of the caller to ensure the correct
1901    /// type(s) are dereferenced (if necessary).
1902    ///
1903    /// # Errors
1904    ///
1905    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
1906    ///   not have a component.
1907    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
1908    ///   is requested multiple times.
1909    ///
1910    /// # Examples
1911    ///
1912    /// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
1913    ///
1914    /// # Panics
1915    ///
1916    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1917    #[inline]
1918    pub fn into_mut_by_id<F: DynamicComponentFetch>(
1919        self,
1920        component_ids: F,
1921    ) -> Result<F::Mut<'w>, EntityComponentError> {
1922        self.into_mutable().into_mut_by_id(component_ids)
1923    }
1924
1925    /// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
1926    /// to component(s) with lifetime `'w` for the current entity, based on the
1927    /// given [`ComponentId`]s.
1928    /// Assumes the given [`ComponentId`]s refer to mutable components.
1929    ///
1930    /// **You should prefer to use the typed API [`EntityWorldMut::into_mut_assume_mutable`] where
1931    /// possible and only use this in cases where the actual component types
1932    /// are not known at compile time.**
1933    ///
1934    /// Unlike [`EntityWorldMut::into_mut_assume_mutable`], this returns untyped reference(s) to
1935    /// component(s), and it's the job of the caller to ensure the correct
1936    /// type(s) are dereferenced (if necessary).
1937    ///
1938    /// # Errors
1939    ///
1940    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
1941    ///   not have a component.
1942    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
1943    ///   is requested multiple times.
1944    ///
1945    /// # Panics
1946    ///
1947    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1948    ///
1949    /// # Safety
1950    /// It is the callers responsibility to ensure that
1951    /// - the provided [`ComponentId`]s must refer to mutable components.
1952    #[inline]
1953    pub unsafe fn into_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
1954        self,
1955        component_ids: F,
1956    ) -> Result<F::Mut<'w>, EntityComponentError> {
1957        self.into_mutable()
1958            .into_mut_assume_mutable_by_id(component_ids)
1959    }
1960
1961    /// Adds a [`Bundle`] of components to the entity.
1962    ///
1963    /// This will overwrite any previous value(s) of the same component type.
1964    ///
1965    /// # Panics
1966    ///
1967    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1968    #[track_caller]
1969    pub fn insert<T: Bundle>(&mut self, bundle: T) -> &mut Self {
1970        move_as_ptr!(bundle);
1971        self.insert_with_caller(
1972            bundle,
1973            InsertMode::Replace,
1974            MaybeLocation::caller(),
1975            RelationshipHookMode::Run,
1976        )
1977    }
1978
1979    /// Adds a [`Bundle`] of components to the entity.
1980    /// [`Relationship`](crate::relationship::Relationship) components in the bundle will follow the configuration
1981    /// in `relationship_hook_mode`.
1982    ///
1983    /// This will overwrite any previous value(s) of the same component type.
1984    ///
1985    /// # Warning
1986    ///
1987    /// This can easily break the integrity of relationships. This is intended to be used for cloning and spawning code internals,
1988    /// not most user-facing scenarios.
1989    ///
1990    /// # Panics
1991    ///
1992    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1993    #[track_caller]
1994    pub fn insert_with_relationship_hook_mode<T: Bundle>(
1995        &mut self,
1996        bundle: T,
1997        relationship_hook_mode: RelationshipHookMode,
1998    ) -> &mut Self {
1999        move_as_ptr!(bundle);
2000        self.insert_with_caller(
2001            bundle,
2002            InsertMode::Replace,
2003            MaybeLocation::caller(),
2004            relationship_hook_mode,
2005        )
2006    }
2007
2008    /// Adds a [`Bundle`] of components to the entity without overwriting.
2009    ///
2010    /// This will leave any previous value(s) of the same component type
2011    /// unchanged.
2012    ///
2013    /// # Panics
2014    ///
2015    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2016    #[track_caller]
2017    pub fn insert_if_new<T: Bundle>(&mut self, bundle: T) -> &mut Self {
2018        move_as_ptr!(bundle);
2019        self.insert_with_caller(
2020            bundle,
2021            InsertMode::Keep,
2022            MaybeLocation::caller(),
2023            RelationshipHookMode::Run,
2024        )
2025    }
2026
2027    /// Adds a [`Bundle`] of components to the entity.
2028    #[inline]
2029    pub(crate) fn insert_with_caller<T: Bundle>(
2030        &mut self,
2031        bundle: MovingPtr<'_, T>,
2032        mode: InsertMode,
2033        caller: MaybeLocation,
2034        relationship_hook_mode: RelationshipHookMode,
2035    ) -> &mut Self {
2036        let location = self.location();
2037        let change_tick = self.world.change_tick();
2038        let mut bundle_inserter =
2039            BundleInserter::new::<T>(self.world, location.archetype_id, change_tick);
2040        // SAFETY:
2041        // - `location` matches current entity and thus must currently exist in the source
2042        //   archetype for this inserter and its location within the archetype.
2043        // - `T` matches the type used to create the `BundleInserter`.
2044        // - `apply_effect` is called exactly once after this function.
2045        // - The value pointed at by `bundle` is not accessed for anything other than `apply_effect`
2046        //   and the caller ensures that the value is not accessed or dropped after this function
2047        //   returns.
2048        let (bundle, location) = bundle.partial_move(|bundle| unsafe {
2049            bundle_inserter.insert(
2050                self.entity,
2051                location,
2052                bundle,
2053                mode,
2054                caller,
2055                relationship_hook_mode,
2056            )
2057        });
2058        self.location = Some(location);
2059        self.world.flush();
2060        self.update_location();
2061        // SAFETY:
2062        // - This is called exactly once after the `BundleInsert::insert` call before returning to safe code.
2063        // - `bundle` points to the same `B` that `BundleInsert::insert` was called on.
2064        unsafe { T::apply_effect(bundle, self) };
2065        self
2066    }
2067
2068    /// Inserts a dynamic [`Component`] into the entity.
2069    ///
2070    /// This will overwrite any previous value(s) of the same component type.
2071    ///
2072    /// You should prefer to use the typed API [`EntityWorldMut::insert`] where possible.
2073    ///
2074    /// # Safety
2075    ///
2076    /// - [`ComponentId`] must be from the same world as [`EntityWorldMut`]
2077    /// - [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
2078    ///
2079    /// # Panics
2080    ///
2081    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2082    #[track_caller]
2083    pub unsafe fn insert_by_id(
2084        &mut self,
2085        component_id: ComponentId,
2086        component: OwningPtr<'_>,
2087    ) -> &mut Self {
2088        self.insert_by_id_with_caller(
2089            component_id,
2090            component,
2091            InsertMode::Replace,
2092            MaybeLocation::caller(),
2093            RelationshipHookMode::Run,
2094        )
2095    }
2096
2097    /// # Safety
2098    ///
2099    /// - [`ComponentId`] must be from the same world as [`EntityWorldMut`]
2100    /// - [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
2101    #[inline]
2102    pub(crate) unsafe fn insert_by_id_with_caller(
2103        &mut self,
2104        component_id: ComponentId,
2105        component: OwningPtr<'_>,
2106        mode: InsertMode,
2107        caller: MaybeLocation,
2108        relationship_hook_insert_mode: RelationshipHookMode,
2109    ) -> &mut Self {
2110        let location = self.location();
2111        let change_tick = self.world.change_tick();
2112        let bundle_id = self.world.bundles.init_component_info(
2113            &mut self.world.storages,
2114            &self.world.components,
2115            component_id,
2116        );
2117        let storage_type = self.world.bundles.get_storage_unchecked(bundle_id);
2118
2119        let bundle_inserter =
2120            BundleInserter::new_with_id(self.world, location.archetype_id, bundle_id, change_tick);
2121
2122        self.location = Some(insert_dynamic_bundle(
2123            bundle_inserter,
2124            self.entity,
2125            location,
2126            Some(component).into_iter(),
2127            Some(storage_type).iter().cloned(),
2128            mode,
2129            caller,
2130            relationship_hook_insert_mode,
2131        ));
2132        self.world.flush();
2133        self.update_location();
2134        self
2135    }
2136
2137    /// Inserts a dynamic [`Bundle`] into the entity.
2138    ///
2139    /// This will overwrite any previous value(s) of the same component type.
2140    ///
2141    /// You should prefer to use the typed API [`EntityWorldMut::insert`] where possible.
2142    /// If your [`Bundle`] only has one component, use the cached API [`EntityWorldMut::insert_by_id`].
2143    ///
2144    /// If possible, pass a sorted slice of `ComponentId` to maximize caching potential.
2145    ///
2146    /// # Safety
2147    /// - Each [`ComponentId`] must be from the same world as [`EntityWorldMut`]
2148    /// - Each [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
2149    ///
2150    /// # Panics
2151    ///
2152    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2153    #[track_caller]
2154    pub unsafe fn insert_by_ids<'a, I: Iterator<Item = OwningPtr<'a>>>(
2155        &mut self,
2156        component_ids: &[ComponentId],
2157        iter_components: I,
2158    ) -> &mut Self {
2159        self.insert_by_ids_internal(component_ids, iter_components, RelationshipHookMode::Run)
2160    }
2161
2162    #[track_caller]
2163    pub(crate) unsafe fn insert_by_ids_internal<'a, I: Iterator<Item = OwningPtr<'a>>>(
2164        &mut self,
2165        component_ids: &[ComponentId],
2166        iter_components: I,
2167        relationship_hook_insert_mode: RelationshipHookMode,
2168    ) -> &mut Self {
2169        let location = self.location();
2170        let change_tick = self.world.change_tick();
2171        let bundle_id = self.world.bundles.init_dynamic_info(
2172            &mut self.world.storages,
2173            &self.world.components,
2174            component_ids,
2175        );
2176        let mut storage_types =
2177            core::mem::take(self.world.bundles.get_storages_unchecked(bundle_id));
2178        let bundle_inserter =
2179            BundleInserter::new_with_id(self.world, location.archetype_id, bundle_id, change_tick);
2180
2181        self.location = Some(insert_dynamic_bundle(
2182            bundle_inserter,
2183            self.entity,
2184            location,
2185            iter_components,
2186            (*storage_types).iter().cloned(),
2187            InsertMode::Replace,
2188            MaybeLocation::caller(),
2189            relationship_hook_insert_mode,
2190        ));
2191        *self.world.bundles.get_storages_unchecked(bundle_id) = core::mem::take(&mut storage_types);
2192        self.world.flush();
2193        self.update_location();
2194        self
2195    }
2196
2197    /// Removes all components in the [`Bundle`] from the entity and returns their previous values.
2198    ///
2199    /// **Note:** If the entity does not have every component in the bundle, this method will not
2200    /// remove any of them.
2201    ///
2202    /// # Panics
2203    ///
2204    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2205    #[must_use]
2206    #[track_caller]
2207    pub fn take<T: Bundle + BundleFromComponents>(&mut self) -> Option<T> {
2208        let location = self.location();
2209        let entity = self.entity;
2210
2211        let mut remover =
2212            // SAFETY: The archetype id must be valid since this entity is in it.
2213            unsafe { BundleRemover::new::<T>(self.world, location.archetype_id, true) }?;
2214        // SAFETY: The passed location has the sane archetype as the remover, since they came from the same location.
2215        let (new_location, result) = unsafe {
2216            remover.remove(
2217                entity,
2218                location,
2219                MaybeLocation::caller(),
2220                |sets, table, components, bundle_components| {
2221                    let mut bundle_components = bundle_components.iter().copied();
2222                    (
2223                        false,
2224                        T::from_components(&mut (sets, table), &mut |(sets, table)| {
2225                            let component_id = bundle_components.next().unwrap();
2226                            // SAFETY: the component existed to be removed, so its id must be valid.
2227                            let component_info = components.get_info_unchecked(component_id);
2228                            match component_info.storage_type() {
2229                                StorageType::Table => {
2230                                    table
2231                                        .as_mut()
2232                                        // SAFETY: The table must be valid if the component is in it.
2233                                        .debug_checked_unwrap()
2234                                        // SAFETY: The remover is cleaning this up.
2235                                        .take_component(component_id, location.table_row)
2236                                }
2237                                StorageType::SparseSet => sets
2238                                    .get_mut(component_id)
2239                                    .unwrap()
2240                                    .remove_and_forget(entity)
2241                                    .unwrap(),
2242                            }
2243                        }),
2244                    )
2245                },
2246            )
2247        };
2248        self.location = Some(new_location);
2249
2250        self.world.flush();
2251        self.update_location();
2252        Some(result)
2253    }
2254
2255    /// Removes any components in the [`Bundle`] from the entity.
2256    ///
2257    /// See [`EntityCommands::remove`](crate::system::EntityCommands::remove) for more details.
2258    ///
2259    /// # Panics
2260    ///
2261    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2262    #[track_caller]
2263    pub fn remove<T: Bundle>(&mut self) -> &mut Self {
2264        self.remove_with_caller::<T>(MaybeLocation::caller())
2265    }
2266
2267    #[inline]
2268    pub(crate) fn remove_with_caller<T: Bundle>(&mut self, caller: MaybeLocation) -> &mut Self {
2269        let location = self.location();
2270
2271        let Some(mut remover) =
2272            // SAFETY: The archetype id must be valid since this entity is in it.
2273            (unsafe { BundleRemover::new::<T>(self.world, location.archetype_id, false) })
2274        else {
2275            return self;
2276        };
2277        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
2278        let new_location = unsafe {
2279            remover.remove(
2280                self.entity,
2281                location,
2282                caller,
2283                BundleRemover::empty_pre_remove,
2284            )
2285        }
2286        .0;
2287
2288        self.location = Some(new_location);
2289        self.world.flush();
2290        self.update_location();
2291        self
2292    }
2293
2294    /// Removes all components in the [`Bundle`] and remove all required components for each component in the bundle
2295    ///
2296    /// # Panics
2297    ///
2298    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2299    #[track_caller]
2300    pub fn remove_with_requires<T: Bundle>(&mut self) -> &mut Self {
2301        self.remove_with_requires_with_caller::<T>(MaybeLocation::caller())
2302    }
2303
2304    pub(crate) fn remove_with_requires_with_caller<T: Bundle>(
2305        &mut self,
2306        caller: MaybeLocation,
2307    ) -> &mut Self {
2308        let location = self.location();
2309        let bundle_id = self.world.register_contributed_bundle_info::<T>();
2310
2311        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
2312        let Some(mut remover) = (unsafe {
2313            BundleRemover::new_with_id(self.world, location.archetype_id, bundle_id, false)
2314        }) else {
2315            return self;
2316        };
2317        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
2318        let new_location = unsafe {
2319            remover.remove(
2320                self.entity,
2321                location,
2322                caller,
2323                BundleRemover::empty_pre_remove,
2324            )
2325        }
2326        .0;
2327
2328        self.location = Some(new_location);
2329        self.world.flush();
2330        self.update_location();
2331        self
2332    }
2333
2334    /// Removes any components except those in the [`Bundle`] (and its Required Components) from the entity.
2335    ///
2336    /// See [`EntityCommands::retain`](crate::system::EntityCommands::retain) for more details.
2337    ///
2338    /// # Panics
2339    ///
2340    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2341    #[track_caller]
2342    pub fn retain<T: Bundle>(&mut self) -> &mut Self {
2343        self.retain_with_caller::<T>(MaybeLocation::caller())
2344    }
2345
2346    #[inline]
2347    pub(crate) fn retain_with_caller<T: Bundle>(&mut self, caller: MaybeLocation) -> &mut Self {
2348        let old_location = self.location();
2349        let retained_bundle = self.world.register_bundle_info::<T>();
2350        let archetypes = &mut self.world.archetypes;
2351
2352        // SAFETY: `retained_bundle` exists as we just registered it.
2353        let retained_bundle_info = unsafe { self.world.bundles.get_unchecked(retained_bundle) };
2354        let old_archetype = &mut archetypes[old_location.archetype_id];
2355
2356        // PERF: this could be stored in an Archetype Edge
2357        let to_remove = &old_archetype
2358            .iter_components()
2359            .filter(|c| !retained_bundle_info.contributed_components().contains(c))
2360            .collect::<Vec<_>>();
2361        let remove_bundle = self.world.bundles.init_dynamic_info(
2362            &mut self.world.storages,
2363            &self.world.components,
2364            to_remove,
2365        );
2366
2367        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
2368        let Some(mut remover) = (unsafe {
2369            BundleRemover::new_with_id(self.world, old_location.archetype_id, remove_bundle, false)
2370        }) else {
2371            return self;
2372        };
2373        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
2374        let new_location = unsafe {
2375            remover.remove(
2376                self.entity,
2377                old_location,
2378                caller,
2379                BundleRemover::empty_pre_remove,
2380            )
2381        }
2382        .0;
2383
2384        self.location = Some(new_location);
2385        self.world.flush();
2386        self.update_location();
2387        self
2388    }
2389
2390    /// Removes a dynamic [`Component`] from the entity if it exists.
2391    ///
2392    /// You should prefer to use the typed API [`EntityWorldMut::remove`] where possible.
2393    ///
2394    /// # Panics
2395    ///
2396    /// Panics if the provided [`ComponentId`] does not exist in the [`World`] or if the
2397    /// entity has been despawned while this `EntityWorldMut` is still alive.
2398    #[track_caller]
2399    pub fn remove_by_id(&mut self, component_id: ComponentId) -> &mut Self {
2400        self.remove_by_id_with_caller(component_id, MaybeLocation::caller())
2401    }
2402
2403    #[inline]
2404    pub(crate) fn remove_by_id_with_caller(
2405        &mut self,
2406        component_id: ComponentId,
2407        caller: MaybeLocation,
2408    ) -> &mut Self {
2409        let location = self.location();
2410        let components = &mut self.world.components;
2411
2412        let bundle_id = self.world.bundles.init_component_info(
2413            &mut self.world.storages,
2414            components,
2415            component_id,
2416        );
2417
2418        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
2419        let Some(mut remover) = (unsafe {
2420            BundleRemover::new_with_id(self.world, location.archetype_id, bundle_id, false)
2421        }) else {
2422            return self;
2423        };
2424        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
2425        let new_location = unsafe {
2426            remover.remove(
2427                self.entity,
2428                location,
2429                caller,
2430                BundleRemover::empty_pre_remove,
2431            )
2432        }
2433        .0;
2434
2435        self.location = Some(new_location);
2436        self.world.flush();
2437        self.update_location();
2438        self
2439    }
2440
2441    /// Removes a dynamic bundle from the entity if it exists.
2442    ///
2443    /// You should prefer to use the typed API [`EntityWorldMut::remove`] where possible.
2444    ///
2445    /// # Panics
2446    ///
2447    /// Panics if any of the provided [`ComponentId`]s do not exist in the [`World`] or if the
2448    /// entity has been despawned while this `EntityWorldMut` is still alive.
2449    #[track_caller]
2450    pub fn remove_by_ids(&mut self, component_ids: &[ComponentId]) -> &mut Self {
2451        self.remove_by_ids_with_caller(
2452            component_ids,
2453            MaybeLocation::caller(),
2454            RelationshipHookMode::Run,
2455            BundleRemover::empty_pre_remove,
2456        )
2457    }
2458
2459    #[inline]
2460    pub(crate) fn remove_by_ids_with_caller<T: 'static>(
2461        &mut self,
2462        component_ids: &[ComponentId],
2463        caller: MaybeLocation,
2464        relationship_hook_mode: RelationshipHookMode,
2465        pre_remove: impl FnOnce(
2466            &mut SparseSets,
2467            Option<&mut Table>,
2468            &Components,
2469            &[ComponentId],
2470        ) -> (bool, T),
2471    ) -> &mut Self {
2472        let location = self.location();
2473        let components = &mut self.world.components;
2474
2475        let bundle_id = self.world.bundles.init_dynamic_info(
2476            &mut self.world.storages,
2477            components,
2478            component_ids,
2479        );
2480
2481        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
2482        let Some(mut remover) = (unsafe {
2483            BundleRemover::new_with_id(self.world, location.archetype_id, bundle_id, false)
2484        }) else {
2485            return self;
2486        };
2487        remover.relationship_hook_mode = relationship_hook_mode;
2488        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
2489        let new_location = unsafe { remover.remove(self.entity, location, caller, pre_remove) }.0;
2490
2491        self.location = Some(new_location);
2492        self.world.flush();
2493        self.update_location();
2494        self
2495    }
2496
2497    /// Removes all components associated with the entity.
2498    ///
2499    /// # Panics
2500    ///
2501    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2502    #[track_caller]
2503    pub fn clear(&mut self) -> &mut Self {
2504        self.clear_with_caller(MaybeLocation::caller())
2505    }
2506
2507    #[inline]
2508    pub(crate) fn clear_with_caller(&mut self, caller: MaybeLocation) -> &mut Self {
2509        let location = self.location();
2510        // PERF: this should not be necessary
2511        let component_ids: Vec<ComponentId> = self.archetype().components().to_vec();
2512        let components = &mut self.world.components;
2513
2514        let bundle_id = self.world.bundles.init_dynamic_info(
2515            &mut self.world.storages,
2516            components,
2517            component_ids.as_slice(),
2518        );
2519
2520        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
2521        let Some(mut remover) = (unsafe {
2522            BundleRemover::new_with_id(self.world, location.archetype_id, bundle_id, false)
2523        }) else {
2524            return self;
2525        };
2526        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
2527        let new_location = unsafe {
2528            remover.remove(
2529                self.entity,
2530                location,
2531                caller,
2532                BundleRemover::empty_pre_remove,
2533            )
2534        }
2535        .0;
2536
2537        self.location = Some(new_location);
2538        self.world.flush();
2539        self.update_location();
2540        self
2541    }
2542
2543    /// Despawns the current entity.
2544    ///
2545    /// See [`World::despawn`] for more details.
2546    ///
2547    /// # Note
2548    ///
2549    /// This will also despawn any [`Children`](crate::hierarchy::Children) entities, and any other [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
2550    /// to despawn descendants. This results in "recursive despawn" behavior.
2551    ///
2552    /// # Panics
2553    ///
2554    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2555    #[track_caller]
2556    pub fn despawn(self) {
2557        self.despawn_with_caller(MaybeLocation::caller());
2558    }
2559
2560    pub(crate) fn despawn_with_caller(self, caller: MaybeLocation) {
2561        let location = self.location();
2562        let world = self.world;
2563        let archetype = &world.archetypes[location.archetype_id];
2564
2565        // SAFETY: Archetype cannot be mutably aliased by DeferredWorld
2566        let (archetype, mut deferred_world) = unsafe {
2567            let archetype: *const Archetype = archetype;
2568            let world = world.as_unsafe_world_cell();
2569            (&*archetype, world.into_deferred())
2570        };
2571
2572        // SAFETY: All components in the archetype exist in world
2573        unsafe {
2574            if archetype.has_despawn_observer() {
2575                // SAFETY: the DESPAWN event_key corresponds to the Despawn event's type
2576                deferred_world.trigger_raw(
2577                    DESPAWN,
2578                    &mut Despawn {
2579                        entity: self.entity,
2580                    },
2581                    &mut EntityComponentsTrigger {
2582                        components: archetype.components(),
2583                    },
2584                    caller,
2585                );
2586            }
2587            deferred_world.trigger_on_despawn(
2588                archetype,
2589                self.entity,
2590                archetype.iter_components(),
2591                caller,
2592            );
2593            if archetype.has_replace_observer() {
2594                // SAFETY: the REPLACE event_key corresponds to the Replace event's type
2595                deferred_world.trigger_raw(
2596                    REPLACE,
2597                    &mut Replace {
2598                        entity: self.entity,
2599                    },
2600                    &mut EntityComponentsTrigger {
2601                        components: archetype.components(),
2602                    },
2603                    caller,
2604                );
2605            }
2606            deferred_world.trigger_on_replace(
2607                archetype,
2608                self.entity,
2609                archetype.iter_components(),
2610                caller,
2611                RelationshipHookMode::Run,
2612            );
2613            if archetype.has_remove_observer() {
2614                // SAFETY: the REMOVE event_key corresponds to the Remove event's type
2615                deferred_world.trigger_raw(
2616                    REMOVE,
2617                    &mut Remove {
2618                        entity: self.entity,
2619                    },
2620                    &mut EntityComponentsTrigger {
2621                        components: archetype.components(),
2622                    },
2623                    caller,
2624                );
2625            }
2626            deferred_world.trigger_on_remove(
2627                archetype,
2628                self.entity,
2629                archetype.iter_components(),
2630                caller,
2631            );
2632        }
2633
2634        for component_id in archetype.iter_components() {
2635            world.removed_components.write(component_id, self.entity);
2636        }
2637
2638        // Observers and on_remove hooks may reserve new entities, which
2639        // requires a flush before Entities::free may be called.
2640        world.flush_entities();
2641
2642        let location = world
2643            .entities
2644            .free(self.entity)
2645            .flatten()
2646            .expect("entity should exist at this point.");
2647        let table_row;
2648        let moved_entity;
2649        let change_tick = world.change_tick();
2650
2651        {
2652            let archetype = &mut world.archetypes[location.archetype_id];
2653            let remove_result = archetype.swap_remove(location.archetype_row);
2654            if let Some(swapped_entity) = remove_result.swapped_entity {
2655                let swapped_location = world.entities.get(swapped_entity).unwrap();
2656                // SAFETY: swapped_entity is valid and the swapped entity's components are
2657                // moved to the new location immediately after.
2658                unsafe {
2659                    world.entities.set(
2660                        swapped_entity.index(),
2661                        Some(EntityLocation {
2662                            archetype_id: swapped_location.archetype_id,
2663                            archetype_row: location.archetype_row,
2664                            table_id: swapped_location.table_id,
2665                            table_row: swapped_location.table_row,
2666                        }),
2667                    );
2668                }
2669            }
2670            table_row = remove_result.table_row;
2671
2672            for component_id in archetype.sparse_set_components() {
2673                // set must have existed for the component to be added.
2674                let sparse_set = world.storages.sparse_sets.get_mut(component_id).unwrap();
2675                sparse_set.remove(self.entity);
2676            }
2677            // SAFETY: table rows stored in archetypes always exist
2678            moved_entity = unsafe {
2679                world.storages.tables[archetype.table_id()].swap_remove_unchecked(table_row)
2680            };
2681        };
2682
2683        if let Some(moved_entity) = moved_entity {
2684            let moved_location = world.entities.get(moved_entity).unwrap();
2685            // SAFETY: `moved_entity` is valid and the provided `EntityLocation` accurately reflects
2686            //         the current location of the entity and its component data.
2687            unsafe {
2688                world.entities.set(
2689                    moved_entity.index(),
2690                    Some(EntityLocation {
2691                        archetype_id: moved_location.archetype_id,
2692                        archetype_row: moved_location.archetype_row,
2693                        table_id: moved_location.table_id,
2694                        table_row,
2695                    }),
2696                );
2697            }
2698            world.archetypes[moved_location.archetype_id]
2699                .set_entity_table_row(moved_location.archetype_row, table_row);
2700        }
2701
2702        // SAFETY: `self.entity` is a valid entity index
2703        unsafe {
2704            world
2705                .entities
2706                .mark_spawn_despawn(self.entity.index(), caller, change_tick);
2707        }
2708
2709        world.flush();
2710    }
2711
2712    /// Ensures any commands triggered by the actions of Self are applied, equivalent to [`World::flush`]
2713    pub fn flush(self) -> Entity {
2714        self.world.flush();
2715        self.entity
2716    }
2717
2718    /// Gets read-only access to the world that the current entity belongs to.
2719    #[inline]
2720    pub fn world(&self) -> &World {
2721        self.world
2722    }
2723
2724    /// Returns this entity's world.
2725    ///
2726    /// See [`EntityWorldMut::world_scope`] or [`EntityWorldMut::into_world_mut`] for a safe alternative.
2727    ///
2728    /// # Safety
2729    /// Caller must not modify the world in a way that changes the current entity's location
2730    /// If the caller _does_ do something that could change the location, `self.update_location()`
2731    /// must be called before using any other methods on this [`EntityWorldMut`].
2732    #[inline]
2733    pub unsafe fn world_mut(&mut self) -> &mut World {
2734        self.world
2735    }
2736
2737    /// Returns this entity's [`World`], consuming itself.
2738    #[inline]
2739    pub fn into_world_mut(self) -> &'w mut World {
2740        self.world
2741    }
2742
2743    /// Gives mutable access to this entity's [`World`] in a temporary scope.
2744    /// This is a safe alternative to using [`EntityWorldMut::world_mut`].
2745    ///
2746    /// # Examples
2747    ///
2748    /// ```
2749    /// # use bevy_ecs::prelude::*;
2750    /// #[derive(Resource, Default, Clone, Copy)]
2751    /// struct R(u32);
2752    ///
2753    /// # let mut world = World::new();
2754    /// # world.init_resource::<R>();
2755    /// # let mut entity = world.spawn_empty();
2756    /// // This closure gives us temporary access to the world.
2757    /// let new_r = entity.world_scope(|world: &mut World| {
2758    ///     // Mutate the world while we have access to it.
2759    ///     let mut r = world.resource_mut::<R>();
2760    ///     r.0 += 1;
2761    ///
2762    ///     // Return a value from the world before giving it back to the `EntityWorldMut`.
2763    ///     *r
2764    /// });
2765    /// # assert_eq!(new_r.0, 1);
2766    /// ```
2767    pub fn world_scope<U>(&mut self, f: impl FnOnce(&mut World) -> U) -> U {
2768        struct Guard<'w, 'a> {
2769            entity_mut: &'a mut EntityWorldMut<'w>,
2770        }
2771
2772        impl Drop for Guard<'_, '_> {
2773            #[inline]
2774            fn drop(&mut self) {
2775                self.entity_mut.update_location();
2776            }
2777        }
2778
2779        // When `guard` is dropped at the end of this scope,
2780        // it will update the cached `EntityLocation` for this instance.
2781        // This will run even in case the closure `f` unwinds.
2782        let guard = Guard { entity_mut: self };
2783        f(guard.entity_mut.world)
2784    }
2785
2786    /// Updates the internal entity location to match the current location in the internal
2787    /// [`World`].
2788    ///
2789    /// This is *only* required when using the unsafe function [`EntityWorldMut::world_mut`],
2790    /// which enables the location to change.
2791    pub fn update_location(&mut self) {
2792        self.location = self.world.entities().get(self.entity);
2793    }
2794
2795    /// Returns if the entity has been despawned.
2796    ///
2797    /// Normally it shouldn't be needed to explicitly check if the entity has been despawned
2798    /// between commands as this shouldn't happen. However, for some special cases where it
2799    /// is known that a hook or an observer might despawn the entity while a [`EntityWorldMut`]
2800    /// reference is still held, this method can be used to check if the entity is still alive
2801    /// to avoid panicking when calling further methods.
2802    #[inline]
2803    pub fn is_despawned(&self) -> bool {
2804        self.location.is_none()
2805    }
2806
2807    /// Gets an Entry into the world for this entity and component for in-place manipulation.
2808    ///
2809    /// The type parameter specifies which component to get.
2810    ///
2811    /// # Examples
2812    ///
2813    /// ```
2814    /// # use bevy_ecs::prelude::*;
2815    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
2816    /// struct Comp(u32);
2817    ///
2818    /// # let mut world = World::new();
2819    /// let mut entity = world.spawn_empty();
2820    /// entity.entry().or_insert_with(|| Comp(4));
2821    /// # let entity_id = entity.id();
2822    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 4);
2823    ///
2824    /// # let mut entity = world.get_entity_mut(entity_id).unwrap();
2825    /// entity.entry::<Comp>().and_modify(|mut c| c.0 += 1);
2826    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 5);
2827    /// ```
2828    ///
2829    /// # Panics
2830    ///
2831    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2832    pub fn entry<'a, T: Component>(&'a mut self) -> ComponentEntry<'w, 'a, T> {
2833        if self.contains::<T>() {
2834            ComponentEntry::Occupied(OccupiedComponentEntry {
2835                entity_world: self,
2836                _marker: PhantomData,
2837            })
2838        } else {
2839            ComponentEntry::Vacant(VacantComponentEntry {
2840                entity_world: self,
2841                _marker: PhantomData,
2842            })
2843        }
2844    }
2845
2846    /// Creates an [`Observer`] watching for an [`EntityEvent`] of type `E` whose [`EntityEvent::event_target`]
2847    /// targets this entity.
2848    ///
2849    /// # Panics
2850    ///
2851    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
2852    ///
2853    /// Panics if the given system is an exclusive system.
2854    #[track_caller]
2855    pub fn observe<E: EntityEvent, B: Bundle, M>(
2856        &mut self,
2857        observer: impl IntoObserverSystem<E, B, M>,
2858    ) -> &mut Self {
2859        self.observe_with_caller(observer, MaybeLocation::caller())
2860    }
2861
2862    pub(crate) fn observe_with_caller<E: EntityEvent, B: Bundle, M>(
2863        &mut self,
2864        observer: impl IntoObserverSystem<E, B, M>,
2865        caller: MaybeLocation,
2866    ) -> &mut Self {
2867        self.assert_not_despawned();
2868        let bundle = Observer::new(observer).with_entity(self.entity);
2869        move_as_ptr!(bundle);
2870        self.world.spawn_with_caller(bundle, caller);
2871        self.world.flush();
2872        self.update_location();
2873        self
2874    }
2875
2876    /// Clones parts of an entity (components, observers, etc.) onto another entity,
2877    /// configured through [`EntityClonerBuilder`].
2878    ///
2879    /// The other entity will receive all the components of the original that implement
2880    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) except those that are
2881    /// [denied](EntityClonerBuilder::deny) in the `config`.
2882    ///
2883    /// # Example
2884    ///
2885    /// ```
2886    /// # use bevy_ecs::prelude::*;
2887    /// # #[derive(Component, Clone, PartialEq, Debug)]
2888    /// # struct ComponentA;
2889    /// # #[derive(Component, Clone, PartialEq, Debug)]
2890    /// # struct ComponentB;
2891    /// # let mut world = World::new();
2892    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
2893    /// # let target = world.spawn_empty().id();
2894    /// // Clone all components except ComponentA onto the target.
2895    /// world.entity_mut(entity).clone_with_opt_out(target, |builder| {
2896    ///     builder.deny::<ComponentA>();
2897    /// });
2898    /// # assert_eq!(world.get::<ComponentA>(target), None);
2899    /// # assert_eq!(world.get::<ComponentB>(target), Some(&ComponentB));
2900    /// ```
2901    ///
2902    /// See [`EntityClonerBuilder<OptOut>`] for more options.
2903    ///
2904    /// # Panics
2905    ///
2906    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
2907    /// - If the target entity does not exist.
2908    pub fn clone_with_opt_out(
2909        &mut self,
2910        target: Entity,
2911        config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static,
2912    ) -> &mut Self {
2913        self.assert_not_despawned();
2914
2915        let mut builder = EntityCloner::build_opt_out(self.world);
2916        config(&mut builder);
2917        builder.clone_entity(self.entity, target);
2918
2919        self.world.flush();
2920        self.update_location();
2921        self
2922    }
2923
2924    /// Clones parts of an entity (components, observers, etc.) onto another entity,
2925    /// configured through [`EntityClonerBuilder`].
2926    ///
2927    /// The other entity will receive only the components of the original that implement
2928    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) and are
2929    /// [allowed](EntityClonerBuilder::allow) in the `config`.
2930    ///
2931    /// # Example
2932    ///
2933    /// ```
2934    /// # use bevy_ecs::prelude::*;
2935    /// # #[derive(Component, Clone, PartialEq, Debug)]
2936    /// # struct ComponentA;
2937    /// # #[derive(Component, Clone, PartialEq, Debug)]
2938    /// # struct ComponentB;
2939    /// # let mut world = World::new();
2940    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
2941    /// # let target = world.spawn_empty().id();
2942    /// // Clone only ComponentA onto the target.
2943    /// world.entity_mut(entity).clone_with_opt_in(target, |builder| {
2944    ///     builder.allow::<ComponentA>();
2945    /// });
2946    /// # assert_eq!(world.get::<ComponentA>(target), Some(&ComponentA));
2947    /// # assert_eq!(world.get::<ComponentB>(target), None);
2948    /// ```
2949    ///
2950    /// See [`EntityClonerBuilder<OptIn>`] for more options.
2951    ///
2952    /// # Panics
2953    ///
2954    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
2955    /// - If the target entity does not exist.
2956    pub fn clone_with_opt_in(
2957        &mut self,
2958        target: Entity,
2959        config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static,
2960    ) -> &mut Self {
2961        self.assert_not_despawned();
2962
2963        let mut builder = EntityCloner::build_opt_in(self.world);
2964        config(&mut builder);
2965        builder.clone_entity(self.entity, target);
2966
2967        self.world.flush();
2968        self.update_location();
2969        self
2970    }
2971
2972    /// Spawns a clone of this entity and returns the [`Entity`] of the clone.
2973    ///
2974    /// The clone will receive all the components of the original that implement
2975    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2976    ///
2977    /// To configure cloning behavior (such as only cloning certain components),
2978    /// use [`EntityWorldMut::clone_and_spawn_with_opt_out`]/
2979    /// [`opt_in`](`EntityWorldMut::clone_and_spawn_with_opt_in`).
2980    ///
2981    /// # Panics
2982    ///
2983    /// If this entity has been despawned while this `EntityWorldMut` is still alive.
2984    pub fn clone_and_spawn(&mut self) -> Entity {
2985        self.clone_and_spawn_with_opt_out(|_| {})
2986    }
2987
2988    /// Spawns a clone of this entity and allows configuring cloning behavior
2989    /// using [`EntityClonerBuilder`], returning the [`Entity`] of the clone.
2990    ///
2991    /// The clone will receive all the components of the original that implement
2992    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) except those that are
2993    /// [denied](EntityClonerBuilder::deny) in the `config`.
2994    ///
2995    /// # Example
2996    ///
2997    /// ```
2998    /// # use bevy_ecs::prelude::*;
2999    /// # let mut world = World::new();
3000    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
3001    /// # #[derive(Component, Clone, PartialEq, Debug)]
3002    /// # struct ComponentA;
3003    /// # #[derive(Component, Clone, PartialEq, Debug)]
3004    /// # struct ComponentB;
3005    /// // Create a clone of an entity but without ComponentA.
3006    /// let entity_clone = world.entity_mut(entity).clone_and_spawn_with_opt_out(|builder| {
3007    ///     builder.deny::<ComponentA>();
3008    /// });
3009    /// # assert_eq!(world.get::<ComponentA>(entity_clone), None);
3010    /// # assert_eq!(world.get::<ComponentB>(entity_clone), Some(&ComponentB));
3011    /// ```
3012    ///
3013    /// See [`EntityClonerBuilder<OptOut>`] for more options.
3014    ///
3015    /// # Panics
3016    ///
3017    /// If this entity has been despawned while this `EntityWorldMut` is still alive.
3018    pub fn clone_and_spawn_with_opt_out(
3019        &mut self,
3020        config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static,
3021    ) -> Entity {
3022        self.assert_not_despawned();
3023
3024        let entity_clone = self.world.entities.reserve_entity();
3025        self.world.flush();
3026
3027        let mut builder = EntityCloner::build_opt_out(self.world);
3028        config(&mut builder);
3029        builder.clone_entity(self.entity, entity_clone);
3030
3031        self.world.flush();
3032        self.update_location();
3033        entity_clone
3034    }
3035
3036    /// Spawns a clone of this entity and allows configuring cloning behavior
3037    /// using [`EntityClonerBuilder`], returning the [`Entity`] of the clone.
3038    ///
3039    /// The clone will receive only the components of the original that implement
3040    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) and are
3041    /// [allowed](EntityClonerBuilder::allow) in the `config`.
3042    ///
3043    /// # Example
3044    ///
3045    /// ```
3046    /// # use bevy_ecs::prelude::*;
3047    /// # let mut world = World::new();
3048    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
3049    /// # #[derive(Component, Clone, PartialEq, Debug)]
3050    /// # struct ComponentA;
3051    /// # #[derive(Component, Clone, PartialEq, Debug)]
3052    /// # struct ComponentB;
3053    /// // Create a clone of an entity but only with ComponentA.
3054    /// let entity_clone = world.entity_mut(entity).clone_and_spawn_with_opt_in(|builder| {
3055    ///     builder.allow::<ComponentA>();
3056    /// });
3057    /// # assert_eq!(world.get::<ComponentA>(entity_clone), Some(&ComponentA));
3058    /// # assert_eq!(world.get::<ComponentB>(entity_clone), None);
3059    /// ```
3060    ///
3061    /// See [`EntityClonerBuilder<OptIn>`] for more options.
3062    ///
3063    /// # Panics
3064    ///
3065    /// If this entity has been despawned while this `EntityWorldMut` is still alive.
3066    pub fn clone_and_spawn_with_opt_in(
3067        &mut self,
3068        config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static,
3069    ) -> Entity {
3070        self.assert_not_despawned();
3071
3072        let entity_clone = self.world.entities.reserve_entity();
3073        self.world.flush();
3074
3075        let mut builder = EntityCloner::build_opt_in(self.world);
3076        config(&mut builder);
3077        builder.clone_entity(self.entity, entity_clone);
3078
3079        self.world.flush();
3080        self.update_location();
3081        entity_clone
3082    }
3083
3084    /// Clones the specified components of this entity and inserts them into another entity.
3085    ///
3086    /// Components can only be cloned if they implement
3087    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
3088    ///
3089    /// # Panics
3090    ///
3091    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
3092    /// - If the target entity does not exist.
3093    pub fn clone_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
3094        self.assert_not_despawned();
3095
3096        EntityCloner::build_opt_in(self.world)
3097            .allow::<B>()
3098            .clone_entity(self.entity, target);
3099
3100        self.world.flush();
3101        self.update_location();
3102        self
3103    }
3104
3105    /// Clones the specified components of this entity and inserts them into another entity,
3106    /// then removes the components from this entity.
3107    ///
3108    /// Components can only be cloned if they implement
3109    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
3110    ///
3111    /// # Panics
3112    ///
3113    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
3114    /// - If the target entity does not exist.
3115    pub fn move_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
3116        self.assert_not_despawned();
3117
3118        EntityCloner::build_opt_in(self.world)
3119            .allow::<B>()
3120            .move_components(true)
3121            .clone_entity(self.entity, target);
3122
3123        self.world.flush();
3124        self.update_location();
3125        self
3126    }
3127
3128    /// Returns the source code location from which this entity has last been spawned.
3129    pub fn spawned_by(&self) -> MaybeLocation {
3130        self.world()
3131            .entities()
3132            .entity_get_spawned_or_despawned_by(self.entity)
3133            .map(|location| location.unwrap())
3134    }
3135
3136    /// Returns the [`Tick`] at which this entity has last been spawned.
3137    pub fn spawn_tick(&self) -> Tick {
3138        self.assert_not_despawned();
3139
3140        // SAFETY: entity being alive was asserted
3141        unsafe {
3142            self.world()
3143                .entities()
3144                .entity_get_spawned_or_despawned_unchecked(self.entity)
3145                .1
3146        }
3147    }
3148
3149    /// Reborrows this entity in a temporary scope.
3150    /// This is useful for executing a function that requires a `EntityWorldMut`
3151    /// but you do not want to move out the entity ownership.
3152    pub fn reborrow_scope<U>(&mut self, f: impl FnOnce(EntityWorldMut) -> U) -> U {
3153        let Self {
3154            entity, location, ..
3155        } = *self;
3156        self.world_scope(move |world| {
3157            f(EntityWorldMut {
3158                world,
3159                entity,
3160                location,
3161            })
3162        })
3163    }
3164
3165    /// Passes the current entity into the given function, and triggers the [`EntityEvent`] returned by that function.
3166    /// See [`EntityCommands::trigger`] for usage examples
3167    ///
3168    /// [`EntityCommands::trigger`]: crate::system::EntityCommands::trigger
3169    #[track_caller]
3170    pub fn trigger<'t, E: EntityEvent<Trigger<'t>: Default>>(
3171        &mut self,
3172        event_fn: impl FnOnce(Entity) -> E,
3173    ) -> &mut Self {
3174        let mut event = (event_fn)(self.entity);
3175        let caller = MaybeLocation::caller();
3176        self.world_scope(|world| {
3177            world.trigger_ref_with_caller(
3178                &mut event,
3179                &mut <E::Trigger<'_> as Default>::default(),
3180                caller,
3181            );
3182        });
3183        self
3184    }
3185}
3186
3187/// A view into a single entity and component in a world, which may either be vacant or occupied.
3188///
3189/// This `enum` can only be constructed from the [`entry`] method on [`EntityWorldMut`].
3190///
3191/// [`entry`]: EntityWorldMut::entry
3192pub enum ComponentEntry<'w, 'a, T: Component> {
3193    /// An occupied entry.
3194    Occupied(OccupiedComponentEntry<'w, 'a, T>),
3195    /// A vacant entry.
3196    Vacant(VacantComponentEntry<'w, 'a, T>),
3197}
3198
3199impl<'w, 'a, T: Component<Mutability = Mutable>> ComponentEntry<'w, 'a, T> {
3200    /// Provides in-place mutable access to an occupied entry.
3201    ///
3202    /// # Examples
3203    ///
3204    /// ```
3205    /// # use bevy_ecs::prelude::*;
3206    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3207    /// struct Comp(u32);
3208    ///
3209    /// # let mut world = World::new();
3210    /// let mut entity = world.spawn(Comp(0));
3211    ///
3212    /// entity.entry::<Comp>().and_modify(|mut c| c.0 += 1);
3213    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 1);
3214    /// ```
3215    #[inline]
3216    pub fn and_modify<F: FnOnce(Mut<'_, T>)>(self, f: F) -> Self {
3217        match self {
3218            ComponentEntry::Occupied(mut entry) => {
3219                f(entry.get_mut());
3220                ComponentEntry::Occupied(entry)
3221            }
3222            ComponentEntry::Vacant(entry) => ComponentEntry::Vacant(entry),
3223        }
3224    }
3225}
3226
3227impl<'w, 'a, T: Component> ComponentEntry<'w, 'a, T> {
3228    /// Replaces the component of the entry, and returns an [`OccupiedComponentEntry`].
3229    ///
3230    /// # Examples
3231    ///
3232    /// ```
3233    /// # use bevy_ecs::prelude::*;
3234    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3235    /// struct Comp(u32);
3236    ///
3237    /// # let mut world = World::new();
3238    /// let mut entity = world.spawn_empty();
3239    ///
3240    /// let entry = entity.entry().insert_entry(Comp(4));
3241    /// assert_eq!(entry.get(), &Comp(4));
3242    ///
3243    /// let entry = entity.entry().insert_entry(Comp(2));
3244    /// assert_eq!(entry.get(), &Comp(2));
3245    /// ```
3246    #[inline]
3247    pub fn insert_entry(self, component: T) -> OccupiedComponentEntry<'w, 'a, T> {
3248        match self {
3249            ComponentEntry::Occupied(mut entry) => {
3250                entry.insert(component);
3251                entry
3252            }
3253            ComponentEntry::Vacant(entry) => entry.insert(component),
3254        }
3255    }
3256
3257    /// Ensures the entry has this component by inserting the given default if empty, and
3258    /// returns a mutable reference to this component in the entry.
3259    ///
3260    /// # Examples
3261    ///
3262    /// ```
3263    /// # use bevy_ecs::prelude::*;
3264    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3265    /// struct Comp(u32);
3266    ///
3267    /// # let mut world = World::new();
3268    /// let mut entity = world.spawn_empty();
3269    ///
3270    /// entity.entry().or_insert(Comp(4));
3271    /// # let entity_id = entity.id();
3272    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 4);
3273    ///
3274    /// # let mut entity = world.get_entity_mut(entity_id).unwrap();
3275    /// entity.entry().or_insert(Comp(15)).into_mut().0 *= 2;
3276    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 8);
3277    /// ```
3278    #[inline]
3279    pub fn or_insert(self, default: T) -> OccupiedComponentEntry<'w, 'a, T> {
3280        match self {
3281            ComponentEntry::Occupied(entry) => entry,
3282            ComponentEntry::Vacant(entry) => entry.insert(default),
3283        }
3284    }
3285
3286    /// Ensures the entry has this component by inserting the result of the default function if
3287    /// empty, and returns a mutable reference to this component in the entry.
3288    ///
3289    /// # Examples
3290    ///
3291    /// ```
3292    /// # use bevy_ecs::prelude::*;
3293    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3294    /// struct Comp(u32);
3295    ///
3296    /// # let mut world = World::new();
3297    /// let mut entity = world.spawn_empty();
3298    ///
3299    /// entity.entry().or_insert_with(|| Comp(4));
3300    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 4);
3301    /// ```
3302    #[inline]
3303    pub fn or_insert_with<F: FnOnce() -> T>(self, default: F) -> OccupiedComponentEntry<'w, 'a, T> {
3304        match self {
3305            ComponentEntry::Occupied(entry) => entry,
3306            ComponentEntry::Vacant(entry) => entry.insert(default()),
3307        }
3308    }
3309}
3310
3311impl<'w, 'a, T: Component + Default> ComponentEntry<'w, 'a, T> {
3312    /// Ensures the entry has this component by inserting the default value if empty, and
3313    /// returns a mutable reference to this component in the entry.
3314    ///
3315    /// # Examples
3316    ///
3317    /// ```
3318    /// # use bevy_ecs::prelude::*;
3319    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3320    /// struct Comp(u32);
3321    ///
3322    /// # let mut world = World::new();
3323    /// let mut entity = world.spawn_empty();
3324    ///
3325    /// entity.entry::<Comp>().or_default();
3326    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 0);
3327    /// ```
3328    #[inline]
3329    pub fn or_default(self) -> OccupiedComponentEntry<'w, 'a, T> {
3330        match self {
3331            ComponentEntry::Occupied(entry) => entry,
3332            ComponentEntry::Vacant(entry) => entry.insert(Default::default()),
3333        }
3334    }
3335}
3336
3337/// A view into an occupied entry in a [`EntityWorldMut`]. It is part of the [`OccupiedComponentEntry`] enum.
3338///
3339/// The contained entity must have the component type parameter if we have this struct.
3340pub struct OccupiedComponentEntry<'w, 'a, T: Component> {
3341    entity_world: &'a mut EntityWorldMut<'w>,
3342    _marker: PhantomData<T>,
3343}
3344
3345impl<'w, 'a, T: Component> OccupiedComponentEntry<'w, 'a, T> {
3346    /// Gets a reference to the component in the entry.
3347    ///
3348    /// # Examples
3349    ///
3350    /// ```
3351    /// # use bevy_ecs::{prelude::*, world::ComponentEntry};
3352    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3353    /// struct Comp(u32);
3354    ///
3355    /// # let mut world = World::new();
3356    /// let mut entity = world.spawn(Comp(5));
3357    ///
3358    /// if let ComponentEntry::Occupied(o) = entity.entry::<Comp>() {
3359    ///     assert_eq!(o.get().0, 5);
3360    /// }
3361    /// ```
3362    #[inline]
3363    pub fn get(&self) -> &T {
3364        // This shouldn't panic because if we have an OccupiedComponentEntry the component must exist.
3365        self.entity_world.get::<T>().unwrap()
3366    }
3367
3368    /// Replaces the component of the entry.
3369    ///
3370    /// # Examples
3371    ///
3372    /// ```
3373    /// # use bevy_ecs::{prelude::*, world::ComponentEntry};
3374    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3375    /// struct Comp(u32);
3376    ///
3377    /// # let mut world = World::new();
3378    /// let mut entity = world.spawn(Comp(5));
3379    ///
3380    /// if let ComponentEntry::Occupied(mut o) = entity.entry::<Comp>() {
3381    ///     o.insert(Comp(10));
3382    /// }
3383    ///
3384    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 10);
3385    /// ```
3386    #[inline]
3387    pub fn insert(&mut self, component: T) {
3388        self.entity_world.insert(component);
3389    }
3390
3391    /// Removes the component from the entry and returns it.
3392    ///
3393    /// # Examples
3394    ///
3395    /// ```
3396    /// # use bevy_ecs::{prelude::*, world::ComponentEntry};
3397    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3398    /// struct Comp(u32);
3399    ///
3400    /// # let mut world = World::new();
3401    /// let mut entity = world.spawn(Comp(5));
3402    ///
3403    /// if let ComponentEntry::Occupied(o) = entity.entry::<Comp>() {
3404    ///     assert_eq!(o.take(), Comp(5));
3405    /// }
3406    ///
3407    /// assert_eq!(world.query::<&Comp>().iter(&world).len(), 0);
3408    /// ```
3409    #[inline]
3410    pub fn take(self) -> T {
3411        // This shouldn't panic because if we have an OccupiedComponentEntry the component must exist.
3412        self.entity_world.take().unwrap()
3413    }
3414}
3415
3416impl<'w, 'a, T: Component<Mutability = Mutable>> OccupiedComponentEntry<'w, 'a, T> {
3417    /// Gets a mutable reference to the component in the entry.
3418    ///
3419    /// If you need a reference to the [`OccupiedComponentEntry`] which may outlive the destruction of
3420    /// the [`OccupiedComponentEntry`] value, see [`into_mut`].
3421    ///
3422    /// [`into_mut`]: Self::into_mut
3423    ///
3424    /// # Examples
3425    ///
3426    /// ```
3427    /// # use bevy_ecs::{prelude::*, world::ComponentEntry};
3428    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3429    /// struct Comp(u32);
3430    ///
3431    /// # let mut world = World::new();
3432    /// let mut entity = world.spawn(Comp(5));
3433    ///
3434    /// if let ComponentEntry::Occupied(mut o) = entity.entry::<Comp>() {
3435    ///     o.get_mut().0 += 10;
3436    ///     assert_eq!(o.get().0, 15);
3437    ///
3438    ///     // We can use the same Entry multiple times.
3439    ///     o.get_mut().0 += 2
3440    /// }
3441    ///
3442    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 17);
3443    /// ```
3444    #[inline]
3445    pub fn get_mut(&mut self) -> Mut<'_, T> {
3446        // This shouldn't panic because if we have an OccupiedComponentEntry the component must exist.
3447        self.entity_world.get_mut::<T>().unwrap()
3448    }
3449
3450    /// Converts the [`OccupiedComponentEntry`] into a mutable reference to the value in the entry with
3451    /// a lifetime bound to the `EntityWorldMut`.
3452    ///
3453    /// If you need multiple references to the [`OccupiedComponentEntry`], see [`get_mut`].
3454    ///
3455    /// [`get_mut`]: Self::get_mut
3456    ///
3457    /// # Examples
3458    ///
3459    /// ```
3460    /// # use bevy_ecs::{prelude::*, world::ComponentEntry};
3461    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3462    /// struct Comp(u32);
3463    ///
3464    /// # let mut world = World::new();
3465    /// let mut entity = world.spawn(Comp(5));
3466    ///
3467    /// if let ComponentEntry::Occupied(o) = entity.entry::<Comp>() {
3468    ///     o.into_mut().0 += 10;
3469    /// }
3470    ///
3471    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 15);
3472    /// ```
3473    #[inline]
3474    pub fn into_mut(self) -> Mut<'a, T> {
3475        // This shouldn't panic because if we have an OccupiedComponentEntry the component must exist.
3476        self.entity_world.get_mut().unwrap()
3477    }
3478}
3479
3480/// A view into a vacant entry in a [`EntityWorldMut`]. It is part of the [`ComponentEntry`] enum.
3481pub struct VacantComponentEntry<'w, 'a, T: Component> {
3482    entity_world: &'a mut EntityWorldMut<'w>,
3483    _marker: PhantomData<T>,
3484}
3485
3486impl<'w, 'a, T: Component> VacantComponentEntry<'w, 'a, T> {
3487    /// Inserts the component into the [`VacantComponentEntry`] and returns an [`OccupiedComponentEntry`].
3488    ///
3489    /// # Examples
3490    ///
3491    /// ```
3492    /// # use bevy_ecs::{prelude::*, world::ComponentEntry};
3493    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
3494    /// struct Comp(u32);
3495    ///
3496    /// # let mut world = World::new();
3497    /// let mut entity = world.spawn_empty();
3498    ///
3499    /// if let ComponentEntry::Vacant(v) = entity.entry::<Comp>() {
3500    ///     v.insert(Comp(10));
3501    /// }
3502    ///
3503    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 10);
3504    /// ```
3505    #[inline]
3506    pub fn insert(self, component: T) -> OccupiedComponentEntry<'w, 'a, T> {
3507        self.entity_world.insert(component);
3508        OccupiedComponentEntry {
3509            entity_world: self.entity_world,
3510            _marker: PhantomData,
3511        }
3512    }
3513}
3514
3515/// Provides read-only access to a single entity and some of its components defined by the contained [`Access`].
3516///
3517/// To define the access when used as a [`QueryData`](crate::query::QueryData),
3518/// use a [`QueryBuilder`](crate::query::QueryBuilder) or [`QueryParamBuilder`](crate::system::QueryParamBuilder).
3519/// The [`FilteredEntityRef`] must be the entire [`QueryData`](crate::query::QueryData), and not nested inside a tuple with other data.
3520///
3521/// ```
3522/// # use bevy_ecs::{prelude::*, world::FilteredEntityRef};
3523/// #
3524/// # #[derive(Component)]
3525/// # struct A;
3526/// #
3527/// # let mut world = World::new();
3528/// # world.spawn(A);
3529/// #
3530/// // This gives the `FilteredEntityRef` access to `&A`.
3531/// let mut query = QueryBuilder::<FilteredEntityRef>::new(&mut world)
3532///     .data::<&A>()
3533///     .build();
3534///
3535/// let filtered_entity: FilteredEntityRef = query.single(&mut world).unwrap();
3536/// let component: &A = filtered_entity.get().unwrap();
3537/// ```
3538#[derive(Clone, Copy)]
3539pub struct FilteredEntityRef<'w, 's> {
3540    entity: UnsafeEntityCell<'w>,
3541    access: &'s Access,
3542}
3543
3544impl<'w, 's> FilteredEntityRef<'w, 's> {
3545    /// # Safety
3546    /// - No `&mut World` can exist from the underlying `UnsafeWorldCell`
3547    /// - If `access` takes read access to a component no mutable reference to that
3548    ///   component can exist at the same time as the returned [`FilteredEntityMut`]
3549    /// - If `access` takes any access for a component `entity` must have that component.
3550    #[inline]
3551    pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: &'s Access) -> Self {
3552        Self { entity, access }
3553    }
3554
3555    /// Returns the [ID](Entity) of the current entity.
3556    #[inline]
3557    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
3558    pub fn id(&self) -> Entity {
3559        self.entity.id()
3560    }
3561
3562    /// Gets metadata indicating the location where the current entity is stored.
3563    #[inline]
3564    pub fn location(&self) -> EntityLocation {
3565        self.entity.location()
3566    }
3567
3568    /// Returns the archetype that the current entity belongs to.
3569    #[inline]
3570    pub fn archetype(&self) -> &Archetype {
3571        self.entity.archetype()
3572    }
3573
3574    /// Returns a reference to the underlying [`Access`].
3575    #[inline]
3576    pub fn access(&self) -> &Access {
3577        self.access
3578    }
3579
3580    /// Returns `true` if the current entity has a component of type `T`.
3581    /// Otherwise, this returns `false`.
3582    ///
3583    /// ## Notes
3584    ///
3585    /// If you do not know the concrete type of a component, consider using
3586    /// [`Self::contains_id`] or [`Self::contains_type_id`].
3587    #[inline]
3588    pub fn contains<T: Component>(&self) -> bool {
3589        self.contains_type_id(TypeId::of::<T>())
3590    }
3591
3592    /// Returns `true` if the current entity has a component identified by `component_id`.
3593    /// Otherwise, this returns false.
3594    ///
3595    /// ## Notes
3596    ///
3597    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
3598    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
3599    ///   [`Self::contains_type_id`].
3600    #[inline]
3601    pub fn contains_id(&self, component_id: ComponentId) -> bool {
3602        self.entity.contains_id(component_id)
3603    }
3604
3605    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
3606    /// Otherwise, this returns false.
3607    ///
3608    /// ## Notes
3609    ///
3610    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
3611    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
3612    #[inline]
3613    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
3614        self.entity.contains_type_id(type_id)
3615    }
3616
3617    /// Gets access to the component of type `T` for the current entity.
3618    /// Returns `None` if the entity does not have a component of type `T`.
3619    #[inline]
3620    pub fn get<T: Component>(&self) -> Option<&'w T> {
3621        let id = self
3622            .entity
3623            .world()
3624            .components()
3625            .get_valid_id(TypeId::of::<T>())?;
3626        self.access
3627            .has_component_read(id)
3628            // SAFETY: We have read access
3629            .then(|| unsafe { self.entity.get() })
3630            .flatten()
3631    }
3632
3633    /// Gets access to the component of type `T` for the current entity,
3634    /// including change detection information as a [`Ref`].
3635    ///
3636    /// Returns `None` if the entity does not have a component of type `T`.
3637    #[inline]
3638    pub fn get_ref<T: Component>(&self) -> Option<Ref<'w, T>> {
3639        let id = self
3640            .entity
3641            .world()
3642            .components()
3643            .get_valid_id(TypeId::of::<T>())?;
3644        self.access
3645            .has_component_read(id)
3646            // SAFETY: We have read access
3647            .then(|| unsafe { self.entity.get_ref() })
3648            .flatten()
3649    }
3650
3651    /// Retrieves the change ticks for the given component. This can be useful for implementing change
3652    /// detection in custom runtimes.
3653    #[inline]
3654    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
3655        let id = self
3656            .entity
3657            .world()
3658            .components()
3659            .get_valid_id(TypeId::of::<T>())?;
3660        self.access
3661            .has_component_read(id)
3662            // SAFETY: We have read access
3663            .then(|| unsafe { self.entity.get_change_ticks::<T>() })
3664            .flatten()
3665    }
3666
3667    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
3668    /// detection in custom runtimes.
3669    ///
3670    /// **You should prefer to use the typed API [`Self::get_change_ticks`] where possible and only
3671    /// use this in cases where the actual component types are not known at
3672    /// compile time.**
3673    #[inline]
3674    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
3675        self.access
3676            .has_component_read(component_id)
3677            // SAFETY: We have read access
3678            .then(|| unsafe { self.entity.get_change_ticks_by_id(component_id) })
3679            .flatten()
3680    }
3681
3682    /// Gets the component of the given [`ComponentId`] from the entity.
3683    ///
3684    /// **You should prefer to use the typed API [`Self::get`] where possible and only
3685    /// use this in cases where the actual component types are not known at
3686    /// compile time.**
3687    ///
3688    /// Unlike [`FilteredEntityRef::get`], this returns a raw pointer to the component,
3689    /// which is only valid while the [`FilteredEntityRef`] is alive.
3690    #[inline]
3691    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'w>> {
3692        self.access
3693            .has_component_read(component_id)
3694            // SAFETY: We have read access
3695            .then(|| unsafe { self.entity.get_by_id(component_id) })
3696            .flatten()
3697    }
3698
3699    /// Returns the source code location from which this entity has been spawned.
3700    pub fn spawned_by(&self) -> MaybeLocation {
3701        self.entity.spawned_by()
3702    }
3703
3704    /// Returns the [`Tick`] at which this entity has been spawned.
3705    pub fn spawn_tick(&self) -> Tick {
3706        self.entity.spawn_tick()
3707    }
3708}
3709
3710impl<'w, 's> From<FilteredEntityMut<'w, 's>> for FilteredEntityRef<'w, 's> {
3711    #[inline]
3712    fn from(entity: FilteredEntityMut<'w, 's>) -> Self {
3713        // SAFETY:
3714        // - `FilteredEntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
3715        unsafe { FilteredEntityRef::new(entity.entity, entity.access) }
3716    }
3717}
3718
3719impl<'w, 's> From<&'w FilteredEntityMut<'_, 's>> for FilteredEntityRef<'w, 's> {
3720    #[inline]
3721    fn from(entity: &'w FilteredEntityMut<'_, 's>) -> Self {
3722        // SAFETY:
3723        // - `FilteredEntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
3724        unsafe { FilteredEntityRef::new(entity.entity, entity.access) }
3725    }
3726}
3727
3728impl<'a> From<EntityRef<'a>> for FilteredEntityRef<'a, 'static> {
3729    fn from(entity: EntityRef<'a>) -> Self {
3730        // SAFETY:
3731        // - `EntityRef` guarantees exclusive access to all components in the new `FilteredEntityRef`.
3732        unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
3733    }
3734}
3735
3736impl<'a> From<&'a EntityRef<'_>> for FilteredEntityRef<'a, 'static> {
3737    fn from(entity: &'a EntityRef<'_>) -> Self {
3738        // SAFETY:
3739        // - `EntityRef` guarantees exclusive access to all components in the new `FilteredEntityRef`.
3740        unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
3741    }
3742}
3743
3744impl<'a> From<EntityMut<'a>> for FilteredEntityRef<'a, 'static> {
3745    fn from(entity: EntityMut<'a>) -> Self {
3746        // SAFETY:
3747        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
3748        unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
3749    }
3750}
3751
3752impl<'a> From<&'a EntityMut<'_>> for FilteredEntityRef<'a, 'static> {
3753    fn from(entity: &'a EntityMut<'_>) -> Self {
3754        // SAFETY:
3755        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityRef`.
3756        unsafe { FilteredEntityRef::new(entity.cell, const { &Access::new_read_all() }) }
3757    }
3758}
3759
3760impl<'a> From<EntityWorldMut<'a>> for FilteredEntityRef<'a, 'static> {
3761    fn from(entity: EntityWorldMut<'a>) -> Self {
3762        // SAFETY:
3763        // - `EntityWorldMut` guarantees exclusive access to the entire world.
3764        unsafe {
3765            FilteredEntityRef::new(
3766                entity.into_unsafe_entity_cell(),
3767                const { &Access::new_read_all() },
3768            )
3769        }
3770    }
3771}
3772
3773impl<'a> From<&'a EntityWorldMut<'_>> for FilteredEntityRef<'a, 'static> {
3774    fn from(entity: &'a EntityWorldMut<'_>) -> Self {
3775        // SAFETY:
3776        // - `EntityWorldMut` guarantees exclusive access to the entire world.
3777        unsafe {
3778            FilteredEntityRef::new(
3779                entity.as_unsafe_entity_cell_readonly(),
3780                const { &Access::new_read_all() },
3781            )
3782        }
3783    }
3784}
3785
3786impl<'w, 's, B: Bundle> From<&'w EntityRefExcept<'_, 's, B>> for FilteredEntityRef<'w, 's> {
3787    fn from(value: &'w EntityRefExcept<'_, 's, B>) -> Self {
3788        // SAFETY:
3789        // - The FilteredEntityRef has the same component access as the given EntityRefExcept.
3790        unsafe { FilteredEntityRef::new(value.entity, value.access) }
3791    }
3792}
3793
3794impl PartialEq for FilteredEntityRef<'_, '_> {
3795    fn eq(&self, other: &Self) -> bool {
3796        self.entity() == other.entity()
3797    }
3798}
3799
3800impl Eq for FilteredEntityRef<'_, '_> {}
3801
3802impl PartialOrd for FilteredEntityRef<'_, '_> {
3803    /// [`FilteredEntityRef`]'s comparison trait implementations match the underlying [`Entity`],
3804    /// and cannot discern between different worlds.
3805    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3806        Some(self.cmp(other))
3807    }
3808}
3809
3810impl Ord for FilteredEntityRef<'_, '_> {
3811    fn cmp(&self, other: &Self) -> Ordering {
3812        self.entity().cmp(&other.entity())
3813    }
3814}
3815
3816impl Hash for FilteredEntityRef<'_, '_> {
3817    fn hash<H: Hasher>(&self, state: &mut H) {
3818        self.entity().hash(state);
3819    }
3820}
3821
3822impl ContainsEntity for FilteredEntityRef<'_, '_> {
3823    fn entity(&self) -> Entity {
3824        self.id()
3825    }
3826}
3827
3828// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
3829unsafe impl EntityEquivalent for FilteredEntityRef<'_, '_> {}
3830
3831/// Provides mutable access to a single entity and some of its components defined by the contained [`Access`].
3832///
3833/// To define the access when used as a [`QueryData`](crate::query::QueryData),
3834/// use a [`QueryBuilder`](crate::query::QueryBuilder) or [`QueryParamBuilder`](crate::system::QueryParamBuilder).
3835/// The `FilteredEntityMut` must be the entire `QueryData`, and not nested inside a tuple with other data.
3836///
3837/// ```
3838/// # use bevy_ecs::{prelude::*, world::FilteredEntityMut};
3839/// #
3840/// # #[derive(Component)]
3841/// # struct A;
3842/// #
3843/// # let mut world = World::new();
3844/// # world.spawn(A);
3845/// #
3846/// // This gives the `FilteredEntityMut` access to `&mut A`.
3847/// let mut query = QueryBuilder::<FilteredEntityMut>::new(&mut world)
3848///     .data::<&mut A>()
3849///     .build();
3850///
3851/// let mut filtered_entity: FilteredEntityMut = query.single_mut(&mut world).unwrap();
3852/// let component: Mut<A> = filtered_entity.get_mut().unwrap();
3853/// ```
3854pub struct FilteredEntityMut<'w, 's> {
3855    entity: UnsafeEntityCell<'w>,
3856    access: &'s Access,
3857}
3858
3859impl<'w, 's> FilteredEntityMut<'w, 's> {
3860    /// # Safety
3861    /// - No `&mut World` can exist from the underlying `UnsafeWorldCell`
3862    /// - If `access` takes read access to a component no mutable reference to that
3863    ///   component can exist at the same time as the returned [`FilteredEntityMut`]
3864    /// - If `access` takes write access to a component, no reference to that component
3865    ///   may exist at the same time as the returned [`FilteredEntityMut`]
3866    /// - If `access` takes any access for a component `entity` must have that component.
3867    #[inline]
3868    pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: &'s Access) -> Self {
3869        Self { entity, access }
3870    }
3871
3872    /// Returns a new instance with a shorter lifetime.
3873    /// This is useful if you have `&mut FilteredEntityMut`, but you need `FilteredEntityMut`.
3874    pub fn reborrow(&mut self) -> FilteredEntityMut<'_, 's> {
3875        // SAFETY: We have exclusive access to the entire entity and its components.
3876        unsafe { Self::new(self.entity, self.access) }
3877    }
3878
3879    /// Gets read-only access to all of the entity's components.
3880    #[inline]
3881    pub fn as_readonly(&self) -> FilteredEntityRef<'_, 's> {
3882        FilteredEntityRef::from(self)
3883    }
3884
3885    /// Returns the [ID](Entity) of the current entity.
3886    #[inline]
3887    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
3888    pub fn id(&self) -> Entity {
3889        self.entity.id()
3890    }
3891
3892    /// Gets metadata indicating the location where the current entity is stored.
3893    #[inline]
3894    pub fn location(&self) -> EntityLocation {
3895        self.entity.location()
3896    }
3897
3898    /// Returns the archetype that the current entity belongs to.
3899    #[inline]
3900    pub fn archetype(&self) -> &Archetype {
3901        self.entity.archetype()
3902    }
3903
3904    /// Returns a reference to the underlying [`Access`].
3905    #[inline]
3906    pub fn access(&self) -> &Access {
3907        self.access
3908    }
3909
3910    /// Returns `true` if the current entity has a component of type `T`.
3911    /// Otherwise, this returns `false`.
3912    ///
3913    /// ## Notes
3914    ///
3915    /// If you do not know the concrete type of a component, consider using
3916    /// [`Self::contains_id`] or [`Self::contains_type_id`].
3917    #[inline]
3918    pub fn contains<T: Component>(&self) -> bool {
3919        self.contains_type_id(TypeId::of::<T>())
3920    }
3921
3922    /// Returns `true` if the current entity has a component identified by `component_id`.
3923    /// Otherwise, this returns false.
3924    ///
3925    /// ## Notes
3926    ///
3927    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
3928    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
3929    ///   [`Self::contains_type_id`].
3930    #[inline]
3931    pub fn contains_id(&self, component_id: ComponentId) -> bool {
3932        self.entity.contains_id(component_id)
3933    }
3934
3935    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
3936    /// Otherwise, this returns false.
3937    ///
3938    /// ## Notes
3939    ///
3940    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
3941    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
3942    #[inline]
3943    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
3944        self.entity.contains_type_id(type_id)
3945    }
3946
3947    /// Gets access to the component of type `T` for the current entity.
3948    /// Returns `None` if the entity does not have a component of type `T`.
3949    #[inline]
3950    pub fn get<T: Component>(&self) -> Option<&'_ T> {
3951        self.as_readonly().get()
3952    }
3953
3954    /// Gets access to the component of type `T` for the current entity,
3955    /// including change detection information as a [`Ref`].
3956    ///
3957    /// Returns `None` if the entity does not have a component of type `T`.
3958    #[inline]
3959    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
3960        self.as_readonly().get_ref()
3961    }
3962
3963    /// Gets mutable access to the component of type `T` for the current entity.
3964    /// Returns `None` if the entity does not have a component of type `T`.
3965    #[inline]
3966    pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
3967        let id = self
3968            .entity
3969            .world()
3970            .components()
3971            .get_valid_id(TypeId::of::<T>())?;
3972        self.access
3973            .has_component_write(id)
3974            // SAFETY: We have write access
3975            .then(|| unsafe { self.entity.get_mut() })
3976            .flatten()
3977    }
3978
3979    /// Consumes self and gets mutable access to the component of type `T`
3980    /// with the world `'w` lifetime for the current entity.
3981    /// Returns `None` if the entity does not have a component of type `T`.
3982    #[inline]
3983    pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
3984        // SAFETY:
3985        // - We have write access
3986        // - The bound `T: Component<Mutability = Mutable>` ensures the component is mutable
3987        unsafe { self.into_mut_assume_mutable() }
3988    }
3989
3990    /// Consumes self and gets mutable access to the component of type `T`
3991    /// with the world `'w` lifetime for the current entity.
3992    /// Returns `None` if the entity does not have a component of type `T`.
3993    ///
3994    /// # Safety
3995    ///
3996    /// - `T` must be a mutable component
3997    #[inline]
3998    pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
3999        let id = self
4000            .entity
4001            .world()
4002            .components()
4003            .get_valid_id(TypeId::of::<T>())?;
4004        self.access
4005            .has_component_write(id)
4006            // SAFETY:
4007            // - We have write access
4008            // - Caller ensures `T` is a mutable component
4009            .then(|| unsafe { self.entity.get_mut_assume_mutable() })
4010            .flatten()
4011    }
4012
4013    /// Retrieves the change ticks for the given component. This can be useful for implementing change
4014    /// detection in custom runtimes.
4015    #[inline]
4016    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
4017        self.as_readonly().get_change_ticks::<T>()
4018    }
4019
4020    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
4021    /// detection in custom runtimes.
4022    ///
4023    /// **You should prefer to use the typed API [`Self::get_change_ticks`] where possible and only
4024    /// use this in cases where the actual component types are not known at
4025    /// compile time.**
4026    #[inline]
4027    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
4028        self.as_readonly().get_change_ticks_by_id(component_id)
4029    }
4030
4031    /// Gets the component of the given [`ComponentId`] from the entity.
4032    ///
4033    /// **You should prefer to use the typed API [`Self::get`] where possible and only
4034    /// use this in cases where the actual component types are not known at
4035    /// compile time.**
4036    ///
4037    /// Unlike [`FilteredEntityMut::get`], this returns a raw pointer to the component,
4038    /// which is only valid while the [`FilteredEntityMut`] is alive.
4039    #[inline]
4040    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>> {
4041        self.as_readonly().get_by_id(component_id)
4042    }
4043
4044    /// Gets a [`MutUntyped`] of the component of the given [`ComponentId`] from the entity.
4045    ///
4046    /// **You should prefer to use the typed API [`Self::get_mut`] where possible and only
4047    /// use this in cases where the actual component types are not known at
4048    /// compile time.**
4049    ///
4050    /// Unlike [`FilteredEntityMut::get_mut`], this returns a raw pointer to the component,
4051    /// which is only valid while the [`FilteredEntityMut`] is alive.
4052    #[inline]
4053    pub fn get_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
4054        self.access
4055            .has_component_write(component_id)
4056            // SAFETY: We have write access
4057            .then(|| unsafe { self.entity.get_mut_by_id(component_id).ok() })
4058            .flatten()
4059    }
4060
4061    /// Returns the source code location from which this entity has last been spawned.
4062    pub fn spawned_by(&self) -> MaybeLocation {
4063        self.entity.spawned_by()
4064    }
4065
4066    /// Returns the [`Tick`] at which this entity has been spawned.
4067    pub fn spawn_tick(&self) -> Tick {
4068        self.entity.spawn_tick()
4069    }
4070}
4071
4072impl<'a> From<EntityMut<'a>> for FilteredEntityMut<'a, 'static> {
4073    fn from(entity: EntityMut<'a>) -> Self {
4074        // SAFETY:
4075        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityMut`.
4076        unsafe { FilteredEntityMut::new(entity.cell, const { &Access::new_write_all() }) }
4077    }
4078}
4079
4080impl<'a> From<&'a mut EntityMut<'_>> for FilteredEntityMut<'a, 'static> {
4081    fn from(entity: &'a mut EntityMut<'_>) -> Self {
4082        // SAFETY:
4083        // - `EntityMut` guarantees exclusive access to all components in the new `FilteredEntityMut`.
4084        unsafe { FilteredEntityMut::new(entity.cell, const { &Access::new_write_all() }) }
4085    }
4086}
4087
4088impl<'a> From<EntityWorldMut<'a>> for FilteredEntityMut<'a, 'static> {
4089    fn from(entity: EntityWorldMut<'a>) -> Self {
4090        // SAFETY:
4091        // - `EntityWorldMut` guarantees exclusive access to the entire world.
4092        unsafe {
4093            FilteredEntityMut::new(
4094                entity.into_unsafe_entity_cell(),
4095                const { &Access::new_write_all() },
4096            )
4097        }
4098    }
4099}
4100
4101impl<'a> From<&'a mut EntityWorldMut<'_>> for FilteredEntityMut<'a, 'static> {
4102    fn from(entity: &'a mut EntityWorldMut<'_>) -> Self {
4103        // SAFETY:
4104        // - `EntityWorldMut` guarantees exclusive access to the entire world.
4105        unsafe {
4106            FilteredEntityMut::new(
4107                entity.as_unsafe_entity_cell(),
4108                const { &Access::new_write_all() },
4109            )
4110        }
4111    }
4112}
4113
4114impl<'w, 's, B: Bundle> From<&'w EntityMutExcept<'_, 's, B>> for FilteredEntityMut<'w, 's> {
4115    fn from(value: &'w EntityMutExcept<'_, 's, B>) -> Self {
4116        // SAFETY:
4117        // - The FilteredEntityMut has the same component access as the given EntityMutExcept.
4118        unsafe { FilteredEntityMut::new(value.entity, value.access) }
4119    }
4120}
4121
4122impl PartialEq for FilteredEntityMut<'_, '_> {
4123    fn eq(&self, other: &Self) -> bool {
4124        self.entity() == other.entity()
4125    }
4126}
4127
4128impl Eq for FilteredEntityMut<'_, '_> {}
4129
4130impl PartialOrd for FilteredEntityMut<'_, '_> {
4131    /// [`FilteredEntityMut`]'s comparison trait implementations match the underlying [`Entity`],
4132    /// and cannot discern between different worlds.
4133    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4134        Some(self.cmp(other))
4135    }
4136}
4137
4138impl Ord for FilteredEntityMut<'_, '_> {
4139    fn cmp(&self, other: &Self) -> Ordering {
4140        self.entity().cmp(&other.entity())
4141    }
4142}
4143
4144impl Hash for FilteredEntityMut<'_, '_> {
4145    fn hash<H: Hasher>(&self, state: &mut H) {
4146        self.entity().hash(state);
4147    }
4148}
4149
4150impl ContainsEntity for FilteredEntityMut<'_, '_> {
4151    fn entity(&self) -> Entity {
4152        self.id()
4153    }
4154}
4155
4156// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
4157unsafe impl EntityEquivalent for FilteredEntityMut<'_, '_> {}
4158
4159/// Error type returned by [`TryFrom`] conversions from filtered entity types
4160/// ([`FilteredEntityRef`]/[`FilteredEntityMut`]) to full-access entity types
4161/// ([`EntityRef`]/[`EntityMut`]).
4162#[derive(Error, Debug)]
4163pub enum TryFromFilteredError {
4164    /// Error indicating that the filtered entity does not have read access to
4165    /// all components.
4166    #[error("Conversion failed, filtered entity ref does not have read access to all components")]
4167    MissingReadAllAccess,
4168    /// Error indicating that the filtered entity does not have write access to
4169    /// all components.
4170    #[error("Conversion failed, filtered entity ref does not have write access to all components")]
4171    MissingWriteAllAccess,
4172}
4173
4174/// Provides read-only access to a single entity and all its components, save
4175/// for an explicitly-enumerated set.
4176pub struct EntityRefExcept<'w, 's, B>
4177where
4178    B: Bundle,
4179{
4180    entity: UnsafeEntityCell<'w>,
4181    access: &'s Access,
4182    phantom: PhantomData<B>,
4183}
4184
4185impl<'w, 's, B> EntityRefExcept<'w, 's, B>
4186where
4187    B: Bundle,
4188{
4189    /// # Safety
4190    /// Other users of `UnsafeEntityCell` must only have mutable access to the components in `B`.
4191    pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: &'s Access) -> Self {
4192        Self {
4193            entity,
4194            access,
4195            phantom: PhantomData,
4196        }
4197    }
4198
4199    /// Returns the [ID](Entity) of the current entity.
4200    #[inline]
4201    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
4202    pub fn id(&self) -> Entity {
4203        self.entity.id()
4204    }
4205
4206    /// Gets access to the component of type `C` for the current entity. Returns
4207    /// `None` if the component doesn't have a component of that type or if the
4208    /// type is one of the excluded components.
4209    #[inline]
4210    pub fn get<C>(&self) -> Option<&'w C>
4211    where
4212        C: Component,
4213    {
4214        let components = self.entity.world().components();
4215        let id = components.valid_component_id::<C>()?;
4216        if bundle_contains_component::<B>(components, id) {
4217            None
4218        } else {
4219            // SAFETY: We have read access for all components that weren't
4220            // covered by the `contains` check above.
4221            unsafe { self.entity.get() }
4222        }
4223    }
4224
4225    /// Gets access to the component of type `C` for the current entity,
4226    /// including change detection information. Returns `None` if the component
4227    /// doesn't have a component of that type or if the type is one of the
4228    /// excluded components.
4229    #[inline]
4230    pub fn get_ref<C>(&self) -> Option<Ref<'w, C>>
4231    where
4232        C: Component,
4233    {
4234        let components = self.entity.world().components();
4235        let id = components.valid_component_id::<C>()?;
4236        if bundle_contains_component::<B>(components, id) {
4237            None
4238        } else {
4239            // SAFETY: We have read access for all components that weren't
4240            // covered by the `contains` check above.
4241            unsafe { self.entity.get_ref() }
4242        }
4243    }
4244
4245    /// Returns the source code location from which this entity has been spawned.
4246    pub fn spawned_by(&self) -> MaybeLocation {
4247        self.entity.spawned_by()
4248    }
4249
4250    /// Returns the [`Tick`] at which this entity has been spawned.
4251    pub fn spawn_tick(&self) -> Tick {
4252        self.entity.spawn_tick()
4253    }
4254
4255    /// Gets the component of the given [`ComponentId`] from the entity.
4256    ///
4257    /// **You should prefer to use the typed API [`Self::get`] where possible and only
4258    /// use this in cases where the actual component types are not known at
4259    /// compile time.**
4260    ///
4261    /// Unlike [`EntityRefExcept::get`], this returns a raw pointer to the component,
4262    /// which is only valid while the [`EntityRefExcept`] is alive.
4263    #[inline]
4264    pub fn get_by_id(&self, component_id: ComponentId) -> Option<Ptr<'w>> {
4265        let components = self.entity.world().components();
4266        (!bundle_contains_component::<B>(components, component_id))
4267            .then(|| {
4268                // SAFETY: We have read access for this component
4269                unsafe { self.entity.get_by_id(component_id) }
4270            })
4271            .flatten()
4272    }
4273
4274    /// Returns `true` if the current entity has a component of type `T`.
4275    /// Otherwise, this returns `false`.
4276    ///
4277    /// ## Notes
4278    ///
4279    /// If you do not know the concrete type of a component, consider using
4280    /// [`Self::contains_id`] or [`Self::contains_type_id`].
4281    #[inline]
4282    pub fn contains<T: Component>(&self) -> bool {
4283        self.contains_type_id(TypeId::of::<T>())
4284    }
4285
4286    /// Returns `true` if the current entity has a component identified by `component_id`.
4287    /// Otherwise, this returns false.
4288    ///
4289    /// ## Notes
4290    ///
4291    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
4292    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
4293    ///   [`Self::contains_type_id`].
4294    #[inline]
4295    pub fn contains_id(&self, component_id: ComponentId) -> bool {
4296        self.entity.contains_id(component_id)
4297    }
4298
4299    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
4300    /// Otherwise, this returns false.
4301    ///
4302    /// ## Notes
4303    ///
4304    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
4305    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
4306    #[inline]
4307    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
4308        self.entity.contains_type_id(type_id)
4309    }
4310
4311    /// Retrieves the change ticks for the given component. This can be useful for implementing change
4312    /// detection in custom runtimes.
4313    #[inline]
4314    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
4315        let component_id = self
4316            .entity
4317            .world()
4318            .components()
4319            .get_valid_id(TypeId::of::<T>())?;
4320        let components = self.entity.world().components();
4321        (!bundle_contains_component::<B>(components, component_id))
4322            .then(|| {
4323                // SAFETY: We have read access
4324                unsafe { self.entity.get_change_ticks::<T>() }
4325            })
4326            .flatten()
4327    }
4328
4329    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
4330    /// detection in custom runtimes.
4331    ///
4332    /// **You should prefer to use the typed API [`Self::get_change_ticks`] where possible and only
4333    /// use this in cases where the actual component types are not known at
4334    /// compile time.**
4335    #[inline]
4336    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
4337        let components = self.entity.world().components();
4338        (!bundle_contains_component::<B>(components, component_id))
4339            .then(|| {
4340                // SAFETY: We have read access
4341                unsafe { self.entity.get_change_ticks_by_id(component_id) }
4342            })
4343            .flatten()
4344    }
4345}
4346
4347impl<'w, 's, B> From<&'w EntityMutExcept<'_, 's, B>> for EntityRefExcept<'w, 's, B>
4348where
4349    B: Bundle,
4350{
4351    fn from(entity: &'w EntityMutExcept<'_, 's, B>) -> Self {
4352        // SAFETY: All accesses that `EntityRefExcept` provides are also
4353        // accesses that `EntityMutExcept` provides.
4354        unsafe { EntityRefExcept::new(entity.entity, entity.access) }
4355    }
4356}
4357
4358impl<B: Bundle> Clone for EntityRefExcept<'_, '_, B> {
4359    fn clone(&self) -> Self {
4360        *self
4361    }
4362}
4363
4364impl<B: Bundle> Copy for EntityRefExcept<'_, '_, B> {}
4365
4366impl<B: Bundle> PartialEq for EntityRefExcept<'_, '_, B> {
4367    fn eq(&self, other: &Self) -> bool {
4368        self.entity() == other.entity()
4369    }
4370}
4371
4372impl<B: Bundle> Eq for EntityRefExcept<'_, '_, B> {}
4373
4374impl<B: Bundle> PartialOrd for EntityRefExcept<'_, '_, B> {
4375    /// [`EntityRefExcept`]'s comparison trait implementations match the underlying [`Entity`],
4376    /// and cannot discern between different worlds.
4377    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4378        Some(self.cmp(other))
4379    }
4380}
4381
4382impl<B: Bundle> Ord for EntityRefExcept<'_, '_, B> {
4383    fn cmp(&self, other: &Self) -> Ordering {
4384        self.entity().cmp(&other.entity())
4385    }
4386}
4387
4388impl<B: Bundle> Hash for EntityRefExcept<'_, '_, B> {
4389    fn hash<H: Hasher>(&self, state: &mut H) {
4390        self.entity().hash(state);
4391    }
4392}
4393
4394impl<B: Bundle> ContainsEntity for EntityRefExcept<'_, '_, B> {
4395    fn entity(&self) -> Entity {
4396        self.id()
4397    }
4398}
4399
4400// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
4401unsafe impl<B: Bundle> EntityEquivalent for EntityRefExcept<'_, '_, B> {}
4402
4403/// Provides mutable access to all components of an entity, with the exception
4404/// of an explicit set.
4405///
4406/// This is a rather niche type that should only be used if you need access to
4407/// *all* components of an entity, while still allowing you to consult other
4408/// queries that might match entities that this query also matches. If you don't
4409/// need access to all components, prefer a standard query with a
4410/// [`Without`](`crate::query::Without`) filter.
4411pub struct EntityMutExcept<'w, 's, B>
4412where
4413    B: Bundle,
4414{
4415    entity: UnsafeEntityCell<'w>,
4416    access: &'s Access,
4417    phantom: PhantomData<B>,
4418}
4419
4420impl<'w, 's, B> EntityMutExcept<'w, 's, B>
4421where
4422    B: Bundle,
4423{
4424    /// # Safety
4425    /// Other users of `UnsafeEntityCell` must not have access to any components not in `B`.
4426    pub(crate) unsafe fn new(entity: UnsafeEntityCell<'w>, access: &'s Access) -> Self {
4427        Self {
4428            entity,
4429            access,
4430            phantom: PhantomData,
4431        }
4432    }
4433
4434    /// Returns the [ID](Entity) of the current entity.
4435    #[inline]
4436    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
4437    pub fn id(&self) -> Entity {
4438        self.entity.id()
4439    }
4440
4441    /// Returns a new instance with a shorter lifetime.
4442    ///
4443    /// This is useful if you have `&mut EntityMutExcept`, but you need
4444    /// `EntityMutExcept`.
4445    pub fn reborrow(&mut self) -> EntityMutExcept<'_, 's, B> {
4446        // SAFETY: We have exclusive access to the entire entity and the
4447        // applicable components.
4448        unsafe { Self::new(self.entity, self.access) }
4449    }
4450
4451    /// Gets read-only access to all of the entity's components, except for the
4452    /// ones in `CL`.
4453    #[inline]
4454    pub fn as_readonly(&self) -> EntityRefExcept<'_, 's, B> {
4455        EntityRefExcept::from(self)
4456    }
4457
4458    /// Gets access to the component of type `C` for the current entity. Returns
4459    /// `None` if the component doesn't have a component of that type or if the
4460    /// type is one of the excluded components.
4461    #[inline]
4462    pub fn get<C>(&self) -> Option<&'_ C>
4463    where
4464        C: Component,
4465    {
4466        self.as_readonly().get()
4467    }
4468
4469    /// Gets access to the component of type `C` for the current entity,
4470    /// including change detection information. Returns `None` if the component
4471    /// doesn't have a component of that type or if the type is one of the
4472    /// excluded components.
4473    #[inline]
4474    pub fn get_ref<C>(&self) -> Option<Ref<'_, C>>
4475    where
4476        C: Component,
4477    {
4478        self.as_readonly().get_ref()
4479    }
4480
4481    /// Gets mutable access to the component of type `C` for the current entity.
4482    /// Returns `None` if the component doesn't have a component of that type or
4483    /// if the type is one of the excluded components.
4484    #[inline]
4485    pub fn get_mut<C>(&mut self) -> Option<Mut<'_, C>>
4486    where
4487        C: Component<Mutability = Mutable>,
4488    {
4489        let components = self.entity.world().components();
4490        let id = components.valid_component_id::<C>()?;
4491        if bundle_contains_component::<B>(components, id) {
4492            None
4493        } else {
4494            // SAFETY: We have write access for all components that weren't
4495            // covered by the `contains` check above.
4496            unsafe { self.entity.get_mut() }
4497        }
4498    }
4499
4500    /// Returns the source code location from which this entity has been spawned.
4501    pub fn spawned_by(&self) -> MaybeLocation {
4502        self.entity.spawned_by()
4503    }
4504
4505    /// Returns the [`Tick`] at which this entity has been spawned.
4506    pub fn spawn_tick(&self) -> Tick {
4507        self.entity.spawn_tick()
4508    }
4509
4510    /// Returns `true` if the current entity has a component of type `T`.
4511    /// Otherwise, this returns `false`.
4512    ///
4513    /// ## Notes
4514    ///
4515    /// If you do not know the concrete type of a component, consider using
4516    /// [`Self::contains_id`] or [`Self::contains_type_id`].
4517    #[inline]
4518    pub fn contains<T: Component>(&self) -> bool {
4519        self.contains_type_id(TypeId::of::<T>())
4520    }
4521
4522    /// Returns `true` if the current entity has a component identified by `component_id`.
4523    /// Otherwise, this returns false.
4524    ///
4525    /// ## Notes
4526    ///
4527    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
4528    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
4529    ///   [`Self::contains_type_id`].
4530    #[inline]
4531    pub fn contains_id(&self, component_id: ComponentId) -> bool {
4532        self.entity.contains_id(component_id)
4533    }
4534
4535    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
4536    /// Otherwise, this returns false.
4537    ///
4538    /// ## Notes
4539    ///
4540    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
4541    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
4542    #[inline]
4543    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
4544        self.entity.contains_type_id(type_id)
4545    }
4546
4547    /// Gets the component of the given [`ComponentId`] from the entity.
4548    ///
4549    /// **You should prefer to use the typed API [`Self::get`] where possible and only
4550    /// use this in cases where the actual component types are not known at
4551    /// compile time.**
4552    ///
4553    /// Unlike [`EntityMutExcept::get`], this returns a raw pointer to the component,
4554    /// which is only valid while the [`EntityMutExcept`] is alive.
4555    #[inline]
4556    pub fn get_by_id(&'w self, component_id: ComponentId) -> Option<Ptr<'w>> {
4557        self.as_readonly().get_by_id(component_id)
4558    }
4559
4560    /// Gets a [`MutUntyped`] of the component of the given [`ComponentId`] from the entity.
4561    ///
4562    /// **You should prefer to use the typed API [`Self::get_mut`] where possible and only
4563    /// use this in cases where the actual component types are not known at
4564    /// compile time.**
4565    ///
4566    /// Unlike [`EntityMutExcept::get_mut`], this returns a raw pointer to the component,
4567    /// which is only valid while the [`EntityMutExcept`] is alive.
4568    #[inline]
4569    pub fn get_mut_by_id<F: DynamicComponentFetch>(
4570        &mut self,
4571        component_id: ComponentId,
4572    ) -> Option<MutUntyped<'_>> {
4573        let components = self.entity.world().components();
4574        (!bundle_contains_component::<B>(components, component_id))
4575            .then(|| {
4576                // SAFETY: We have write access
4577                unsafe { self.entity.get_mut_by_id(component_id).ok() }
4578            })
4579            .flatten()
4580    }
4581}
4582
4583impl<B: Bundle> PartialEq for EntityMutExcept<'_, '_, B> {
4584    fn eq(&self, other: &Self) -> bool {
4585        self.entity() == other.entity()
4586    }
4587}
4588
4589impl<B: Bundle> Eq for EntityMutExcept<'_, '_, B> {}
4590
4591impl<B: Bundle> PartialOrd for EntityMutExcept<'_, '_, B> {
4592    /// [`EntityMutExcept`]'s comparison trait implementations match the underlying [`Entity`],
4593    /// and cannot discern between different worlds.
4594    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4595        Some(self.cmp(other))
4596    }
4597}
4598
4599impl<B: Bundle> Ord for EntityMutExcept<'_, '_, B> {
4600    fn cmp(&self, other: &Self) -> Ordering {
4601        self.entity().cmp(&other.entity())
4602    }
4603}
4604
4605impl<B: Bundle> Hash for EntityMutExcept<'_, '_, B> {
4606    fn hash<H: Hasher>(&self, state: &mut H) {
4607        self.entity().hash(state);
4608    }
4609}
4610
4611impl<B: Bundle> ContainsEntity for EntityMutExcept<'_, '_, B> {
4612    fn entity(&self) -> Entity {
4613        self.id()
4614    }
4615}
4616
4617// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
4618unsafe impl<B: Bundle> EntityEquivalent for EntityMutExcept<'_, '_, B> {}
4619
4620fn bundle_contains_component<B>(components: &Components, query_id: ComponentId) -> bool
4621where
4622    B: Bundle,
4623{
4624    let mut found = false;
4625    B::get_component_ids(components, &mut |maybe_id| {
4626        if let Some(id) = maybe_id {
4627            found = found || id == query_id;
4628        }
4629    });
4630    found
4631}
4632
4633/// Inserts a dynamic [`Bundle`] into the entity.
4634///
4635/// # Safety
4636///
4637/// - [`OwningPtr`] and [`StorageType`] iterators must correspond to the
4638///   [`BundleInfo`](crate::bundle::BundleInfo) used to construct [`BundleInserter`]
4639/// - [`Entity`] must correspond to [`EntityLocation`]
4640unsafe fn insert_dynamic_bundle<
4641    'a,
4642    I: Iterator<Item = OwningPtr<'a>>,
4643    S: Iterator<Item = StorageType>,
4644>(
4645    mut bundle_inserter: BundleInserter<'_>,
4646    entity: Entity,
4647    location: EntityLocation,
4648    components: I,
4649    storage_types: S,
4650    mode: InsertMode,
4651    caller: MaybeLocation,
4652    relationship_hook_insert_mode: RelationshipHookMode,
4653) -> EntityLocation {
4654    struct DynamicInsertBundle<'a, I: Iterator<Item = (StorageType, OwningPtr<'a>)>> {
4655        components: I,
4656    }
4657
4658    impl<'a, I: Iterator<Item = (StorageType, OwningPtr<'a>)>> DynamicBundle
4659        for DynamicInsertBundle<'a, I>
4660    {
4661        type Effect = ();
4662        unsafe fn get_components(
4663            mut ptr: MovingPtr<'_, Self>,
4664            func: &mut impl FnMut(StorageType, OwningPtr<'_>),
4665        ) {
4666            (&mut ptr.components).for_each(|(t, ptr)| func(t, ptr));
4667        }
4668
4669        unsafe fn apply_effect(
4670            _ptr: MovingPtr<'_, MaybeUninit<Self>>,
4671            _entity: &mut EntityWorldMut,
4672        ) {
4673        }
4674    }
4675
4676    let bundle = DynamicInsertBundle {
4677        components: storage_types.zip(components),
4678    };
4679
4680    move_as_ptr!(bundle);
4681
4682    // SAFETY:
4683    // - `location` matches `entity`.  and thus must currently exist in the source
4684    //   archetype for this inserter and its location within the archetype.
4685    // - The caller must ensure that the iterators and storage types match up with the `BundleInserter`
4686    // - `apply_effect` is never called on this bundle.
4687    // - `bundle` is not used or dropped after this point.
4688    unsafe {
4689        bundle_inserter.insert(
4690            entity,
4691            location,
4692            bundle,
4693            mode,
4694            caller,
4695            relationship_hook_insert_mode,
4696        )
4697    }
4698}
4699
4700/// Types that can be used to fetch components from an entity dynamically by
4701/// [`ComponentId`]s.
4702///
4703/// Provided implementations are:
4704/// - [`ComponentId`]: Returns a single untyped reference.
4705/// - `[ComponentId; N]` and `&[ComponentId; N]`: Returns a same-sized array of untyped references.
4706/// - `&[ComponentId]`: Returns a [`Vec`] of untyped references.
4707/// - [`&HashSet<ComponentId>`](HashSet): Returns a [`HashMap`] of IDs to untyped references.
4708///
4709/// # Performance
4710///
4711/// - The slice and array implementations perform an aliased mutability check in
4712///   [`DynamicComponentFetch::fetch_mut`] that is `O(N^2)`.
4713/// - The [`HashSet`] implementation performs no such check as the type itself
4714///   guarantees unique IDs.
4715/// - The single [`ComponentId`] implementation performs no such check as only
4716///   one reference is returned.
4717///
4718/// # Safety
4719///
4720/// Implementor must ensure that:
4721/// - No aliased mutability is caused by the returned references.
4722/// - [`DynamicComponentFetch::fetch_ref`] returns only read-only references.
4723pub unsafe trait DynamicComponentFetch {
4724    /// The read-only reference type returned by [`DynamicComponentFetch::fetch_ref`].
4725    type Ref<'w>;
4726
4727    /// The mutable reference type returned by [`DynamicComponentFetch::fetch_mut`].
4728    type Mut<'w>;
4729
4730    /// Returns untyped read-only reference(s) to the component(s) with the
4731    /// given [`ComponentId`]s, as determined by `self`.
4732    ///
4733    /// # Safety
4734    ///
4735    /// It is the caller's responsibility to ensure that:
4736    /// - The given [`UnsafeEntityCell`] has read-only access to the fetched components.
4737    /// - No other mutable references to the fetched components exist at the same time.
4738    ///
4739    /// # Errors
4740    ///
4741    /// - Returns [`EntityComponentError::MissingComponent`] if a component is missing from the entity.
4742    unsafe fn fetch_ref(
4743        self,
4744        cell: UnsafeEntityCell<'_>,
4745    ) -> Result<Self::Ref<'_>, EntityComponentError>;
4746
4747    /// Returns untyped mutable reference(s) to the component(s) with the
4748    /// given [`ComponentId`]s, as determined by `self`.
4749    ///
4750    /// # Safety
4751    ///
4752    /// It is the caller's responsibility to ensure that:
4753    /// - The given [`UnsafeEntityCell`] has mutable access to the fetched components.
4754    /// - No other references to the fetched components exist at the same time.
4755    ///
4756    /// # Errors
4757    ///
4758    /// - Returns [`EntityComponentError::MissingComponent`] if a component is missing from the entity.
4759    /// - Returns [`EntityComponentError::AliasedMutability`] if a component is requested multiple times.
4760    unsafe fn fetch_mut(
4761        self,
4762        cell: UnsafeEntityCell<'_>,
4763    ) -> Result<Self::Mut<'_>, EntityComponentError>;
4764
4765    /// Returns untyped mutable reference(s) to the component(s) with the
4766    /// given [`ComponentId`]s, as determined by `self`.
4767    /// Assumes all [`ComponentId`]s refer to mutable components.
4768    ///
4769    /// # Safety
4770    ///
4771    /// It is the caller's responsibility to ensure that:
4772    /// - The given [`UnsafeEntityCell`] has mutable access to the fetched components.
4773    /// - No other references to the fetched components exist at the same time.
4774    /// - The requested components are all mutable.
4775    ///
4776    /// # Errors
4777    ///
4778    /// - Returns [`EntityComponentError::MissingComponent`] if a component is missing from the entity.
4779    /// - Returns [`EntityComponentError::AliasedMutability`] if a component is requested multiple times.
4780    unsafe fn fetch_mut_assume_mutable(
4781        self,
4782        cell: UnsafeEntityCell<'_>,
4783    ) -> Result<Self::Mut<'_>, EntityComponentError>;
4784}
4785
4786// SAFETY:
4787// - No aliased mutability is caused because a single reference is returned.
4788// - No mutable references are returned by `fetch_ref`.
4789unsafe impl DynamicComponentFetch for ComponentId {
4790    type Ref<'w> = Ptr<'w>;
4791    type Mut<'w> = MutUntyped<'w>;
4792
4793    unsafe fn fetch_ref(
4794        self,
4795        cell: UnsafeEntityCell<'_>,
4796    ) -> Result<Self::Ref<'_>, EntityComponentError> {
4797        // SAFETY: caller ensures that the cell has read access to the component.
4798        unsafe { cell.get_by_id(self) }.ok_or(EntityComponentError::MissingComponent(self))
4799    }
4800
4801    unsafe fn fetch_mut(
4802        self,
4803        cell: UnsafeEntityCell<'_>,
4804    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4805        // SAFETY: caller ensures that the cell has mutable access to the component.
4806        unsafe { cell.get_mut_by_id(self) }
4807            .map_err(|_| EntityComponentError::MissingComponent(self))
4808    }
4809
4810    unsafe fn fetch_mut_assume_mutable(
4811        self,
4812        cell: UnsafeEntityCell<'_>,
4813    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4814        // SAFETY: caller ensures that the cell has mutable access to the component.
4815        unsafe { cell.get_mut_assume_mutable_by_id(self) }
4816            .map_err(|_| EntityComponentError::MissingComponent(self))
4817    }
4818}
4819
4820// SAFETY:
4821// - No aliased mutability is caused because the array is checked for duplicates.
4822// - No mutable references are returned by `fetch_ref`.
4823unsafe impl<const N: usize> DynamicComponentFetch for [ComponentId; N] {
4824    type Ref<'w> = [Ptr<'w>; N];
4825    type Mut<'w> = [MutUntyped<'w>; N];
4826
4827    unsafe fn fetch_ref(
4828        self,
4829        cell: UnsafeEntityCell<'_>,
4830    ) -> Result<Self::Ref<'_>, EntityComponentError> {
4831        <&Self>::fetch_ref(&self, cell)
4832    }
4833
4834    unsafe fn fetch_mut(
4835        self,
4836        cell: UnsafeEntityCell<'_>,
4837    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4838        <&Self>::fetch_mut(&self, cell)
4839    }
4840
4841    unsafe fn fetch_mut_assume_mutable(
4842        self,
4843        cell: UnsafeEntityCell<'_>,
4844    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4845        <&Self>::fetch_mut_assume_mutable(&self, cell)
4846    }
4847}
4848
4849// SAFETY:
4850// - No aliased mutability is caused because the array is checked for duplicates.
4851// - No mutable references are returned by `fetch_ref`.
4852unsafe impl<const N: usize> DynamicComponentFetch for &'_ [ComponentId; N] {
4853    type Ref<'w> = [Ptr<'w>; N];
4854    type Mut<'w> = [MutUntyped<'w>; N];
4855
4856    unsafe fn fetch_ref(
4857        self,
4858        cell: UnsafeEntityCell<'_>,
4859    ) -> Result<Self::Ref<'_>, EntityComponentError> {
4860        let mut ptrs = [const { MaybeUninit::uninit() }; N];
4861        for (ptr, &id) in core::iter::zip(&mut ptrs, self) {
4862            *ptr = MaybeUninit::new(
4863                // SAFETY: caller ensures that the cell has read access to the component.
4864                unsafe { cell.get_by_id(id) }.ok_or(EntityComponentError::MissingComponent(id))?,
4865            );
4866        }
4867
4868        // SAFETY: Each ptr was initialized in the loop above.
4869        let ptrs = ptrs.map(|ptr| unsafe { MaybeUninit::assume_init(ptr) });
4870
4871        Ok(ptrs)
4872    }
4873
4874    unsafe fn fetch_mut(
4875        self,
4876        cell: UnsafeEntityCell<'_>,
4877    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4878        // Check for duplicate component IDs.
4879        for i in 0..self.len() {
4880            for j in 0..i {
4881                if self[i] == self[j] {
4882                    return Err(EntityComponentError::AliasedMutability(self[i]));
4883                }
4884            }
4885        }
4886
4887        let mut ptrs = [const { MaybeUninit::uninit() }; N];
4888        for (ptr, &id) in core::iter::zip(&mut ptrs, self) {
4889            *ptr = MaybeUninit::new(
4890                // SAFETY: caller ensures that the cell has mutable access to the component.
4891                unsafe { cell.get_mut_by_id(id) }
4892                    .map_err(|_| EntityComponentError::MissingComponent(id))?,
4893            );
4894        }
4895
4896        // SAFETY: Each ptr was initialized in the loop above.
4897        let ptrs = ptrs.map(|ptr| unsafe { MaybeUninit::assume_init(ptr) });
4898
4899        Ok(ptrs)
4900    }
4901
4902    unsafe fn fetch_mut_assume_mutable(
4903        self,
4904        cell: UnsafeEntityCell<'_>,
4905    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4906        // Check for duplicate component IDs.
4907        for i in 0..self.len() {
4908            for j in 0..i {
4909                if self[i] == self[j] {
4910                    return Err(EntityComponentError::AliasedMutability(self[i]));
4911                }
4912            }
4913        }
4914
4915        let mut ptrs = [const { MaybeUninit::uninit() }; N];
4916        for (ptr, &id) in core::iter::zip(&mut ptrs, self) {
4917            *ptr = MaybeUninit::new(
4918                // SAFETY: caller ensures that the cell has mutable access to the component.
4919                unsafe { cell.get_mut_assume_mutable_by_id(id) }
4920                    .map_err(|_| EntityComponentError::MissingComponent(id))?,
4921            );
4922        }
4923
4924        // SAFETY: Each ptr was initialized in the loop above.
4925        let ptrs = ptrs.map(|ptr| unsafe { MaybeUninit::assume_init(ptr) });
4926
4927        Ok(ptrs)
4928    }
4929}
4930
4931// SAFETY:
4932// - No aliased mutability is caused because the slice is checked for duplicates.
4933// - No mutable references are returned by `fetch_ref`.
4934unsafe impl DynamicComponentFetch for &'_ [ComponentId] {
4935    type Ref<'w> = Vec<Ptr<'w>>;
4936    type Mut<'w> = Vec<MutUntyped<'w>>;
4937
4938    unsafe fn fetch_ref(
4939        self,
4940        cell: UnsafeEntityCell<'_>,
4941    ) -> Result<Self::Ref<'_>, EntityComponentError> {
4942        let mut ptrs = Vec::with_capacity(self.len());
4943        for &id in self {
4944            ptrs.push(
4945                // SAFETY: caller ensures that the cell has read access to the component.
4946                unsafe { cell.get_by_id(id) }.ok_or(EntityComponentError::MissingComponent(id))?,
4947            );
4948        }
4949        Ok(ptrs)
4950    }
4951
4952    unsafe fn fetch_mut(
4953        self,
4954        cell: UnsafeEntityCell<'_>,
4955    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4956        // Check for duplicate component IDs.
4957        for i in 0..self.len() {
4958            for j in 0..i {
4959                if self[i] == self[j] {
4960                    return Err(EntityComponentError::AliasedMutability(self[i]));
4961                }
4962            }
4963        }
4964
4965        let mut ptrs = Vec::with_capacity(self.len());
4966        for &id in self {
4967            ptrs.push(
4968                // SAFETY: caller ensures that the cell has mutable access to the component.
4969                unsafe { cell.get_mut_by_id(id) }
4970                    .map_err(|_| EntityComponentError::MissingComponent(id))?,
4971            );
4972        }
4973        Ok(ptrs)
4974    }
4975
4976    unsafe fn fetch_mut_assume_mutable(
4977        self,
4978        cell: UnsafeEntityCell<'_>,
4979    ) -> Result<Self::Mut<'_>, EntityComponentError> {
4980        // Check for duplicate component IDs.
4981        for i in 0..self.len() {
4982            for j in 0..i {
4983                if self[i] == self[j] {
4984                    return Err(EntityComponentError::AliasedMutability(self[i]));
4985                }
4986            }
4987        }
4988
4989        let mut ptrs = Vec::with_capacity(self.len());
4990        for &id in self {
4991            ptrs.push(
4992                // SAFETY: caller ensures that the cell has mutable access to the component.
4993                unsafe { cell.get_mut_assume_mutable_by_id(id) }
4994                    .map_err(|_| EntityComponentError::MissingComponent(id))?,
4995            );
4996        }
4997        Ok(ptrs)
4998    }
4999}
5000
5001// SAFETY:
5002// - No aliased mutability is caused because `HashSet` guarantees unique elements.
5003// - No mutable references are returned by `fetch_ref`.
5004unsafe impl DynamicComponentFetch for &'_ HashSet<ComponentId> {
5005    type Ref<'w> = HashMap<ComponentId, Ptr<'w>>;
5006    type Mut<'w> = HashMap<ComponentId, MutUntyped<'w>>;
5007
5008    unsafe fn fetch_ref(
5009        self,
5010        cell: UnsafeEntityCell<'_>,
5011    ) -> Result<Self::Ref<'_>, EntityComponentError> {
5012        let mut ptrs = HashMap::with_capacity_and_hasher(self.len(), Default::default());
5013        for &id in self {
5014            ptrs.insert(
5015                id,
5016                // SAFETY: caller ensures that the cell has read access to the component.
5017                unsafe { cell.get_by_id(id) }.ok_or(EntityComponentError::MissingComponent(id))?,
5018            );
5019        }
5020        Ok(ptrs)
5021    }
5022
5023    unsafe fn fetch_mut(
5024        self,
5025        cell: UnsafeEntityCell<'_>,
5026    ) -> Result<Self::Mut<'_>, EntityComponentError> {
5027        let mut ptrs = HashMap::with_capacity_and_hasher(self.len(), Default::default());
5028        for &id in self {
5029            ptrs.insert(
5030                id,
5031                // SAFETY: caller ensures that the cell has mutable access to the component.
5032                unsafe { cell.get_mut_by_id(id) }
5033                    .map_err(|_| EntityComponentError::MissingComponent(id))?,
5034            );
5035        }
5036        Ok(ptrs)
5037    }
5038
5039    unsafe fn fetch_mut_assume_mutable(
5040        self,
5041        cell: UnsafeEntityCell<'_>,
5042    ) -> Result<Self::Mut<'_>, EntityComponentError> {
5043        let mut ptrs = HashMap::with_capacity_and_hasher(self.len(), Default::default());
5044        for &id in self {
5045            ptrs.insert(
5046                id,
5047                // SAFETY: caller ensures that the cell has mutable access to the component.
5048                unsafe { cell.get_mut_assume_mutable_by_id(id) }
5049                    .map_err(|_| EntityComponentError::MissingComponent(id))?,
5050            );
5051        }
5052        Ok(ptrs)
5053    }
5054}
5055
5056#[cfg(test)]
5057mod tests {
5058    use alloc::{vec, vec::Vec};
5059    use bevy_ptr::{OwningPtr, Ptr};
5060    use core::panic::AssertUnwindSafe;
5061    use std::sync::OnceLock;
5062
5063    use crate::component::Tick;
5064    use crate::lifecycle::HookContext;
5065    use crate::{
5066        change_detection::{MaybeLocation, MutUntyped},
5067        component::ComponentId,
5068        prelude::*,
5069        system::{assert_is_system, RunSystemOnce as _},
5070        world::{error::EntityComponentError, DeferredWorld, FilteredEntityMut, FilteredEntityRef},
5071    };
5072
5073    use super::{EntityMutExcept, EntityRefExcept};
5074
5075    #[derive(Component, Clone, Copy, Debug, PartialEq)]
5076    struct TestComponent(u32);
5077
5078    #[derive(Component, Clone, Copy, Debug, PartialEq)]
5079    #[component(storage = "SparseSet")]
5080    struct TestComponent2(u32);
5081
5082    #[test]
5083    fn entity_ref_get_by_id() {
5084        let mut world = World::new();
5085        let entity = world.spawn(TestComponent(42)).id();
5086        let component_id = world
5087            .components()
5088            .get_valid_id(core::any::TypeId::of::<TestComponent>())
5089            .unwrap();
5090
5091        let entity = world.entity(entity);
5092        let test_component = entity.get_by_id(component_id).unwrap();
5093        // SAFETY: points to a valid `TestComponent`
5094        let test_component = unsafe { test_component.deref::<TestComponent>() };
5095
5096        assert_eq!(test_component.0, 42);
5097    }
5098
5099    #[test]
5100    fn entity_mut_get_by_id() {
5101        let mut world = World::new();
5102        let entity = world.spawn(TestComponent(42)).id();
5103        let component_id = world
5104            .components()
5105            .get_valid_id(core::any::TypeId::of::<TestComponent>())
5106            .unwrap();
5107
5108        let mut entity_mut = world.entity_mut(entity);
5109        let mut test_component = entity_mut.get_mut_by_id(component_id).unwrap();
5110        {
5111            test_component.set_changed();
5112            let test_component =
5113                // SAFETY: `test_component` has unique access of the `EntityWorldMut` and is not used afterwards
5114                unsafe { test_component.into_inner().deref_mut::<TestComponent>() };
5115            test_component.0 = 43;
5116        }
5117
5118        let entity = world.entity(entity);
5119        let test_component = entity.get_by_id(component_id).unwrap();
5120        // SAFETY: `TestComponent` is the correct component type
5121        let test_component = unsafe { test_component.deref::<TestComponent>() };
5122
5123        assert_eq!(test_component.0, 43);
5124    }
5125
5126    #[test]
5127    fn entity_ref_get_by_id_invalid_component_id() {
5128        let invalid_component_id = ComponentId::new(usize::MAX);
5129
5130        let mut world = World::new();
5131        let entity = world.spawn_empty().id();
5132        let entity = world.entity(entity);
5133        assert!(entity.get_by_id(invalid_component_id).is_err());
5134    }
5135
5136    #[test]
5137    fn entity_mut_get_by_id_invalid_component_id() {
5138        let invalid_component_id = ComponentId::new(usize::MAX);
5139
5140        let mut world = World::new();
5141        let mut entity = world.spawn_empty();
5142        assert!(entity.get_by_id(invalid_component_id).is_err());
5143        assert!(entity.get_mut_by_id(invalid_component_id).is_err());
5144    }
5145
5146    #[derive(Resource)]
5147    struct R(usize);
5148
5149    #[test]
5150    fn entity_mut_resource_scope() {
5151        // Keep in sync with the `resource_scope` test in lib.rs
5152        let mut world = World::new();
5153        let mut entity = world.spawn_empty();
5154
5155        assert!(entity.try_resource_scope::<R, _>(|_, _| {}).is_none());
5156        entity.world_scope(|world| world.insert_resource(R(0)));
5157        entity.resource_scope(|entity: &mut EntityWorldMut, mut value: Mut<R>| {
5158            value.0 += 1;
5159            assert!(!entity.world().contains_resource::<R>());
5160        });
5161        assert_eq!(entity.resource::<R>().0, 1);
5162    }
5163
5164    #[test]
5165    fn entity_mut_resource_scope_panic() {
5166        let mut world = World::new();
5167        world.insert_resource(R(0));
5168
5169        let mut entity = world.spawn_empty();
5170        let old_location = entity.location();
5171        let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
5172            entity.resource_scope(|entity: &mut EntityWorldMut, _: Mut<R>| {
5173                // Change the entity's `EntityLocation`.
5174                entity.insert(TestComponent(0));
5175
5176                // Ensure that the entity location still gets updated even in case of a panic.
5177                panic!("this should get caught by the outer scope")
5178            });
5179        }));
5180        assert!(result.is_err());
5181
5182        // Ensure that the location has been properly updated.
5183        assert_ne!(entity.location(), old_location);
5184    }
5185
5186    // regression test for https://github.com/bevyengine/bevy/pull/7387
5187    #[test]
5188    fn entity_mut_world_scope_panic() {
5189        let mut world = World::new();
5190
5191        let mut entity = world.spawn_empty();
5192        let old_location = entity.location();
5193        let id = entity.id();
5194        let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
5195            entity.world_scope(|w| {
5196                // Change the entity's `EntityLocation`, which invalidates the original `EntityWorldMut`.
5197                // This will get updated at the end of the scope.
5198                w.entity_mut(id).insert(TestComponent(0));
5199
5200                // Ensure that the entity location still gets updated even in case of a panic.
5201                panic!("this should get caught by the outer scope")
5202            });
5203        }));
5204        assert!(res.is_err());
5205
5206        // Ensure that the location has been properly updated.
5207        assert_ne!(entity.location(), old_location);
5208    }
5209
5210    #[test]
5211    fn entity_mut_reborrow_scope_panic() {
5212        let mut world = World::new();
5213
5214        let mut entity = world.spawn_empty();
5215        let old_location = entity.location();
5216        let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
5217            entity.reborrow_scope(|mut entity| {
5218                // Change the entity's `EntityLocation`, which invalidates the original `EntityWorldMut`.
5219                // This will get updated at the end of the scope.
5220                entity.insert(TestComponent(0));
5221
5222                // Ensure that the entity location still gets updated even in case of a panic.
5223                panic!("this should get caught by the outer scope")
5224            });
5225        }));
5226        assert!(res.is_err());
5227
5228        // Ensure that the location has been properly updated.
5229        assert_ne!(entity.location(), old_location);
5230    }
5231
5232    // regression test for https://github.com/bevyengine/bevy/pull/7805
5233    #[test]
5234    fn removing_sparse_updates_archetype_row() {
5235        #[derive(Component, PartialEq, Debug)]
5236        struct Dense(u8);
5237
5238        #[derive(Component)]
5239        #[component(storage = "SparseSet")]
5240        struct Sparse;
5241
5242        let mut world = World::new();
5243        let e1 = world.spawn((Dense(0), Sparse)).id();
5244        let e2 = world.spawn((Dense(1), Sparse)).id();
5245
5246        world.entity_mut(e1).remove::<Sparse>();
5247        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
5248    }
5249
5250    // regression test for https://github.com/bevyengine/bevy/pull/7805
5251    #[test]
5252    fn removing_dense_updates_table_row() {
5253        #[derive(Component, PartialEq, Debug)]
5254        struct Dense(u8);
5255
5256        #[derive(Component)]
5257        #[component(storage = "SparseSet")]
5258        struct Sparse;
5259
5260        let mut world = World::new();
5261        let e1 = world.spawn((Dense(0), Sparse)).id();
5262        let e2 = world.spawn((Dense(1), Sparse)).id();
5263
5264        world.entity_mut(e1).remove::<Dense>();
5265        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
5266    }
5267
5268    // Test that calling retain with `()` removes all components.
5269    #[test]
5270    fn retain_nothing() {
5271        #[derive(Component)]
5272        struct Marker<const N: usize>;
5273
5274        let mut world = World::new();
5275        let ent = world.spawn((Marker::<1>, Marker::<2>, Marker::<3>)).id();
5276
5277        world.entity_mut(ent).retain::<()>();
5278        assert_eq!(world.entity(ent).archetype().components().len(), 0);
5279    }
5280
5281    // Test removing some components with `retain`, including components not on the entity.
5282    #[test]
5283    fn retain_some_components() {
5284        #[derive(Component)]
5285        struct Marker<const N: usize>;
5286
5287        let mut world = World::new();
5288        let ent = world.spawn((Marker::<1>, Marker::<2>, Marker::<3>)).id();
5289
5290        world.entity_mut(ent).retain::<(Marker<2>, Marker<4>)>();
5291        // Check that marker 2 was retained.
5292        assert!(world.entity(ent).get::<Marker<2>>().is_some());
5293        // Check that only marker 2 was retained.
5294        assert_eq!(world.entity(ent).archetype().components().len(), 1);
5295    }
5296
5297    // regression test for https://github.com/bevyengine/bevy/pull/7805
5298    #[test]
5299    fn inserting_sparse_updates_archetype_row() {
5300        #[derive(Component, PartialEq, Debug)]
5301        struct Dense(u8);
5302
5303        #[derive(Component)]
5304        #[component(storage = "SparseSet")]
5305        struct Sparse;
5306
5307        let mut world = World::new();
5308        let e1 = world.spawn(Dense(0)).id();
5309        let e2 = world.spawn(Dense(1)).id();
5310
5311        world.entity_mut(e1).insert(Sparse);
5312        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
5313    }
5314
5315    // regression test for https://github.com/bevyengine/bevy/pull/7805
5316    #[test]
5317    fn inserting_dense_updates_archetype_row() {
5318        #[derive(Component, PartialEq, Debug)]
5319        struct Dense(u8);
5320
5321        #[derive(Component)]
5322        struct Dense2;
5323
5324        #[derive(Component)]
5325        #[component(storage = "SparseSet")]
5326        struct Sparse;
5327
5328        let mut world = World::new();
5329        let e1 = world.spawn(Dense(0)).id();
5330        let e2 = world.spawn(Dense(1)).id();
5331
5332        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
5333
5334        // archetype with [e2, e1]
5335        // table with [e1, e2]
5336
5337        world.entity_mut(e2).insert(Dense2);
5338
5339        assert_eq!(world.entity(e1).get::<Dense>().unwrap(), &Dense(0));
5340    }
5341
5342    #[test]
5343    fn inserting_dense_updates_table_row() {
5344        #[derive(Component, PartialEq, Debug)]
5345        struct Dense(u8);
5346
5347        #[derive(Component)]
5348        struct Dense2;
5349
5350        #[derive(Component)]
5351        #[component(storage = "SparseSet")]
5352        struct Sparse;
5353
5354        let mut world = World::new();
5355        let e1 = world.spawn(Dense(0)).id();
5356        let e2 = world.spawn(Dense(1)).id();
5357
5358        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
5359
5360        // archetype with [e2, e1]
5361        // table with [e1, e2]
5362
5363        world.entity_mut(e1).insert(Dense2);
5364
5365        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
5366    }
5367
5368    // regression test for https://github.com/bevyengine/bevy/pull/7805
5369    #[test]
5370    fn despawning_entity_updates_archetype_row() {
5371        #[derive(Component, PartialEq, Debug)]
5372        struct Dense(u8);
5373
5374        #[derive(Component)]
5375        #[component(storage = "SparseSet")]
5376        struct Sparse;
5377
5378        let mut world = World::new();
5379        let e1 = world.spawn(Dense(0)).id();
5380        let e2 = world.spawn(Dense(1)).id();
5381
5382        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
5383
5384        // archetype with [e2, e1]
5385        // table with [e1, e2]
5386
5387        world.entity_mut(e2).despawn();
5388
5389        assert_eq!(world.entity(e1).get::<Dense>().unwrap(), &Dense(0));
5390    }
5391
5392    // regression test for https://github.com/bevyengine/bevy/pull/7805
5393    #[test]
5394    fn despawning_entity_updates_table_row() {
5395        #[derive(Component, PartialEq, Debug)]
5396        struct Dense(u8);
5397
5398        #[derive(Component)]
5399        #[component(storage = "SparseSet")]
5400        struct Sparse;
5401
5402        let mut world = World::new();
5403        let e1 = world.spawn(Dense(0)).id();
5404        let e2 = world.spawn(Dense(1)).id();
5405
5406        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();
5407
5408        // archetype with [e2, e1]
5409        // table with [e1, e2]
5410
5411        world.entity_mut(e1).despawn();
5412
5413        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
5414    }
5415
5416    #[test]
5417    fn entity_mut_insert_by_id() {
5418        let mut world = World::new();
5419        let test_component_id = world.register_component::<TestComponent>();
5420
5421        let mut entity = world.spawn_empty();
5422        OwningPtr::make(TestComponent(42), |ptr| {
5423            // SAFETY: `ptr` matches the component id
5424            unsafe { entity.insert_by_id(test_component_id, ptr) };
5425        });
5426
5427        let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();
5428
5429        assert_eq!(components, vec![&TestComponent(42)]);
5430
5431        // Compare with `insert_bundle_by_id`
5432
5433        let mut entity = world.spawn_empty();
5434        OwningPtr::make(TestComponent(84), |ptr| {
5435            // SAFETY: `ptr` matches the component id
5436            unsafe { entity.insert_by_ids(&[test_component_id], vec![ptr].into_iter()) };
5437        });
5438
5439        let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();
5440
5441        assert_eq!(components, vec![&TestComponent(42), &TestComponent(84)]);
5442    }
5443
5444    #[test]
5445    fn entity_mut_insert_bundle_by_id() {
5446        let mut world = World::new();
5447        let test_component_id = world.register_component::<TestComponent>();
5448        let test_component_2_id = world.register_component::<TestComponent2>();
5449
5450        let component_ids = [test_component_id, test_component_2_id];
5451        let test_component_value = TestComponent(42);
5452        let test_component_2_value = TestComponent2(84);
5453
5454        let mut entity = world.spawn_empty();
5455        OwningPtr::make(test_component_value, |ptr1| {
5456            OwningPtr::make(test_component_2_value, |ptr2| {
5457                // SAFETY: `ptr1` and `ptr2` match the component ids
5458                unsafe { entity.insert_by_ids(&component_ids, vec![ptr1, ptr2].into_iter()) };
5459            });
5460        });
5461
5462        let dynamic_components: Vec<_> = world
5463            .query::<(&TestComponent, &TestComponent2)>()
5464            .iter(&world)
5465            .collect();
5466
5467        assert_eq!(
5468            dynamic_components,
5469            vec![(&TestComponent(42), &TestComponent2(84))]
5470        );
5471
5472        // Compare with `World` generated using static type equivalents
5473        let mut static_world = World::new();
5474
5475        static_world.spawn((test_component_value, test_component_2_value));
5476        let static_components: Vec<_> = static_world
5477            .query::<(&TestComponent, &TestComponent2)>()
5478            .iter(&static_world)
5479            .collect();
5480
5481        assert_eq!(dynamic_components, static_components);
5482    }
5483
5484    #[test]
5485    fn entity_mut_remove_by_id() {
5486        let mut world = World::new();
5487        let test_component_id = world.register_component::<TestComponent>();
5488
5489        let mut entity = world.spawn(TestComponent(42));
5490        entity.remove_by_id(test_component_id);
5491
5492        let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();
5493
5494        assert_eq!(components, vec![] as Vec<&TestComponent>);
5495
5496        // remove non-existent component does not panic
5497        world.spawn_empty().remove_by_id(test_component_id);
5498    }
5499
5500    /// Tests that components can be accessed through an `EntityRefExcept`.
5501    #[test]
5502    fn entity_ref_except() {
5503        let mut world = World::new();
5504        world.register_component::<TestComponent>();
5505        world.register_component::<TestComponent2>();
5506
5507        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5508
5509        let mut query = world.query::<EntityRefExcept<TestComponent>>();
5510
5511        let mut found = false;
5512        for entity_ref in query.iter_mut(&mut world) {
5513            found = true;
5514            assert!(entity_ref.get::<TestComponent>().is_none());
5515            assert!(entity_ref.get_ref::<TestComponent>().is_none());
5516            assert!(matches!(
5517                entity_ref.get::<TestComponent2>(),
5518                Some(TestComponent2(0))
5519            ));
5520        }
5521
5522        assert!(found);
5523    }
5524
5525    // Test that a single query can't both contain a mutable reference to a
5526    // component C and an `EntityRefExcept` that doesn't include C among its
5527    // exclusions.
5528    #[test]
5529    #[should_panic]
5530    fn entity_ref_except_conflicts_with_self() {
5531        let mut world = World::new();
5532        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5533
5534        // This should panic, because we have a mutable borrow on
5535        // `TestComponent` but have a simultaneous indirect immutable borrow on
5536        // that component via `EntityRefExcept`.
5537        world.run_system_once(system).unwrap();
5538
5539        fn system(_: Query<(&mut TestComponent, EntityRefExcept<TestComponent2>)>) {}
5540    }
5541
5542    // Test that an `EntityRefExcept` that doesn't include a component C among
5543    // its exclusions can't coexist with a mutable query for that component.
5544    #[test]
5545    #[should_panic]
5546    fn entity_ref_except_conflicts_with_other() {
5547        let mut world = World::new();
5548        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5549
5550        // This should panic, because we have a mutable borrow on
5551        // `TestComponent` but have a simultaneous indirect immutable borrow on
5552        // that component via `EntityRefExcept`.
5553        world.run_system_once(system).unwrap();
5554
5555        fn system(_: Query<&mut TestComponent>, _: Query<EntityRefExcept<TestComponent2>>) {}
5556    }
5557
5558    // Test that an `EntityRefExcept` with an exception for some component C can
5559    // coexist with a query for that component C.
5560    #[test]
5561    fn entity_ref_except_doesnt_conflict() {
5562        let mut world = World::new();
5563        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5564
5565        world.run_system_once(system).unwrap();
5566
5567        fn system(_: Query<&mut TestComponent>, query: Query<EntityRefExcept<TestComponent>>) {
5568            for entity_ref in query.iter() {
5569                assert!(matches!(
5570                    entity_ref.get::<TestComponent2>(),
5571                    Some(TestComponent2(0))
5572                ));
5573            }
5574        }
5575    }
5576
5577    /// Tests that components can be mutably accessed through an
5578    /// `EntityMutExcept`.
5579    #[test]
5580    fn entity_mut_except() {
5581        let mut world = World::new();
5582        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5583
5584        let mut query = world.query::<EntityMutExcept<TestComponent>>();
5585
5586        let mut found = false;
5587        for mut entity_mut in query.iter_mut(&mut world) {
5588            found = true;
5589            assert!(entity_mut.get::<TestComponent>().is_none());
5590            assert!(entity_mut.get_ref::<TestComponent>().is_none());
5591            assert!(entity_mut.get_mut::<TestComponent>().is_none());
5592            assert!(matches!(
5593                entity_mut.get::<TestComponent2>(),
5594                Some(TestComponent2(0))
5595            ));
5596        }
5597
5598        assert!(found);
5599    }
5600
5601    // Test that a single query can't both contain a mutable reference to a
5602    // component C and an `EntityMutExcept` that doesn't include C among its
5603    // exclusions.
5604    #[test]
5605    #[should_panic]
5606    fn entity_mut_except_conflicts_with_self() {
5607        let mut world = World::new();
5608        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5609
5610        // This should panic, because we have a mutable borrow on
5611        // `TestComponent` but have a simultaneous indirect immutable borrow on
5612        // that component via `EntityRefExcept`.
5613        world.run_system_once(system).unwrap();
5614
5615        fn system(_: Query<(&mut TestComponent, EntityMutExcept<TestComponent2>)>) {}
5616    }
5617
5618    // Test that an `EntityMutExcept` that doesn't include a component C among
5619    // its exclusions can't coexist with a query for that component.
5620    #[test]
5621    #[should_panic]
5622    fn entity_mut_except_conflicts_with_other() {
5623        let mut world = World::new();
5624        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5625
5626        // This should panic, because we have a mutable borrow on
5627        // `TestComponent` but have a simultaneous indirect immutable borrow on
5628        // that component via `EntityRefExcept`.
5629        world.run_system_once(system).unwrap();
5630
5631        fn system(_: Query<&mut TestComponent>, mut query: Query<EntityMutExcept<TestComponent2>>) {
5632            for mut entity_mut in query.iter_mut() {
5633                assert!(entity_mut
5634                    .get_mut::<TestComponent2>()
5635                    .is_some_and(|component| component.0 == 0));
5636            }
5637        }
5638    }
5639
5640    // Test that an `EntityMutExcept` with an exception for some component C can
5641    // coexist with a query for that component C.
5642    #[test]
5643    fn entity_mut_except_doesnt_conflict() {
5644        let mut world = World::new();
5645        world.spawn(TestComponent(0)).insert(TestComponent2(0));
5646
5647        world.run_system_once(system).unwrap();
5648
5649        fn system(_: Query<&mut TestComponent>, mut query: Query<EntityMutExcept<TestComponent>>) {
5650            for mut entity_mut in query.iter_mut() {
5651                assert!(entity_mut
5652                    .get_mut::<TestComponent2>()
5653                    .is_some_and(|component| component.0 == 0));
5654            }
5655        }
5656    }
5657
5658    #[test]
5659    fn entity_mut_except_registers_components() {
5660        // Checks for a bug where `EntityMutExcept` would not register the component and
5661        // would therefore not include an exception, causing it to conflict with the later query.
5662        fn system1(_query: Query<EntityMutExcept<TestComponent>>, _: Query<&mut TestComponent>) {}
5663        let mut world = World::new();
5664        world.run_system_once(system1).unwrap();
5665
5666        fn system2(_: Query<&mut TestComponent>, _query: Query<EntityMutExcept<TestComponent>>) {}
5667        let mut world = World::new();
5668        world.run_system_once(system2).unwrap();
5669    }
5670
5671    #[derive(Component)]
5672    struct A;
5673
5674    #[test]
5675    fn disjoint_access() {
5676        fn disjoint_readonly(_: Query<EntityMut, With<A>>, _: Query<EntityRef, Without<A>>) {}
5677
5678        fn disjoint_mutable(_: Query<EntityMut, With<A>>, _: Query<EntityMut, Without<A>>) {}
5679
5680        assert_is_system(disjoint_readonly);
5681        assert_is_system(disjoint_mutable);
5682    }
5683
5684    #[test]
5685    fn ref_compatible() {
5686        fn borrow_system(_: Query<(EntityRef, &A)>, _: Query<&A>) {}
5687
5688        assert_is_system(borrow_system);
5689    }
5690
5691    #[test]
5692    fn ref_compatible_with_resource() {
5693        fn borrow_system(_: Query<EntityRef>, _: Res<R>) {}
5694
5695        assert_is_system(borrow_system);
5696    }
5697
5698    #[test]
5699    fn ref_compatible_with_resource_mut() {
5700        fn borrow_system(_: Query<EntityRef>, _: ResMut<R>) {}
5701
5702        assert_is_system(borrow_system);
5703    }
5704
5705    #[test]
5706    #[should_panic]
5707    fn ref_incompatible_with_mutable_component() {
5708        fn incompatible_system(_: Query<(EntityRef, &mut A)>) {}
5709
5710        assert_is_system(incompatible_system);
5711    }
5712
5713    #[test]
5714    #[should_panic]
5715    fn ref_incompatible_with_mutable_query() {
5716        fn incompatible_system(_: Query<EntityRef>, _: Query<&mut A>) {}
5717
5718        assert_is_system(incompatible_system);
5719    }
5720
5721    #[test]
5722    fn mut_compatible_with_entity() {
5723        fn borrow_mut_system(_: Query<(Entity, EntityMut)>) {}
5724
5725        assert_is_system(borrow_mut_system);
5726    }
5727
5728    #[test]
5729    fn mut_compatible_with_resource() {
5730        fn borrow_mut_system(_: Res<R>, _: Query<EntityMut>) {}
5731
5732        assert_is_system(borrow_mut_system);
5733    }
5734
5735    #[test]
5736    fn mut_compatible_with_resource_mut() {
5737        fn borrow_mut_system(_: ResMut<R>, _: Query<EntityMut>) {}
5738
5739        assert_is_system(borrow_mut_system);
5740    }
5741
5742    #[test]
5743    #[should_panic]
5744    fn mut_incompatible_with_read_only_component() {
5745        fn incompatible_system(_: Query<(EntityMut, &A)>) {}
5746
5747        assert_is_system(incompatible_system);
5748    }
5749
5750    #[test]
5751    #[should_panic]
5752    fn mut_incompatible_with_mutable_component() {
5753        fn incompatible_system(_: Query<(EntityMut, &mut A)>) {}
5754
5755        assert_is_system(incompatible_system);
5756    }
5757
5758    #[test]
5759    #[should_panic]
5760    fn mut_incompatible_with_read_only_query() {
5761        fn incompatible_system(_: Query<EntityMut>, _: Query<&A>) {}
5762
5763        assert_is_system(incompatible_system);
5764    }
5765
5766    #[test]
5767    #[should_panic]
5768    fn mut_incompatible_with_mutable_query() {
5769        fn incompatible_system(_: Query<EntityMut>, _: Query<&mut A>) {}
5770
5771        assert_is_system(incompatible_system);
5772    }
5773
5774    #[test]
5775    fn filtered_entity_ref_normal() {
5776        let mut world = World::new();
5777        let a_id = world.register_component::<A>();
5778
5779        let e: FilteredEntityRef = world.spawn(A).into();
5780
5781        assert!(e.get::<A>().is_some());
5782        assert!(e.get_ref::<A>().is_some());
5783        assert!(e.get_change_ticks::<A>().is_some());
5784        assert!(e.get_by_id(a_id).is_some());
5785        assert!(e.get_change_ticks_by_id(a_id).is_some());
5786    }
5787
5788    #[test]
5789    fn filtered_entity_ref_missing() {
5790        let mut world = World::new();
5791        let a_id = world.register_component::<A>();
5792
5793        let e: FilteredEntityRef = world.spawn(()).into();
5794
5795        assert!(e.get::<A>().is_none());
5796        assert!(e.get_ref::<A>().is_none());
5797        assert!(e.get_change_ticks::<A>().is_none());
5798        assert!(e.get_by_id(a_id).is_none());
5799        assert!(e.get_change_ticks_by_id(a_id).is_none());
5800    }
5801
5802    #[test]
5803    fn filtered_entity_mut_normal() {
5804        let mut world = World::new();
5805        let a_id = world.register_component::<A>();
5806
5807        let mut e: FilteredEntityMut = world.spawn(A).into();
5808
5809        assert!(e.get::<A>().is_some());
5810        assert!(e.get_ref::<A>().is_some());
5811        assert!(e.get_mut::<A>().is_some());
5812        assert!(e.get_change_ticks::<A>().is_some());
5813        assert!(e.get_by_id(a_id).is_some());
5814        assert!(e.get_mut_by_id(a_id).is_some());
5815        assert!(e.get_change_ticks_by_id(a_id).is_some());
5816    }
5817
5818    #[test]
5819    fn filtered_entity_mut_missing() {
5820        let mut world = World::new();
5821        let a_id = world.register_component::<A>();
5822
5823        let mut e: FilteredEntityMut = world.spawn(()).into();
5824
5825        assert!(e.get::<A>().is_none());
5826        assert!(e.get_ref::<A>().is_none());
5827        assert!(e.get_mut::<A>().is_none());
5828        assert!(e.get_change_ticks::<A>().is_none());
5829        assert!(e.get_by_id(a_id).is_none());
5830        assert!(e.get_mut_by_id(a_id).is_none());
5831        assert!(e.get_change_ticks_by_id(a_id).is_none());
5832    }
5833
5834    #[derive(Component, PartialEq, Eq, Debug)]
5835    struct X(usize);
5836
5837    #[derive(Component, PartialEq, Eq, Debug)]
5838    struct Y(usize);
5839
5840    #[test]
5841    fn get_components() {
5842        let mut world = World::default();
5843        let e1 = world.spawn((X(7), Y(10))).id();
5844        let e2 = world.spawn(X(8)).id();
5845        let e3 = world.spawn_empty().id();
5846
5847        assert_eq!(
5848            Some((&X(7), &Y(10))),
5849            world.entity(e1).get_components::<(&X, &Y)>()
5850        );
5851        assert_eq!(None, world.entity(e2).get_components::<(&X, &Y)>());
5852        assert_eq!(None, world.entity(e3).get_components::<(&X, &Y)>());
5853    }
5854
5855    #[test]
5856    fn get_by_id_array() {
5857        let mut world = World::default();
5858        let e1 = world.spawn((X(7), Y(10))).id();
5859        let e2 = world.spawn(X(8)).id();
5860        let e3 = world.spawn_empty().id();
5861
5862        let x_id = world.register_component::<X>();
5863        let y_id = world.register_component::<Y>();
5864
5865        assert_eq!(
5866            Ok((&X(7), &Y(10))),
5867            world
5868                .entity(e1)
5869                .get_by_id([x_id, y_id])
5870                .map(|[x_ptr, y_ptr]| {
5871                    // SAFETY: components match the id they were fetched with
5872                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
5873                })
5874        );
5875        assert_eq!(
5876            Err(EntityComponentError::MissingComponent(y_id)),
5877            world
5878                .entity(e2)
5879                .get_by_id([x_id, y_id])
5880                .map(|[x_ptr, y_ptr]| {
5881                    // SAFETY: components match the id they were fetched with
5882                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
5883                })
5884        );
5885        assert_eq!(
5886            Err(EntityComponentError::MissingComponent(x_id)),
5887            world
5888                .entity(e3)
5889                .get_by_id([x_id, y_id])
5890                .map(|[x_ptr, y_ptr]| {
5891                    // SAFETY: components match the id they were fetched with
5892                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
5893                })
5894        );
5895    }
5896
5897    #[test]
5898    fn get_by_id_vec() {
5899        let mut world = World::default();
5900        let e1 = world.spawn((X(7), Y(10))).id();
5901        let e2 = world.spawn(X(8)).id();
5902        let e3 = world.spawn_empty().id();
5903
5904        let x_id = world.register_component::<X>();
5905        let y_id = world.register_component::<Y>();
5906
5907        assert_eq!(
5908            Ok((&X(7), &Y(10))),
5909            world
5910                .entity(e1)
5911                .get_by_id(&[x_id, y_id] as &[ComponentId])
5912                .map(|ptrs| {
5913                    let Ok([x_ptr, y_ptr]): Result<[Ptr; 2], _> = ptrs.try_into() else {
5914                        panic!("get_by_id(slice) didn't return 2 elements")
5915                    };
5916
5917                    // SAFETY: components match the id they were fetched with
5918                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
5919                })
5920        );
5921        assert_eq!(
5922            Err(EntityComponentError::MissingComponent(y_id)),
5923            world
5924                .entity(e2)
5925                .get_by_id(&[x_id, y_id] as &[ComponentId])
5926                .map(|ptrs| {
5927                    let Ok([x_ptr, y_ptr]): Result<[Ptr; 2], _> = ptrs.try_into() else {
5928                        panic!("get_by_id(slice) didn't return 2 elements")
5929                    };
5930
5931                    // SAFETY: components match the id they were fetched with
5932                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
5933                })
5934        );
5935        assert_eq!(
5936            Err(EntityComponentError::MissingComponent(x_id)),
5937            world
5938                .entity(e3)
5939                .get_by_id(&[x_id, y_id] as &[ComponentId])
5940                .map(|ptrs| {
5941                    let Ok([x_ptr, y_ptr]): Result<[Ptr; 2], _> = ptrs.try_into() else {
5942                        panic!("get_by_id(slice) didn't return 2 elements")
5943                    };
5944
5945                    // SAFETY: components match the id they were fetched with
5946                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
5947                })
5948        );
5949    }
5950
5951    #[test]
5952    fn get_mut_by_id_array() {
5953        let mut world = World::default();
5954        let e1 = world.spawn((X(7), Y(10))).id();
5955        let e2 = world.spawn(X(8)).id();
5956        let e3 = world.spawn_empty().id();
5957
5958        let x_id = world.register_component::<X>();
5959        let y_id = world.register_component::<Y>();
5960
5961        assert_eq!(
5962            Ok((&mut X(7), &mut Y(10))),
5963            world
5964                .entity_mut(e1)
5965                .get_mut_by_id([x_id, y_id])
5966                .map(|[x_ptr, y_ptr]| {
5967                    // SAFETY: components match the id they were fetched with
5968                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
5969                        y_ptr.into_inner().deref_mut::<Y>()
5970                    })
5971                })
5972        );
5973        assert_eq!(
5974            Err(EntityComponentError::MissingComponent(y_id)),
5975            world
5976                .entity_mut(e2)
5977                .get_mut_by_id([x_id, y_id])
5978                .map(|[x_ptr, y_ptr]| {
5979                    // SAFETY: components match the id they were fetched with
5980                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
5981                        y_ptr.into_inner().deref_mut::<Y>()
5982                    })
5983                })
5984        );
5985        assert_eq!(
5986            Err(EntityComponentError::MissingComponent(x_id)),
5987            world
5988                .entity_mut(e3)
5989                .get_mut_by_id([x_id, y_id])
5990                .map(|[x_ptr, y_ptr]| {
5991                    // SAFETY: components match the id they were fetched with
5992                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
5993                        y_ptr.into_inner().deref_mut::<Y>()
5994                    })
5995                })
5996        );
5997
5998        assert_eq!(
5999            Err(EntityComponentError::AliasedMutability(x_id)),
6000            world
6001                .entity_mut(e1)
6002                .get_mut_by_id([x_id, x_id])
6003                .map(|_| { unreachable!() })
6004        );
6005        assert_eq!(
6006            Err(EntityComponentError::AliasedMutability(x_id)),
6007            world
6008                .entity_mut(e3)
6009                .get_mut_by_id([x_id, x_id])
6010                .map(|_| { unreachable!() })
6011        );
6012    }
6013
6014    #[test]
6015    fn get_mut_by_id_vec() {
6016        let mut world = World::default();
6017        let e1 = world.spawn((X(7), Y(10))).id();
6018        let e2 = world.spawn(X(8)).id();
6019        let e3 = world.spawn_empty().id();
6020
6021        let x_id = world.register_component::<X>();
6022        let y_id = world.register_component::<Y>();
6023
6024        assert_eq!(
6025            Ok((&mut X(7), &mut Y(10))),
6026            world
6027                .entity_mut(e1)
6028                .get_mut_by_id(&[x_id, y_id] as &[ComponentId])
6029                .map(|ptrs| {
6030                    let Ok([x_ptr, y_ptr]): Result<[MutUntyped; 2], _> = ptrs.try_into() else {
6031                        panic!("get_mut_by_id(slice) didn't return 2 elements")
6032                    };
6033
6034                    // SAFETY: components match the id they were fetched with
6035                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
6036                        y_ptr.into_inner().deref_mut::<Y>()
6037                    })
6038                })
6039        );
6040        assert_eq!(
6041            Err(EntityComponentError::MissingComponent(y_id)),
6042            world
6043                .entity_mut(e2)
6044                .get_mut_by_id(&[x_id, y_id] as &[ComponentId])
6045                .map(|ptrs| {
6046                    let Ok([x_ptr, y_ptr]): Result<[MutUntyped; 2], _> = ptrs.try_into() else {
6047                        panic!("get_mut_by_id(slice) didn't return 2 elements")
6048                    };
6049
6050                    // SAFETY: components match the id they were fetched with
6051                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
6052                        y_ptr.into_inner().deref_mut::<Y>()
6053                    })
6054                })
6055        );
6056        assert_eq!(
6057            Err(EntityComponentError::MissingComponent(x_id)),
6058            world
6059                .entity_mut(e3)
6060                .get_mut_by_id(&[x_id, y_id] as &[ComponentId])
6061                .map(|ptrs| {
6062                    let Ok([x_ptr, y_ptr]): Result<[MutUntyped; 2], _> = ptrs.try_into() else {
6063                        panic!("get_mut_by_id(slice) didn't return 2 elements")
6064                    };
6065
6066                    // SAFETY: components match the id they were fetched with
6067                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
6068                        y_ptr.into_inner().deref_mut::<Y>()
6069                    })
6070                })
6071        );
6072
6073        assert_eq!(
6074            Err(EntityComponentError::AliasedMutability(x_id)),
6075            world
6076                .entity_mut(e1)
6077                .get_mut_by_id(&[x_id, x_id])
6078                .map(|_| { unreachable!() })
6079        );
6080        assert_eq!(
6081            Err(EntityComponentError::AliasedMutability(x_id)),
6082            world
6083                .entity_mut(e3)
6084                .get_mut_by_id(&[x_id, x_id])
6085                .map(|_| { unreachable!() })
6086        );
6087    }
6088
6089    #[test]
6090    fn get_mut_by_id_unchecked() {
6091        let mut world = World::default();
6092        let e1 = world.spawn((X(7), Y(10))).id();
6093        let x_id = world.register_component::<X>();
6094        let y_id = world.register_component::<Y>();
6095
6096        let e1_mut = &world.get_entity_mut([e1]).unwrap()[0];
6097        // SAFETY: The entity e1 contains component X.
6098        let x_ptr = unsafe { e1_mut.get_mut_by_id_unchecked(x_id) }.unwrap();
6099        // SAFETY: The entity e1 contains component Y, with components X and Y being mutually independent.
6100        let y_ptr = unsafe { e1_mut.get_mut_by_id_unchecked(y_id) }.unwrap();
6101
6102        // SAFETY: components match the id they were fetched with
6103        let x_component = unsafe { x_ptr.into_inner().deref_mut::<X>() };
6104        x_component.0 += 1;
6105        // SAFETY: components match the id they were fetched with
6106        let y_component = unsafe { y_ptr.into_inner().deref_mut::<Y>() };
6107        y_component.0 -= 1;
6108
6109        assert_eq!((&mut X(8), &mut Y(9)), (x_component, y_component));
6110    }
6111
6112    #[derive(EntityEvent)]
6113    struct TestEvent(Entity);
6114
6115    #[test]
6116    fn adding_observer_updates_location() {
6117        let mut world = World::new();
6118        let entity = world
6119            .spawn_empty()
6120            .observe(|event: On<TestEvent>, mut commands: Commands| {
6121                commands
6122                    .entity(event.event_target())
6123                    .insert(TestComponent(0));
6124            })
6125            .id();
6126
6127        // this should not be needed, but is currently required to tease out the bug
6128        world.flush();
6129
6130        let mut a = world.entity_mut(entity);
6131        // SAFETY: this _intentionally_ doesn't update the location, to ensure that we're actually testing
6132        // that observe() updates location
6133        unsafe { a.world_mut().trigger(TestEvent(entity)) }
6134        a.observe(|_: On<TestEvent>| {}); // this flushes commands implicitly by spawning
6135        let location = a.location();
6136        assert_eq!(world.entities().get(entity), Some(location));
6137    }
6138
6139    #[test]
6140    #[should_panic]
6141    fn location_on_despawned_entity_panics() {
6142        let mut world = World::new();
6143        world.add_observer(|add: On<Add, TestComponent>, mut commands: Commands| {
6144            commands.entity(add.entity).despawn();
6145        });
6146        let entity = world.spawn_empty().id();
6147        let mut a = world.entity_mut(entity);
6148        a.insert(TestComponent(0));
6149        a.location();
6150    }
6151
6152    #[derive(Resource)]
6153    struct TestFlush(usize);
6154
6155    fn count_flush(world: &mut World) {
6156        world.resource_mut::<TestFlush>().0 += 1;
6157    }
6158
6159    #[test]
6160    fn archetype_modifications_trigger_flush() {
6161        let mut world = World::new();
6162        world.insert_resource(TestFlush(0));
6163        world.add_observer(|_: On<Add, TestComponent>, mut commands: Commands| {
6164            commands.queue(count_flush);
6165        });
6166        world.add_observer(|_: On<Remove, TestComponent>, mut commands: Commands| {
6167            commands.queue(count_flush);
6168        });
6169        world.commands().queue(count_flush);
6170        let entity = world.spawn_empty().id();
6171        assert_eq!(world.resource::<TestFlush>().0, 1);
6172        world.commands().queue(count_flush);
6173        world.flush_commands();
6174        let mut a = world.entity_mut(entity);
6175        assert_eq!(a.world().resource::<TestFlush>().0, 2);
6176        a.insert(TestComponent(0));
6177        assert_eq!(a.world().resource::<TestFlush>().0, 3);
6178        a.remove::<TestComponent>();
6179        assert_eq!(a.world().resource::<TestFlush>().0, 4);
6180        a.insert(TestComponent(0));
6181        assert_eq!(a.world().resource::<TestFlush>().0, 5);
6182        let _ = a.take::<TestComponent>();
6183        assert_eq!(a.world().resource::<TestFlush>().0, 6);
6184        a.insert(TestComponent(0));
6185        assert_eq!(a.world().resource::<TestFlush>().0, 7);
6186        a.retain::<()>();
6187        assert_eq!(a.world().resource::<TestFlush>().0, 8);
6188        a.insert(TestComponent(0));
6189        assert_eq!(a.world().resource::<TestFlush>().0, 9);
6190        a.clear();
6191        assert_eq!(a.world().resource::<TestFlush>().0, 10);
6192        a.insert(TestComponent(0));
6193        assert_eq!(a.world().resource::<TestFlush>().0, 11);
6194        a.despawn();
6195        assert_eq!(world.resource::<TestFlush>().0, 12);
6196    }
6197
6198    #[derive(Resource)]
6199    struct TestVec(Vec<&'static str>);
6200
6201    #[derive(Component)]
6202    #[component(on_add = ord_a_hook_on_add, on_insert = ord_a_hook_on_insert, on_replace = ord_a_hook_on_replace, on_remove = ord_a_hook_on_remove)]
6203    struct OrdA;
6204
6205    fn ord_a_hook_on_add(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
6206        world.resource_mut::<TestVec>().0.push("OrdA hook on_add");
6207        world.commands().entity(entity).insert(OrdB);
6208    }
6209
6210    fn ord_a_hook_on_insert(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
6211        world
6212            .resource_mut::<TestVec>()
6213            .0
6214            .push("OrdA hook on_insert");
6215        world.commands().entity(entity).remove::<OrdA>();
6216        world.commands().entity(entity).remove::<OrdB>();
6217    }
6218
6219    fn ord_a_hook_on_replace(mut world: DeferredWorld, _: HookContext) {
6220        world
6221            .resource_mut::<TestVec>()
6222            .0
6223            .push("OrdA hook on_replace");
6224    }
6225
6226    fn ord_a_hook_on_remove(mut world: DeferredWorld, _: HookContext) {
6227        world
6228            .resource_mut::<TestVec>()
6229            .0
6230            .push("OrdA hook on_remove");
6231    }
6232
6233    fn ord_a_observer_on_add(_event: On<Add, OrdA>, mut res: ResMut<TestVec>) {
6234        res.0.push("OrdA observer on_add");
6235    }
6236
6237    fn ord_a_observer_on_insert(_event: On<Insert, OrdA>, mut res: ResMut<TestVec>) {
6238        res.0.push("OrdA observer on_insert");
6239    }
6240
6241    fn ord_a_observer_on_replace(_event: On<Replace, OrdA>, mut res: ResMut<TestVec>) {
6242        res.0.push("OrdA observer on_replace");
6243    }
6244
6245    fn ord_a_observer_on_remove(_event: On<Remove, OrdA>, mut res: ResMut<TestVec>) {
6246        res.0.push("OrdA observer on_remove");
6247    }
6248
6249    #[derive(Component)]
6250    #[component(on_add = ord_b_hook_on_add, on_insert = ord_b_hook_on_insert, on_replace = ord_b_hook_on_replace, on_remove = ord_b_hook_on_remove)]
6251    struct OrdB;
6252
6253    fn ord_b_hook_on_add(mut world: DeferredWorld, _: HookContext) {
6254        world.resource_mut::<TestVec>().0.push("OrdB hook on_add");
6255        world.commands().queue(|world: &mut World| {
6256            world
6257                .resource_mut::<TestVec>()
6258                .0
6259                .push("OrdB command on_add");
6260        });
6261    }
6262
6263    fn ord_b_hook_on_insert(mut world: DeferredWorld, _: HookContext) {
6264        world
6265            .resource_mut::<TestVec>()
6266            .0
6267            .push("OrdB hook on_insert");
6268    }
6269
6270    fn ord_b_hook_on_replace(mut world: DeferredWorld, _: HookContext) {
6271        world
6272            .resource_mut::<TestVec>()
6273            .0
6274            .push("OrdB hook on_replace");
6275    }
6276
6277    fn ord_b_hook_on_remove(mut world: DeferredWorld, _: HookContext) {
6278        world
6279            .resource_mut::<TestVec>()
6280            .0
6281            .push("OrdB hook on_remove");
6282    }
6283
6284    fn ord_b_observer_on_add(_event: On<Add, OrdB>, mut res: ResMut<TestVec>) {
6285        res.0.push("OrdB observer on_add");
6286    }
6287
6288    fn ord_b_observer_on_insert(_event: On<Insert, OrdB>, mut res: ResMut<TestVec>) {
6289        res.0.push("OrdB observer on_insert");
6290    }
6291
6292    fn ord_b_observer_on_replace(_event: On<Replace, OrdB>, mut res: ResMut<TestVec>) {
6293        res.0.push("OrdB observer on_replace");
6294    }
6295
6296    fn ord_b_observer_on_remove(_event: On<Remove, OrdB>, mut res: ResMut<TestVec>) {
6297        res.0.push("OrdB observer on_remove");
6298    }
6299
6300    #[test]
6301    fn command_ordering_is_correct() {
6302        let mut world = World::new();
6303        world.insert_resource(TestVec(Vec::new()));
6304        world.add_observer(ord_a_observer_on_add);
6305        world.add_observer(ord_a_observer_on_insert);
6306        world.add_observer(ord_a_observer_on_replace);
6307        world.add_observer(ord_a_observer_on_remove);
6308        world.add_observer(ord_b_observer_on_add);
6309        world.add_observer(ord_b_observer_on_insert);
6310        world.add_observer(ord_b_observer_on_replace);
6311        world.add_observer(ord_b_observer_on_remove);
6312        let _entity = world.spawn(OrdA).id();
6313        let expected = [
6314            "OrdA hook on_add", // adds command to insert OrdB
6315            "OrdA observer on_add",
6316            "OrdA hook on_insert", // adds command to despawn entity
6317            "OrdA observer on_insert",
6318            "OrdB hook on_add", // adds command to just add to this log
6319            "OrdB observer on_add",
6320            "OrdB hook on_insert",
6321            "OrdB observer on_insert",
6322            "OrdB command on_add", // command added by OrdB hook on_add, needs to run before despawn command
6323            "OrdA observer on_replace", // start of despawn
6324            "OrdA hook on_replace",
6325            "OrdA observer on_remove",
6326            "OrdA hook on_remove",
6327            "OrdB observer on_replace",
6328            "OrdB hook on_replace",
6329            "OrdB observer on_remove",
6330            "OrdB hook on_remove",
6331        ];
6332        world.flush();
6333        assert_eq!(world.resource_mut::<TestVec>().0.as_slice(), &expected[..]);
6334    }
6335
6336    #[test]
6337    fn entity_world_mut_clone_and_move_components() {
6338        #[derive(Component, Clone, PartialEq, Debug)]
6339        struct A;
6340
6341        #[derive(Component, Clone, PartialEq, Debug)]
6342        struct B;
6343
6344        #[derive(Component, Clone, PartialEq, Debug)]
6345        struct C(u32);
6346
6347        let mut world = World::new();
6348        let entity_a = world.spawn((A, B, C(5))).id();
6349        let entity_b = world.spawn((A, C(4))).id();
6350
6351        world.entity_mut(entity_a).clone_components::<B>(entity_b);
6352        assert_eq!(world.entity(entity_a).get::<B>(), Some(&B));
6353        assert_eq!(world.entity(entity_b).get::<B>(), Some(&B));
6354
6355        world.entity_mut(entity_a).move_components::<C>(entity_b);
6356        assert_eq!(world.entity(entity_a).get::<C>(), None);
6357        assert_eq!(world.entity(entity_b).get::<C>(), Some(&C(5)));
6358
6359        assert_eq!(world.entity(entity_a).get::<A>(), Some(&A));
6360        assert_eq!(world.entity(entity_b).get::<A>(), Some(&A));
6361    }
6362
6363    #[test]
6364    fn entity_world_mut_clone_with_move_and_require() {
6365        #[derive(Component, Clone, PartialEq, Debug)]
6366        #[require(B(3))]
6367        struct A;
6368
6369        #[derive(Component, Clone, PartialEq, Debug, Default)]
6370        #[require(C(3))]
6371        struct B(u32);
6372
6373        #[derive(Component, Clone, PartialEq, Debug, Default)]
6374        #[require(D)]
6375        struct C(u32);
6376
6377        #[derive(Component, Clone, PartialEq, Debug, Default)]
6378        struct D;
6379
6380        let mut world = World::new();
6381        let entity_a = world.spawn((A, B(5))).id();
6382        let entity_b = world.spawn_empty().id();
6383
6384        world
6385            .entity_mut(entity_a)
6386            .clone_with_opt_in(entity_b, |builder| {
6387                builder
6388                    .move_components(true)
6389                    .allow::<C>()
6390                    .without_required_components(|builder| {
6391                        builder.allow::<A>();
6392                    });
6393            });
6394
6395        assert_eq!(world.entity(entity_a).get::<A>(), None);
6396        assert_eq!(world.entity(entity_b).get::<A>(), Some(&A));
6397
6398        assert_eq!(world.entity(entity_a).get::<B>(), Some(&B(5)));
6399        assert_eq!(world.entity(entity_b).get::<B>(), Some(&B(3)));
6400
6401        assert_eq!(world.entity(entity_a).get::<C>(), None);
6402        assert_eq!(world.entity(entity_b).get::<C>(), Some(&C(3)));
6403
6404        assert_eq!(world.entity(entity_a).get::<D>(), None);
6405        assert_eq!(world.entity(entity_b).get::<D>(), Some(&D));
6406    }
6407
6408    #[test]
6409    fn update_despawned_by_after_observers() {
6410        let mut world = World::new();
6411
6412        #[derive(Component)]
6413        #[component(on_remove = get_tracked)]
6414        struct C;
6415
6416        static TRACKED: OnceLock<(MaybeLocation, Tick)> = OnceLock::new();
6417        fn get_tracked(world: DeferredWorld, HookContext { entity, .. }: HookContext) {
6418            TRACKED.get_or_init(|| {
6419                let by = world
6420                    .entities
6421                    .entity_get_spawned_or_despawned_by(entity)
6422                    .map(|l| l.unwrap());
6423                let at = world
6424                    .entities
6425                    .entity_get_spawn_or_despawn_tick(entity)
6426                    .unwrap();
6427                (by, at)
6428            });
6429        }
6430
6431        #[track_caller]
6432        fn caller_spawn(world: &mut World) -> (Entity, MaybeLocation, Tick) {
6433            let caller = MaybeLocation::caller();
6434            (world.spawn(C).id(), caller, world.change_tick())
6435        }
6436        let (entity, spawner, spawn_tick) = caller_spawn(&mut world);
6437
6438        assert_eq!(
6439            spawner,
6440            world
6441                .entities()
6442                .entity_get_spawned_or_despawned_by(entity)
6443                .map(|l| l.unwrap())
6444        );
6445
6446        #[track_caller]
6447        fn caller_despawn(world: &mut World, entity: Entity) -> (MaybeLocation, Tick) {
6448            world.despawn(entity);
6449            (MaybeLocation::caller(), world.change_tick())
6450        }
6451        let (despawner, despawn_tick) = caller_despawn(&mut world, entity);
6452
6453        assert_eq!((spawner, spawn_tick), *TRACKED.get().unwrap());
6454        assert_eq!(
6455            despawner,
6456            world
6457                .entities()
6458                .entity_get_spawned_or_despawned_by(entity)
6459                .map(|l| l.unwrap())
6460        );
6461        assert_eq!(
6462            despawn_tick,
6463            world
6464                .entities()
6465                .entity_get_spawn_or_despawn_tick(entity)
6466                .unwrap()
6467        );
6468    }
6469
6470    #[test]
6471    fn with_component_activates_hooks() {
6472        use core::sync::atomic::{AtomicBool, AtomicU8, Ordering};
6473
6474        #[derive(Component, PartialEq, Eq, Debug)]
6475        #[component(immutable)]
6476        struct Foo(bool);
6477
6478        static EXPECTED_VALUE: AtomicBool = AtomicBool::new(false);
6479
6480        static ADD_COUNT: AtomicU8 = AtomicU8::new(0);
6481        static REMOVE_COUNT: AtomicU8 = AtomicU8::new(0);
6482        static REPLACE_COUNT: AtomicU8 = AtomicU8::new(0);
6483        static INSERT_COUNT: AtomicU8 = AtomicU8::new(0);
6484
6485        let mut world = World::default();
6486
6487        world.register_component::<Foo>();
6488        world
6489            .register_component_hooks::<Foo>()
6490            .on_add(|world, context| {
6491                ADD_COUNT.fetch_add(1, Ordering::Relaxed);
6492
6493                assert_eq!(
6494                    world.get(context.entity),
6495                    Some(&Foo(EXPECTED_VALUE.load(Ordering::Relaxed)))
6496                );
6497            })
6498            .on_remove(|world, context| {
6499                REMOVE_COUNT.fetch_add(1, Ordering::Relaxed);
6500
6501                assert_eq!(
6502                    world.get(context.entity),
6503                    Some(&Foo(EXPECTED_VALUE.load(Ordering::Relaxed)))
6504                );
6505            })
6506            .on_replace(|world, context| {
6507                REPLACE_COUNT.fetch_add(1, Ordering::Relaxed);
6508
6509                assert_eq!(
6510                    world.get(context.entity),
6511                    Some(&Foo(EXPECTED_VALUE.load(Ordering::Relaxed)))
6512                );
6513            })
6514            .on_insert(|world, context| {
6515                INSERT_COUNT.fetch_add(1, Ordering::Relaxed);
6516
6517                assert_eq!(
6518                    world.get(context.entity),
6519                    Some(&Foo(EXPECTED_VALUE.load(Ordering::Relaxed)))
6520                );
6521            });
6522
6523        let entity = world.spawn(Foo(false)).id();
6524
6525        assert_eq!(ADD_COUNT.load(Ordering::Relaxed), 1);
6526        assert_eq!(REMOVE_COUNT.load(Ordering::Relaxed), 0);
6527        assert_eq!(REPLACE_COUNT.load(Ordering::Relaxed), 0);
6528        assert_eq!(INSERT_COUNT.load(Ordering::Relaxed), 1);
6529
6530        let mut entity = world.entity_mut(entity);
6531
6532        let archetype_pointer_before = &raw const *entity.archetype();
6533
6534        assert_eq!(entity.get::<Foo>(), Some(&Foo(false)));
6535
6536        entity.modify_component(|foo: &mut Foo| {
6537            foo.0 = true;
6538            EXPECTED_VALUE.store(foo.0, Ordering::Relaxed);
6539        });
6540
6541        let archetype_pointer_after = &raw const *entity.archetype();
6542
6543        assert_eq!(entity.get::<Foo>(), Some(&Foo(true)));
6544
6545        assert_eq!(ADD_COUNT.load(Ordering::Relaxed), 1);
6546        assert_eq!(REMOVE_COUNT.load(Ordering::Relaxed), 0);
6547        assert_eq!(REPLACE_COUNT.load(Ordering::Relaxed), 1);
6548        assert_eq!(INSERT_COUNT.load(Ordering::Relaxed), 2);
6549
6550        assert_eq!(archetype_pointer_before, archetype_pointer_after);
6551    }
6552
6553    #[test]
6554    fn bundle_remove_only_triggers_for_present_components() {
6555        let mut world = World::default();
6556
6557        #[derive(Component)]
6558        struct A;
6559
6560        #[derive(Component)]
6561        struct B;
6562
6563        #[derive(Resource, PartialEq, Eq, Debug)]
6564        struct Tracker {
6565            a: bool,
6566            b: bool,
6567        }
6568
6569        world.insert_resource(Tracker { a: false, b: false });
6570        let entity = world.spawn(A).id();
6571
6572        world.add_observer(|_: On<Remove, A>, mut tracker: ResMut<Tracker>| {
6573            tracker.a = true;
6574        });
6575        world.add_observer(|_: On<Remove, B>, mut tracker: ResMut<Tracker>| {
6576            tracker.b = true;
6577        });
6578
6579        world.entity_mut(entity).remove::<(A, B)>();
6580
6581        assert_eq!(
6582            world.resource::<Tracker>(),
6583            &Tracker {
6584                a: true,
6585                // The entity didn't have a B component, so it should not have been triggered.
6586                b: false,
6587            }
6588        );
6589    }
6590
6591    #[test]
6592    fn spawned_after_swap_remove() {
6593        #[derive(Component)]
6594        struct Marker;
6595
6596        let mut world = World::new();
6597        let id1 = world.spawn(Marker).id();
6598        let _id2 = world.spawn(Marker).id();
6599        let id3 = world.spawn(Marker).id();
6600
6601        #[cfg(feature = "track_location")]
6602        let e1_spawned = world.entity(id1).spawned_by();
6603
6604        let spawn = world.entity(id3).spawned_by();
6605        world.entity_mut(id1).despawn();
6606        #[cfg(feature = "track_location")]
6607        let e1_despawned = world.entities().entity_get_spawned_or_despawned_by(id1);
6608        #[cfg(feature = "track_location")]
6609        assert_ne!(e1_spawned.map(Some), e1_despawned);
6610
6611        let spawn_after = world.entity(id3).spawned_by();
6612        assert_eq!(spawn, spawn_after);
6613    }
6614
6615    #[test]
6616    fn spawned_by_set_before_flush() {
6617        #[derive(Component)]
6618        #[component(on_despawn = on_despawn)]
6619        struct C;
6620
6621        fn on_despawn(mut world: DeferredWorld, context: HookContext) {
6622            let spawned = world.entity(context.entity).spawned_by();
6623            world.commands().queue(move |world: &mut World| {
6624                // The entity has finished despawning...
6625                assert!(world.get_entity(context.entity).is_err());
6626                let despawned = world
6627                    .entities()
6628                    .entity_get_spawned_or_despawned_by(context.entity);
6629                // These assertions are only possible if the `track_location` feature is enabled
6630                if let (Some(spawned), Some(despawned)) =
6631                    (spawned.into_option(), despawned.into_option())
6632                {
6633                    // ... so ensure that `despawned_by` has been written
6634                    assert!(despawned.is_some());
6635                    assert_ne!(Some(spawned), despawned);
6636                }
6637            });
6638        }
6639
6640        let mut world = World::new();
6641        let original = world.spawn(C).id();
6642        world.despawn(original);
6643    }
6644}