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