|
| 1 | +#![warn(unsafe_op_in_unsafe_fn)] |
| 2 | + |
| 3 | +use super::{Mut, World}; |
| 4 | +use crate::{ |
| 5 | + change_detection::{MutUntyped, Ticks}, |
| 6 | + component::ComponentId, |
| 7 | + system::Resource, |
| 8 | +}; |
| 9 | +use bevy_ptr::Ptr; |
| 10 | +use bevy_ptr::UnsafeCellDeref; |
| 11 | +use std::any::TypeId; |
| 12 | + |
| 13 | +/// Variant of the [`World`] where resource and component accesses takes a `&World`, and the responsibility to avoid |
| 14 | +/// aliasing violations are given to the caller instead of being checked at compile-time by rust's unique XOR shared rule. |
| 15 | +/// |
| 16 | +/// ### Rationale |
| 17 | +/// In rust, having a `&mut World` means that there are absolutely no other references to the safe world alive at the same time, |
| 18 | +/// without exceptions. Not even unsafe code can change this. |
| 19 | +/// |
| 20 | +/// But there are situations where careful shared mutable access through a type is possible and safe. For this, rust provides the [`UnsafeCell`](std::cell::UnsafeCell) |
| 21 | +/// escape hatch, which allows you to get a `*mut T` from a `&UnsafeCell<T>` and around which safe abstractions can be built. |
| 22 | +/// |
| 23 | +/// Access to resources and components can be done uniquely using [`World::resource_mut`] and [`World::entity_mut`], and shared using [`World::resource`] and [`World::entity`]. |
| 24 | +/// These methods use lifetimes to check at compile time that no aliasing rules are being broken. |
| 25 | +/// |
| 26 | +/// This alone is not enough to implement bevy systems where multiple systems can access *disjoint* parts of the world concurrently. For this, bevy stores all values of |
| 27 | +/// resources and components (and [`ComponentTicks`](crate::component::ComponentTicks)) in [`UnsafeCell`](std::cell::UnsafeCell)s, and carefully validates disjoint access patterns using |
| 28 | +/// APIs like [`System::component_access`](crate::system::System::component_access). |
| 29 | +/// |
| 30 | +/// A system then can be executed using [`System::run_unsafe`](crate::system::System::run_unsafe) with a `&World` and use methods with interior mutability to access resource values. |
| 31 | +/// access resource values. |
| 32 | +/// |
| 33 | +/// ### Example Usage |
| 34 | +/// |
| 35 | +/// [`InteriorMutableWorld`] can be used as a building block for writing APIs that safely allow disjoint access into the world. |
| 36 | +/// In the following example, the world is split into a resource access half and a component access half, where each one can |
| 37 | +/// safely hand out mutable references. |
| 38 | +/// |
| 39 | +/// ``` |
| 40 | +/// use bevy_ecs::world::World; |
| 41 | +/// use bevy_ecs::change_detection::Mut; |
| 42 | +/// use bevy_ecs::system::Resource; |
| 43 | +/// use bevy_ecs::world::interior_mutable_world::InteriorMutableWorld; |
| 44 | +/// |
| 45 | +/// // INVARIANT: existance of this struct means that users of it are the only ones being able to access resources in the world |
| 46 | +/// struct OnlyResourceAccessWorld<'w>(InteriorMutableWorld<'w>); |
| 47 | +/// // INVARIANT: existance of this struct means that users of it are the only ones being able to access components in the world |
| 48 | +/// struct OnlyComponentAccessWorld<'w>(InteriorMutableWorld<'w>); |
| 49 | +/// |
| 50 | +/// impl<'w> OnlyResourceAccessWorld<'w> { |
| 51 | +/// fn get_resource_mut<T: Resource>(&mut self) -> Option<Mut<'w, T>> { |
| 52 | +/// // SAFETY: resource access is allowed through this InteriorMutableWorld |
| 53 | +/// unsafe { self.0.get_resource_mut::<T>() } |
| 54 | +/// } |
| 55 | +/// } |
| 56 | +/// // impl<'w> OnlyComponentAccessWorld<'w> { |
| 57 | +/// // ... |
| 58 | +/// // } |
| 59 | +/// |
| 60 | +/// // the two interior mutable worlds borrow from the `&mut World`, so it cannot be accessed while they are live |
| 61 | +/// fn split_world_access(world: &mut World) -> (OnlyResourceAccessWorld<'_>, OnlyComponentAccessWorld<'_>) { |
| 62 | +/// let resource_access = OnlyResourceAccessWorld(unsafe { world.as_interior_mutable() }); |
| 63 | +/// let component_access = OnlyComponentAccessWorld(unsafe { world.as_interior_mutable() }); |
| 64 | +/// (resource_access, component_access) |
| 65 | +/// } |
| 66 | +/// ``` |
| 67 | +#[derive(Copy, Clone)] |
| 68 | +pub struct InteriorMutableWorld<'w>(&'w World); |
| 69 | + |
| 70 | +impl<'w> InteriorMutableWorld<'w> { |
| 71 | + pub(crate) fn new(world: &'w World) -> Self { |
| 72 | + InteriorMutableWorld(world) |
| 73 | + } |
| 74 | + |
| 75 | + /// Gets a reference to the [`&World`](crate::world::World) this [`InteriorMutableWorld`] belongs to. |
| 76 | + /// This can be used to call methods like [`World::read_change_tick`] which aren't exposed here but don't perform any accesses. |
| 77 | + /// |
| 78 | + /// **Note**: You *must not* hand out a `&World` reference to arbitrary safe code when the [`InteriorMutableWorld`] is currently |
| 79 | + /// being used for mutable accesses. |
| 80 | + /// |
| 81 | + /// SAFETY: |
| 82 | + /// - the world must not be used to access any resources or components. You can use it to safely access metadata. |
| 83 | + pub unsafe fn world(&self) -> &'w World { |
| 84 | + self.0 |
| 85 | + } |
| 86 | + |
| 87 | + /// Gets a reference to the resource of the given type if it exists |
| 88 | + /// |
| 89 | + /// # Safety |
| 90 | + /// All [`InteriorMutableWorld`] methods take `&self` and thus do not check that there is only one unique reference or multiple shared ones. |
| 91 | + /// It is the callers responsibility to make sure that there will never be a mutable reference to a value that has other references pointing to it, |
| 92 | + /// and that no arbitrary safe code can access a `&World` while some value is mutably borrowed. |
| 93 | + #[inline] |
| 94 | + pub unsafe fn get_resource<R: Resource>(&self) -> Option<&'w R> { |
| 95 | + self.0.get_resource::<R>() |
| 96 | + } |
| 97 | + |
| 98 | + /// Gets a pointer to the resource with the id [`ComponentId`] if it exists. |
| 99 | + /// The returned pointer must not be used to modify the resource, and must not be |
| 100 | + /// dereferenced after the borrow of the [`World`] ends. |
| 101 | + /// |
| 102 | + /// **You should prefer to use the typed API [`InteriorMutableWorld::get_resource`] where possible and only |
| 103 | + /// use this in cases where the actual types are not known at compile time.** |
| 104 | + /// |
| 105 | + /// # Safety |
| 106 | + /// All [`InteriorMutableWorld`] methods take `&self` and thus do not check that there is only one unique reference or multiple shared ones. |
| 107 | + /// It is the callers responsibility to make sure that there will never be a mutable reference to a value that has other references pointing to it, |
| 108 | + /// and that no arbitrary safe code can access a `&World` while some value is mutably borrowed. |
| 109 | + #[inline] |
| 110 | + pub unsafe fn get_resource_by_id(&self, component_id: ComponentId) -> Option<Ptr<'w>> { |
| 111 | + self.0.get_resource_by_id(component_id) |
| 112 | + } |
| 113 | + |
| 114 | + /// Gets a mutable reference to the resource of the given type if it exists |
| 115 | + /// |
| 116 | + /// # Safety |
| 117 | + /// All [`InteriorMutableWorld`] methods take `&self` and thus do not check that there is only one unique reference or multiple shared ones. |
| 118 | + /// It is the callers responsibility to make sure that there will never be a mutable reference to a value that has other references pointing to it, |
| 119 | + /// and that no arbitrary safe code can access a `&World` while some value is mutably borrowed. |
| 120 | + #[inline] |
| 121 | + pub unsafe fn get_resource_mut<R: Resource>(&self) -> Option<Mut<'w, R>> { |
| 122 | + let component_id = self.0.components.get_resource_id(TypeId::of::<R>())?; |
| 123 | + // SAFETY: |
| 124 | + // - component_id is of type `R` |
| 125 | + // - caller ensures aliasing rules |
| 126 | + // - `R` is Send + Sync |
| 127 | + unsafe { self.0.get_resource_unchecked_mut_with_id(component_id) } |
| 128 | + } |
| 129 | + |
| 130 | + /// Gets a pointer to the resource with the id [`ComponentId`] if it exists. |
| 131 | + /// The returned pointer may be used to modify the resource, as long as the mutable borrow |
| 132 | + /// of the [`InteriorMutableWorld`] is still valid. |
| 133 | + /// |
| 134 | + /// **You should prefer to use the typed API [`InteriorMutableWorld::get_resource_mut`] where possible and only |
| 135 | + /// use this in cases where the actual types are not known at compile time.** |
| 136 | + /// |
| 137 | + /// # Safety |
| 138 | + /// All [`InteriorMutableWorld`] methods take `&self` and thus do not check that there is only one unique reference or multiple shared ones. |
| 139 | + /// It is the callers responsibility to make sure that there will never be a mutable reference to a value that has other references pointing to it, |
| 140 | + /// and that no arbitrary safe code can access a `&World` while some value is mutably borrowed. |
| 141 | + #[inline] |
| 142 | + pub unsafe fn get_resource_mut_by_id( |
| 143 | + &self, |
| 144 | + component_id: ComponentId, |
| 145 | + ) -> Option<MutUntyped<'w>> { |
| 146 | + let info = self.0.components.get_info(component_id)?; |
| 147 | + if !info.is_send_and_sync() { |
| 148 | + self.0.validate_non_send_access_untyped(info.name()); |
| 149 | + } |
| 150 | + |
| 151 | + let (ptr, ticks) = self.0.get_resource_with_ticks(component_id)?; |
| 152 | + |
| 153 | + // SAFETY: |
| 154 | + // - index is in-bounds because the column is initialized and non-empty |
| 155 | + // - the caller promises that no other reference to the ticks of the same row can exist at the same time |
| 156 | + let ticks = unsafe { |
| 157 | + Ticks::from_tick_cells(ticks, self.0.last_change_tick(), self.0.read_change_tick()) |
| 158 | + }; |
| 159 | + |
| 160 | + Some(MutUntyped { |
| 161 | + // SAFETY: This function has exclusive access to the world so nothing aliases `ptr`. |
| 162 | + value: unsafe { ptr.assert_unique() }, |
| 163 | + ticks, |
| 164 | + }) |
| 165 | + } |
| 166 | + |
| 167 | + /// Gets a reference to the non-send resource of the given type, if it exists. |
| 168 | + /// Otherwise returns [None] |
| 169 | + #[inline] |
| 170 | + pub unsafe fn get_non_send_resource<R: 'static>(&self) -> Option<&R> { |
| 171 | + self.0.get_non_send_resource::<R>() |
| 172 | + } |
| 173 | + /// Gets a mutable reference to the non-send resource of the given type, if it exists. |
| 174 | + /// Otherwise returns [None] |
| 175 | + #[inline] |
| 176 | + pub unsafe fn get_non_send_resource_mut<R: 'static>(&mut self) -> Option<Mut<'w, R>> { |
| 177 | + let component_id = self.0.components.get_resource_id(TypeId::of::<R>())?; |
| 178 | + // SAFETY: safety requirement is deferred to the caller |
| 179 | + unsafe { self.0.get_non_send_unchecked_mut_with_id(component_id) } |
| 180 | + } |
| 181 | +} |
0 commit comments