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