bevy_ecs/world/entity_access/
world_mut.rs

1use crate::{
2    archetype::Archetype,
3    bundle::{
4        Bundle, BundleFromComponents, BundleInserter, BundleRemover, DynamicBundle, InsertMode,
5    },
6    change_detection::{ComponentTicks, MaybeLocation, MutUntyped, Tick},
7    component::{Component, ComponentId, Components, Mutable, StorageType},
8    entity::{Entity, EntityCloner, EntityClonerBuilder, EntityLocation, OptIn, OptOut},
9    event::{EntityComponentsTrigger, EntityEvent},
10    lifecycle::{Despawn, Remove, Replace, DESPAWN, REMOVE, REPLACE},
11    observer::Observer,
12    query::{
13        has_conflicts, Access, DebugCheckedUnwrap, QueryAccessError, ReadOnlyQueryData,
14        ReleaseStateQueryData,
15    },
16    relationship::RelationshipHookMode,
17    resource::Resource,
18    storage::{SparseSets, Table},
19    system::IntoObserverSystem,
20    world::{
21        error::EntityComponentError, unsafe_world_cell::UnsafeEntityCell, ComponentEntry,
22        DynamicComponentFetch, EntityMut, EntityRef, FilteredEntityMut, FilteredEntityRef, Mut,
23        OccupiedComponentEntry, Ref, VacantComponentEntry, World,
24    },
25};
26
27use alloc::vec::Vec;
28use bevy_ptr::{move_as_ptr, MovingPtr, OwningPtr};
29use core::{any::TypeId, marker::PhantomData, mem::MaybeUninit};
30
31/// A mutable reference to a particular [`Entity`], and the entire world.
32///
33/// This is essentially a performance-optimized `(Entity, &mut World)` tuple,
34/// which caches the [`EntityLocation`] to reduce duplicate lookups.
35///
36/// Since this type provides mutable access to the entire world, only one
37/// [`EntityWorldMut`] can exist at a time for a given world.
38///
39/// See also [`EntityMut`], which allows disjoint mutable access to multiple
40/// entities at once.  Unlike `EntityMut`, this type allows adding and
41/// removing components, and despawning the entity.
42///
43/// # Invariants and Risk
44///
45/// An [`EntityWorldMut`] may point to a despawned entity.
46/// You can check this via [`is_despawned`](Self::is_despawned).
47/// Using an [`EntityWorldMut`] of a despawned entity may panic in some contexts, so read method documentation carefully.
48///
49/// Unless you have strong reason to assume these invariants, you should generally avoid keeping an [`EntityWorldMut`] to an entity that is potentially not spawned.
50/// For example, when inserting a component, that component insert may trigger an observer that despawns the entity.
51/// So, when you don't have full knowledge of what commands may interact with this entity,
52/// do not further use this value without first checking [`is_despawned`](Self::is_despawned).
53pub struct EntityWorldMut<'w> {
54    world: &'w mut World,
55    entity: Entity,
56    location: Option<EntityLocation>,
57}
58
59impl<'w> EntityWorldMut<'w> {
60    #[track_caller]
61    #[inline(never)]
62    #[cold]
63    fn panic_despawned(&self) -> ! {
64        panic!(
65            "Entity {} {}",
66            self.entity,
67            self.world.entities().get_spawned(self.entity).unwrap_err()
68        );
69    }
70
71    #[inline(always)]
72    #[track_caller]
73    pub(crate) fn assert_not_despawned(&self) {
74        if self.location.is_none() {
75            self.panic_despawned()
76        }
77    }
78
79    #[inline(always)]
80    fn as_unsafe_entity_cell_readonly(&self) -> UnsafeEntityCell<'_> {
81        let location = self.location();
82        let last_change_tick = self.world.last_change_tick;
83        let change_tick = self.world.read_change_tick();
84        UnsafeEntityCell::new(
85            self.world.as_unsafe_world_cell_readonly(),
86            self.entity,
87            location,
88            last_change_tick,
89            change_tick,
90        )
91    }
92
93    #[inline(always)]
94    fn as_unsafe_entity_cell(&mut self) -> UnsafeEntityCell<'_> {
95        let location = self.location();
96        let last_change_tick = self.world.last_change_tick;
97        let change_tick = self.world.change_tick();
98        UnsafeEntityCell::new(
99            self.world.as_unsafe_world_cell(),
100            self.entity,
101            location,
102            last_change_tick,
103            change_tick,
104        )
105    }
106
107    #[inline(always)]
108    fn into_unsafe_entity_cell(self) -> UnsafeEntityCell<'w> {
109        let location = self.location();
110        let last_change_tick = self.world.last_change_tick;
111        let change_tick = self.world.change_tick();
112        UnsafeEntityCell::new(
113            self.world.as_unsafe_world_cell(),
114            self.entity,
115            location,
116            last_change_tick,
117            change_tick,
118        )
119    }
120
121    /// # Safety
122    ///
123    ///  The `location` must be sourced from `world`'s `Entities` and must exactly match the location for `entity`.
124    ///  If the `entity` is not spawned for any reason (See [`EntityNotSpawnedError`](crate::entity::EntityNotSpawnedError)), the location should be `None`.
125    ///
126    ///  The above is trivially satisfied if `location` was sourced from `world.entities().get_spawned(entity).ok()`.
127    #[inline]
128    pub(crate) unsafe fn new(
129        world: &'w mut World,
130        entity: Entity,
131        location: Option<EntityLocation>,
132    ) -> Self {
133        debug_assert_eq!(world.entities().get_spawned(entity).ok(), location);
134
135        EntityWorldMut {
136            world,
137            entity,
138            location,
139        }
140    }
141
142    /// Consumes `self` and returns read-only access to all of the entity's
143    /// components, with the world `'w` lifetime.
144    pub fn into_readonly(self) -> EntityRef<'w> {
145        EntityRef::from(self)
146    }
147
148    /// Gets read-only access to all of the entity's components.
149    #[inline]
150    pub fn as_readonly(&self) -> EntityRef<'_> {
151        EntityRef::from(self)
152    }
153
154    /// Consumes `self` and returns non-structural mutable access to all of the
155    /// entity's components, with the world `'w` lifetime.
156    pub fn into_mutable(self) -> EntityMut<'w> {
157        EntityMut::from(self)
158    }
159
160    /// Gets non-structural mutable access to all of the entity's components.
161    #[inline]
162    pub fn as_mutable(&mut self) -> EntityMut<'_> {
163        EntityMut::from(self)
164    }
165
166    /// Returns the [ID](Entity) of the current entity.
167    #[inline]
168    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
169    pub fn id(&self) -> Entity {
170        self.entity
171    }
172
173    /// Gets metadata indicating the location where the current entity is stored.
174    #[inline]
175    pub fn try_location(&self) -> Option<EntityLocation> {
176        self.location
177    }
178
179    /// Returns if the entity is spawned or not.
180    #[inline]
181    pub fn is_spawned(&self) -> bool {
182        self.try_location().is_some()
183    }
184
185    /// Returns the archetype that the current entity belongs to.
186    #[inline]
187    pub fn try_archetype(&self) -> Option<&Archetype> {
188        self.try_location()
189            .map(|location| &self.world.archetypes[location.archetype_id])
190    }
191
192    /// Gets metadata indicating the location where the current entity is stored.
193    ///
194    /// # Panics
195    ///
196    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
197    #[inline]
198    pub fn location(&self) -> EntityLocation {
199        match self.try_location() {
200            Some(a) => a,
201            None => self.panic_despawned(),
202        }
203    }
204
205    /// Returns the archetype that the current entity belongs to.
206    ///
207    /// # Panics
208    ///
209    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
210    #[inline]
211    pub fn archetype(&self) -> &Archetype {
212        match self.try_archetype() {
213            Some(a) => a,
214            None => self.panic_despawned(),
215        }
216    }
217
218    /// Returns `true` if the current entity has a component of type `T`.
219    /// Otherwise, this returns `false`.
220    ///
221    /// ## Notes
222    ///
223    /// If you do not know the concrete type of a component, consider using
224    /// [`Self::contains_id`] or [`Self::contains_type_id`].
225    ///
226    /// # Panics
227    ///
228    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
229    #[inline]
230    pub fn contains<T: Component>(&self) -> bool {
231        self.contains_type_id(TypeId::of::<T>())
232    }
233
234    /// Returns `true` if the current entity has a component identified by `component_id`.
235    /// Otherwise, this returns false.
236    ///
237    /// ## Notes
238    ///
239    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
240    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
241    ///   [`Self::contains_type_id`].
242    ///
243    /// # Panics
244    ///
245    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
246    #[inline]
247    pub fn contains_id(&self, component_id: ComponentId) -> bool {
248        self.as_unsafe_entity_cell_readonly()
249            .contains_id(component_id)
250    }
251
252    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
253    /// Otherwise, this returns false.
254    ///
255    /// ## Notes
256    ///
257    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
258    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
259    ///
260    /// # Panics
261    ///
262    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
263    #[inline]
264    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
265        self.as_unsafe_entity_cell_readonly()
266            .contains_type_id(type_id)
267    }
268
269    /// Gets access to the component of type `T` for the current entity.
270    /// Returns `None` if the entity does not have a component of type `T`.
271    ///
272    /// # Panics
273    ///
274    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
275    #[inline]
276    pub fn get<T: Component>(&self) -> Option<&'_ T> {
277        self.as_readonly().get()
278    }
279
280    /// Returns read-only components for the current entity that match the query `Q`.
281    ///
282    /// # Panics
283    ///
284    /// If the entity does not have the components required by the query `Q` or if the entity
285    /// has been despawned while this `EntityWorldMut` is still alive.
286    #[inline]
287    pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(&self) -> Q::Item<'_, 'static> {
288        self.as_readonly().components::<Q>()
289    }
290
291    /// Returns read-only components for the current entity that match the query `Q`,
292    /// or `None` if the entity does not have the components required by the query `Q`.
293    ///
294    /// # Panics
295    ///
296    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
297    #[inline]
298    pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData>(
299        &self,
300    ) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
301        self.as_readonly().get_components::<Q>()
302    }
303
304    /// Returns components for the current entity that match the query `Q`,
305    /// or `None` if the entity does not have the components required by the query `Q`.
306    ///
307    /// # Example
308    ///
309    /// ```
310    /// # use bevy_ecs::prelude::*;
311    /// #
312    /// #[derive(Component)]
313    /// struct X(usize);
314    /// #[derive(Component)]
315    /// struct Y(usize);
316    ///
317    /// # let mut world = World::default();
318    /// let mut entity = world.spawn((X(0), Y(0)));
319    /// // Get mutable access to two components at once
320    /// // SAFETY: X and Y are different components
321    /// let (mut x, mut y) =
322    ///     unsafe { entity.get_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
323    /// *x = X(1);
324    /// *y = Y(1);
325    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
326    /// // entity.get_components_mut_unchecked::<(&mut X, &mut X)>();
327    /// ```
328    ///
329    /// # Safety
330    /// It is the caller's responsibility to ensure that
331    /// the `QueryData` does not provide aliasing mutable references to the same component.
332    ///
333    /// /// # See also
334    ///
335    /// - [`Self::get_components_mut`] for the safe version that performs aliasing checks
336    pub unsafe fn get_components_mut_unchecked<Q: ReleaseStateQueryData>(
337        &mut self,
338    ) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
339        // SAFETY: Caller the `QueryData` does not provide aliasing mutable references to the same component
340        unsafe { self.as_mutable().into_components_mut_unchecked::<Q>() }
341    }
342
343    /// Returns components for the current entity that match the query `Q`.
344    /// In the case of conflicting [`QueryData`](crate::query::QueryData), unregistered components, or missing components,
345    /// this will return a [`QueryAccessError`]
346    ///
347    /// # Example
348    ///
349    /// ```
350    /// # use bevy_ecs::prelude::*;
351    /// #
352    /// #[derive(Component)]
353    /// struct X(usize);
354    /// #[derive(Component)]
355    /// struct Y(usize);
356    ///
357    /// # let mut world = World::default();
358    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
359    /// // Get mutable access to two components at once
360    /// // SAFETY: X and Y are different components
361    /// let (mut x, mut y) = entity.get_components_mut::<(&mut X, &mut Y)>().unwrap();
362    /// ```
363    ///
364    /// Note that this does a O(n^2) check that the [`QueryData`](crate::query::QueryData) does not conflict. If performance is a
365    /// consideration you should use [`Self::get_components_mut_unchecked`] instead.
366    pub fn get_components_mut<Q: ReleaseStateQueryData>(
367        &mut self,
368    ) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
369        self.as_mutable().into_components_mut::<Q>()
370    }
371
372    /// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
373    /// or `None` if the entity does not have the components required by the query `Q`.
374    ///
375    /// # Example
376    ///
377    /// ```
378    /// # use bevy_ecs::prelude::*;
379    /// #
380    /// #[derive(Component)]
381    /// struct X(usize);
382    /// #[derive(Component)]
383    /// struct Y(usize);
384    ///
385    /// # let mut world = World::default();
386    /// let mut entity = world.spawn((X(0), Y(0)));
387    /// // Get mutable access to two components at once
388    /// // SAFETY: X and Y are different components
389    /// let (mut x, mut y) =
390    ///     unsafe { entity.into_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
391    /// *x = X(1);
392    /// *y = Y(1);
393    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
394    /// // entity.into_components_mut_unchecked::<(&mut X, &mut X)>();
395    /// ```
396    ///
397    /// # Safety
398    /// It is the caller's responsibility to ensure that
399    /// the `QueryData` does not provide aliasing mutable references to the same component.
400    ///
401    /// # See also
402    ///
403    /// - [`Self::into_components_mut`] for the safe version that performs aliasing checks
404    pub unsafe fn into_components_mut_unchecked<Q: ReleaseStateQueryData>(
405        self,
406    ) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
407        // SAFETY: Caller the `QueryData` does not provide aliasing mutable references to the same component
408        unsafe { self.into_mutable().into_components_mut_unchecked::<Q>() }
409    }
410
411    /// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
412    /// or `None` if the entity does not have the components required by the query `Q`.
413    ///
414    /// The checks for aliasing mutable references may be expensive.
415    /// If performance is a concern, consider making multiple calls to [`Self::get_mut`].
416    /// If that is not possible, consider using [`Self::into_components_mut_unchecked`] to skip the checks.
417    ///
418    /// # Panics
419    ///
420    /// - If the `QueryData` provides aliasing mutable references to the same component.
421    /// - If the entity has been despawned while this `EntityWorldMut` is still alive.
422    ///
423    /// # Example
424    ///
425    /// ```
426    /// # use bevy_ecs::prelude::*;
427    /// #
428    /// #[derive(Component)]
429    /// struct X(usize);
430    /// #[derive(Component)]
431    /// struct Y(usize);
432    ///
433    /// # let mut world = World::default();
434    /// let mut entity = world.spawn((X(0), Y(0)));
435    /// // Get mutable access to two components at once
436    /// let (mut x, mut y) = entity.into_components_mut::<(&mut X, &mut Y)>().unwrap();
437    /// *x = X(1);
438    /// *y = Y(1);
439    /// ```
440    ///
441    /// ```should_panic
442    /// # use bevy_ecs::prelude::*;
443    /// #
444    /// # #[derive(Component)]
445    /// # struct X(usize);
446    /// #
447    /// # let mut world = World::default();
448    /// let mut entity = world.spawn((X(0)));
449    /// // This panics, as the `&mut X`s would alias:
450    /// entity.into_components_mut::<(&mut X, &mut X)>();
451    /// ```
452    pub fn into_components_mut<Q: ReleaseStateQueryData>(
453        self,
454    ) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
455        has_conflicts::<Q>(self.world.components())?;
456        // SAFETY: we checked that there were not conflicting components above
457        unsafe { self.into_mutable().into_components_mut_unchecked::<Q>() }
458    }
459
460    /// Consumes `self` and gets access to the component of type `T` with
461    /// the world `'w` lifetime for the current entity.
462    /// Returns `None` if the entity does not have a component of type `T`.
463    ///
464    /// # Panics
465    ///
466    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
467    #[inline]
468    pub fn into_borrow<T: Component>(self) -> Option<&'w T> {
469        self.into_readonly().get()
470    }
471
472    /// Gets access to the component of type `T` for the current entity,
473    /// including change detection information as a [`Ref`].
474    ///
475    /// Returns `None` if the entity does not have a component of type `T`.
476    ///
477    /// # Panics
478    ///
479    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
480    #[inline]
481    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
482        self.as_readonly().get_ref()
483    }
484
485    /// Consumes `self` and gets access to the component of type `T`
486    /// with the world `'w` lifetime for the current entity,
487    /// including change detection information as a [`Ref`].
488    ///
489    /// Returns `None` if the entity does not have a component of type `T`.
490    ///
491    /// # Panics
492    ///
493    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
494    #[inline]
495    pub fn into_ref<T: Component>(self) -> Option<Ref<'w, T>> {
496        self.into_readonly().get_ref()
497    }
498
499    /// Gets mutable access to the component of type `T` for the current entity.
500    /// Returns `None` if the entity does not have a component of type `T`.
501    ///
502    /// # Panics
503    ///
504    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
505    #[inline]
506    pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
507        self.as_mutable().into_mut()
508    }
509
510    /// Temporarily removes a [`Component`] `T` from this [`Entity`] and runs the
511    /// provided closure on it, returning the result if `T` was available.
512    /// This will trigger the `Remove` and `Replace` component hooks without
513    /// causing an archetype move.
514    ///
515    /// This is most useful with immutable components, where removal and reinsertion
516    /// is the only way to modify a value.
517    ///
518    /// If you do not need to ensure the above hooks are triggered, and your component
519    /// is mutable, prefer using [`get_mut`](EntityWorldMut::get_mut).
520    ///
521    /// # Examples
522    ///
523    /// ```rust
524    /// # use bevy_ecs::prelude::*;
525    /// #
526    /// #[derive(Component, PartialEq, Eq, Debug)]
527    /// #[component(immutable)]
528    /// struct Foo(bool);
529    ///
530    /// # let mut world = World::default();
531    /// # world.register_component::<Foo>();
532    /// #
533    /// # let entity = world.spawn(Foo(false)).id();
534    /// #
535    /// # let mut entity = world.entity_mut(entity);
536    /// #
537    /// # assert_eq!(entity.get::<Foo>(), Some(&Foo(false)));
538    /// #
539    /// entity.modify_component(|foo: &mut Foo| {
540    ///     foo.0 = true;
541    /// });
542    /// #
543    /// # assert_eq!(entity.get::<Foo>(), Some(&Foo(true)));
544    /// ```
545    ///
546    /// # Panics
547    ///
548    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
549    #[inline]
550    pub fn modify_component<T: Component, R>(&mut self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
551        self.assert_not_despawned();
552
553        let result = self
554            .world
555            .modify_component(self.entity, f)
556            .expect("entity access must be valid")?;
557
558        self.update_location();
559
560        Some(result)
561    }
562
563    /// Temporarily removes a [`Component`] `T` from this [`Entity`] and runs the
564    /// provided closure on it, returning the result if `T` was available.
565    /// This will trigger the `Remove` and `Replace` component hooks without
566    /// causing an archetype move.
567    ///
568    /// This is most useful with immutable components, where removal and reinsertion
569    /// is the only way to modify a value.
570    ///
571    /// If you do not need to ensure the above hooks are triggered, and your component
572    /// is mutable, prefer using [`get_mut`](EntityWorldMut::get_mut).
573    ///
574    /// # Panics
575    ///
576    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
577    #[inline]
578    pub fn modify_component_by_id<R>(
579        &mut self,
580        component_id: ComponentId,
581        f: impl for<'a> FnOnce(MutUntyped<'a>) -> R,
582    ) -> Option<R> {
583        self.assert_not_despawned();
584
585        let result = self
586            .world
587            .modify_component_by_id(self.entity, component_id, f)
588            .expect("entity access must be valid")?;
589
590        self.update_location();
591
592        Some(result)
593    }
594
595    /// Gets mutable access to the component of type `T` for the current entity.
596    /// Returns `None` if the entity does not have a component of type `T`.
597    ///
598    /// # Safety
599    ///
600    /// - `T` must be a mutable component
601    #[inline]
602    pub unsafe fn get_mut_assume_mutable<T: Component>(&mut self) -> Option<Mut<'_, T>> {
603        self.as_mutable().into_mut_assume_mutable()
604    }
605
606    /// Consumes `self` and gets mutable access to the component of type `T`
607    /// with the world `'w` lifetime for the current entity.
608    /// Returns `None` if the entity does not have a component of type `T`.
609    ///
610    /// # Panics
611    ///
612    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
613    #[inline]
614    pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
615        // SAFETY: consuming `self` implies exclusive access
616        unsafe { self.into_unsafe_entity_cell().get_mut() }
617    }
618
619    /// Consumes `self` and gets mutable access to the component of type `T`
620    /// with the world `'w` lifetime for the current entity.
621    /// Returns `None` if the entity does not have a component of type `T`.
622    ///
623    /// # Panics
624    ///
625    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
626    ///
627    /// # Safety
628    ///
629    /// - `T` must be a mutable component
630    #[inline]
631    pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
632        // SAFETY: consuming `self` implies exclusive access
633        unsafe { self.into_unsafe_entity_cell().get_mut_assume_mutable() }
634    }
635
636    /// Gets a reference to the resource of the given type
637    ///
638    /// # Panics
639    ///
640    /// Panics if the resource does not exist.
641    /// Use [`get_resource`](EntityWorldMut::get_resource) instead if you want to handle this case.
642    #[inline]
643    #[track_caller]
644    pub fn resource<R: Resource>(&self) -> &R {
645        self.world.resource::<R>()
646    }
647
648    /// Gets a mutable reference to the resource of the given type
649    ///
650    /// # Panics
651    ///
652    /// Panics if the resource does not exist.
653    /// Use [`get_resource_mut`](World::get_resource_mut) instead if you want to handle this case.
654    ///
655    /// If you want to instead insert a value if the resource does not exist,
656    /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
657    #[inline]
658    #[track_caller]
659    pub fn resource_mut<R: Resource>(&mut self) -> Mut<'_, R> {
660        self.world.resource_mut::<R>()
661    }
662
663    /// Gets a reference to the resource of the given type if it exists
664    #[inline]
665    pub fn get_resource<R: Resource>(&self) -> Option<&R> {
666        self.world.get_resource()
667    }
668
669    /// Gets a mutable reference to the resource of the given type if it exists
670    #[inline]
671    pub fn get_resource_mut<R: Resource>(&mut self) -> Option<Mut<'_, R>> {
672        self.world.get_resource_mut()
673    }
674
675    /// Temporarily removes the requested resource from the [`World`], runs custom user code,
676    /// then re-adds the resource before returning.
677    ///
678    /// # Panics
679    ///
680    /// Panics if the resource does not exist.
681    /// Use [`try_resource_scope`](Self::try_resource_scope) instead if you want to handle this case.
682    ///
683    /// See [`World::resource_scope`] for further details.
684    #[track_caller]
685    pub fn resource_scope<R: Resource, U>(
686        &mut self,
687        f: impl FnOnce(&mut EntityWorldMut, Mut<R>) -> U,
688    ) -> U {
689        let id = self.id();
690        self.world_scope(|world| {
691            world.resource_scope(|world, res| {
692                // Acquiring a new EntityWorldMut here and using that instead of `self` is fine because
693                // the outer `world_scope` will handle updating our location if it gets changed by the user code
694                let mut this = world.entity_mut(id);
695                f(&mut this, res)
696            })
697        })
698    }
699
700    /// Temporarily removes the requested resource from the [`World`] if it exists, runs custom user code,
701    /// then re-adds the resource before returning. Returns `None` if the resource does not exist in the [`World`].
702    ///
703    /// See [`World::try_resource_scope`] for further details.
704    pub fn try_resource_scope<R: Resource, U>(
705        &mut self,
706        f: impl FnOnce(&mut EntityWorldMut, Mut<R>) -> U,
707    ) -> Option<U> {
708        let id = self.id();
709        self.world_scope(|world| {
710            world.try_resource_scope(|world, res| {
711                // Acquiring a new EntityWorldMut here and using that instead of `self` is fine because
712                // the outer `world_scope` will handle updating our location if it gets changed by the user code
713                let mut this = world.entity_mut(id);
714                f(&mut this, res)
715            })
716        })
717    }
718
719    /// Retrieves the change ticks for the given component. This can be useful for implementing change
720    /// detection in custom runtimes.
721    ///
722    /// # Panics
723    ///
724    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
725    #[inline]
726    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
727        self.as_readonly().get_change_ticks::<T>()
728    }
729
730    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
731    /// detection in custom runtimes.
732    ///
733    /// **You should prefer to use the typed API [`EntityWorldMut::get_change_ticks`] where possible and only
734    /// use this in cases where the actual component types are not known at
735    /// compile time.**
736    ///
737    /// # Panics
738    ///
739    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
740    #[inline]
741    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
742        self.as_readonly().get_change_ticks_by_id(component_id)
743    }
744
745    /// Returns untyped read-only reference(s) to component(s) for the
746    /// current entity, based on the given [`ComponentId`]s.
747    ///
748    /// **You should prefer to use the typed API [`EntityWorldMut::get`] where
749    /// possible and only use this in cases where the actual component types
750    /// are not known at compile time.**
751    ///
752    /// Unlike [`EntityWorldMut::get`], this returns untyped reference(s) to
753    /// component(s), and it's the job of the caller to ensure the correct
754    /// type(s) are dereferenced (if necessary).
755    ///
756    /// # Errors
757    ///
758    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
759    /// not have a component.
760    ///
761    /// # Examples
762    ///
763    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
764    ///
765    /// # Panics
766    ///
767    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
768    #[inline]
769    pub fn get_by_id<F: DynamicComponentFetch>(
770        &self,
771        component_ids: F,
772    ) -> Result<F::Ref<'_>, EntityComponentError> {
773        self.as_readonly().get_by_id(component_ids)
774    }
775
776    /// Consumes `self` and returns untyped read-only reference(s) to
777    /// component(s) with lifetime `'w` for the current entity, based on the
778    /// given [`ComponentId`]s.
779    ///
780    /// **You should prefer to use the typed API [`EntityWorldMut::into_borrow`]
781    /// where possible and only use this in cases where the actual component
782    /// types are not known at compile time.**
783    ///
784    /// Unlike [`EntityWorldMut::into_borrow`], this returns untyped reference(s) to
785    /// component(s), and it's the job of the caller to ensure the correct
786    /// type(s) are dereferenced (if necessary).
787    ///
788    /// # Errors
789    ///
790    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
791    /// not have a component.
792    ///
793    /// # Examples
794    ///
795    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
796    ///
797    /// # Panics
798    ///
799    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
800    #[inline]
801    pub fn into_borrow_by_id<F: DynamicComponentFetch>(
802        self,
803        component_ids: F,
804    ) -> Result<F::Ref<'w>, EntityComponentError> {
805        self.into_readonly().get_by_id(component_ids)
806    }
807
808    /// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
809    /// the current entity, based on the given [`ComponentId`]s.
810    ///
811    /// **You should prefer to use the typed API [`EntityWorldMut::get_mut`] where
812    /// possible and only use this in cases where the actual component types
813    /// are not known at compile time.**
814    ///
815    /// Unlike [`EntityWorldMut::get_mut`], this returns untyped reference(s) to
816    /// component(s), and it's the job of the caller to ensure the correct
817    /// type(s) are dereferenced (if necessary).
818    ///
819    /// # Errors
820    ///
821    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
822    ///   not have a component.
823    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
824    ///   is requested multiple times.
825    ///
826    /// # Examples
827    ///
828    /// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
829    ///
830    /// # Panics
831    ///
832    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
833    #[inline]
834    pub fn get_mut_by_id<F: DynamicComponentFetch>(
835        &mut self,
836        component_ids: F,
837    ) -> Result<F::Mut<'_>, EntityComponentError> {
838        self.as_mutable().into_mut_by_id(component_ids)
839    }
840
841    /// Returns [untyped mutable reference(s)](MutUntyped) to component(s) for
842    /// the current entity, based on the given [`ComponentId`]s.
843    /// Assumes the given [`ComponentId`]s refer to mutable components.
844    ///
845    /// **You should prefer to use the typed API [`EntityWorldMut::get_mut_assume_mutable`] where
846    /// possible and only use this in cases where the actual component types
847    /// are not known at compile time.**
848    ///
849    /// Unlike [`EntityWorldMut::get_mut_assume_mutable`], this returns untyped reference(s) to
850    /// component(s), and it's the job of the caller to ensure the correct
851    /// type(s) are dereferenced (if necessary).
852    ///
853    /// # Errors
854    ///
855    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
856    ///   not have a component.
857    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
858    ///   is requested multiple times.
859    ///
860    /// # Panics
861    ///
862    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
863    ///
864    /// # Safety
865    /// It is the callers responsibility to ensure that
866    /// - the provided [`ComponentId`]s must refer to mutable components.
867    #[inline]
868    pub unsafe fn get_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
869        &mut self,
870        component_ids: F,
871    ) -> Result<F::Mut<'_>, EntityComponentError> {
872        // SAFETY: Upheld by caller
873        unsafe {
874            self.as_mutable()
875                .into_mut_assume_mutable_by_id(component_ids)
876        }
877    }
878
879    /// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
880    /// to component(s) with lifetime `'w` for the current entity, based on the
881    /// given [`ComponentId`]s.
882    ///
883    /// **You should prefer to use the typed API [`EntityWorldMut::into_mut`] where
884    /// possible and only use this in cases where the actual component types
885    /// are not known at compile time.**
886    ///
887    /// Unlike [`EntityWorldMut::into_mut`], this returns untyped reference(s) to
888    /// component(s), and it's the job of the caller to ensure the correct
889    /// type(s) are dereferenced (if necessary).
890    ///
891    /// # Errors
892    ///
893    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
894    ///   not have a component.
895    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
896    ///   is requested multiple times.
897    ///
898    /// # Examples
899    ///
900    /// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
901    ///
902    /// # Panics
903    ///
904    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
905    #[inline]
906    pub fn into_mut_by_id<F: DynamicComponentFetch>(
907        self,
908        component_ids: F,
909    ) -> Result<F::Mut<'w>, EntityComponentError> {
910        self.into_mutable().into_mut_by_id(component_ids)
911    }
912
913    /// Consumes `self` and returns [untyped mutable reference(s)](MutUntyped)
914    /// to component(s) with lifetime `'w` for the current entity, based on the
915    /// given [`ComponentId`]s.
916    /// Assumes the given [`ComponentId`]s refer to mutable components.
917    ///
918    /// **You should prefer to use the typed API [`EntityWorldMut::into_mut_assume_mutable`] where
919    /// possible and only use this in cases where the actual component types
920    /// are not known at compile time.**
921    ///
922    /// Unlike [`EntityWorldMut::into_mut_assume_mutable`], this returns untyped reference(s) to
923    /// component(s), and it's the job of the caller to ensure the correct
924    /// type(s) are dereferenced (if necessary).
925    ///
926    /// # Errors
927    ///
928    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
929    ///   not have a component.
930    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
931    ///   is requested multiple times.
932    ///
933    /// # Panics
934    ///
935    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
936    ///
937    /// # Safety
938    /// It is the callers responsibility to ensure that
939    /// - the provided [`ComponentId`]s must refer to mutable components.
940    #[inline]
941    pub unsafe fn into_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
942        self,
943        component_ids: F,
944    ) -> Result<F::Mut<'w>, EntityComponentError> {
945        // SAFETY: Upheld by caller
946        unsafe {
947            self.into_mutable()
948                .into_mut_assume_mutable_by_id(component_ids)
949        }
950    }
951
952    /// Adds a [`Bundle`] of components to the entity.
953    ///
954    /// This will overwrite any previous value(s) of the same component type.
955    ///
956    /// # Panics
957    ///
958    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
959    #[track_caller]
960    pub fn insert<T: Bundle>(&mut self, bundle: T) -> &mut Self {
961        move_as_ptr!(bundle);
962        self.insert_with_caller(
963            bundle,
964            InsertMode::Replace,
965            MaybeLocation::caller(),
966            RelationshipHookMode::Run,
967        )
968    }
969
970    /// Adds a [`Bundle`] of components to the entity.
971    /// [`Relationship`](crate::relationship::Relationship) components in the bundle will follow the configuration
972    /// in `relationship_hook_mode`.
973    ///
974    /// This will overwrite any previous value(s) of the same component type.
975    ///
976    /// # Warning
977    ///
978    /// This can easily break the integrity of relationships. This is intended to be used for cloning and spawning code internals,
979    /// not most user-facing scenarios.
980    ///
981    /// # Panics
982    ///
983    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
984    #[track_caller]
985    pub fn insert_with_relationship_hook_mode<T: Bundle>(
986        &mut self,
987        bundle: T,
988        relationship_hook_mode: RelationshipHookMode,
989    ) -> &mut Self {
990        move_as_ptr!(bundle);
991        self.insert_with_caller(
992            bundle,
993            InsertMode::Replace,
994            MaybeLocation::caller(),
995            relationship_hook_mode,
996        )
997    }
998
999    /// Adds a [`Bundle`] of components to the entity without overwriting.
1000    ///
1001    /// This will leave any previous value(s) of the same component type
1002    /// unchanged.
1003    ///
1004    /// # Panics
1005    ///
1006    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1007    #[track_caller]
1008    pub fn insert_if_new<T: Bundle>(&mut self, bundle: T) -> &mut Self {
1009        move_as_ptr!(bundle);
1010        self.insert_with_caller(
1011            bundle,
1012            InsertMode::Keep,
1013            MaybeLocation::caller(),
1014            RelationshipHookMode::Run,
1015        )
1016    }
1017
1018    /// Adds a [`Bundle`] of components to the entity.
1019    #[inline]
1020    pub(crate) fn insert_with_caller<T: Bundle>(
1021        &mut self,
1022        bundle: MovingPtr<'_, T>,
1023        mode: InsertMode,
1024        caller: MaybeLocation,
1025        relationship_hook_mode: RelationshipHookMode,
1026    ) -> &mut Self {
1027        let location = self.location();
1028        let change_tick = self.world.change_tick();
1029        let mut bundle_inserter =
1030            BundleInserter::new::<T>(self.world, location.archetype_id, change_tick);
1031        // SAFETY:
1032        // - `location` matches current entity and thus must currently exist in the source
1033        //   archetype for this inserter and its location within the archetype.
1034        // - `T` matches the type used to create the `BundleInserter`.
1035        // - `apply_effect` is called exactly once after this function.
1036        // - The value pointed at by `bundle` is not accessed for anything other than `apply_effect`
1037        //   and the caller ensures that the value is not accessed or dropped after this function
1038        //   returns.
1039        let (bundle, location) = bundle.partial_move(|bundle| unsafe {
1040            bundle_inserter.insert(
1041                self.entity,
1042                location,
1043                bundle,
1044                mode,
1045                caller,
1046                relationship_hook_mode,
1047            )
1048        });
1049        self.location = Some(location);
1050        self.world.flush();
1051        self.update_location();
1052        // SAFETY:
1053        // - This is called exactly once after the `BundleInsert::insert` call before returning to safe code.
1054        // - `bundle` points to the same `B` that `BundleInsert::insert` was called on.
1055        unsafe { T::apply_effect(bundle, self) };
1056        self
1057    }
1058
1059    /// Inserts a dynamic [`Component`] into the entity.
1060    ///
1061    /// This will overwrite any previous value(s) of the same component type.
1062    ///
1063    /// You should prefer to use the typed API [`EntityWorldMut::insert`] where possible.
1064    ///
1065    /// # Safety
1066    ///
1067    /// - [`ComponentId`] must be from the same world as [`EntityWorldMut`]
1068    /// - [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
1069    ///
1070    /// # Panics
1071    ///
1072    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1073    #[track_caller]
1074    pub unsafe fn insert_by_id(
1075        &mut self,
1076        component_id: ComponentId,
1077        component: OwningPtr<'_>,
1078    ) -> &mut Self {
1079        // SAFETY: Upheld by caller
1080        unsafe {
1081            self.insert_by_id_with_caller(
1082                component_id,
1083                component,
1084                InsertMode::Replace,
1085                MaybeLocation::caller(),
1086                RelationshipHookMode::Run,
1087            )
1088        }
1089    }
1090
1091    /// # Safety
1092    ///
1093    /// - [`ComponentId`] must be from the same world as [`EntityWorldMut`]
1094    /// - [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
1095    #[inline]
1096    pub(crate) unsafe fn insert_by_id_with_caller(
1097        &mut self,
1098        component_id: ComponentId,
1099        component: OwningPtr<'_>,
1100        mode: InsertMode,
1101        caller: MaybeLocation,
1102        relationship_hook_insert_mode: RelationshipHookMode,
1103    ) -> &mut Self {
1104        let location = self.location();
1105        let change_tick = self.world.change_tick();
1106        let bundle_id = self.world.bundles.init_component_info(
1107            &mut self.world.storages,
1108            &self.world.components,
1109            component_id,
1110        );
1111        let storage_type = self.world.bundles.get_storage_unchecked(bundle_id);
1112
1113        let bundle_inserter =
1114            BundleInserter::new_with_id(self.world, location.archetype_id, bundle_id, change_tick);
1115
1116        self.location = Some(insert_dynamic_bundle(
1117            bundle_inserter,
1118            self.entity,
1119            location,
1120            Some(component).into_iter(),
1121            Some(storage_type).iter().cloned(),
1122            mode,
1123            caller,
1124            relationship_hook_insert_mode,
1125        ));
1126        self.world.flush();
1127        self.update_location();
1128        self
1129    }
1130
1131    /// Inserts a dynamic [`Bundle`] into the entity.
1132    ///
1133    /// This will overwrite any previous value(s) of the same component type.
1134    ///
1135    /// You should prefer to use the typed API [`EntityWorldMut::insert`] where possible.
1136    /// If your [`Bundle`] only has one component, use the cached API [`EntityWorldMut::insert_by_id`].
1137    ///
1138    /// If possible, pass a sorted slice of `ComponentId` to maximize caching potential.
1139    ///
1140    /// # Safety
1141    /// - Each [`ComponentId`] must be from the same world as [`EntityWorldMut`]
1142    /// - Each [`OwningPtr`] must be a valid reference to the type represented by [`ComponentId`]
1143    ///
1144    /// # Panics
1145    ///
1146    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1147    #[track_caller]
1148    pub unsafe fn insert_by_ids<'a, I: Iterator<Item = OwningPtr<'a>>>(
1149        &mut self,
1150        component_ids: &[ComponentId],
1151        iter_components: I,
1152    ) -> &mut Self {
1153        self.insert_by_ids_internal(component_ids, iter_components, RelationshipHookMode::Run)
1154    }
1155
1156    #[track_caller]
1157    pub(crate) unsafe fn insert_by_ids_internal<'a, I: Iterator<Item = OwningPtr<'a>>>(
1158        &mut self,
1159        component_ids: &[ComponentId],
1160        iter_components: I,
1161        relationship_hook_insert_mode: RelationshipHookMode,
1162    ) -> &mut Self {
1163        let location = self.location();
1164        let change_tick = self.world.change_tick();
1165        let bundle_id = self.world.bundles.init_dynamic_info(
1166            &mut self.world.storages,
1167            &self.world.components,
1168            component_ids,
1169        );
1170        let mut storage_types =
1171            core::mem::take(self.world.bundles.get_storages_unchecked(bundle_id));
1172        let bundle_inserter =
1173            BundleInserter::new_with_id(self.world, location.archetype_id, bundle_id, change_tick);
1174
1175        self.location = Some(insert_dynamic_bundle(
1176            bundle_inserter,
1177            self.entity,
1178            location,
1179            iter_components,
1180            (*storage_types).iter().cloned(),
1181            InsertMode::Replace,
1182            MaybeLocation::caller(),
1183            relationship_hook_insert_mode,
1184        ));
1185        *self.world.bundles.get_storages_unchecked(bundle_id) = core::mem::take(&mut storage_types);
1186        self.world.flush();
1187        self.update_location();
1188        self
1189    }
1190
1191    /// Removes all components in the [`Bundle`] from the entity and returns their previous values.
1192    ///
1193    /// **Note:** If the entity does not have every component in the bundle, this method will not
1194    /// remove any of them.
1195    ///
1196    /// # Panics
1197    ///
1198    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1199    #[must_use]
1200    #[track_caller]
1201    pub fn take<T: Bundle + BundleFromComponents>(&mut self) -> Option<T> {
1202        let location = self.location();
1203        let entity = self.entity;
1204
1205        let mut remover =
1206            // SAFETY: The archetype id must be valid since this entity is in it.
1207            unsafe { BundleRemover::new::<T>(self.world, location.archetype_id, true) }?;
1208        // SAFETY: The passed location has the sane archetype as the remover, since they came from the same location.
1209        let (new_location, result) = unsafe {
1210            remover.remove(
1211                entity,
1212                location,
1213                MaybeLocation::caller(),
1214                |sets, table, components, bundle_components| {
1215                    let mut bundle_components = bundle_components.iter().copied();
1216                    (
1217                        false,
1218                        T::from_components(&mut (sets, table), &mut |(sets, table)| {
1219                            let component_id = bundle_components.next().unwrap();
1220                            // SAFETY: the component existed to be removed, so its id must be valid.
1221                            let component_info = components.get_info_unchecked(component_id);
1222                            match component_info.storage_type() {
1223                                StorageType::Table => {
1224                                    table
1225                                        .as_mut()
1226                                        // SAFETY: The table must be valid if the component is in it.
1227                                        .debug_checked_unwrap()
1228                                        // SAFETY: The remover is cleaning this up.
1229                                        .take_component(component_id, location.table_row)
1230                                }
1231                                StorageType::SparseSet => sets
1232                                    .get_mut(component_id)
1233                                    .unwrap()
1234                                    .remove_and_forget(entity)
1235                                    .unwrap(),
1236                            }
1237                        }),
1238                    )
1239                },
1240            )
1241        };
1242        self.location = Some(new_location);
1243
1244        self.world.flush();
1245        self.update_location();
1246        Some(result)
1247    }
1248
1249    /// Removes any components in the [`Bundle`] from the entity.
1250    ///
1251    /// See [`EntityCommands::remove`](crate::system::EntityCommands::remove) for more details.
1252    ///
1253    /// # Panics
1254    ///
1255    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1256    #[track_caller]
1257    pub fn remove<T: Bundle>(&mut self) -> &mut Self {
1258        self.remove_with_caller::<T>(MaybeLocation::caller())
1259    }
1260
1261    #[inline]
1262    pub(crate) fn remove_with_caller<T: Bundle>(&mut self, caller: MaybeLocation) -> &mut Self {
1263        let location = self.location();
1264
1265        let Some(mut remover) =
1266            // SAFETY: The archetype id must be valid since this entity is in it.
1267            (unsafe { BundleRemover::new::<T>(self.world, location.archetype_id, false) })
1268        else {
1269            return self;
1270        };
1271        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
1272        let new_location = unsafe {
1273            remover.remove(
1274                self.entity,
1275                location,
1276                caller,
1277                BundleRemover::empty_pre_remove,
1278            )
1279        }
1280        .0;
1281
1282        self.location = Some(new_location);
1283        self.world.flush();
1284        self.update_location();
1285        self
1286    }
1287
1288    /// Removes all components in the [`Bundle`] and remove all required components for each component in the bundle
1289    ///
1290    /// # Panics
1291    ///
1292    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1293    #[track_caller]
1294    pub fn remove_with_requires<T: Bundle>(&mut self) -> &mut Self {
1295        self.remove_with_requires_with_caller::<T>(MaybeLocation::caller())
1296    }
1297
1298    pub(crate) fn remove_with_requires_with_caller<T: Bundle>(
1299        &mut self,
1300        caller: MaybeLocation,
1301    ) -> &mut Self {
1302        let location = self.location();
1303        let bundle_id = self.world.register_contributed_bundle_info::<T>();
1304
1305        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
1306        let Some(mut remover) = (unsafe {
1307            BundleRemover::new_with_id(self.world, location.archetype_id, bundle_id, false)
1308        }) else {
1309            return self;
1310        };
1311        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
1312        let new_location = unsafe {
1313            remover.remove(
1314                self.entity,
1315                location,
1316                caller,
1317                BundleRemover::empty_pre_remove,
1318            )
1319        }
1320        .0;
1321
1322        self.location = Some(new_location);
1323        self.world.flush();
1324        self.update_location();
1325        self
1326    }
1327
1328    /// Removes any components except those in the [`Bundle`] (and its Required Components) from the entity.
1329    ///
1330    /// See [`EntityCommands::retain`](crate::system::EntityCommands::retain) for more details.
1331    ///
1332    /// # Panics
1333    ///
1334    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1335    #[track_caller]
1336    pub fn retain<T: Bundle>(&mut self) -> &mut Self {
1337        self.retain_with_caller::<T>(MaybeLocation::caller())
1338    }
1339
1340    #[inline]
1341    pub(crate) fn retain_with_caller<T: Bundle>(&mut self, caller: MaybeLocation) -> &mut Self {
1342        let old_location = self.location();
1343        let retained_bundle = self.world.register_bundle_info::<T>();
1344        let archetypes = &mut self.world.archetypes;
1345
1346        // SAFETY: `retained_bundle` exists as we just registered it.
1347        let retained_bundle_info = unsafe { self.world.bundles.get_unchecked(retained_bundle) };
1348        let old_archetype = &mut archetypes[old_location.archetype_id];
1349
1350        // PERF: this could be stored in an Archetype Edge
1351        let to_remove = &old_archetype
1352            .iter_components()
1353            .filter(|c| !retained_bundle_info.contributed_components().contains(c))
1354            .collect::<Vec<_>>();
1355        let remove_bundle = self.world.bundles.init_dynamic_info(
1356            &mut self.world.storages,
1357            &self.world.components,
1358            to_remove,
1359        );
1360
1361        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
1362        let Some(mut remover) = (unsafe {
1363            BundleRemover::new_with_id(self.world, old_location.archetype_id, remove_bundle, false)
1364        }) else {
1365            return self;
1366        };
1367        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
1368        let new_location = unsafe {
1369            remover.remove(
1370                self.entity,
1371                old_location,
1372                caller,
1373                BundleRemover::empty_pre_remove,
1374            )
1375        }
1376        .0;
1377
1378        self.location = Some(new_location);
1379        self.world.flush();
1380        self.update_location();
1381        self
1382    }
1383
1384    /// Removes a dynamic [`Component`] from the entity if it exists.
1385    ///
1386    /// You should prefer to use the typed API [`EntityWorldMut::remove`] where possible.
1387    ///
1388    /// # Panics
1389    ///
1390    /// Panics if the provided [`ComponentId`] does not exist in the [`World`] or if the
1391    /// entity has been despawned while this `EntityWorldMut` is still alive.
1392    #[track_caller]
1393    pub fn remove_by_id(&mut self, component_id: ComponentId) -> &mut Self {
1394        self.remove_by_id_with_caller(component_id, MaybeLocation::caller())
1395    }
1396
1397    #[inline]
1398    pub(crate) fn remove_by_id_with_caller(
1399        &mut self,
1400        component_id: ComponentId,
1401        caller: MaybeLocation,
1402    ) -> &mut Self {
1403        let location = self.location();
1404        let components = &mut self.world.components;
1405
1406        let bundle_id = self.world.bundles.init_component_info(
1407            &mut self.world.storages,
1408            components,
1409            component_id,
1410        );
1411
1412        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
1413        let Some(mut remover) = (unsafe {
1414            BundleRemover::new_with_id(self.world, location.archetype_id, bundle_id, false)
1415        }) else {
1416            return self;
1417        };
1418        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
1419        let new_location = unsafe {
1420            remover.remove(
1421                self.entity,
1422                location,
1423                caller,
1424                BundleRemover::empty_pre_remove,
1425            )
1426        }
1427        .0;
1428
1429        self.location = Some(new_location);
1430        self.world.flush();
1431        self.update_location();
1432        self
1433    }
1434
1435    /// Removes a dynamic bundle from the entity if it exists.
1436    ///
1437    /// You should prefer to use the typed API [`EntityWorldMut::remove`] where possible.
1438    ///
1439    /// # Panics
1440    ///
1441    /// Panics if any of the provided [`ComponentId`]s do not exist in the [`World`] or if the
1442    /// entity has been despawned while this `EntityWorldMut` is still alive.
1443    #[track_caller]
1444    pub fn remove_by_ids(&mut self, component_ids: &[ComponentId]) -> &mut Self {
1445        self.remove_by_ids_with_caller(
1446            component_ids,
1447            MaybeLocation::caller(),
1448            RelationshipHookMode::Run,
1449            BundleRemover::empty_pre_remove,
1450        )
1451    }
1452
1453    #[inline]
1454    pub(crate) fn remove_by_ids_with_caller<T: 'static>(
1455        &mut self,
1456        component_ids: &[ComponentId],
1457        caller: MaybeLocation,
1458        relationship_hook_mode: RelationshipHookMode,
1459        pre_remove: impl FnOnce(
1460            &mut SparseSets,
1461            Option<&mut Table>,
1462            &Components,
1463            &[ComponentId],
1464        ) -> (bool, T),
1465    ) -> &mut Self {
1466        let location = self.location();
1467        let components = &mut self.world.components;
1468
1469        let bundle_id = self.world.bundles.init_dynamic_info(
1470            &mut self.world.storages,
1471            components,
1472            component_ids,
1473        );
1474
1475        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
1476        let Some(mut remover) = (unsafe {
1477            BundleRemover::new_with_id(self.world, location.archetype_id, bundle_id, false)
1478        }) else {
1479            return self;
1480        };
1481        remover.relationship_hook_mode = relationship_hook_mode;
1482        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
1483        let new_location = unsafe { remover.remove(self.entity, location, caller, pre_remove) }.0;
1484
1485        self.location = Some(new_location);
1486        self.world.flush();
1487        self.update_location();
1488        self
1489    }
1490
1491    /// Removes all components associated with the entity.
1492    ///
1493    /// # Panics
1494    ///
1495    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1496    #[track_caller]
1497    pub fn clear(&mut self) -> &mut Self {
1498        self.clear_with_caller(MaybeLocation::caller())
1499    }
1500
1501    #[inline]
1502    pub(crate) fn clear_with_caller(&mut self, caller: MaybeLocation) -> &mut Self {
1503        let location = self.location();
1504        // PERF: this should not be necessary
1505        let component_ids: Vec<ComponentId> = self.archetype().components().to_vec();
1506        let components = &mut self.world.components;
1507
1508        let bundle_id = self.world.bundles.init_dynamic_info(
1509            &mut self.world.storages,
1510            components,
1511            component_ids.as_slice(),
1512        );
1513
1514        // SAFETY: We just created the bundle, and the archetype is valid, since we are in it.
1515        let Some(mut remover) = (unsafe {
1516            BundleRemover::new_with_id(self.world, location.archetype_id, bundle_id, false)
1517        }) else {
1518            return self;
1519        };
1520        // SAFETY: The remover archetype came from the passed location and the removal can not fail.
1521        let new_location = unsafe {
1522            remover.remove(
1523                self.entity,
1524                location,
1525                caller,
1526                BundleRemover::empty_pre_remove,
1527            )
1528        }
1529        .0;
1530
1531        self.location = Some(new_location);
1532        self.world.flush();
1533        self.update_location();
1534        self
1535    }
1536
1537    /// Despawns the entity without freeing it to the allocator.
1538    /// This returns the new [`Entity`], which you must manage.
1539    /// Note that this still increases the generation to differentiate different spawns of the same row.
1540    ///
1541    /// Additionally, keep in mind the limitations documented in the type-level docs.
1542    /// Unless you have full knowledge of this [`EntityWorldMut`]'s lifetime,
1543    /// you may not assume that nothing else has taken responsibility of this [`Entity`].
1544    /// If you are not careful, this could cause a double free.
1545    ///
1546    /// This may be later [`spawn_at`](World::spawn_at).
1547    /// See [`World::despawn_no_free`] for details and usage examples.
1548    #[track_caller]
1549    pub fn despawn_no_free(mut self) -> Entity {
1550        self.despawn_no_free_with_caller(MaybeLocation::caller());
1551        self.entity
1552    }
1553
1554    /// This despawns this entity if it is currently spawned, storing the new [`EntityGeneration`](crate::entity::EntityGeneration) in [`Self::entity`] but not freeing it.
1555    pub(crate) fn despawn_no_free_with_caller(&mut self, caller: MaybeLocation) {
1556        // setup
1557        let Some(location) = self.location else {
1558            // If there is no location, we are already despawned
1559            return;
1560        };
1561        let archetype = &self.world.archetypes[location.archetype_id];
1562
1563        // SAFETY: Archetype cannot be mutably aliased by DeferredWorld
1564        let (archetype, mut deferred_world) = unsafe {
1565            let archetype: *const Archetype = archetype;
1566            let world = self.world.as_unsafe_world_cell();
1567            (&*archetype, world.into_deferred())
1568        };
1569
1570        // SAFETY: All components in the archetype exist in world
1571        unsafe {
1572            if archetype.has_despawn_observer() {
1573                // SAFETY: the DESPAWN event_key corresponds to the Despawn event's type
1574                deferred_world.trigger_raw(
1575                    DESPAWN,
1576                    &mut Despawn {
1577                        entity: self.entity,
1578                    },
1579                    &mut EntityComponentsTrigger {
1580                        components: archetype.components(),
1581                    },
1582                    caller,
1583                );
1584            }
1585            deferred_world.trigger_on_despawn(
1586                archetype,
1587                self.entity,
1588                archetype.iter_components(),
1589                caller,
1590            );
1591            if archetype.has_replace_observer() {
1592                // SAFETY: the REPLACE event_key corresponds to the Replace event's type
1593                deferred_world.trigger_raw(
1594                    REPLACE,
1595                    &mut Replace {
1596                        entity: self.entity,
1597                    },
1598                    &mut EntityComponentsTrigger {
1599                        components: archetype.components(),
1600                    },
1601                    caller,
1602                );
1603            }
1604            deferred_world.trigger_on_replace(
1605                archetype,
1606                self.entity,
1607                archetype.iter_components(),
1608                caller,
1609                RelationshipHookMode::Run,
1610            );
1611            if archetype.has_remove_observer() {
1612                // SAFETY: the REMOVE event_key corresponds to the Remove event's type
1613                deferred_world.trigger_raw(
1614                    REMOVE,
1615                    &mut Remove {
1616                        entity: self.entity,
1617                    },
1618                    &mut EntityComponentsTrigger {
1619                        components: archetype.components(),
1620                    },
1621                    caller,
1622                );
1623            }
1624            deferred_world.trigger_on_remove(
1625                archetype,
1626                self.entity,
1627                archetype.iter_components(),
1628                caller,
1629            );
1630        }
1631
1632        // do the despawn
1633        let change_tick = self.world.change_tick();
1634        for component_id in archetype.components() {
1635            self.world
1636                .removed_components
1637                .write(*component_id, self.entity);
1638        }
1639        // SAFETY: Since we had a location, and it was valid, this is safe.
1640        unsafe {
1641            let was_at = self
1642                .world
1643                .entities
1644                .update_existing_location(self.entity.index(), None);
1645            debug_assert_eq!(was_at, Some(location));
1646            self.world
1647                .entities
1648                .mark_spawned_or_despawned(self.entity.index(), caller, change_tick);
1649        }
1650
1651        let table_row;
1652        let moved_entity;
1653        {
1654            let archetype = &mut self.world.archetypes[location.archetype_id];
1655            let remove_result = archetype.swap_remove(location.archetype_row);
1656            if let Some(swapped_entity) = remove_result.swapped_entity {
1657                let swapped_location = self.world.entities.get_spawned(swapped_entity).unwrap();
1658                // SAFETY: swapped_entity is valid and the swapped entity's components are
1659                // moved to the new location immediately after.
1660                unsafe {
1661                    self.world.entities.update_existing_location(
1662                        swapped_entity.index(),
1663                        Some(EntityLocation {
1664                            archetype_id: swapped_location.archetype_id,
1665                            archetype_row: location.archetype_row,
1666                            table_id: swapped_location.table_id,
1667                            table_row: swapped_location.table_row,
1668                        }),
1669                    );
1670                }
1671            }
1672            table_row = remove_result.table_row;
1673
1674            for component_id in archetype.sparse_set_components() {
1675                // set must have existed for the component to be added.
1676                let sparse_set = self
1677                    .world
1678                    .storages
1679                    .sparse_sets
1680                    .get_mut(component_id)
1681                    .unwrap();
1682                sparse_set.remove(self.entity);
1683            }
1684            // SAFETY: table rows stored in archetypes always exist
1685            moved_entity = unsafe {
1686                self.world.storages.tables[archetype.table_id()].swap_remove_unchecked(table_row)
1687            };
1688        };
1689
1690        // Handle displaced entity
1691        if let Some(moved_entity) = moved_entity {
1692            let moved_location = self.world.entities.get_spawned(moved_entity).unwrap();
1693            // SAFETY: `moved_entity` is valid and the provided `EntityLocation` accurately reflects
1694            //         the current location of the entity and its component data.
1695            unsafe {
1696                self.world.entities.update_existing_location(
1697                    moved_entity.index(),
1698                    Some(EntityLocation {
1699                        archetype_id: moved_location.archetype_id,
1700                        archetype_row: moved_location.archetype_row,
1701                        table_id: moved_location.table_id,
1702                        table_row,
1703                    }),
1704                );
1705            }
1706            self.world.archetypes[moved_location.archetype_id]
1707                .set_entity_table_row(moved_location.archetype_row, table_row);
1708        }
1709
1710        // finish
1711        // SAFETY: We just despawned it.
1712        self.entity = unsafe { self.world.entities.mark_free(self.entity.index(), 1) };
1713        self.world.flush();
1714    }
1715
1716    /// Despawns the current entity.
1717    ///
1718    /// See [`World::despawn`] for more details.
1719    ///
1720    /// # Note
1721    ///
1722    /// This will also despawn any [`Children`](crate::hierarchy::Children) entities, and any other [`RelationshipTarget`](crate::relationship::RelationshipTarget) that is configured
1723    /// to despawn descendants. This results in "recursive despawn" behavior.
1724    #[track_caller]
1725    pub fn despawn(self) {
1726        self.despawn_with_caller(MaybeLocation::caller());
1727    }
1728
1729    pub(crate) fn despawn_with_caller(mut self, caller: MaybeLocation) {
1730        self.despawn_no_free_with_caller(caller);
1731        if let Ok(None) = self.world.entities.get(self.entity) {
1732            self.world.allocator.free(self.entity);
1733        }
1734
1735        // Otherwise:
1736        // A command must have reconstructed it (had a location); don't free
1737        // A command must have already despawned it (err) or otherwise made the free unneeded (ex by spawning and despawning in commands); don't free
1738    }
1739
1740    /// Ensures any commands triggered by the actions of Self are applied, equivalent to [`World::flush`]
1741    pub fn flush(self) -> Entity {
1742        self.world.flush();
1743        self.entity
1744    }
1745
1746    /// Gets read-only access to the world that the current entity belongs to.
1747    #[inline]
1748    pub fn world(&self) -> &World {
1749        self.world
1750    }
1751
1752    /// Returns this entity's world.
1753    ///
1754    /// See [`EntityWorldMut::world_scope`] or [`EntityWorldMut::into_world_mut`] for a safe alternative.
1755    ///
1756    /// # Safety
1757    /// Caller must not modify the world in a way that changes the current entity's location
1758    /// If the caller _does_ do something that could change the location, `self.update_location()`
1759    /// must be called before using any other methods on this [`EntityWorldMut`].
1760    #[inline]
1761    pub unsafe fn world_mut(&mut self) -> &mut World {
1762        self.world
1763    }
1764
1765    /// Returns this entity's [`World`], consuming itself.
1766    #[inline]
1767    pub fn into_world_mut(self) -> &'w mut World {
1768        self.world
1769    }
1770
1771    /// Gives mutable access to this entity's [`World`] in a temporary scope.
1772    /// This is a safe alternative to using [`EntityWorldMut::world_mut`].
1773    ///
1774    /// # Examples
1775    ///
1776    /// ```
1777    /// # use bevy_ecs::prelude::*;
1778    /// #[derive(Resource, Default, Clone, Copy)]
1779    /// struct R(u32);
1780    ///
1781    /// # let mut world = World::new();
1782    /// # world.init_resource::<R>();
1783    /// # let mut entity = world.spawn_empty();
1784    /// // This closure gives us temporary access to the world.
1785    /// let new_r = entity.world_scope(|world: &mut World| {
1786    ///     // Mutate the world while we have access to it.
1787    ///     let mut r = world.resource_mut::<R>();
1788    ///     r.0 += 1;
1789    ///
1790    ///     // Return a value from the world before giving it back to the `EntityWorldMut`.
1791    ///     *r
1792    /// });
1793    /// # assert_eq!(new_r.0, 1);
1794    /// ```
1795    pub fn world_scope<U>(&mut self, f: impl FnOnce(&mut World) -> U) -> U {
1796        struct Guard<'w, 'a> {
1797            entity_mut: &'a mut EntityWorldMut<'w>,
1798        }
1799
1800        impl Drop for Guard<'_, '_> {
1801            #[inline]
1802            fn drop(&mut self) {
1803                self.entity_mut.update_location();
1804            }
1805        }
1806
1807        // When `guard` is dropped at the end of this scope,
1808        // it will update the cached `EntityLocation` for this instance.
1809        // This will run even in case the closure `f` unwinds.
1810        let guard = Guard { entity_mut: self };
1811        f(guard.entity_mut.world)
1812    }
1813
1814    /// Updates the internal entity location to match the current location in the internal
1815    /// [`World`].
1816    ///
1817    /// This is *only* required when using the unsafe function [`EntityWorldMut::world_mut`],
1818    /// which enables the location to change.
1819    ///
1820    /// Note that if the entity is not spawned for any reason,
1821    /// this will have a location of `None`, leading some methods to panic.
1822    pub fn update_location(&mut self) {
1823        self.location = self.world.entities().get_spawned(self.entity).ok();
1824    }
1825
1826    /// Returns if the entity has been despawned.
1827    ///
1828    /// Normally it shouldn't be needed to explicitly check if the entity has been despawned
1829    /// between commands as this shouldn't happen. However, for some special cases where it
1830    /// is known that a hook or an observer might despawn the entity while a [`EntityWorldMut`]
1831    /// reference is still held, this method can be used to check if the entity is still alive
1832    /// to avoid panicking when calling further methods.
1833    #[inline]
1834    pub fn is_despawned(&self) -> bool {
1835        self.location.is_none()
1836    }
1837
1838    /// Gets an Entry into the world for this entity and component for in-place manipulation.
1839    ///
1840    /// The type parameter specifies which component to get.
1841    ///
1842    /// # Examples
1843    ///
1844    /// ```
1845    /// # use bevy_ecs::prelude::*;
1846    /// #[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
1847    /// struct Comp(u32);
1848    ///
1849    /// # let mut world = World::new();
1850    /// let mut entity = world.spawn_empty();
1851    /// entity.entry().or_insert_with(|| Comp(4));
1852    /// # let entity_id = entity.id();
1853    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 4);
1854    ///
1855    /// # let mut entity = world.get_entity_mut(entity_id).unwrap();
1856    /// entity.entry::<Comp>().and_modify(|mut c| c.0 += 1);
1857    /// assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 5);
1858    /// ```
1859    ///
1860    /// # Panics
1861    ///
1862    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1863    pub fn entry<'a, T: Component>(&'a mut self) -> ComponentEntry<'w, 'a, T> {
1864        if self.contains::<T>() {
1865            ComponentEntry::Occupied(OccupiedComponentEntry {
1866                entity_world: self,
1867                _marker: PhantomData,
1868            })
1869        } else {
1870            ComponentEntry::Vacant(VacantComponentEntry {
1871                entity_world: self,
1872                _marker: PhantomData,
1873            })
1874        }
1875    }
1876
1877    /// Creates an [`Observer`] watching for an [`EntityEvent`] of type `E` whose [`EntityEvent::event_target`]
1878    /// targets this entity.
1879    ///
1880    /// # Panics
1881    ///
1882    /// If the entity has been despawned while this `EntityWorldMut` is still alive.
1883    ///
1884    /// Panics if the given system is an exclusive system.
1885    #[track_caller]
1886    pub fn observe<E: EntityEvent, B: Bundle, M>(
1887        &mut self,
1888        observer: impl IntoObserverSystem<E, B, M>,
1889    ) -> &mut Self {
1890        self.observe_with_caller(observer, MaybeLocation::caller())
1891    }
1892
1893    pub(crate) fn observe_with_caller<E: EntityEvent, B: Bundle, M>(
1894        &mut self,
1895        observer: impl IntoObserverSystem<E, B, M>,
1896        caller: MaybeLocation,
1897    ) -> &mut Self {
1898        self.assert_not_despawned();
1899        let bundle = Observer::new(observer).with_entity(self.entity);
1900        move_as_ptr!(bundle);
1901        self.world.spawn_with_caller(bundle, caller);
1902        self.world.flush();
1903        self.update_location();
1904        self
1905    }
1906
1907    /// Clones parts of an entity (components, observers, etc.) onto another entity,
1908    /// configured through [`EntityClonerBuilder`].
1909    ///
1910    /// The other entity will receive all the components of the original that implement
1911    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) except those that are
1912    /// [denied](EntityClonerBuilder::deny) in the `config`.
1913    ///
1914    /// # Example
1915    ///
1916    /// ```
1917    /// # use bevy_ecs::prelude::*;
1918    /// # #[derive(Component, Clone, PartialEq, Debug)]
1919    /// # struct ComponentA;
1920    /// # #[derive(Component, Clone, PartialEq, Debug)]
1921    /// # struct ComponentB;
1922    /// # let mut world = World::new();
1923    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
1924    /// # let target = world.spawn_empty().id();
1925    /// // Clone all components except ComponentA onto the target.
1926    /// world.entity_mut(entity).clone_with_opt_out(target, |builder| {
1927    ///     builder.deny::<ComponentA>();
1928    /// });
1929    /// # assert_eq!(world.get::<ComponentA>(target), None);
1930    /// # assert_eq!(world.get::<ComponentB>(target), Some(&ComponentB));
1931    /// ```
1932    ///
1933    /// See [`EntityClonerBuilder<OptOut>`] for more options.
1934    ///
1935    /// # Panics
1936    ///
1937    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
1938    /// - If the target entity does not exist.
1939    pub fn clone_with_opt_out(
1940        &mut self,
1941        target: Entity,
1942        config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static,
1943    ) -> &mut Self {
1944        self.assert_not_despawned();
1945
1946        let mut builder = EntityCloner::build_opt_out(self.world);
1947        config(&mut builder);
1948        builder.clone_entity(self.entity, target);
1949
1950        self.world.flush();
1951        self.update_location();
1952        self
1953    }
1954
1955    /// Clones parts of an entity (components, observers, etc.) onto another entity,
1956    /// configured through [`EntityClonerBuilder`].
1957    ///
1958    /// The other entity will receive only the components of the original that implement
1959    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) and are
1960    /// [allowed](EntityClonerBuilder::allow) in the `config`.
1961    ///
1962    /// # Example
1963    ///
1964    /// ```
1965    /// # use bevy_ecs::prelude::*;
1966    /// # #[derive(Component, Clone, PartialEq, Debug)]
1967    /// # struct ComponentA;
1968    /// # #[derive(Component, Clone, PartialEq, Debug)]
1969    /// # struct ComponentB;
1970    /// # let mut world = World::new();
1971    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
1972    /// # let target = world.spawn_empty().id();
1973    /// // Clone only ComponentA onto the target.
1974    /// world.entity_mut(entity).clone_with_opt_in(target, |builder| {
1975    ///     builder.allow::<ComponentA>();
1976    /// });
1977    /// # assert_eq!(world.get::<ComponentA>(target), Some(&ComponentA));
1978    /// # assert_eq!(world.get::<ComponentB>(target), None);
1979    /// ```
1980    ///
1981    /// See [`EntityClonerBuilder<OptIn>`] for more options.
1982    ///
1983    /// # Panics
1984    ///
1985    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
1986    /// - If the target entity does not exist.
1987    pub fn clone_with_opt_in(
1988        &mut self,
1989        target: Entity,
1990        config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static,
1991    ) -> &mut Self {
1992        self.assert_not_despawned();
1993
1994        let mut builder = EntityCloner::build_opt_in(self.world);
1995        config(&mut builder);
1996        builder.clone_entity(self.entity, target);
1997
1998        self.world.flush();
1999        self.update_location();
2000        self
2001    }
2002
2003    /// Spawns a clone of this entity and returns the [`Entity`] of the clone.
2004    ///
2005    /// The clone will receive all the components of the original that implement
2006    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2007    ///
2008    /// To configure cloning behavior (such as only cloning certain components),
2009    /// use [`EntityWorldMut::clone_and_spawn_with_opt_out`]/
2010    /// [`opt_in`](`EntityWorldMut::clone_and_spawn_with_opt_in`).
2011    ///
2012    /// # Panics
2013    ///
2014    /// If this entity has been despawned while this `EntityWorldMut` is still alive.
2015    pub fn clone_and_spawn(&mut self) -> Entity {
2016        self.clone_and_spawn_with_opt_out(|_| {})
2017    }
2018
2019    /// Spawns a clone of this entity and allows configuring cloning behavior
2020    /// using [`EntityClonerBuilder`], returning the [`Entity`] of the clone.
2021    ///
2022    /// The clone will receive all the components of the original that implement
2023    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) except those that are
2024    /// [denied](EntityClonerBuilder::deny) in the `config`.
2025    ///
2026    /// # Example
2027    ///
2028    /// ```
2029    /// # use bevy_ecs::prelude::*;
2030    /// # let mut world = World::new();
2031    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
2032    /// # #[derive(Component, Clone, PartialEq, Debug)]
2033    /// # struct ComponentA;
2034    /// # #[derive(Component, Clone, PartialEq, Debug)]
2035    /// # struct ComponentB;
2036    /// // Create a clone of an entity but without ComponentA.
2037    /// let entity_clone = world.entity_mut(entity).clone_and_spawn_with_opt_out(|builder| {
2038    ///     builder.deny::<ComponentA>();
2039    /// });
2040    /// # assert_eq!(world.get::<ComponentA>(entity_clone), None);
2041    /// # assert_eq!(world.get::<ComponentB>(entity_clone), Some(&ComponentB));
2042    /// ```
2043    ///
2044    /// See [`EntityClonerBuilder<OptOut>`] for more options.
2045    ///
2046    /// # Panics
2047    ///
2048    /// If this entity has been despawned while this `EntityWorldMut` is still alive.
2049    pub fn clone_and_spawn_with_opt_out(
2050        &mut self,
2051        config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static,
2052    ) -> Entity {
2053        self.assert_not_despawned();
2054        let entity_clone = self.world.spawn_empty().id();
2055
2056        let mut builder = EntityCloner::build_opt_out(self.world);
2057        config(&mut builder);
2058        builder.clone_entity(self.entity, entity_clone);
2059
2060        self.world.flush();
2061        self.update_location();
2062        entity_clone
2063    }
2064
2065    /// Spawns a clone of this entity and allows configuring cloning behavior
2066    /// using [`EntityClonerBuilder`], returning the [`Entity`] of the clone.
2067    ///
2068    /// The clone will receive only the components of the original that implement
2069    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect) and are
2070    /// [allowed](EntityClonerBuilder::allow) in the `config`.
2071    ///
2072    /// # Example
2073    ///
2074    /// ```
2075    /// # use bevy_ecs::prelude::*;
2076    /// # let mut world = World::new();
2077    /// # let entity = world.spawn((ComponentA, ComponentB)).id();
2078    /// # #[derive(Component, Clone, PartialEq, Debug)]
2079    /// # struct ComponentA;
2080    /// # #[derive(Component, Clone, PartialEq, Debug)]
2081    /// # struct ComponentB;
2082    /// // Create a clone of an entity but only with ComponentA.
2083    /// let entity_clone = world.entity_mut(entity).clone_and_spawn_with_opt_in(|builder| {
2084    ///     builder.allow::<ComponentA>();
2085    /// });
2086    /// # assert_eq!(world.get::<ComponentA>(entity_clone), Some(&ComponentA));
2087    /// # assert_eq!(world.get::<ComponentB>(entity_clone), None);
2088    /// ```
2089    ///
2090    /// See [`EntityClonerBuilder<OptIn>`] for more options.
2091    ///
2092    /// # Panics
2093    ///
2094    /// If this entity has been despawned while this `EntityWorldMut` is still alive.
2095    pub fn clone_and_spawn_with_opt_in(
2096        &mut self,
2097        config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static,
2098    ) -> Entity {
2099        self.assert_not_despawned();
2100        let entity_clone = self.world.spawn_empty().id();
2101
2102        let mut builder = EntityCloner::build_opt_in(self.world);
2103        config(&mut builder);
2104        builder.clone_entity(self.entity, entity_clone);
2105
2106        self.world.flush();
2107        self.update_location();
2108        entity_clone
2109    }
2110
2111    /// Clones the specified components of this entity and inserts them into another entity.
2112    ///
2113    /// Components can only be cloned if they implement
2114    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2115    ///
2116    /// # Panics
2117    ///
2118    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
2119    /// - If the target entity does not exist.
2120    pub fn clone_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
2121        self.assert_not_despawned();
2122
2123        EntityCloner::build_opt_in(self.world)
2124            .allow::<B>()
2125            .clone_entity(self.entity, target);
2126
2127        self.world.flush();
2128        self.update_location();
2129        self
2130    }
2131
2132    /// Clones the specified components of this entity and inserts them into another entity,
2133    /// then removes the components from this entity.
2134    ///
2135    /// Components can only be cloned if they implement
2136    /// [`Clone`] or [`Reflect`](bevy_reflect::Reflect).
2137    ///
2138    /// # Panics
2139    ///
2140    /// - If this entity has been despawned while this `EntityWorldMut` is still alive.
2141    /// - If the target entity does not exist.
2142    pub fn move_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
2143        self.assert_not_despawned();
2144
2145        EntityCloner::build_opt_in(self.world)
2146            .allow::<B>()
2147            .move_components(true)
2148            .clone_entity(self.entity, target);
2149
2150        self.world.flush();
2151        self.update_location();
2152        self
2153    }
2154
2155    /// Returns the source code location from which this entity has last been spawned.
2156    pub fn spawned_by(&self) -> MaybeLocation {
2157        self.world()
2158            .entities()
2159            .entity_get_spawned_or_despawned_by(self.entity)
2160            .map(|location| location.unwrap())
2161    }
2162
2163    /// Returns the [`Tick`] at which this entity has last been spawned.
2164    pub fn spawn_tick(&self) -> Tick {
2165        self.assert_not_despawned();
2166
2167        // SAFETY: entity being alive was asserted
2168        unsafe {
2169            self.world()
2170                .entities()
2171                .entity_get_spawned_or_despawned_unchecked(self.entity)
2172                .1
2173        }
2174    }
2175
2176    /// Reborrows this entity in a temporary scope.
2177    /// This is useful for executing a function that requires a `EntityWorldMut`
2178    /// but you do not want to move out the entity ownership.
2179    pub fn reborrow_scope<U>(&mut self, f: impl FnOnce(EntityWorldMut) -> U) -> U {
2180        let Self {
2181            entity, location, ..
2182        } = *self;
2183        self.world_scope(move |world| {
2184            f(EntityWorldMut {
2185                world,
2186                entity,
2187                location,
2188            })
2189        })
2190    }
2191
2192    /// Passes the current entity into the given function, and triggers the [`EntityEvent`] returned by that function.
2193    /// See [`EntityCommands::trigger`] for usage examples
2194    ///
2195    /// [`EntityCommands::trigger`]: crate::system::EntityCommands::trigger
2196    #[track_caller]
2197    pub fn trigger<'t, E: EntityEvent<Trigger<'t>: Default>>(
2198        &mut self,
2199        event_fn: impl FnOnce(Entity) -> E,
2200    ) -> &mut Self {
2201        let mut event = (event_fn)(self.entity);
2202        let caller = MaybeLocation::caller();
2203        self.world_scope(|world| {
2204            world.trigger_ref_with_caller(
2205                &mut event,
2206                &mut <E::Trigger<'_> as Default>::default(),
2207                caller,
2208            );
2209        });
2210        self
2211    }
2212}
2213
2214impl<'w> From<EntityWorldMut<'w>> for EntityRef<'w> {
2215    fn from(entity: EntityWorldMut<'w>) -> EntityRef<'w> {
2216        // SAFETY:
2217        // - `EntityWorldMut` guarantees exclusive access to the entire world.
2218        unsafe { EntityRef::new(entity.into_unsafe_entity_cell()) }
2219    }
2220}
2221
2222impl<'a> From<&'a EntityWorldMut<'_>> for EntityRef<'a> {
2223    fn from(entity: &'a EntityWorldMut<'_>) -> Self {
2224        // SAFETY:
2225        // - `EntityWorldMut` guarantees exclusive access to the entire world.
2226        // - `&entity` ensures no mutable accesses are active.
2227        unsafe { EntityRef::new(entity.as_unsafe_entity_cell_readonly()) }
2228    }
2229}
2230
2231impl<'w> From<EntityWorldMut<'w>> for EntityMut<'w> {
2232    fn from(entity: EntityWorldMut<'w>) -> Self {
2233        // SAFETY: `EntityWorldMut` guarantees exclusive access to the entire world.
2234        unsafe { EntityMut::new(entity.into_unsafe_entity_cell()) }
2235    }
2236}
2237
2238impl<'a> From<&'a mut EntityWorldMut<'_>> for EntityMut<'a> {
2239    #[inline]
2240    fn from(entity: &'a mut EntityWorldMut<'_>) -> Self {
2241        // SAFETY: `EntityWorldMut` guarantees exclusive access to the entire world.
2242        unsafe { EntityMut::new(entity.as_unsafe_entity_cell()) }
2243    }
2244}
2245
2246impl<'a> From<EntityWorldMut<'a>> for FilteredEntityRef<'a, 'static> {
2247    fn from(entity: EntityWorldMut<'a>) -> Self {
2248        // SAFETY:
2249        // - `EntityWorldMut` guarantees exclusive access to the entire world.
2250        unsafe {
2251            FilteredEntityRef::new(
2252                entity.into_unsafe_entity_cell(),
2253                const { &Access::new_read_all() },
2254            )
2255        }
2256    }
2257}
2258
2259impl<'a> From<&'a EntityWorldMut<'_>> for FilteredEntityRef<'a, 'static> {
2260    fn from(entity: &'a EntityWorldMut<'_>) -> Self {
2261        // SAFETY:
2262        // - `EntityWorldMut` guarantees exclusive access to the entire world.
2263        unsafe {
2264            FilteredEntityRef::new(
2265                entity.as_unsafe_entity_cell_readonly(),
2266                const { &Access::new_read_all() },
2267            )
2268        }
2269    }
2270}
2271
2272impl<'a> From<EntityWorldMut<'a>> for FilteredEntityMut<'a, 'static> {
2273    fn from(entity: EntityWorldMut<'a>) -> Self {
2274        // SAFETY:
2275        // - `EntityWorldMut` guarantees exclusive access to the entire world.
2276        unsafe {
2277            FilteredEntityMut::new(
2278                entity.into_unsafe_entity_cell(),
2279                const { &Access::new_write_all() },
2280            )
2281        }
2282    }
2283}
2284
2285impl<'a> From<&'a mut EntityWorldMut<'_>> for FilteredEntityMut<'a, 'static> {
2286    fn from(entity: &'a mut EntityWorldMut<'_>) -> Self {
2287        // SAFETY:
2288        // - `EntityWorldMut` guarantees exclusive access to the entire world.
2289        unsafe {
2290            FilteredEntityMut::new(
2291                entity.as_unsafe_entity_cell(),
2292                const { &Access::new_write_all() },
2293            )
2294        }
2295    }
2296}
2297
2298/// Inserts a dynamic [`Bundle`] into the entity.
2299///
2300/// # Safety
2301///
2302/// - [`OwningPtr`] and [`StorageType`] iterators must correspond to the
2303///   [`BundleInfo`](crate::bundle::BundleInfo) used to construct [`BundleInserter`]
2304/// - [`Entity`] must correspond to [`EntityLocation`]
2305unsafe fn insert_dynamic_bundle<
2306    'a,
2307    I: Iterator<Item = OwningPtr<'a>>,
2308    S: Iterator<Item = StorageType>,
2309>(
2310    mut bundle_inserter: BundleInserter<'_>,
2311    entity: Entity,
2312    location: EntityLocation,
2313    components: I,
2314    storage_types: S,
2315    mode: InsertMode,
2316    caller: MaybeLocation,
2317    relationship_hook_insert_mode: RelationshipHookMode,
2318) -> EntityLocation {
2319    struct DynamicInsertBundle<'a, I: Iterator<Item = (StorageType, OwningPtr<'a>)>> {
2320        components: I,
2321    }
2322
2323    impl<'a, I: Iterator<Item = (StorageType, OwningPtr<'a>)>> DynamicBundle
2324        for DynamicInsertBundle<'a, I>
2325    {
2326        type Effect = ();
2327        unsafe fn get_components(
2328            mut ptr: MovingPtr<'_, Self>,
2329            func: &mut impl FnMut(StorageType, OwningPtr<'_>),
2330        ) {
2331            (&mut ptr.components).for_each(|(t, ptr)| func(t, ptr));
2332        }
2333
2334        unsafe fn apply_effect(
2335            _ptr: MovingPtr<'_, MaybeUninit<Self>>,
2336            _entity: &mut EntityWorldMut,
2337        ) {
2338        }
2339    }
2340
2341    let bundle = DynamicInsertBundle {
2342        components: storage_types.zip(components),
2343    };
2344
2345    move_as_ptr!(bundle);
2346
2347    // SAFETY:
2348    // - `location` matches `entity`.  and thus must currently exist in the source
2349    //   archetype for this inserter and its location within the archetype.
2350    // - The caller must ensure that the iterators and storage types match up with the `BundleInserter`
2351    // - `apply_effect` is never called on this bundle.
2352    // - `bundle` is not used or dropped after this point.
2353    unsafe {
2354        bundle_inserter.insert(
2355            entity,
2356            location,
2357            bundle,
2358            mode,
2359            caller,
2360            relationship_hook_insert_mode,
2361        )
2362    }
2363}