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