Skip to main content

bevy_ecs/world/entity_access/
entity_mut.rs

1use crate::{
2    archetype::Archetype,
3    change_detection::{ComponentTicks, MaybeLocation, Tick},
4    component::{Component, ComponentId, Mutable},
5    entity::{ContainsEntity, Entity, EntityEquivalent, EntityLocation},
6    query::{
7        has_conflicts, Access, QueryAccessError, ReadOnlyQueryData, ReleaseStateQueryData,
8        SingleEntityQueryData,
9    },
10    world::{
11        error::EntityComponentError, unsafe_world_cell::UnsafeEntityCell, DynamicComponentFetch,
12        EntityRef, FilteredEntityMut, FilteredEntityRef, Mut, Ref,
13    },
14};
15
16use core::{
17    any::TypeId,
18    cmp::Ordering,
19    hash::{Hash, Hasher},
20};
21
22/// Provides mutable access to a single entity and all of its components.
23///
24/// Contrast with [`EntityWorldMut`], which allows adding and removing components,
25/// despawning the entity, and provides mutable access to the entire world.
26/// Because of this, `EntityWorldMut` cannot coexist with any other world accesses.
27///
28/// # Examples
29///
30/// Disjoint mutable access.
31///
32/// ```
33/// # use bevy_ecs::prelude::*;
34/// # #[derive(Component)] pub struct A;
35/// fn disjoint_system(
36///     query1: Query<EntityMut, With<A>>,
37///     query2: Query<EntityMut, Without<A>>,
38/// ) {
39///     // ...
40/// }
41/// # bevy_ecs::system::assert_is_system(disjoint_system);
42/// ```
43///
44/// [`EntityWorldMut`]: crate::world::EntityWorldMut
45pub struct EntityMut<'w> {
46    cell: UnsafeEntityCell<'w>,
47}
48
49impl<'w> EntityMut<'w> {
50    /// # Safety
51    /// - `cell` must have permission to mutate every component of the entity.
52    /// - No accesses to any of the entity's components may exist
53    ///   at the same time as the returned [`EntityMut`].
54    #[inline]
55    pub(crate) unsafe fn new(cell: UnsafeEntityCell<'w>) -> Self {
56        Self { cell }
57    }
58
59    /// Returns a new instance with a shorter lifetime.
60    /// This is useful if you have `&mut EntityMut`, but you need `EntityMut`.
61    #[inline]
62    pub fn reborrow(&mut self) -> EntityMut<'_> {
63        // SAFETY:
64        // - We have exclusive access to the entire entity and its components.
65        // - `&mut self` ensures there are no other accesses.
66        unsafe { Self::new(self.cell) }
67    }
68
69    /// Consumes `self` and returns read-only access to all of the entity's
70    /// components, with the world `'w` lifetime.
71    #[inline]
72    pub fn into_readonly(self) -> EntityRef<'w> {
73        // SAFETY:
74        // - We have exclusive access to the entire entity and its components.
75        // - Consuming `self` ensures there are no other accesses.
76        unsafe { EntityRef::new(self.cell) }
77    }
78
79    /// Gets read-only access to all of the entity's components.
80    #[inline]
81    pub fn as_readonly(&self) -> EntityRef<'_> {
82        // SAFETY:
83        // - We have exclusive access to the entire entity and its components.
84        // - `&self` ensures there are no mutable accesses.
85        unsafe { EntityRef::new(self.cell) }
86    }
87
88    /// Consumes `self` and returns a [`FilteredEntityMut`] which has mutable
89    /// access to all of the entity's components, with the world `'w` lifetime.
90    #[inline]
91    pub fn into_filtered(self) -> FilteredEntityMut<'w, 'static> {
92        // SAFETY:
93        // - We have exclusive access to the entire entity and its components.
94        // - Consuming `self` ensures there are no other accesses.
95        unsafe { FilteredEntityMut::new(self.cell, const { &Access::new_write_all() }) }
96    }
97
98    /// Get access to the underlying [`UnsafeEntityCell`].
99    #[inline]
100    pub fn as_unsafe_entity_cell(&mut self) -> UnsafeEntityCell<'_> {
101        self.cell
102    }
103
104    /// Returns the [ID](Entity) of the current entity.
105    #[inline]
106    #[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
107    pub fn id(&self) -> Entity {
108        self.cell.id()
109    }
110
111    /// Gets metadata indicating the location where the current entity is stored.
112    #[inline]
113    pub fn location(&self) -> EntityLocation {
114        self.cell.location()
115    }
116
117    /// Returns the archetype that the current entity belongs to.
118    #[inline]
119    pub fn archetype(&self) -> &Archetype {
120        self.cell.archetype()
121    }
122
123    /// Returns `true` if the current entity has a component of type `T`.
124    /// Otherwise, this returns `false`.
125    ///
126    /// ## Notes
127    ///
128    /// If you do not know the concrete type of a component, consider using
129    /// [`Self::contains_id`] or [`Self::contains_type_id`].
130    #[inline]
131    pub fn contains<T: Component>(&self) -> bool {
132        self.contains_type_id(TypeId::of::<T>())
133    }
134
135    /// Returns `true` if the current entity has a component identified by `component_id`.
136    /// Otherwise, this returns false.
137    ///
138    /// ## Notes
139    ///
140    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
141    /// - If you know the component's [`TypeId`] but not its [`ComponentId`], consider using
142    ///   [`Self::contains_type_id`].
143    #[inline]
144    pub fn contains_id(&self, component_id: ComponentId) -> bool {
145        self.cell.contains_id(component_id)
146    }
147
148    /// Returns `true` if the current entity has a component with the type identified by `type_id`.
149    /// Otherwise, this returns false.
150    ///
151    /// ## Notes
152    ///
153    /// - If you know the concrete type of the component, you should prefer [`Self::contains`].
154    /// - If you have a [`ComponentId`] instead of a [`TypeId`], consider using [`Self::contains_id`].
155    #[inline]
156    pub fn contains_type_id(&self, type_id: TypeId) -> bool {
157        self.cell.contains_type_id(type_id)
158    }
159
160    /// Gets access to the component of type `T` for the current entity.
161    /// Returns `None` if the entity does not have a component of type `T`.
162    #[inline]
163    pub fn get<T: Component>(&self) -> Option<&'_ T> {
164        self.as_readonly().get()
165    }
166
167    /// Returns read-only components for the current entity that match the query `Q`.
168    ///
169    /// # Panics
170    ///
171    /// If the entity does not have the components required by the query `Q`.
172    pub fn components<Q: ReadOnlyQueryData + ReleaseStateQueryData + SingleEntityQueryData>(
173        &self,
174    ) -> Q::Item<'_, 'static> {
175        self.as_readonly().components::<Q>()
176    }
177
178    /// Returns read-only components for the current entity that match the query `Q`,
179    /// or `None` if the entity does not have the components required by the query `Q`.
180    pub fn get_components<Q: ReadOnlyQueryData + ReleaseStateQueryData + SingleEntityQueryData>(
181        &self,
182    ) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
183        self.as_readonly().get_components::<Q>()
184    }
185
186    /// Returns components for the current entity that match the query `Q`,
187    /// or `None` if the entity does not have the components required by the query `Q`.
188    ///
189    /// # Example
190    ///
191    /// ```
192    /// # use bevy_ecs::prelude::*;
193    /// #
194    /// #[derive(Component)]
195    /// struct X(usize);
196    /// #[derive(Component)]
197    /// struct Y(usize);
198    ///
199    /// # let mut world = World::default();
200    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
201    /// // Get mutable access to two components at once
202    /// // SAFETY: X and Y are different components
203    /// let (mut x, mut y) =
204    ///     unsafe { entity.get_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
205    /// *x = X(1);
206    /// *y = Y(1);
207    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
208    /// // entity.get_components_mut_unchecked::<(&mut X, &mut X)>();
209    /// ```
210    ///
211    /// # Safety
212    /// It is the caller's responsibility to ensure that
213    /// the `QueryData` does not provide aliasing mutable references to the same component.
214    ///
215    /// # See also
216    ///
217    /// - [`Self::get_components_mut`] for the safe version that performs aliasing checks
218    pub unsafe fn get_components_mut_unchecked<Q: ReleaseStateQueryData + SingleEntityQueryData>(
219        &mut self,
220    ) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
221        // SAFETY: Caller ensures the `QueryData` does not provide aliasing mutable references to the same component
222        unsafe { self.reborrow().into_components_mut_unchecked::<Q>() }
223    }
224
225    /// Returns components for the current entity that match the query `Q`.
226    /// In the case of conflicting [`QueryData`](crate::query::QueryData), unregistered components, or missing components,
227    /// this will return a [`QueryAccessError`]
228    ///
229    /// # Example
230    ///
231    /// ```
232    /// # use bevy_ecs::prelude::*;
233    /// #
234    /// #[derive(Component)]
235    /// struct X(usize);
236    /// #[derive(Component)]
237    /// struct Y(usize);
238    ///
239    /// # let mut world = World::default();
240    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
241    /// // Get mutable access to two components at once
242    /// // SAFETY: X and Y are different components
243    /// let (mut x, mut y) = entity.get_components_mut::<(&mut X, &mut Y)>().unwrap();
244    /// ```
245    ///
246    /// Note that this does a O(n^2) check that the [`QueryData`](crate::query::QueryData) does not conflict. If performance is a
247    /// consideration you should use [`Self::get_components_mut_unchecked`] instead.
248    pub fn get_components_mut<Q: ReleaseStateQueryData + SingleEntityQueryData>(
249        &mut self,
250    ) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
251        self.reborrow().into_components_mut::<Q>()
252    }
253
254    /// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
255    /// or `None` if the entity does not have the components required by the query `Q`.
256    ///
257    /// # Example
258    ///
259    /// ```
260    /// # use bevy_ecs::prelude::*;
261    /// #
262    /// #[derive(Component)]
263    /// struct X(usize);
264    /// #[derive(Component)]
265    /// struct Y(usize);
266    ///
267    /// # let mut world = World::default();
268    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
269    /// // Get mutable access to two components at once
270    /// // SAFETY: X and Y are different components
271    /// let (mut x, mut y) =
272    ///     unsafe { entity.into_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
273    /// *x = X(1);
274    /// *y = Y(1);
275    /// // This would trigger undefined behavior, as the `&mut X`s would alias:
276    /// // entity.into_components_mut_unchecked::<(&mut X, &mut X)>();
277    /// ```
278    ///
279    /// # Safety
280    /// It is the caller's responsibility to ensure that
281    /// the `QueryData` does not provide aliasing mutable references to the same component.
282    ///
283    /// # See also
284    ///
285    /// - [`Self::into_components_mut`] for the safe version that performs aliasing checks
286    pub unsafe fn into_components_mut_unchecked<
287        Q: ReleaseStateQueryData + SingleEntityQueryData,
288    >(
289        self,
290    ) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
291        // SAFETY:
292        // - We have mutable access to all components of this entity.
293        // - Caller asserts the `QueryData` does not provide aliasing mutable references to the same component
294        unsafe { self.cell.get_components::<Q>() }
295    }
296
297    /// Consumes self and returns components for the current entity that match the query `Q` for the world lifetime `'w`,
298    /// or `None` if the entity does not have the components required by the query `Q`.
299    ///
300    /// The checks for aliasing mutable references may be expensive.
301    /// If performance is a concern, consider making multiple calls to [`Self::get_mut`].
302    /// If that is not possible, consider using [`Self::into_components_mut_unchecked`] to skip the checks.
303    ///
304    /// # Panics
305    ///
306    /// If the `QueryData` provides aliasing mutable references to the same component.
307    ///
308    /// # Example
309    ///
310    /// ```
311    /// # use bevy_ecs::prelude::*;
312    /// #
313    /// #[derive(Component)]
314    /// struct X(usize);
315    /// #[derive(Component)]
316    /// struct Y(usize);
317    ///
318    /// # let mut world = World::default();
319    /// let mut entity = world.spawn((X(0), Y(0))).into_mutable();
320    /// // Get mutable access to two components at once
321    /// let (mut x, mut y) = entity.into_components_mut::<(&mut X, &mut Y)>().unwrap();
322    /// *x = X(1);
323    /// *y = Y(1);
324    /// ```
325    ///
326    /// ```should_panic
327    /// # use bevy_ecs::prelude::*;
328    /// #
329    /// # #[derive(Component)]
330    /// # struct X(usize);
331    /// #
332    /// # let mut world = World::default();
333    /// let mut entity = world.spawn((X(0))).into_mutable();
334    /// // This panics, as the `&mut X`s would alias:
335    /// entity.into_components_mut::<(&mut X, &mut X)>();
336    /// ```
337    pub fn into_components_mut<Q: ReleaseStateQueryData + SingleEntityQueryData>(
338        self,
339    ) -> Result<Q::Item<'w, 'static>, QueryAccessError> {
340        has_conflicts::<Q>(self.cell.world().components())?;
341
342        // SAFETY: we checked that there were not conflicting components above
343        unsafe { self.into_components_mut_unchecked::<Q>() }
344    }
345
346    /// Consumes `self` and gets access to the component of type `T` with the
347    /// world `'w` lifetime for the current entity.
348    ///
349    /// Returns `None` if the entity does not have a component of type `T`.
350    #[inline]
351    pub fn into_borrow<T: Component>(self) -> Option<&'w T> {
352        self.into_readonly().get()
353    }
354
355    /// Gets access to the component of type `T` for the current entity,
356    /// including change detection information as a [`Ref`].
357    ///
358    /// Returns `None` if the entity does not have a component of type `T`.
359    #[inline]
360    pub fn get_ref<T: Component>(&self) -> Option<Ref<'_, T>> {
361        self.as_readonly().get_ref()
362    }
363
364    /// Consumes `self` and gets access to the component of type `T` with world
365    /// `'w` lifetime for the current entity, including change detection information
366    /// as a [`Ref<'w>`].
367    ///
368    /// Returns `None` if the entity does not have a component of type `T`.
369    #[inline]
370    pub fn into_ref<T: Component>(self) -> Option<Ref<'w, T>> {
371        self.into_readonly().get_ref()
372    }
373
374    /// Gets mutable access to the component of type `T` for the current entity.
375    /// Returns `None` if the entity does not have a component of type `T`.
376    #[inline]
377    pub fn get_mut<T: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, T>> {
378        // SAFETY: &mut self implies exclusive access for duration of returned value
379        unsafe { self.cell.get_mut() }
380    }
381
382    /// Gets mutable access to the component of type `T` for the current entity.
383    /// Returns `None` if the entity does not have a component of type `T`.
384    ///
385    /// # Safety
386    ///
387    /// - `T` must be a mutable component
388    #[inline]
389    pub unsafe fn get_mut_assume_mutable<T: Component>(&mut self) -> Option<Mut<'_, T>> {
390        // SAFETY:
391        // - &mut self implies exclusive access for duration of returned value
392        // - Caller ensures `T` is a mutable component
393        unsafe { self.cell.get_mut_assume_mutable() }
394    }
395
396    /// Consumes self and gets mutable access to the component of type `T`
397    /// with the world `'w` lifetime for the current entity.
398    /// Returns `None` if the entity does not have a component of type `T`.
399    #[inline]
400    pub fn into_mut<T: Component<Mutability = Mutable>>(self) -> Option<Mut<'w, T>> {
401        // SAFETY: consuming `self` implies exclusive access
402        unsafe { self.cell.get_mut() }
403    }
404
405    /// Gets mutable access to the component of type `T` for the current entity.
406    /// Returns `None` if the entity does not have a component of type `T`.
407    ///
408    /// # Safety
409    ///
410    /// - `T` must be a mutable component
411    #[inline]
412    pub unsafe fn into_mut_assume_mutable<T: Component>(self) -> Option<Mut<'w, T>> {
413        // SAFETY:
414        // - Consuming `self` implies exclusive access
415        // - Caller ensures `T` is a mutable component
416        unsafe { self.cell.get_mut_assume_mutable() }
417    }
418
419    /// Retrieves the change ticks for the given component. This can be useful for implementing change
420    /// detection in custom runtimes.
421    #[inline]
422    pub fn get_change_ticks<T: Component>(&self) -> Option<ComponentTicks> {
423        self.as_readonly().get_change_ticks::<T>()
424    }
425
426    /// Retrieves the change ticks for the given [`ComponentId`]. This can be useful for implementing change
427    /// detection in custom runtimes.
428    ///
429    /// **You should prefer to use the typed API [`EntityWorldMut::get_change_ticks`] where possible and only
430    /// use this in cases where the actual component types are not known at
431    /// compile time.**
432    ///
433    /// [`EntityWorldMut::get_change_ticks`]: crate::world::EntityWorldMut::get_change_ticks
434    #[inline]
435    pub fn get_change_ticks_by_id(&self, component_id: ComponentId) -> Option<ComponentTicks> {
436        self.as_readonly().get_change_ticks_by_id(component_id)
437    }
438
439    /// Returns untyped read-only reference(s) to component(s) for the
440    /// current entity, based on the given [`ComponentId`]s.
441    ///
442    /// **You should prefer to use the typed API [`EntityMut::get`] where
443    /// possible and only use this in cases where the actual component types
444    /// are not known at compile time.**
445    ///
446    /// Unlike [`EntityMut::get`], this returns untyped reference(s) to
447    /// component(s), and it's the job of the caller to ensure the correct
448    /// type(s) are dereferenced (if necessary).
449    ///
450    /// # Errors
451    ///
452    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
453    /// not have a component.
454    ///
455    /// # Examples
456    ///
457    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
458    #[inline]
459    pub fn get_by_id<F: DynamicComponentFetch>(
460        &self,
461        component_ids: F,
462    ) -> Result<F::Ref<'_>, EntityComponentError> {
463        self.as_readonly().get_by_id(component_ids)
464    }
465
466    /// Consumes `self` and returns untyped read-only reference(s) to
467    /// component(s) with lifetime `'w` for the current entity, based on the
468    /// given [`ComponentId`]s.
469    ///
470    /// **You should prefer to use the typed API [`EntityMut::into_borrow`]
471    /// where possible and only use this in cases where the actual component
472    /// types are not known at compile time.**
473    ///
474    /// Unlike [`EntityMut::into_borrow`], this returns untyped reference(s) to
475    /// component(s), and it's the job of the caller to ensure the correct
476    /// type(s) are dereferenced (if necessary).
477    ///
478    /// # Errors
479    ///
480    /// Returns [`EntityComponentError::MissingComponent`] if the entity does
481    /// not have a component.
482    ///
483    /// # Examples
484    ///
485    /// For examples on how to use this method, see [`EntityRef::get_by_id`].
486    #[inline]
487    pub fn into_borrow_by_id<F: DynamicComponentFetch>(
488        self,
489        component_ids: F,
490    ) -> Result<F::Ref<'w>, EntityComponentError> {
491        self.into_readonly().get_by_id(component_ids)
492    }
493
494    /// Returns untyped mutable reference(s) to component(s) for
495    /// the current entity, based on the given [`ComponentId`]s.
496    ///
497    /// **You should prefer to use the typed API [`EntityMut::get_mut`] where
498    /// possible and only use this in cases where the actual component types
499    /// are not known at compile time.**
500    ///
501    /// Unlike [`EntityMut::get_mut`], this returns untyped reference(s) to
502    /// component(s), and it's the job of the caller to ensure the correct
503    /// type(s) are dereferenced (if necessary).
504    ///
505    /// # Errors
506    ///
507    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
508    ///   not have a component.
509    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
510    ///   is requested multiple times.
511    ///
512    /// # Examples
513    ///
514    /// ## Single [`ComponentId`]
515    ///
516    /// ```
517    /// # use bevy_ecs::prelude::*;
518    /// #
519    /// # #[derive(Component, PartialEq, Debug)]
520    /// # pub struct Foo(i32);
521    /// # let mut world = World::new();
522    /// let entity = world.spawn(Foo(42)).id();
523    ///
524    /// // Grab the component ID for `Foo` in whatever way you like.
525    /// let component_id = world.register_component::<Foo>();
526    ///
527    /// // Then, get the component by ID.
528    /// let mut entity_mut = world.entity_mut(entity);
529    /// let mut ptr = entity_mut.get_mut_by_id(component_id)
530    /// #   .unwrap();
531    /// # assert_eq!(unsafe { ptr.as_mut().deref_mut::<Foo>() }, &mut Foo(42));
532    /// ```
533    ///
534    /// ## Array of [`ComponentId`]s
535    ///
536    /// ```
537    /// # use bevy_ecs::prelude::*;
538    /// #
539    /// # #[derive(Component, PartialEq, Debug)]
540    /// # pub struct X(i32);
541    /// # #[derive(Component, PartialEq, Debug)]
542    /// # pub struct Y(i32);
543    /// # let mut world = World::new();
544    /// let entity = world.spawn((X(42), Y(10))).id();
545    ///
546    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
547    /// let x_id = world.register_component::<X>();
548    /// let y_id = world.register_component::<Y>();
549    ///
550    /// // Then, get the components by ID. You'll receive a same-sized array.
551    /// let mut entity_mut = world.entity_mut(entity);
552    /// let Ok([mut x_ptr, mut y_ptr]) = entity_mut.get_mut_by_id([x_id, y_id]) else {
553    ///     // Up to you to handle if a component is missing from the entity.
554    /// #   unreachable!();
555    /// };
556    /// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
557    /// ```
558    ///
559    /// ## Slice of [`ComponentId`]s
560    ///
561    /// ```
562    /// # use bevy_ecs::{prelude::*, component::ComponentId, change_detection::MutUntyped};
563    /// #
564    /// # #[derive(Component, PartialEq, Debug)]
565    /// # pub struct X(i32);
566    /// # #[derive(Component, PartialEq, Debug)]
567    /// # pub struct Y(i32);
568    /// # let mut world = World::new();
569    /// let entity = world.spawn((X(42), Y(10))).id();
570    ///
571    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
572    /// let x_id = world.register_component::<X>();
573    /// let y_id = world.register_component::<Y>();
574    ///
575    /// // Then, get the components by ID. You'll receive a vec of ptrs.
576    /// let mut entity_mut = world.entity_mut(entity);
577    /// let ptrs = entity_mut.get_mut_by_id(&[x_id, y_id] as &[ComponentId])
578    /// #   .unwrap();
579    /// # let [mut x_ptr, mut y_ptr]: [MutUntyped; 2] = ptrs.try_into().unwrap();
580    /// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
581    /// ```
582    ///
583    /// ## `HashSet` of [`ComponentId`]s
584    ///
585    /// ```
586    /// # use bevy_platform::collections::HashSet;
587    /// # use bevy_ecs::{prelude::*, component::ComponentId};
588    /// #
589    /// # #[derive(Component, PartialEq, Debug)]
590    /// # pub struct X(i32);
591    /// # #[derive(Component, PartialEq, Debug)]
592    /// # pub struct Y(i32);
593    /// # let mut world = World::new();
594    /// let entity = world.spawn((X(42), Y(10))).id();
595    ///
596    /// // Grab the component IDs for `X` and `Y` in whatever way you like.
597    /// let x_id = world.register_component::<X>();
598    /// let y_id = world.register_component::<Y>();
599    ///
600    /// // Then, get the components by ID. You'll receive a `HashMap` of ptrs.
601    /// let mut entity_mut = world.entity_mut(entity);
602    /// let mut ptrs = entity_mut.get_mut_by_id(&HashSet::from_iter([x_id, y_id]))
603    /// #   .unwrap();
604    /// # let [Some(mut x_ptr), Some(mut y_ptr)] = ptrs.get_many_mut([&x_id, &y_id]) else { unreachable!() };
605    /// # assert_eq!((unsafe { x_ptr.as_mut().deref_mut::<X>() }, unsafe { y_ptr.as_mut().deref_mut::<Y>() }), (&mut X(42), &mut Y(10)));
606    /// ```
607    #[inline]
608    pub fn get_mut_by_id<F: DynamicComponentFetch>(
609        &mut self,
610        component_ids: F,
611    ) -> Result<F::Mut<'_>, EntityComponentError> {
612        // SAFETY:
613        // - `&mut self` ensures that no references exist to this entity's components.
614        // - We have exclusive access to all components of this entity.
615        unsafe { component_ids.fetch_mut(self.cell) }
616    }
617
618    /// Returns untyped mutable reference(s) to component(s) for
619    /// the current entity, based on the given [`ComponentId`]s.
620    /// Assumes the given [`ComponentId`]s refer to mutable components.
621    ///
622    /// **You should prefer to use the typed API [`EntityMut::get_mut_assume_mutable`] where
623    /// possible and only use this in cases where the actual component types
624    /// are not known at compile time.**
625    ///
626    /// Unlike [`EntityMut::get_mut_assume_mutable`], this returns untyped reference(s) to
627    /// component(s), and it's the job of the caller to ensure the correct
628    /// type(s) are dereferenced (if necessary).
629    ///
630    /// # Errors
631    ///
632    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
633    ///   not have a component.
634    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
635    ///   is requested multiple times.
636    ///
637    /// # Safety
638    /// It is the callers responsibility to ensure that
639    /// - the provided [`ComponentId`]s must refer to mutable components.
640    #[inline]
641    pub unsafe fn get_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
642        &mut self,
643        component_ids: F,
644    ) -> Result<F::Mut<'_>, EntityComponentError> {
645        // SAFETY:
646        // - `&mut self` ensures that no references exist to this entity's components.
647        // - We have exclusive access to all components of this entity.
648        unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
649    }
650
651    /// Returns untyped mutable reference to component for
652    /// the current entity, based on the given [`ComponentId`].
653    ///
654    /// Unlike [`EntityMut::get_mut_by_id`], this method borrows &self instead of
655    /// &mut self, allowing the caller to access multiple components simultaneously.
656    ///
657    /// # Errors
658    ///
659    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
660    ///   not have a component.
661    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
662    ///   is requested multiple times.
663    ///
664    /// # Safety
665    /// It is the callers responsibility to ensure that
666    /// - the [`UnsafeEntityCell`] has permission to access the component mutably
667    /// - no other references to the component exist at the same time
668    #[inline]
669    pub unsafe fn get_mut_by_id_unchecked<F: DynamicComponentFetch>(
670        &self,
671        component_ids: F,
672    ) -> Result<F::Mut<'_>, EntityComponentError> {
673        // SAFETY:
674        // - The caller must ensure simultaneous access is limited
675        // - to components that are mutually independent.
676        unsafe { component_ids.fetch_mut(self.cell) }
677    }
678
679    /// Returns untyped mutable reference to component for
680    /// the current entity, based on the given [`ComponentId`].
681    /// Assumes the given [`ComponentId`]s refer to mutable components.
682    ///
683    /// Unlike [`EntityMut::get_mut_assume_mutable_by_id`], this method borrows &self instead of
684    /// &mut self, allowing the caller to access multiple components simultaneously.
685    ///
686    /// # Errors
687    ///
688    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
689    ///   not have a component.
690    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
691    ///   is requested multiple times.
692    ///
693    /// # Safety
694    /// It is the callers responsibility to ensure that
695    /// - the [`UnsafeEntityCell`] has permission to access the component mutably
696    /// - no other references to the component exist at the same time
697    /// - the provided [`ComponentId`]s must refer to mutable components.
698    #[inline]
699    pub unsafe fn get_mut_assume_mutable_by_id_unchecked<F: DynamicComponentFetch>(
700        &self,
701        component_ids: F,
702    ) -> Result<F::Mut<'_>, EntityComponentError> {
703        // SAFETY:
704        // - The caller must ensure simultaneous access is limited
705        // - to components that are mutually independent.
706        unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
707    }
708
709    /// Consumes `self` and returns untyped mutable reference(s)
710    /// to component(s) with lifetime `'w` for the current entity, based on the
711    /// given [`ComponentId`]s.
712    ///
713    /// **You should prefer to use the typed API [`EntityMut::into_mut`] where
714    /// possible and only use this in cases where the actual component types
715    /// are not known at compile time.**
716    ///
717    /// Unlike [`EntityMut::into_mut`], this returns untyped reference(s) to
718    /// component(s), and it's the job of the caller to ensure the correct
719    /// type(s) are dereferenced (if necessary).
720    ///
721    /// # Errors
722    ///
723    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
724    ///   not have a component.
725    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
726    ///   is requested multiple times.
727    ///
728    /// # Examples
729    ///
730    /// For examples on how to use this method, see [`EntityMut::get_mut_by_id`].
731    #[inline]
732    pub fn into_mut_by_id<F: DynamicComponentFetch>(
733        self,
734        component_ids: F,
735    ) -> Result<F::Mut<'w>, EntityComponentError> {
736        // SAFETY:
737        // - consuming `self` ensures that no references exist to this entity's components.
738        // - We have exclusive access to all components of this entity.
739        unsafe { component_ids.fetch_mut(self.cell) }
740    }
741
742    /// Consumes `self` and returns untyped mutable reference(s)
743    /// to component(s) with lifetime `'w` for the current entity, based on the
744    /// given [`ComponentId`]s.
745    /// Assumes the given [`ComponentId`]s refer to mutable components.
746    ///
747    /// **You should prefer to use the typed API [`EntityMut::into_mut_assume_mutable`] where
748    /// possible and only use this in cases where the actual component types
749    /// are not known at compile time.**
750    ///
751    /// Unlike [`EntityMut::into_mut_assume_mutable`], this returns untyped reference(s) to
752    /// component(s), and it's the job of the caller to ensure the correct
753    /// type(s) are dereferenced (if necessary).
754    ///
755    /// # Errors
756    ///
757    /// - Returns [`EntityComponentError::MissingComponent`] if the entity does
758    ///   not have a component.
759    /// - Returns [`EntityComponentError::AliasedMutability`] if a component
760    ///   is requested multiple times.
761    ///
762    /// # Safety
763    /// It is the callers responsibility to ensure that
764    /// - the provided [`ComponentId`]s must refer to mutable components.
765    #[inline]
766    pub unsafe fn into_mut_assume_mutable_by_id<F: DynamicComponentFetch>(
767        self,
768        component_ids: F,
769    ) -> Result<F::Mut<'w>, EntityComponentError> {
770        // SAFETY:
771        // - consuming `self` ensures that no references exist to this entity's components.
772        // - We have exclusive access to all components of this entity.
773        unsafe { component_ids.fetch_mut_assume_mutable(self.cell) }
774    }
775
776    /// Returns the source code location from which this entity has been spawned.
777    pub fn spawned_by(&self) -> MaybeLocation {
778        self.cell.spawned_by()
779    }
780
781    /// Returns the [`Tick`] at which this entity has been spawned.
782    pub fn spawn_tick(&self) -> Tick {
783        self.cell.spawn_tick()
784    }
785}
786
787impl<'w> From<EntityMut<'w>> for EntityRef<'w> {
788    #[inline]
789    fn from(entity: EntityMut<'w>) -> Self {
790        entity.into_readonly()
791    }
792}
793
794impl<'a> From<&'a EntityMut<'_>> for EntityRef<'a> {
795    #[inline]
796    fn from(entity: &'a EntityMut<'_>) -> Self {
797        entity.as_readonly()
798    }
799}
800
801impl<'w> From<&'w mut EntityMut<'_>> for EntityMut<'w> {
802    #[inline]
803    fn from(entity: &'w mut EntityMut<'_>) -> Self {
804        entity.reborrow()
805    }
806}
807
808impl<'a> From<EntityMut<'a>> for FilteredEntityRef<'a, 'static> {
809    #[inline]
810    fn from(entity: EntityMut<'a>) -> Self {
811        entity.into_readonly().into_filtered()
812    }
813}
814
815impl<'a> From<&'a EntityMut<'_>> for FilteredEntityRef<'a, 'static> {
816    #[inline]
817    fn from(entity: &'a EntityMut<'_>) -> Self {
818        entity.as_readonly().into_filtered()
819    }
820}
821
822impl<'a> From<EntityMut<'a>> for FilteredEntityMut<'a, 'static> {
823    #[inline]
824    fn from(entity: EntityMut<'a>) -> Self {
825        entity.into_filtered()
826    }
827}
828
829impl<'a> From<&'a mut EntityMut<'_>> for FilteredEntityMut<'a, 'static> {
830    #[inline]
831    fn from(entity: &'a mut EntityMut<'_>) -> Self {
832        entity.reborrow().into_filtered()
833    }
834}
835
836impl PartialEq for EntityMut<'_> {
837    fn eq(&self, other: &Self) -> bool {
838        self.entity() == other.entity()
839    }
840}
841
842impl Eq for EntityMut<'_> {}
843
844impl PartialOrd for EntityMut<'_> {
845    /// [`EntityMut`]'s comparison trait implementations match the underlying [`Entity`],
846    /// and cannot discern between different worlds.
847    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
848        Some(self.cmp(other))
849    }
850}
851
852impl Ord for EntityMut<'_> {
853    fn cmp(&self, other: &Self) -> Ordering {
854        self.entity().cmp(&other.entity())
855    }
856}
857
858impl Hash for EntityMut<'_> {
859    fn hash<H: Hasher>(&self, state: &mut H) {
860        self.entity().hash(state);
861    }
862}
863
864impl ContainsEntity for EntityMut<'_> {
865    fn entity(&self) -> Entity {
866        self.id()
867    }
868}
869
870// SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity.
871unsafe impl EntityEquivalent for EntityMut<'_> {}